blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
6b244ff95e61b4ec7c663e228169c04793d4d81c | c-h-a-r-l-i-e/part2modules | /graphics/practical_1/task0_grayscale.py | 1,835 | 3.78125 | 4 | # This is an example on how to read and display an image, convert between colour spaces.
# This file does not need to be included in the submission.
import os.path as path
import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
import skimage.io as io
import skimage.color as color
import skimage.util as... |
03e8ef95675cc9fc84484befa1fad2cb6736ee3a | matthias-jaeger-net/UTOPIA | /src/tests/analyze.py | 3,061 | 3.59375 | 4 | def analyze(self):
# Procedural test of the colors values (Work in progress)
message = 'Hello, my name is #' + str(self.hex) + ' and I am a '
# Saturation test
if (self.saturation >= 0.0 and self.saturation <= 0.3):
message += 'desaturated '
if (self.saturation >= 0... |
86c5dbac2a4828297ec381dfc7b605151b41ba6d | yichaopku/leetcode | /code_0/456. 132 Pattern.py | 408 | 3.609375 | 4 | class Solution:
def find132pattern(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
stack=[]
s=None
for n in nums[::-1]:
if s and n<s:
return True
while stack and n>stack[-1]:
s=stack.pop()
... |
a3ead97f6bea37d51d20be56476f5fab42890294 | yichaopku/leetcode | /code_0/797. All Paths From Source to Target.py | 528 | 3.609375 | 4 | class Solution:
def recursive(self,k,res):
if k==self.target:
self.rs.append(res+[k])
return
for i in self.graph[k]:
self.recursive(i,res+[k])
def allPathsSourceTarget(self, graph):
"""
:type graph: List[List[int]]
:rtype: List[List[in... |
0a1087a8bc572e2e22c0b04426a3e91fdfb2cb9a | deniscapeto/Hacktoberfest | /Python/Fibonacci.py | 389 | 3.765625 | 4 | first = -1
second = -1
quantityOfNumbersToFind = int(input("Enter a quatity of numbers to calc: "))
for i in range(1,quantityOfNumbersToFind,1):
if second == -1 :
print(1)
if first>0:
second = 1
else:
first = 1
continue
else:
sum = second +... |
0c5904a6bb8d509ed55c9bd2addbd55343e0c7c8 | LucyLu717/Coal-HMM | /src/combine_alignments.py | 4,398 | 3.59375 | 4 | import argparse
from utility import OUTPUT_DIR
"""
Reads output files from first.sh.
Arguments:
input_file: base position pairs of a certain pairwise alignment
Returns:
pos: an array of base position pairs on the human genome from the
pairwise alignment given
"""
def read_input(input_file):
count... |
455bc25bcc6463800059bab1ea1d5d8bccf30255 | Krishan00007/Python_practicals | /AI_ML_visulizations/null_data_filter.py | 318 | 3.546875 | 4 | #filtering data
# displaying data only with Gender = NaN
import pandas as pd
import numpy as np
data=pd.read_csv('employees_with_missing_data.csv')
#bool_series=data["Gender"].isnull()
bool_series=data.isnull()
result1 = data[bool_series]
#result2 = data["Gender"][bool_series]
print(result1)
#print(result2) |
3e8715e64fe0540e8b00d7c28567773c3a8b178c | Krishan00007/Python_practicals | /AI_ML_visulizations/ML_linear_regression.py | 1,873 | 4.15625 | 4 | import warnings
warnings.filterwarnings(action="ignore")
# Practical implementation of Linear Regression
# -----------------------------------------------
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
def get_data(filename):
dataframe = pd.read_csv(fil... |
61c414f192b860ad7fd4f392ce611b22d58d0f98 | Krishan00007/Python_practicals | /practical_6(2).py | 2,141 | 4.28125 | 4 | """
Write a GUI-based program that allows the user to convert temperature values between degrees Fahrenheit
and degrees Celsius. The interface should have labeled entry fields for these two values. These components
should be arranged in a grid where the labels occupy the first row and the corresponding fields occu... |
d8c97706c79eaeff2111524b111e3a25753176b7 | Krishan00007/Python_practicals | /AI_ML_visulizations/value_fill.py | 1,035 | 4.34375 | 4 | # Filling a null values using interpolate() method
#using interpolate() functon to fill missing values using Linear method
import pandas as pd
# Creating the dataframe
df = pd.DataFrame(
{ "A": [12, 4, 5, None, 1],
"B": [None, 2, 54, 3, None],
... |
23c50555c6cf85b3157b30c463e390d4b374d50c | Krishan00007/Python_practicals | /practical_3(1).py | 2,229 | 4.78125 | 5 | """
A bit shift is a procedure whereby the bits in a bit string are moved to the left or to the right.
For example, we can shift the bits in the string 1011 two places to the left to produce the string 1110.
Note that the leftmost two bits are wrapped around to the right side of the string in this operation.
Def... |
14c47f156cf416431864448d62d3f27918d5226b | PNai07/Python_1st_homework | /02_datatypes.py | 1,888 | 4.5625 | 5 | # Data Types
# Computers are stupid
#They doi not understand context, and we need to be specific with data types.
#Strings
# List of Characters bundled together in a specific order
#Using Index
print('hello')
print(type('hello'))
#Concatenation of Strings - joining of two strings
string_a = 'hello there'
name_perso... |
9908be12de460b5cb7a690eae3b9030e8422e8a2 | PNai07/Python_1st_homework | /06_datatypes_booleans.py | 1,426 | 4.5625 | 5 | # Booleans
# Booleans are a data type that is either TRUE or FALSE
var_true = True
var_false = False
#Syntax is capital letter
print(type(var_true))
print(type(var_false))
# When we equate/ evaluate something we get a boolean as a response.
# Logical operator return boolean
# == / ! / <> / >= / <=
weather = 'Rain... |
7c36b5e35dd41338606b869635daafed9dfaeaf8 | monkeydunkey/interviewCakeProblems | /checkStrRot.py | 404 | 4 | 4 | '''
Check if the second string is a rotated version of the first one
'''
def checkRot(s1, s2):
joinedSt = s1 + s1
for i in range(0, len(joinedSt) - len(s2)):
#print joinedSt[i: i + len(s2)], s2
if joinedSt[i:i + len(s2)] == s2:
return 1
return 0
tests = int(input())
for t_ in r... |
e8016647428bd14ebc967f1f98855f694558558b | monkeydunkey/interviewCakeProblems | /kNonRepeating.py | 525 | 3.609375 | 4 | def kNonRepeating(st, k):
charCount = {}
for i, s in enumerate(st):
if charCount.get(s, None) is None:
charCount[s] = i
else:
charCount[s] = -1
i = 0
arr = sorted(filter(lambda x: x[1] !=-1, charCount.items()), key = lambda x: x[1])
if len(arr) < k :
return 'K... |
df5976d853b80f66a5c8d6d3466100d1912c2aea | monkeydunkey/interviewCakeProblems | /stringDecompresion.py | 881 | 3.78125 | 4 | def stringDecompression(st):
#import pdb; pdb.set_trace()
stack = []
tempSt = ''
finalSt = ''
i = 0
while i < len(st):
if st[i] == '[':
#start string
stack.append(int(tempSt))
tempSt = ''
elif st[i] == ']':
stackSt = ''
... |
4a1ed5ef41436163fbd0d6405b2368d6a4fe6d34 | monkeydunkey/interviewCakeProblems | /coinChange.py | 465 | 3.515625 | 4 | def coinChange(coins, totalAmount):
amountArr = [[0 for x in coins] for y in range(totalAmount + 1)]
for i in range(len(coins)):
amountArr[0][i] = 1
for i in range(1, totalAmount + 1):
for j, c in enumerate(coins):
x = amountArr[i - c][j] if i - c >= 0 else 0
y = amou... |
e4b56f5f11646664df6ce94fce14ab08a88557e5 | monkeydunkey/interviewCakeProblems | /findPeak.py | 473 | 3.703125 | 4 | def findPeak(arr, left, right):
if left + 1 >= right:
return left if arr[left] > arr[right] else right
mid = (left + right) // 2
if arr[mid] <= arr[mid + 1]:
return findPeak(arr, mid + 1, right)
elif arr[mid] <= arr[mid - 1]:
return findPeak(arr, left, mid - 1)
retur... |
5db3f27a07aaa7da436a7c57bdde7296e0ba38da | monkeydunkey/interviewCakeProblems | /withoutString.py | 655 | 3.53125 | 4 | def removeInstances(base, rem):
base, rem = list(base), rem.lower()
stInd = 0
remInd = 0
for i, b in enumerate(base):
if remInd == len(rem):
base[stInd: i] = [''] * (i - stInd)
remInd = 0
if rem[remInd] == b.lower():
stInd = i if remInd == 0 else stIn... |
0d35c9a50f1c2341ff4beb9e77427fd6bd8040c3 | ishubham169/Logistic-TrackApp | /code.py | 262 | 3.828125 | 4 | from dataclasses import dataclass
class a():
def __init__(self,num):
print("Class a",num)
class b(a):
def __init__(self,num):
print("Class b",num)
A.__init__(self,num-1)
if True:
obj = b(10)
print("hello")
print("shubham")
|
5cbbe93cf89cbff7b0acb8b2c5031398293bd211 | rudranshsharma123/shark-itionary | /Backend/cockroachDB/cockroach.py | 2,316 | 3.5 | 4 | import psycopg2
import numpy
import functools
import operator
conn = psycopg2.connect(
database='Sharks',
user='rudransh',
password='',
sslmode='require',
port=26257,
host='free-tier.gcp-us-central1.cockroachlabs.cloud',
options="--cluster=shiny-wolf-1947"
)
class cockroachDB():
def __... |
6c272388426804156bafacfb88b1611b715da1f7 | remedialchaostheory/square-deposit-id | /squareccdeposits.py | 6,065 | 3.65625 | 4 | #!usr/bin/env python3
import csv
from tkinter import *
from tkinter import filedialog
from tkinter import messagebox
from operator import itemgetter
from pathlib import Path
def format_date(orig_date):
"""
:param orig_date: e.g. 04/01/18
:return: e.g. 2018-04-01
"""
new_date_split = orig_date.spli... |
4dca55cb92b40311b5e5480734d5030f84cd5e17 | mourakf/MVCAD | /Python_II/lista_loop_append.py | 190 | 3.796875 | 4 | N = int(input())
nomes = []
for numero in range(N):
nome = input()
nomes.append(nome)
print(sorted(nomes))
print("\n".join(nomes))
# for nome in nomes:
# print(nome)
|
d1bb9cd23da738e97aaacca10cc1caec06255638 | GuyCChan/Fall2018-PY210A | /students/JimJenkins/test.py | 371 | 3.765625 | 4 |
def thirds(seq):
l = seq
length = len(l) // 3
l_first = l[:len(l) // 3]
l_last = l[-(length):]
l_middle = l[len(l_first):-(len(l_last))]
l_new = l_last + l_first + l_middle
return l_new
a_tuple2 = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18)
a_string2 = 'aabbccddeeffgghh... |
b86f1239f742cfd4f40f129bea1961437b6b5ad1 | Parth731/Python-Tutorial | /Telusko/51_Constructor_Self.py | 537 | 3.578125 | 4 |
class compter:
def __init__(self):
self.age = 29
self.name = "Navin"
def update(self):
self.age = 32
def compare(self,other):
if self.age == other.age:
return True
else:
return False
c1 = compter()
print(id(c1)) #address
c1.age = 30
c2 =... |
7872f29c102fe1eb10d83509671afa0cb36cf292 | Parth731/Python-Tutorial | /pythontut/75_Python2.0_vs_python3.0.py | 1,416 | 4.03125 | 4 |
'''
google search:
python 2 code to python 3
'''
'''
python2.0
print 'Hello world!'
exec code
exec code in globals
exec code in (globals, locals)
/ and //:
5 / 2 = 2
raise:
1. raise Exception, args
2. raise Exception, args, traceback
3. raise "Error"
except:
except Exception, variable:
def:
def function(arg1... |
53e2fc8c6c8ba4b78ad525d40a369a082611cb30 | Parth731/Python-Tutorial | /Quiz/4_Quiz.py | 264 | 4.125 | 4 |
# break and continue satement use in one loop
while (True):
print("Enter Integer number")
num = int(input())
if num < 100:
print("Print try again\n")
continue
else:
print("congrautlation you input is 100\n")
break
|
670dc4105eb2b07ef9db1be80f3e610d3541b0bc | Parth731/Python-Tutorial | /Telusko/39_Factorial.py | 160 | 3.78125 | 4 |
# 5! 5*4*3*2*1
def fact(n):
f = 1
for x in range(1,n+1):
f = f * x
print(f,end=" ")
return f
res = fact(5)
print()
print(res) |
0e6c8202533c3ef5645f21efcf3c017bdceafa08 | Parth731/Python-Tutorial | /Durga Software/Datatype/14_dictionary.py | 118 | 3.796875 | 4 | d = {101:'durga',102:'ravi',103:'shiva'}
d[101] = 'sanny'
print(d)
d = {}
d['a'] = "apple"
d['b'] = 'banana'
print(d) |
9641bd85b9168ca13ea4e70c287dd703d3f7c19c | Parth731/Python-Tutorial | /Exercise/2_Faulty_Calculator.py | 920 | 4.1875 | 4 | #Exercise 2 - Faulty Calculator
# 45*3 = 555, 56+9 = 77 , 56/6 = 4
# Design a caluclator which will correctly solve all the problems except
# the following ones:
# Your program should take operator and the two numbers as input from the user and then return the result
print("+ Addition")
print("- Subtraction")
print("... |
5eea18b63b502449301e6a2b94d8c2ea21fc28f4 | Parth731/Python-Tutorial | /Durga Software/Datatype/11_range.py | 147 | 3.90625 | 4 | r = range(10)
for x in r: print(x)
r = range(10,20)
for x in r: print(x)
r = range(10,20,2)
for x in r: print(x)
l = list(range(1,10))
print(l)
|
d30b268727d4bfe28f39af889fab61cd69b83637 | Parth731/Python-Tutorial | /pythontut/12_Dictionary.py | 653 | 4.03125 | 4 |
# Dictionary is nothing but key value pairs
dl = {}
print(type(dl))
d2 = {"harry" : "Burgar", "Rohan":"Fiish", "parth" : "Bhindi" ,
"shubham": {"B" : "maggie", "L" :"roti", "D":"chicken"}}
d2["Ankit"]="Junk Food"
d2[420] = "Kabab"
print(d2["harry"])
print(d2["parth"])
print(d2["shubham"]["B"])
print(d2)
del d2... |
293e1425918adf8c1080945ef6b1ebe8a33b1243 | Parth731/Python-Tutorial | /pythontut/41_Map_Filter_Reduce.py | 1,269 | 3.984375 | 4 |
# ----------------------------- map() ------------------------
numbers = ["3","34","64"]
# for item in range(len(numbers)):
# numbers[item] = int(numbers[item])
# using map function
numbers = list(map(int,numbers))
numbers[2] = numbers[2] + 1
print(numbers) # [3, 34, 65]
print(numbers[2]) # 65
def seq(a):
... |
4d26271e43cb6b703eea6abc5ea1d9f730200072 | Parth731/Python-Tutorial | /pythontut/55_Super_Override.py | 1,122 | 3.953125 | 4 |
class A:
classvar1 = "I am a class variable in class A"
def __init__(self):
self.var1 = "I am inside class A's constructor"
# instance variable
self.classvar1 = "Instance var in class A"
self.special = "_special"
class B(A):
classvar1 = "I am a class variable in class B"... |
390d991c03c773f937ce6a479b434149c42688d6 | KWMalik/simpleutils | /simpleutils/simpledecorators.py | 4,972 | 4.15625 | 4 | """
Decorators to handle simple tasks, like making decorators well-behaved,
or catching exceptions.
contains:
-simple_decorator - decorator to make decorators preserve function metadata
-catch_exceptions - decorator to catch exceptions and handle them
TODO: test catch_exceptions' handler
-dump_args... |
933dcee028b53c9b6d20ec428d26707a3cd7b36e | KWMalik/simpleutils | /simpleutils/fixwhitespace.py | 2,886 | 3.703125 | 4 | """
Clean white space - a quasi-module with some handy functions.
NOTE: for now must be run in interactive mode(python -i
cleanwhitespace.py), may change that in the future.
NOTE2: No tests yet, so be forewarned (though replace_tabs_with_spaces
has been tested These are just a few functions that can easily and
quickl... |
ea45b07deb1afc7a765a9d4cc5011aa3906ffee4 | influencemobile/gallery_demo | /solution.py | 4,832 | 3.71875 | 4 | import os
import sqlite3
from sqlite3 import Error
def create_connection():
""" create a database connection and return connection object """
conn = None;
cwd = os.getcwd()
try:
conn = sqlite3.connect(f'{cwd}\db\development.sqlite3')
print(sqlite3.version)
return conn
ex... |
9817b27cca0de9ada8ecfd1c18b8007e520a47df | DruiadinMonk/Yahtzee-Framework-Update | /dice.py | 727 | 3.796875 | 4 | # Dice for rolling
# MODULES
import pygame
import random
# DICE CLASS
class Dice:
# INITIALIZE
def __init__(self, window, color, x, y, sq, number):
self.window = window
self.color = color
self.x = x
self.y = y
self.sq = sq
self.number = number
# DRAW DICE: Hollow
def draw(self):
# DICE
pygame... |
1db6261da586b3041c860a36b8c4452c9a9a144e | SEOULVING-C1UB/Daily-Algorithm | /Daily-Algo/2020-09-01 Stack2/Magnetic/이지영_Magnetic.py | 735 | 3.546875 | 4 | for tc in range(1, 11):
side = int(input())
# 100까지 받을꺼니까 +1
board = [[0]*(side+1) for _ in range(side+1)]
for i in range(side):
board[i] = (list(map(int, input().split())))
# board = [list(map(int, input().split())) for _ in range(side)]
cnt = 0
for col in range(side):
... |
8ce4308549078e6ae69199a7b7cb5102295524ae | SEOULVING-C1UB/Daily-Algorithm | /Daily-Algo/2020-09-10 Tree/사칙연산/김민정_사칙연산.py | 1,231 | 3.8125 | 4 |
ops = ['+', '-', '*', '/']
def postorder(node): # 중위연산으로 처리
if node != 0:
postorder(tree[node][0])
postorder(tree[node][1])
value = tree[node][2]
if value in ops : # 만약 value 값이 연산자면
second = num_list.pop() # 스택에 저장되어있는 애들을 꺼내서
first = num_l... |
ae0acaf984b338d6b683d0ecb226916c92a4b90a | SEOULVING-C1UB/Daily-Algorithm | /IM 대비 문제/참외밭/고영길_참외밭.py | 1,366 | 3.578125 | 4 | """
First trial
You can notice that you can approach always from long width and height
to short width and height. Find area of big rectangle, then subtract
area of small rectangle.
"""
K = int(input())
infos = []
for _ in range(6):
infos.append(list(map(int, input().split())))
w = sum([info[1] for info in infos if... |
6e08d0f2e13dbf29f4c837353548b3767016222e | SEOULVING-C1UB/Daily-Algorithm | /Daily-Algo/2020-09-04/격자판에숫자이어붙이기/최정휴_격자판에숫자이어붙이기.py | 1,635 | 3.671875 | 4 | '''
<기본컨셉>
1) 주어진 4X4행렬의 모든 원소를 방문하며 이를 시작점으로 꼬리물기를 시작한다
2) 현재 위치를 기반으로 상하좌우를 방문하여 꼬리를 물며 이어 붙이는 재귀함수를 만든다
3) 만들어진 문자열을 리스트에 담은 후 set을 이용해 중복을 제거한다
<주의사항>
1) 상하좌우를 돌릴때 음수 인덱스는 에러가 안나므로 꼭 try가 아닌 if문으로 0에서 n까지 조건 처리할것
2) 꼬리물기하는 결과를 재귀함수안에서 리스트로 처리하면 역시나 문제가된다
'''
def makeworm(x,y,n,worm): # 숫... |
ec4e0ab21bb0a7c57bc67a654f939924dc32fd53 | SEOULVING-C1UB/Daily-Algorithm | /Daily-Algo/2020-09-11 Tree prac/고영길_가능한시험점수.py | 973 | 3.59375 | 4 | # Sometimes, loop is better than recursion.
for tc in range(1, int(input()) + 1):
N = int(input())
points = list(map(int, input().split()))
scores = set([0])
# Add points[idx] at score in scores
for point in points:
scores.update(set([score + point for score in scores]))
print('#{} {}... |
3f6d20a4d209825acf802fd8f6f01e1fa2778d38 | SEOULVING-C1UB/Daily-Algorithm | /Daily-Algo/2020-09-02 영준이의카드카운팅/이건우_영준이의카드카운팅.py | 1,110 | 3.515625 | 4 | def check():
global flag
for i in range(0,len(info),3):
dict[info[i]] -= 1 # 무늬에 해당하는 dict에서 1을 빼준다
if (info[i],int(info[i+1])*10 + int(info[i+2])) not in visited: # (무늬, 숫자)형식으로 visited에 저장
visited.append((info[i],int(info[i+1])*10 + int(info[i+2]))) # 만약 카드가 이미 ... |
db03a2a074ef3010fcf7c1f8aa169a271870442b | surajpaib/DesignPatternsInPython | /SimpleFactory/SimpleFactory.py | 1,013 | 3.953125 | 4 | import abc
class Cornflakes:
"""
Cornflakes metaclass which is equivalent to a Java interface
"""
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def getMilk(self):
pass
@abc.abstractmethod
def getCornflakes(self):
pass
class Chocos(Cornflakes):
"""
Chocos in... |
9efb9f240e8030d47a113a6b633a12b4725ac617 | standbyme227/study | /practice_coding/20.18.07.21.override.py | 893 | 3.65625 | 4 | # 부모 Animal이라는 class를 상속받는데
# 자식에서 같은 이름의 함수를 생성하면 덮어쓰기가 가능해진다.
# 이 덮어쓰기를 override라고 한다.
# Override란 같은 이름을 가진 메소드를 덮어쓴다는 의미
class Animal():
def walk(self):
print("걷는다")
def eat(self):
print("먹는다")
def greet(self):
print("인사한다")
class Human(Animal):
'''사람'''
def wave(se... |
6cce36444c392608b2089bc6809feb9d28bbcb3e | standbyme227/study | /practice_coding/practice_oop.py | 2,596 | 4.03125 | 4 | class Animal():
def __init__(self, name, height, weight):
if isinstance(name, str):
self.name = name
else:
print("name은 string이어야 합니다.")
if isinstance(height, int) and height < 1000:
self.height = height
else:
print("height는 0~1000 사이의... |
92517adabc0067be6e0d64ab2d9b549ab2ab252b | seggyn/ProgrammingParadigm | /lection1/map.py | 187 | 3.875 | 4 | array = [1, 2, 3]
# -- functional --
points = [val*6 for val in array]
print(points)
# -- algorithmical --
points = []
for val in array:
points.append(val*6)
print(points) |
bcbd5079e14dda9af9a30e52333b0dc132ef3a0b | austin-pan/comp-sim-labs | /Polynomial/Main.py | 736 | 3.796875 | 4 | from Polynomial import Poly
from Polynomial import Rand
def main():
pa = Poly([2, 0, 4, -1, 0, 6])
pb = Poly([-1, 3, 0, 4.5])
print("Pa(x) = " + str(pa))
print("Pb(x) = " + str(pb))
print()
print("Order of Pa: " + str(pa.order()))
total = pa + pb
print("Pa(x) + Pb(x) ... |
c36351c652f6459ff32de47f8f23735fd38ac615 | austin-pan/comp-sim-labs | /Traffic/Traffic.py | 4,486 | 3.640625 | 4 | '''
Created on Jan 28, 2019
@author: austinp
'''
import random
import numpy as np
import matplotlib.pyplot as plt
class Traffic(object):
def __init__(self, roadLength, carDensity): # Initialize a new road
self.newRoad(roadLength, carDensity)
def newRoad(self, roadLength, carDensity): ... |
710afd7cef19a7b6ce942820f3d662bbaa813ae7 | eastSalangane/Algorithm | /sort/bubble_sort.py | 356 | 3.65625 | 4 | """
冒泡排序
@author : qiyubing
@date : 2020-06-08
"""
num_list = [int(n) for n in input("请输入要排序的数,空格分隔:").split(" ")]
for i in range(1, len(num_list)):
for j in range(len(num_list) - i):
if num_list[j] > num_list[j + 1]:
num_list[j], num_list[j + 1] = num_list[j + 1], num_list[j]
print(num_list)
|
1ca6a7630519bf40f223ef6c2d9e69dba05553b2 | MikoGD/General-Projects | /python/Numo/FileHandling.py | 1,111 | 3.5 | 4 | import sys
import string
def test():
"Test if imported correctly"
print ("FileHandling imported")
#END test()
def returnContents (filename):
"Returns content of file"
with open (filename, 'r') as file:
return file.read()
#END WITH
#END returnContents()
def returnWords (filename):
"R... |
69880c7a4832160128dffd4e2d179d2938b7226c | Koki-Chance/voice_recognition | /voice_recognition.py | 952 | 3.953125 | 4 | # REFERENCE
# 1. Python Speech Recognition Tutorial for Beginners(https://geekscoders.com/python-speech-recognition-tutorial-for-beginners/)
# 2. Python Speech Recognition | Speech To Text Converter | Google Speech(https://www.youtube.com/watch?v=GluSLXFGfJ8)
import speech_recognition as sr
# from selenium import webdr... |
7a51f9e6a9385c5ece6ada6e30eee163544786a1 | l7ui/crawler | /nmpa.py | 1,847 | 3.609375 | 4 | # 爬取监管局化妆品生产许可证
import requests
import os
import json
folder_path = './nmpa/'
def get_ids():
post_url = 'http://scxk.nmpa.gov.cn:81/xk/itownet/portalAction.do?method=getXkzsList'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.42... |
82c5cdcf9d25c96501a09f7745e92c0746aab07f | coffeemug17/Kresentbot | /Kresentbot/kresentbot.py | 2,868 | 3.515625 | 4 | import praw
import os
import pdb
import re
import random
min = 1
max = 6
#Introductory text
name = input("Please input your name here: ")
print("Hello,", name, "this is the Kresent bot, a bot that surfs the chosen subreddits and fetches top 6 hot posts from subreddit1 and replies to the posts having a spec... |
6d28437ff747439221d75ad93771fe89c3513c05 | ykmc/atcoder_old | /2017/0701_ABC066_ARC077/B_20190208.py | 153 | 3.546875 | 4 | S = input()
Ans = 0
half = len(S)//2
for i in range(1,half):
if S[0:half-i]==S[half-i:len(S)-i*2]:
Ans = (half-i)*2
break
print(Ans) |
13d63064e81736d8a8e2306d44ac9b71a4e08020 | ykmc/atcoder_old | /2017/0520_ABC062_ARC074/A_20190113.py | 164 | 3.609375 | 4 | X,Y = map(int,input().split())
Ans = "No"
A = [[1,3,5,7,8,10,12],[4,6,9,11],[2]]
for i in range(3):
if X in A[i] and Y in A[i]:
Ans = "Yes"
print(Ans) |
18eb8b3ba1c319df2da214552e142779b1a8f528 | mcanearm/code_eval | /setdiff/setdiff.py | 414 | 3.546875 | 4 | import sys
input_file = sys.argv[1]
with open(input_file) as i:
for line in i:
sets = line.split(';')
set1 = set([int(val) for val in sets[0].split(',')])
set2 = set([int(val) for val in sets[1].split(',')])
output_set = sorted(set1.intersection(set2))
if output_set:
... |
62bb612168342cb1fc947f160b7e99b8afc85bf1 | chrismaurer/chrism | /looo.py | 483 | 3.890625 | 4 | grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5]
def grades_sum(scores):
sum_of_grades = 0
for score in scores:
sum_of_grades += score
print 'sum of grades: %s' % sum_of_grades
return sum_of_grades
def grades_average(grades):
grades_total = grades_sum(... |
0141788aa49b8fa2bea485d40a2b899ac32851d8 | MiPiNi/Hangman | /wordlist.py | 791 | 3.65625 | 4 | import random
def random_word(min_lenght:int):
if min_lenght > 0:
with open("WORDLIST.txt") as f:
num_lines = file_len("WORDLIST.txt")
lines = f.readlines()
i = 0
while True:
random_line_number = random.randrange(0, num_lines, 1)
... |
b37d3509cbc77815b1861a85e02ebda9d20d1c93 | crisstels/HelloApp | /src/Calculator.py | 717 | 3.6875 | 4 | '''REST Interface to add up two numbers. Use the
curl -H "Content-Type: application/json" -X POST -d '{"num1": 1, "num2": 1}' http://127.0.01:5000/
command to test it.'''
from flask import Flask
from flask import request
from flask_restful import Resource, Api
app = Flask(__name__)
api = Api(app)
class Calculator(Re... |
0a5b0d751a1fcbfa086452b6076527668aa4fcbc | shrobinson/python-problems-and-solutions | /series (2,11).py | 365 | 4.28125 | 4 | #Given two integers A and B. Print all numbers from A to B inclusively, in ascending order, if A < B, or in descending order, if A ≥ B.
#Recommendation. Use for loops.
#For example, on input
#4
#2
#output must be
#4 3 2
A = int(input())
B = int(input())
if A < B:
for i in range(A, B+1):
print(i)
else:
for i... |
46b4bd658faeb4a21da8f298633ccd92c48f1d90 | shrobinson/python-problems-and-solutions | /fibonacci (2,9).py | 494 | 4.09375 | 4 | #Fibonocci numbers are defined as follows:
#Zeroth Fibonacci number F(0) is equal 0
#Second Fibonacci number F(1) is equal 1
#Third Fibonacci number F(2) is equal F(0) + F(1) is equal 1
...
#Nth Fibonacci number F(N) is equal F(N-1) + F(N-2)
#Given a nonegative integer N, print the N-th Fibonacci number F(N)
#For ex... |
bb4b6083ef0eca3abca1627acfab5a77dd0bc485 | shrobinson/python-problems-and-solutions | /length_of_sequence (2,4).py | 394 | 4.1875 | 4 | #Given a sequence of non-negative integers, where each number is written in a separate line. Determine the length of the sequence, where the sequence ends when the integer is equal to 0. Print the length of the sequence (not counting the integer 0).
#For example, on input
#3
#2
#7
#0
#output should be
#3
n = int(inp... |
608a587c0123d50950fb43f3321572f01a2450e2 | shrobinson/python-problems-and-solutions | /countries_and_cities (3,18).py | 855 | 4.28125 | 4 | #First line of the input is a number, which indicates how many pairs of words will follow (each pair in a separate line). The pairs are of the form COUNTRY CITY specifying in which country a city is located. The last line is the name of a city. Print the number of cities that are located in the same country as this cit... |
28150f1848962980561507ee3bf9a41804f3e564 | shrobinson/python-problems-and-solutions | /leap_year (1,13).py | 508 | 4.15625 | 4 | #Given the year number. You need to check if this year is a leap year. If it is, print LEAP, otherwise print COMMON.
#The rules in Gregorian calendar are as follows:
#a year is a leap year if its number is exactly divisible by 4 and is not exactly divisible by 100
#a year is always a leap year if its number is exactly... |
0d501a6599dfeb5860e380bdd00a3cac1ba34b93 | shrobinson/python-problems-and-solutions | /least_divisor (2,2).py | 288 | 4.0625 | 4 | #Given an integer not less than 2. Print its smallest integer divisor greater than 1.
#For example, on input
#9
#output must be
#3
n = int(input())
divisor = 2
small_div = 0
while n % divisor!= 0:
if n % divisor == 0:
small_div = divisor
else:
divisor += 1
print(divisor)
|
07dd71e8f51346aa701637837b35f6d6a914f88d | shrobinson/python-problems-and-solutions | /greater_than_previous (3,3).py | 366 | 4 | 4 | #Given a list of numbers, find and print all the elements that are greater than the previous element.
#For example, on input
#10 6 11 13 10 10 23
#output must be
#11 13 23
s = input()
num_strs = s.split()
nums = []
for num_str in num_strs:
nums.append(int(num_str))
for i in range(0, len(nums)-1):
if nums[i+... |
38479ff9685f5ceeb57eb1fc9dc3942190ffc5ce | feladie/D08 | /mimsmind1.py | 3,377 | 4 | 4 | import random
import sys
# def intro():
# """Introduces the player to the game. Asks the player whether or not
# they would like to choose the number of digits to play with.
# """
# length = input()
# print("Let's play the mimsmind1 game.")
# return length
def exceptions(s):
try:
for n in range(1, digits + ... |
48a9f29fb9e329b0688387447d013cb5a23aab3d | davidmokken/CS50-IDE | /Python/inventory.py | 452 | 3.640625 | 4 | from item import Item
class Inventory(object):
"""
Representation of an inventory in Adventure
"""
def __init__(self):
self.items = dict()
def add_item(self, item):
self.items[item.name] = item
def remove_item(self, item):
del self.items[item.name]
def __str__(sel... |
999e206f3b3979f98ecc34148ac28e190fbd04dd | Surebu/Projekt | /gui/Button.py | 1,697 | 3.515625 | 4 | # input lib
from misc import *
class Button:
"""
Enkel klass för att göra och rita ut knappar i GUI:t. Knapparna kan kopplas till en funktion/metod och ett objekt
"""
def __init__(self, coordinates, dimensions, text, main_colour, rim_colour, text_colour, function, obj):
self.main_colour = mai... |
f40725d0667c8757b54855d4755aa220bf34eae5 | mhudn/CSSI | /Mad Libs/Python/pluralizer.py | 335 | 4.09375 | 4 | number = int(raw_input("Enter a number: "))
word = raw_input("Enter a word: ")
if number == 1:
print number ,word
elif number == 0 or number > 1:
print number, word+'s'
if word[-3:] = ife:
print word:[1] + 'ives'
elif word[-2:] = sh or word[-2:] = ch:
print word + 'es'
elif word[-2:] = us:
print w... |
1c809d1f8855a6ddb75e8a27e8fc54bb4156f6f5 | Mjheverett/python_functions | /Small_Exercises/6only_evens.py | 218 | 3.78125 | 4 | def only_evens(initial):
list_evens = []
for initial in initial:
if initial % 2 == 0:
list_evens.append(initial)
return list_evens
result = only_evens([11,20,42,97,23,10])
print(result) |
63c9d2b953830eae0cd59c1cc2781b92b4cf7e13 | JiaqiGe/puzzle | /wildmatch.py | 959 | 3.6875 | 4 |
def isMatch(a, p):
rows = len(a) + 1
columns = len(p) + 1
matrix = [[False for x in range(columns)] for y in range(rows)]
# initialization
for i in range(0,rows):
matrix[i][columns-1] = False
matrix[rows -1][columns-1] = True
for j in range(0,columns-1):
matrix[rows-1][j]... |
f67d0cecf1e4fcd8f6279c4b134e9c01eafcfe3e | JacobLutin/Python_bmstu | /2_semestr/lab_02_def.py | 2,517 | 3.828125 | 4 | from math import sqrt
def inp():
points = []
n = int(input("Введите количество точек A: "))
print("Введите координаты точек x и у построчно")
for i in range(n):
x, y = input().split()
points.append([int(x), int(y)])
circles = []
n = int(input("Введите количество окружностей ... |
588b38c36ba2d8f96e78885f2010807c2cbd4d78 | JacobLutin/Python_bmstu | /2_semestr/tkinter_05.py | 427 | 3.6875 | 4 | from tkinter import *
import tkinter.messagebox as box
window = Tk()
#window.co
def dialog():
answer = box.askyesno('Test', 'ARe you sure')
if answer:
box.showinfo('Hello', entry.get())
else:
box.showwarning('Error', 'sorry')
entry = Entry(window, text='Enter name')
btn = Button(window... |
afb961ae70a61631727779d2ab7c8904ce0eaf03 | JacobLutin/Python_bmstu | /codeforces/633B.py | 448 | 3.734375 | 4 | #m = int(input())
#m = 1
def fact(x):
result = 1
for i in range(2, x+1):
result *= i
print(result)
def program(m):
print(m)
x = 1
result = []
m = 10**m
for i in range(1, 10000):
x *= i
if x % m == 0 and x % (m*10) != 0:
result.appen... |
30206dd069bb8973635d850eaa079c41080592d2 | JacobLutin/Python_bmstu | /lab_stroki.py | 4,466 | 3.796875 | 4 |
def removeLetter(st, pos): # функция удаляющая любую из букв в строках
st = list(st)
if pos == -1:
st.pop()
else:
st.pop(pos)
st = ''.join(st)
return st
def removeComma(word): # функция для проверки наличия запятой и ее исключения
if (len(word) > 0 and word... |
91e2c9df7ba31c2d9528072002e5c44770ec2c3d | JacobLutin/Python_bmstu | /2_semestr/lec_10.py | 452 | 3.640625 | 4 | from tkinter import *
import tkinter.messagebox as box
window = Tk()
window.title('Виджет Entry')
frame = Frame(window)
entry = Entry(frame)
def dialog():
box.showinfo('Приглашение', 'Сдавать экзамен в сентябре ' + entry.get())
btn = Button(frame, text='Введите фамилию', command=dialog)
btn.pack(side=RIGHT, p... |
dc7d7ceebe02dfa3c6d17913c5c80c872e19f785 | JacobLutin/Python_bmstu | /2_semestr/tkinter_03.py | 352 | 3.71875 | 4 | from tkinter import *
import tkinter.messagebox as box
window = Tk()
window.title('Widget Entry')
frame = Frame(window)
entry = Entry(window)
def dialog():
box.showinfo('Test dialog', 'Hello! ' + entry.get())
btn = Button(, text='Enter text', command=dialog)
btn.pack(side=RIGHT, padx=20)
entry.pack(side=LEFT)... |
772a148b7eae5719b5183f241131aed3a67c60f6 | JacobLutin/Python_bmstu | /2_semestr/tkinter_calculator/main.py | 802 | 3.828125 | 4 | from tkinter import *
import tkinter.messagebox as box
window = Tk()
window.title("Title")
frame = Frame(window)
entry = Entry(frame)
def showDialog():
box.showinfo("Тест", entry.get())
btn = Button(frame, text="Введите число", command=showDialog)
btn.pack(side=RIGHT, padx=10)
entry.pack(side=LEFT)
frame.pac... |
cb9f5fbb2916ce9ef2a6478c475e46702ebb94d6 | JacobLutin/Python_bmstu | /sem_2.py | 160 | 3.65625 | 4 | x = float(input(""))
eps = float(input())
y = 1
a = 1
i = 0
while abs(a) >= eps:
i += 2
a *= -((x * x)/((i-1) * i))
y += a
print(y)
|
46058d94dd65f62cd79b41d45eedfcc7e548d360 | JacobLutin/Python_bmstu | /pygame/hexagon.py | 1,321 | 3.53125 | 4 | import pygame
from math import *
def vector(x, y, r, theta=0):
theta = radians(theta)
x = x + cos(theta) * r
y = y - sin(theta) * r
return (int(x), int(y))
class Hexagon:
color = (0,0,0)
def calc_points(self):
for theta in range(30, 390, 60):
self.points.a... |
e13c1c8e25ddfe7cc1daa060ceb1636a8d87dd6c | JacobLutin/Python_bmstu | /2_semestr/tkinter_calculator.py | 388 | 3.671875 | 4 | from tkinter import *
import tkinter.messagebox as box
window = Tk()
window.title('Calculator')
def add_sum():
sum = 0
sum = 0
book = StringVar()
btn_num_1 = Button(window, text='1', variable=book, value=1, command=add_sum)
btn_num_2 = Button(window, text='2', variable=book, value=2, command=add_sum)
btn_num_3 ... |
5e94ce48ff9c5298744ae0f5444ad9775308140d | JacobLutin/Python_bmstu | /2_semestr/tkinter_06.py | 461 | 3.6875 | 4 | from tkinter import *
import tkinter.messagebox as box
window = Tk()
window.title('listbox test')
frame = Frame(window)
listbox = Listbox(frame)
listbox.insert(1, 'Test 1')
listbox.insert(2, 'Test 2')
listbox.insert(3, 'test 3')
def dialog():
box.showinfo('your choice ', listbox.get(listbox.curselection()))
bt... |
9250e311c043c916ccf0820d91d3a294006bc53b | JacobLutin/Python_bmstu | /lab_4_1.py | 1,535 | 3.640625 | 4 | """
Лабораторная работа 4.1
Условие: Поменять местами первый положительный элемент массива ZT(8) с
первым отрицательным. Напечатать измененный массив ZT и номера переставленных
элементов. Если в массиве не окажется положительных элементов, то напечатать
соответсвующий текст.
Лютин Я. С. Группа ИУ7-11
"""
ZT = input... |
6a08c353c0e1e713e9e72635bbfa070bfe6af7b5 | mmsrubar/code-snippets | /python/hexdump/hexdump.py | 975 | 3.65625 | 4 | # get all printable chars and . (dot) for non-printable chars
HEX_FILTER = ''.join(
[(len(repr(chr(i))) == 3) and chr(i) or '.' for i in range(256)])
# Read a given string (src) and print its hexdump
def hexdump(src, length=16, show=True):
if isinstance(src, bytes):
src = src.decode()
results = list()... |
40861b19351648b058fee1f74ff2ce0d236808ab | chiefmky/ArrayAndStringProblem | /StringCompression.py | 798 | 4.1875 | 4 | #Implement a method to perform basic string compression using count of repeated characters
#input:aabcccccaaa
#output:a2b1c5a3
def compression(astr):
# aabcccccaa
ch = astr[0]
count = 1
ans = ""
for i in range(1, len(astr)):
if ch == astr[i]:
count += 1
else:
... |
dcdc2bf8912dd7aa31dcdaee8ac4df82a0012403 | chiefmky/ArrayAndStringProblem | /OneWay.py | 1,282 | 3.71875 | 4 | #write a function to check if two strings are one edit away
def oneWay(aString, bString):
c = 0
for ch in aString:
if ch not in bString:
c += 1
if c > 1:
return False
else:
return True
# ***************************************************
# This is editing
def one... |
a7a8ba21ad69cd68dc8ab7d57faf2cd40681524f | Get2dacode/python_projects | /quickSort.py | 1,180 | 4.15625 | 4 |
def quicksort(arr,left,right):
if left < right:
#splitting our array
partition_pos = partition(arr,left,right)
quicksort(arr,left, partition_pos - 1)
quicksort(arr,partition_pos+1,right)
def partition(arr,left,right):
i = left
j = right -1
pivot = arr[right]
while i < j:
... |
e10519c39e2ee2eb03adf844eda3d6ea6c0ed891 | soumyaracherla/python-programs | /tenth.py | 662 | 4.28125 | 4 | fruits=['mango', 'apple', 'banana']
print(fruits)
print(fruits[2])
print(fruits[-2]) # list
print(fruits.index("apple"))
fruits.append('grapes')
print(fruits) # append operation
vegetables=['onion', 'carrot', 'beetroot', 'tomato']
fruits.extend(vegetables)
print(fruits) # extend operation
fruits.insert(2,'pinea... |
89f783f08ad3e926fc25090f2d973479a86e50a2 | soumyaracherla/python-programs | /creating thread.py | 372 | 4 | 4 | import threading
def worker():
"""thread worker function"""
print("Worker starts running..")
return
def hello(num):
print("Hello ",num)
return
threads = []
for i in range(5):
#create a new thread
t=threading.Thread(target=hello,args=(i,))
#threads are added to list
threads.append(... |
fb1fb77d27b6f0490b890a1a4c528cb8f949e81b | soumyaracherla/python-programs | /parameterized constructor.py | 494 | 3.875 | 4 | class student:
def __init__(self,name,age,address):
self.name=name
self.age=age
self.address=address
def displaystudentData(self):
name= "sowmya"
print("name",name)
print("age", self.age)
print("address", self.address)
student1=student("ram",22,"hyd") ... |
aa5d9816f2c86040b919bf22a70398c52150ac98 | soumyaracherla/python-programs | /common property.py | 1,011 | 3.90625 | 4 | class student:
count=0 # constructor
def __init__(self,name,age,address):
self.name=name
self.age=age
self.address=address
student.count=student.count+1 #class variable
def displaystudentData(self):
name= "sowmya"
print("name",name)
print("ag... |
7d4d7559813df3799e3eab088cae6203ca3d4672 | soumyaracherla/python-programs | /fifteen.py | 145 | 3.984375 | 4 | def validate(age):
if age>=18:
print(" valid age ")
else:
print("invalid age")
age= int(input("enter age"))
validate(21) |
dd3a72637d8884653aea991cea43698d1ea15c42 | soumyaracherla/python-programs | /letter guessname.py | 718 | 3.921875 | 4 | class CustomException(Exception):
pass
class PreceedingLetterException(CustomException):
pass
class SucceedingLetterEexception(CustomException):
pass
alphabet='E'
while True:
try:
letter=input("enter alphabet:")
if letter < alphabet:
raise PreceedingLetterException
... |
7c2adb7212af9b9998dac700d270f3576d51c144 | edim024/learning_python | /assign4/stats.py | 944 | 3.734375 | 4 | #!/usr/bin/env python3
from math import sqrt
import fileinput
# Write a program that computes typical stats
# Count, Min, Max, Mean, Std. Dev, Median
# No, you cannot import any other modules!
count = 0
sum = 0
sd = 0
med = 0
numbers = []
for line in fileinput.input():
if line.startswith( '#' ): continu... |
95b54d9bc9b392692cc342b12de6e3c00ccb427e | SebastianMM-96/NLP-Python | /fake-news/Model/improvinModel.py | 636 | 3.546875 | 4 | # Create the list of alphas: alphas
alphas = np.arange(0, 1, .1)
# Define train_and_predict()
def train_and_predict(alpha):
# Instantiate the classifier: nb_classifier
nb_classifier = MultinomialNB(alpha=alpha)
# Fit to the training data
nb_classifier.fit(tfidf_train, y_train)
# Predict the labels:... |
7b145f2578ad8e7a8b78b3230f38631bdc1f76c7 | aadilkadiwal/Guess_game | /user_guess.py | 651 | 4.15625 | 4 | # Number guess by User
import random
def user_guess(number):
random_number = random.randint(1, number)
guess = 0
guess_count = 0
while guess != random_number:
guess = int(input(f'Guess the number between 1 and {number}: '))
guess_count += 1
if guess > random_number:
... |
f6631aabe8edc44357bec9914d16d102e9478059 | juliusfrost/411-group-project | /when2eat/session/timeHandler.py | 7,135 | 3.71875 | 4 | import datetime, time
def getEndDate(startDate):
"""
Given a start date string, return a datetime object for the start date
and the end date. If there is no start date, make the next day the
start date.
"""
if startDate == "":
startDate = datetime.datetime.today()
timeDelta = da... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.