blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
347940de62058edc0a229ebd819349c6fed1dbe4
satwik3011/my_python
/test.py
5,091
4.09375
4
''' #Removing spaces from string getString = input('Enter string for action: ') #Removing spaces from left print(getString.lstrip(), 'has length: ', len(getString.lstrip())) #Removing spaces from right print(getString.rstrip(), 'has length: ', len(getString.rstrip())) #Removing all spaces print(getString.strip(), 'has length: ', len(getString.strip())) #Program for checking Even/Odd var = int(input("Enter Number: ")) if (var % 2 == 0): print(var,"is Even") else : print(var,"is Odd") #For loops name = input("Your Name: ") for element in range(0, len(name)): if name[element] == 'i': break else: print(name[element]) name = input("Your Name: ") for element in range(0, len(name)): if name[element] == 'i': continue else: print(name[element]) name = input("Your Name: ") for element in range(0, len(name)): if name[element] == 'i': continue else: print(name[element], end='') ''' ''' #Fibonacci sequence length = int(input("Enter length of series: ")) firstNumber = int(input("Enter first number: ")) secondNumber = int(input("Enter second number: ")) print(str(firstNumber) + "," + str(secondNumber),end = ",") for i in range(2,length): next = firstNumber + secondNumber print(next, end=",") firstNumber = secondNumber secondNumber = next ''' ''' #Program to check for prime var = int(input("Enter Number: ")) flag=1 for i in range(2,var): if var%i==0: flag=0 break else: flag=1 if flag==0: print("Number is not prime") else: print("Number is prime") ''' ''' #Check for palindrome name = input("Enter name: ") if name.lower()[::] == name.lower()[::-1]: print(name," is a Palindrome") else: print(name," is not a Palindrome") ''' ''' #Counting different datatypes mainString = 'Python 2019 Batch' countChar = countDigit = 0 for i in mainString: if i.isalpha(): countChar += 1 elif i.isdigit(): countDigit += 1 else: pass print("Number of characters: ",countChar) print("Number of digits: ",countDigit) ''' ''' #Checking for Anagram name1 = input("Enter first name: ") name2 = input("Enter second name: ") if sorted(name1) == sorted(name2): print("They are Anagrams") else: print("They are not Anagrams") ''' ''' #Input into list elements = int(input("Enter number of elements: ")) lst = [] for ele in range(elements): print("Enter Element", ele+1, ende+',') ''' ''' #Splitting name = input("What is your name: ") var = name.split() print(var) name1, name2 = input('What are the names: (with,splitting): ').split(',') print(name1,name2) ''' ''' #Joining lst = [10, 20, 30] string = "-".join(str(e) for e in lst) print(string) ''' ''' #Ammending Lists lst = [20, 10, 30, 40] lst.append(999) #Adds a value to the list print(lst) lst[2]=500 #Replaces a value in the list print(lst) lst[3:4]=111,222 #Replaces multiple values in list print(lst) del lst[0] #Deletes a term in the list by index print(lst) lst.remove(111) #Deletes a term in the list by value print(lst) print(lst.index(999)) #Prints index value of the term #Aliasing lst = [10, 20, 30, 40] lst1 = lst lst[2] = 30 print(lst1) #Copying lst = [1, 2, 3, 4, 5] lst1 = lst.copy() #Pop print(lst.pop()) #Removes last term of the list and prints it out ''' ''' #Sorting lst = [Monday, Tuesday, Wednesday, Thursday, Friday, Saturday] print("Original: ",lst) print("Sorted: ", sorted(lst, reverse = True)) ''' ''' #EmployeeData name = input("Enter name: ") age = int(input("Enter age: ")) salary = float(input("Enter salary: ")) lst = [] lst.append(name) lst.append(age) lst.append(salary) name1 = input("Enter name 2: ") age1 = int(input("Enter age 2: ")) salary1 = float(input("Enter salary 2: ")) lst1 = [] lst1.append(name1) lst1.append(age1) lst1.append(salary1) name2 = input("Enter name 3: ") age2 = int(input("Enter age 3: ")) salary2 = float(input("Enter salary 3: ")) lst2 = [] lst2.append(name2) lst2.append(age2) lst2.append(salary2) mainlst = [] mainlst.append(lst) mainlst.append(lst1) mainlst.append(lst2) print(mainlst) ''' ''' #Functions def primex(var): for i in range(2,var): if var%i==0: flag=0 break else: flag=1 if flag==0: print("Number is not prime") else: print("Number is prime") n = eval(input("Enter Number: ")) primex(n) def divbyfive(var): if var%5==0: print("Number is divisible by 5") else: print("Number is not divisible by 5") n = eval(input("Enter Number: ")) divbyfive(n) div = lambda a: a**0.5 n = eval(input("Enter Number: ")) div(n) ''' #FileHAndling ''' f = open('myfile.txt',"a") str = input("Enter my text: ") f.write(str) f.close() ''' ''' f = open("myfile.txt",'r') str = f.read() print(str) f.close() ''' f = open("myfile.txt",'w') print("Enter text (@ at the end): ") while str != '@': str = input() if str != '@': f.write(str + '\n')
77530c893fa0782d3849a2e9137e19ca2aa914b6
github-felipe/ExerciciosEmPython-cursoemvideo
/PythonExercicios/ex095.py
1,402
3.671875
4
jogador = dict() listaGols = list() cadastros = list() while True: totgols = 0 print('-' * 20) nome = str(input('Nome: ')) quant = int(input(f'Quantos jogos {nome} jogou? ')) jogador['nome'] = nome for jogo in range(1, quant+1): gols = int(input(f'Gols feitos no {jogo}º jogo: ')) totgols += gols listaGols.append(gols) jogador['gols'] = listaGols[:] jogador['totGols'] = totgols cadastros.append(jogador.copy()) jogador.clear() listaGols.clear() continuar = str(input('Deseja cadastrar mais alguem? [S/N]')).upper() if continuar == 'N': break print('-='*30) print(f'ID Nome Gols Total') print('_' * 45) contador = 0 for jog in cadastros: print(f'{contador:>2} {jog["nome"]:<19} {str(jog["gols"]):<16} {jog["totGols"]:<5}') contador += 1 continuar = 0 while continuar != 999: print('-=' * 30) while True: escolha = int(input('Digite o ID do jogador que você quer ver os dados: (999 para parar)')) if escolha in range(0, contador) or escolha == 999: break print('Valor inválido, tente novamente...') if escolha == 999: break cont = 0 for jogo in cadastros[escolha]['gols']: cont += 1 print(f'Gols feitos no {cont}º jogo: {jogo}') print('Muito obrigado por usar nosso programa, tenha um ótimo dia!')
34f0cc3361aa98ab434313e1905e4db42340024a
alanazip/market
/Mercado/projetoFinal.py
708
3.6875
4
produto = [] numero = [] preco = [] print('''<<< Cadastro de produtos - digite exit para sair >>>''') produto.append(str (input("Nome do Produto: \n"))) numero.append((int(input("Número de série: \n")))) preco.append((float(input("Valor R$: \n")))) if produto or numero or preco == "exit": print("Nome do produto",produto,"Codigo",numero,"Preço R$",preco) else: for i in range(1,4): print('''<<< Cadastro de produtos - digite exit para sair >>>''') produto.append(str (input("Nome do Produto: \n"))) numero.append((int(input("Número de série: \n")))) preco.append((float(input("Valor R$: \n")))) print("Nome do produto",produto,"Codigo",numero,"Preço R$",preco)
e7fb96b620814487a1078ab7be99115ed91ccf03
nicob825/Bruno_Nico
/Lesson_09/lesson_09.py
62
3.546875
4
myList = [1, 2, 3, 4, 5] print(myList[2]) print(myList[:2])
36aa32ee37554a7858e1abb629fa66fef56e8a31
TSLNIHAOGIT/gene
/geatpy_example/frame/shortest_path/bfs.py
734
3.75
4
import queue import random def bfs(adj, start): visited = set() q = queue.Queue() q.put(start) # 把起始点放入队列 while not q.empty(): u = q.get() print('u',u) # print('adj.get(u, [])',adj.get(u, [])) a=adj.get(u, []) random.shuffle(a) print('a', a) for v in a: # print('v',v) if v not in visited: visited.add(v) q.put(v) if __name__=='__main__': nodes = [[], [2, 3], [3, 4, 5], [5, 6], [7, 8], [4, 6], [7, 9], [8, 9], [9, 10], [10]] graph={index:each for index ,each in enumerate(nodes)} # graph = {1: [4, 2], 2: [3, 4], 3: [4], 4: [5]} print('graph',graph) bfs(graph, 1)
f59d8a2c6248a983cc08de4302e520e1f2ad52e9
H-huihui/Python_work
/programming project2/project2.py
1,322
4.125
4
def checkTile(tile, number): #YOUR CODE HERE #always return false when tile is invalid if tile<1 or tile>12: return False if number == "one": if tile%3 == 0: return True else: return False if number == "two": if tile <=3 or tile==5 or tile==7 or tile>=10: return True else: return False if number == "three": if tile==4 or tile==7 or tile==8: return False else: return True if number == "four": if tile%3==0 or tile/3==1 or tile==1: return True else: return False if number == "five": if tile== 7 or tile == 8: return False else: return True def isEmptyOnThree(tile, width): #YOUR CODE HERE if tile <1 or tile > 4*width or width<3: return "invalid" #top and bottom if tile <= width or tile>3*width: return False #second row elif tile >width and tile<=2*width: if tile > width+width/2 and tile<=2*width: return False else: return True #3rd row elif tile>2*width and tile<=3*width: if tile==3*width: return False else: return True else: return True
2832553e8a27962fde03710e13d72331730a152c
thenowrrock/parcial_electiva_02
/punto2.py
1,735
4.1875
4
#Autores Juan David Jimenez ''' •Escriba un programa en python que utilizando expresiones lambda devuelva los números de la siguiente serie: (2n)! (n + 1)!n! •Para generar los n números a calcular en la serie, utilice una función generadora de números enteros mayores a 0. •Punto No. 2 Valor del punto 2 = 1.5 ''' import math import random #Input usuario , Rango incial y rango final . r_i = int(input('Ingrese el rango inicial para generar aletorios que sean > 0 :')) r_f = int(input('Ingrese el rango final para generar aletorios que sean > 0 :')) #Funcion generadora de numeros aletorios, en el rango de n #Yo aplique que los numeros generados podrian ser aletorios y en un rango dado. randoms = list(random.randint(r_i,r_f) for r_i in range(r_i,r_f)) #Genera numeros apartir del r_i >= r_f y apartir de la cantidad de elemtos entre el rango genera los elementos. print("Lista generada aletoriamente :",list(randoms), end=' ') #Imprime la lista de los numeros generados ''' Serie a calcular (2n)! (n + 1)!n! ''' serie = (lambda n: math.factorial( 2*n ) / (math.factorial(n + 1) * math.factorial(n))) #calculamos la serie con la funcion lambda, math.factorial() de la libreria de math en python , nos calcula el factorial de un elemnto, esto es programacio funcional, lo implemente con la razon de que sea mas eficiente y sencillo de entender este calculo calcular_serie = list((map(serie, randoms))) #aplicamos la serie sobre la lista de numeros generados por medio de map que como parametro recibe una funcion de calculo y un parametro de tipo lista en este caso. #imprimimos la serie print("Serie calculada :",(calcular_serie))
17fefe9501c33240dbcaa7a926a31a1aa46258eb
mshahpazova/Python-course-solutions
/week2_solutions/reduce_file_path.py
502
3.6875
4
import os import sys def reduce_file_path(file_path): splitted_path = file_path.split('/') cleared_path = list(filter(lambda x: x != '' and x != '.', splitted_path)) reduced_path = [] for element in cleared_path: if element == '..': reduced_path.pop() else: reduced_path.append(element) return('/' + '/'.join(reduced_path)) def main(): file_path = sys.argv[1] print(reduce_file_path(file_path)) if __name__ == '__main__': main()
36ddb9ca7d5a8260300f66b6f406e1af8e476e80
Dutch-Man/Company
/MyTest/python/bbb.py
729
3.859375
4
#!/usr/bin/python #coding:utf-8 class Test(): val1 = 1 def __init__(self): val2 = 2 self.val3 = 3 def fun(self): Test.val1 += 1 ''' def show(self): print "m = %d"%m print "n = %d"%n ''' def main(): print "Test.val1 = %d"%Test.val1 test1 = Test() test1.fun() print "Test.val1 = %d"%Test.val1 print "test1.val1 = %d"%test1.val1 print "" print id(Test.val1) test2 = Test() print id(test2.val1) test2.fun() print id(Test.val1) print id(test2.val1) print "Test.val1 = %d"%Test.val1 print "test1.val1 = %d"%test1.val1 print "test2.val1 = %d"%test2.val1 print "" if __name__ == "__main__": main()
86a7f7011e2279110340d19cecc38a1f6dd1d3af
a-recknagel/auxtest
/src/auxtest/checks/check_funcs.py
4,657
3.53125
4
"""Collection of check functions that can be called in the check-route. Right now their names are equal to the names of their return keys, so we might chose to streamline some of the logic to make this very configurable. It would nail this app to only support keyword arguments that conform to python's function naming rules, so it might be a bad call to nail this down just yet. Notes: * Might extend the call api with the 'country' kwarg to disambiguate in case there are many cities with the submitted name. """ from datetime import datetime, time from urllib.parse import unquote import requests from requests import get from auxtest.util import ( DAY_TEMP, NIGHT_TEMP, RIVAL_CITY, SUNDOWN, SUNRISE, WEATHER_API_KEY, WEATHER_API_UNITS, WEATHER_API_URL, ) def naming(city: str) -> bool: """Check whether the input string has an uneven number of characters. Only those characters count that are part of the city's name. Python 3 makes this part easy (in particular when hosted on linux, where the default for locales is UTF-8), because strings are always handled as proper unicode character sequences and not byte arrays. So stuff like len('ü') returning 2 doesn't happen. In case ascii descriptions of utf-8 encodings are used, this function unquotes them before computing their length, since that is assumed to be the more sane behavior. Args: city: The name of a city. Returns: True iff the number of characters is uneven. """ city_name = unquote(city).split(",")[0] # comas are not allowed in queries return (len(city_name.strip()) % 2) == 1 def run_weathermap_query(city: str, appid: str, url: str) -> dict: """Help function to handle get-requests to the weathermap API. Args: city: The name of a city. appid: API token used to authenticate this service against it. url: Base API url where we acquire temperature measurement. Returns: The json output from the request. Raises: ValueError in case something goes wrong with the weather request. """ payload = {"q": city, "appid": appid, "units": WEATHER_API_UNITS} try: res = get(url, payload) except requests.exceptions.RequestException as e: raise ValueError(f"Can't acquire request: {type(e).__name__} - {e}") if res.status_code != 200: raise ValueError(f"Invalid status: {res.text}") return res.json() def daytemp( city: str, appid: str = WEATHER_API_KEY, url: str = WEATHER_API_URL ) -> bool: """Check if the current temperature conforms to a daytime/nightime setting. The expected ranges can be looked up in the settings file, and this function only returns True if the temperature is strictly in-between the ranges. For example, given the daytime setting (17, 25) and a measurement of 17 at the target's daytime, the expected result is False. Args: city: The name of a city. appid: API token used to authenticate this service against it. url: Base API url where we acquire temperature measurement. Returns: True iff the temperature is in-between the expected range. Raises: ValueError in case something goes wrong with the weather request. """ temperature = run_weathermap_query(city, appid, url) # day or night? dt_of_measure = datetime.utcfromtimestamp(temperature["dt"]) dt_comp = time(dt_of_measure.hour, dt_of_measure.minute) day_time = SUNRISE < dt_comp < SUNDOWN if day_time: return DAY_TEMP[0] < temperature["main"]["temp"] < DAY_TEMP[1] else: return NIGHT_TEMP[0] < temperature["main"]["temp"] < NIGHT_TEMP[1] def rival( city: str, rival_city: str = RIVAL_CITY, appid: str = WEATHER_API_KEY, url: str = WEATHER_API_URL, ) -> bool: """Check if the current temperature is higher than the rival's. The rival can be defaulted in the settings file, or set explicitly in this function. Args: city: The name of a city. rival_city: The name of a rival city. appid: API token used to authenticate this service against it. url: Base API url where we acquire temperature measurement. Returns: True iff the city is currently warmer than the rival. Raises: ValueError in case something goes wrong with the weather request. """ temperature = run_weathermap_query(city, appid, url) rival_temperature = run_weathermap_query(rival_city, appid, url) return temperature["main"]["temp"] > rival_temperature["main"]["temp"]
ba9cf37cf27421edd4ca63e107ec217d7dc4707e
AymanMagdy/hands-on-python
/tuples/add_to_tuple.py
348
4.25
4
# Write a func to add an element to a tuple. def add_to_tuple(tupleElements, newElement): resultTuple = (*tupleElements, newElement) return resultTuple if __name__ == "__main__": testTuple = ('ayman', 45 ) newValue = input("Enter a new value to add to tuple: ") newTuple = add_to_tuple(testTuple, newValue) print(newTuple)
3af2281f7abc520c7b1794093dc7b7e0e793239a
AnshulRoonwal/2.Artificial-Intelligence
/3) Sudoku Solver/ReadGameState.py
2,136
3.6875
4
__author__ = 'Anshul/Aditi' class ReadGameState: def __init__(self): self.board = [] self.AllEmptyPositions = [] def readGameState(self, filePath): #New Function for reading game state #Reading file fileHandle = open(filePath, 'r') rawState = fileHandle.readline().strip().split(';') ##replace , with ; # print rawState #Debug # print rawState[0] #Debug # print len(rawState[0]) configuration = rawState[0].split(',') #print configuration N = configuration[0]; M = configuration[1]; K = configuration[2]; #print 'N=', N, 'M=', M, 'K=', K #updating game state with all 0 N=int(N); M=int(M); K=int(K); if (N!=M*K): print "What is this man! Don't know basic Sudoku configuration? N=MxK should be maintained" exit(0) self.board = [[0 for i in range(N)] for j in range(N)] self.AllEmptyPositions = [] #check for dimension of given board if len(rawState) != N+2: print "Wrong gameState given, check txt file" exit(0) else: for i in range(N): row = rawState[i+1].split(',') if len(row) != N: print "Wrong gameState given, check txt file" exit(0) else: for j in range(N): #Ignored the condition of a character other than '-' and 'A number' if row[j] not in('-','1','2','3','4','5','6','7','8','9','10','11','12'): print 'Wrong characters in the input file, plz check it. It should have either '-' or number between 1 to 9' exit(0) if row[j] == '-': self.board[i][j]=int("0") self.FindEmptyPosition(i,j) else: self.board[i][j]=int(row[j]) return self.board, self.AllEmptyPositions, N,M,K def FindEmptyPosition(self,i,j): self.AllEmptyPositions.append([i,j])
1b1065a24baf626d25eba8c75d63dd3c77aa261a
deniscarr/pands-problem-set
/primes.py
436
4.28125
4
# Program Name: primes.py # Programmer: Denis Carr # Date: March 2019 # request user for positive number - convert it to int and store in variable number number = int(input("Please enter a positive integer: ")) # loop from 2 to number -1 for i in range(2,number): # if number is divisible, it is not prime if number % i==0: print("That is not a prime.") exit(0) # else it is a prime print("That is a prime.")
387b400fc2bae91b0fc545770b5f4eae7fa54a2b
k-jinwoo/python
/Ch02/2_4_String.py
1,437
4
4
""" 날짜 : 2021/04/26 이름 : 김진우 내용 : 파이썬 String 예제 교재 p48 """ # 문자열 더하기 str1 = 'Hello' str2 = "Python" str3 = str1 + str2 print('str3 :', str3) # 문자열 곱하기 name = '홍길동' print('name * 3 :', name *3) # 문자열 길이 msg = 'Hello World' print('msg 길이 :', len(msg)) # 문자열 인덱스 print('msg 1번째 문자 :', msg[0]) print('msg 7번째 문자 :', msg[6]) print('msg -1번째 문자 :', msg[-1]) # 뒤에서 부터 print('msg -5번째 문자 :', msg[-5]) # 문자열 자르기 (substring) print('msg 0~5 까지 문자열 :', msg[0:5]) print('msg 처음~5 까지 문자열 :', msg[:5]) # 시작점이 없으면 처음번호로 지정 print('msg 6~11 까지 문자열 :', msg[6:11]) print('msg 6~마지막 까지 문자열 :', msg[6:]) # 종료점이 없으면 마지막번호로 지정 # 문자열 분리 people = '김유신^김춘추^장보고^강감찬^이순신' # 분리되는것 하나당 token p1, p2, p3, p4, p5 = people.split('^') # 구분자 지정을 해줘야함 print('p1 :', p1) print('p2 :', p2) print('p3 :', p3) print('p4 :', p4) print('p5 :', p5) # 문자열 이스케이프 print('서울\n대전\n대구\n부산\n광주') # \n는 new line(다음줄) print('서울\t대전\t대구\t부산\t광주') # \t는 tap (한칸씩 띄워주기) print('저는 \'홍길동\' 입니다.') # \'는 '로 출력되게 함 print("저는 '홍길동' 입니다.")
675e446eb31505faf8d2597366b968a300463ce4
josivantarcio/Desafios-em-Python
/Desafios/desafio067.py
226
3.734375
4
n = int(input('Digite um numero: ')) i = 0 while n >= 0: while True: print(f'{i} x {n} = {i * n}') i += 1 if i > 10: break i = 0 n = int(input('Digite um numero: ')) print('FIM')
63d00e8e67d33eb7df8b48c8ccd662993e30ec60
sidv/Assignments
/Bijith/Aug23/filter_3first.py
126
3.984375
4
print("Filter first 3 letter from the given list .") lst = ["Siddhant", "Pavan", "Ramya", "Raja"] print([x[:3] for x in lst])
b79c8b3bb5146844ce57f73725a590c1948bd265
SGTAn0nY/hashing_utilities
/dict_attack.py
3,262
3.890625
4
import random, hashlib from string import ascii_letters numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] length = 4 def menu(): print("Dictionary attacks!") print("ATTENTION:") print(">> Change 'length' for different data length <<") operation = str(input("what do you want to do ?\n1 --- Initialise new dictionary\n2 --- Test dictionary\n3 --- Bruteforce hash using dictionary\n4 --- Change mode\n5 --- Change mask\n99 --- Exit\n=> ")) if operation == "1": create_dict() if operation == "2": test_dict() if operation == "3": bruteforce() if operation == "4": set_mode() if operation == "5": set_mask() if operation == "99": exit() else: menu() def set_mode(): mode = str(input("1 --- Numbers only\n2 --- String only\n3 --- Mixed string and numbers\n=> ")) return mode def set_mask(): mask = [] for counter in range(0, length): mask.append(str(input("Enter next character of data (i for int / s for string): "))) return mask def create_dict(): #file = open("D:\coding_etc\projects\python\hashing_utilities\dictattack\i_4_md5.txt", "w+") file_path = input("Enter new dictionary path: ") file_full_path = file_path + "i_" + str(length) + "_md5.txt" file = open(file_full_path, "w+") for i in range(0, pow(10, length)): guess = "" for y in range(0, length): guess = guess + str(random.choice(numbers)) if guess not in file.read(): print(guess) file.write(guess) guess_hash = hashlib.md5(guess.encode('UTF-8')) file.write(str(guess_hash.hexdigest())) file.close() menu() def test_dict(): wrong = True counter = 0 blacklist = [] file_open = open("D:\coding_etc\projects\python\hashing_utilities\dictattack\dicts\int_only\i_4_md5.txt", "r") file = file_open.read() while wrong: guess = "" for y in range(0, length): guess = guess + str(random.choice(numbers)) if guess not in blacklist: blacklist.append(guess) print(counter) if guess not in file: wrong = False counter += 1 if guess in blacklist: if len(blacklist) == 10000: print("") print(">> Checked ", counter, "guesses! <<") print(">> Entire file checked, it is complete! <<") print("") wrong = False menu() def bruteforce(): file_open = open("D:\coding_etc\projects\python\hashing_utilities\dictattack\dicts\int_only\i_4_md5.txt", "r") file = file_open.read() index = [] result = "" hash = str(input("Enter hash to crack here:\n=> ")) try: for y in range(0, length): index.append(file.index(hash) - length + y) for x in range(0, len(index)): result = result + file[index[x]] print("") print(">> Cracked hash result: ", result, " <<") print("") except: print("Failure!") menu() mode = set_mode() mask = set_mask() menu()
6840627bd389da023df6c83755672ae5eb43db18
Qondor/Python-Daily-Challenge
/Daily Challenges/Daily Challenge #95 - CamelCase Method/camel.py
355
4.5
4
def camelcase(input_text): """Camel Case text generator. All words must have their first letter capitalized without spaces. """ words = input_text.split() result = "" for word in words: result += f'{word[0].upper()}{word[1:]}' return result if __name__ == "__main__": print(camelcase("oh camel camel texterino"))
3cf129e610ef2574f9e601b144eac1478555211b
atfelix/exercism-python
/collatz-conjecture/collatz_conjecture.py
298
3.90625
4
from functools import reduce def collatz_steps(number): if number <= 0: raise ValueError('Invalid argument: number > 0 is required') count = 0 while number != 1: count += 1 number = number // 2 if number % 2 == 0 else 3 * number + 1 return count
64892f26ca721b09de7af70cd2d6a7f681b489d7
evac/MachineProgrammer
/main/algorithms.py
861
3.515625
4
import random def mutate(program): if len(program[:]) > 1: temp = program[:] random.shuffle(temp) program[:] = temp return program def merge(prog1, prog2): prog1[:] = prog1 + prog2 return prog1 def multiply(prog1, prog2): prog1[:], prog2[:] = prog1 + prog2, prog2 + prog1 return prog1, prog2 def mate(prog1, prog2): if len(prog1[:]) > 1 and len(prog2[:]) > 1: size = min(len(prog1), len(prog2)) cxpoint1 = random.randint(1, size) cxpoint2 = random.randint(1, size - 1) if cxpoint2 >= cxpoint1: cxpoint2 += 1 else: # Swap the two cx points cxpoint1, cxpoint2 = cxpoint2, cxpoint1 prog1[cxpoint1:cxpoint2], prog2[cxpoint1:cxpoint2] \ = prog2[cxpoint1:cxpoint2], prog1[cxpoint1:cxpoint2] return prog1, prog2
39bbbb555d9aac26f42302766de3ea6d71c0df50
pangguoping/python-study
/day7/xml-test.py
1,187
3.640625
4
#!/usr/bin/env python # -*- coding:utf-8 -*- # Auther: pangguoping ''' from xml.etree import ElementTree as ET tree = ET.parse('xo.xml') root = tree.getroot() print(root) for child in root: print(child) print(child.tag,child.attrib) for gradechild in child: #print(gradechild) print(gradechild.tag,gradechild.text,gradechild.attrib) ''' ''' from xml.etree import ElementTree as ET str_xml = open('xo.xml','r').read() root = ET.XML(str_xml) print(root) ''' ''' from xml.etree import ElementTree as ET str_xml = open('xo.xml','r').read() root = ET.XML(str_xml) print(root.tag) for node in root.iter('year'): new_year = int(node.text) + 1 node.text = str(new_year) node.set('name','alex') node.set('age','18') ''' from xml.etree import ElementTree as ET root = ET.Element("famliy") son1 = ET.Element('son',{'name':'er1'}) son2 = ET.Element('son',{'name':'er2'}) grandson1 = ET.Element('grandson',{'name':'er11'}) grandson2 = ET.Element('grandson',{'name':'er22'}) son1.append(grandson1) son2.append(grandson2) root.append(son1) root.append(son2) tree = ET.ElementTree(root) tree.write('ooo.xml',encoding='utf-8',short_empty_elements=False)
0e3b0f05aaff1524f927a326d3673c07e0b33646
arvakagdi/UdacityNanodegree
/Stacks/Postfix.py
2,395
4.0625
4
''' Goal : Given a postfix expression as input, evaluate and return the correct final answer. Input: List containing the postfix expression Output: int: Postfix expression solution Example: 3 1 + 4 * Solution: (3 + 1) * 4 = 16 ''' class LinkedListNode: def __init__(self, data): self.data = data self.next = None class Stack: def __init__(self): self.num_elements = 0 self.head = None def push(self, data): new_node = LinkedListNode(data) if self.head is None: self.head = new_node else: new_node.next = self.head self.head = new_node self.num_elements += 1 def pop(self): if self.is_empty(): return None temp = self.head.data self.head = self.head.next self.num_elements -= 1 return temp def top(self): if self.head is None: return None return self.head.data def size(self): return self.num_elements def is_empty(self): return self.num_elements == 0 def evaluate_post_fix(input_list): # TODO: Iterate over elements # TODO: Use stacks to control the element positions stack = Stack() for elem in input_list: if (elem != '+') and (elem != '-') and (elem != '/') and (elem != '*'): stack.push(elem) else: data2 = stack.top() stack.pop() data1 = stack.top() stack.pop() if elem == '+': stack.push(int(data1) + int(data2)) elif elem == '-': stack.push(int(data1) - int(data2)) elif elem == '/': stack.push(int(int(data1) / int(data2))) elif elem == '*': stack.push(int(data1) * int(data2)) return stack.top() def test_function(test_case): output = evaluate_post_fix(test_case[0]) print(output) if output == test_case[1]: print("Pass") else: print("Fail") test_case_1 = [["3", "1", "+", "4", "*"], 16] test_function(test_case_1) test_case_2 = [["4", "13", "5", "/", "+"], 6] test_function(test_case_2) test_case_3 = [["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"], 22] test_function(test_case_3)
9febea3cef5239ca48a272f740b6438c0988bac3
m-hegyi/stocker
/classes/MovingAverage.py
2,491
3.671875
4
from classes.Stock import Stock class MovingAverage(): prev = 0 prevLow = 0 prevHigh = 0 def __init__(self, lower, higher, Stock: Stock): self.lower = lower self.higher = higher self.Stock = Stock def getLowerValueByDate(self, date): # az első átlag kiszámítása index = self.Stock.getIndexByDate(date) if (index == False): print('not valid date') return False else: value = self.calculateAverage(self.lower, index) return value def getHigherValueByDate(self, date): index = self.Stock.getIndexByDate(date) if (index == False): print('not valid date') return False else: value = self.calculateAverage(self.higher, index) return value def getLowerValueByIndex(self, index): # az első átlag kiszámítása if (index == False): print('not valid date') return False else: value = self.calculateAverage(self.lower, index) return value def getHigherValueByIndex(self, index): if (index == False): print('not valid date') return False else: value = self.calculateAverage(self.higher, index) return value def getDiff(self, index): # akkor lesz negatív ha a rövidebb MA növekedése megáll lower = self.getLowerValueByIndex(index) higher = self.getHigherValueByIndex(index) if higher == 0 or lower == 0: self.prev = 0 return 0 diff = lower - higher if self.prev < 0 and diff > 0: self.prev = diff self.prevLow = lower self.prevHigh = higher return 1 elif self.prevLow > lower: self.prev = diff self.prevLow = lower self.prevHigh = higher return -1 self.prevLow = lower self.prevHigh = higher self.prev = diff return 0 def calculateAverage(self, length, dateIndex): # (napi adat + köv napi adat) / számolt adatok hossza average = 0 for i in range(length): index = dateIndex - i data = self.Stock.getValuesByIndex(index) if (data == False): return 0 average += data.open return average / length
1ad21e5d085c7b00e36496a8c0bc2ec799ccf301
AlexHahnPublic/EulerProblems
/problem7_10001stPrime.py
1,363
3.71875
4
# Euler Problem 7: # By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see # that the 6th prime number is 13. # What is the 10001st prime number? #Solution, Off the top of my head we could either greedily use trial division # or more efficiently use a sieve (Sieve of Eratosthenes) # Using the contrapositive of if a number n is composite then it has at leas # one divisor less than sqrt(n) import time def isPrime(num): i = 2 boolVal = True while i*i <= num and boolVal == True: if num%i == 0: boolVal = False else: i += 1 return boolVal #Trial Division ignoring even numbers def findNthPrime(n): start_time = time.time() num2check = 3 counter = 1 while counter < n: if isPrime(num2check) and counter != n-1: counter += 1 num2check += 2 # evens can't be prime elif isPrime(num2check) and counter == n-1: break else: num2check +=2 total_time = time.time() - start_time print "The", n, "prime number is:", num2check print "This program took:", total_time, "seconds to run" #def findNthPrime(n): # currNum = 2 # nums = range(1,n+1) # while len nums > 1 and currNum < n # multiplier = if __name__ == "__main__": import sys findNthPrime(int(sys.argv[1]))
20cb42f4569ae2d1475dfefc332a2635e0f3579b
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/sieve/d70734ec439f425e9c842157ef2262b5.py
254
3.65625
4
def sieve(limit): numbers = range(2, limit + 1) not_primes = [] for number in numbers: for multiple in xrange(number + number, limit +1, number): not_primes.append(multiple) return list(set(numbers) ^ set(not_primes))
b7de7500178457bd40eff94e63cc23e673f31b3e
navaneeth-rajagopalan/Algorithms-and-Data-Structures
/Tree/Test.py
1,215
3.859375
4
import BinarySearchTree my_bst = BinarySearchTree.Tree() my_bst.add(11) my_bst.add(6) my_bst.add(8) my_bst.add(3) my_bst.add(15) my_bst.add(13) my_bst.add(17) my_bst.add(19) my_bst.add(14) my_bst.add(12) my_bst.add(3) my_bst.add(1) my_bst.add(5) ordered_tree = my_bst.traverse(BinarySearchTree.TreeTraversalOrder.IN_ORDER) print(ordered_tree) print("\n\n") ordered_tree = my_bst.traverse(BinarySearchTree.TreeTraversalOrder.PRE_ORDER) print(ordered_tree) print("\n\n") ordered_tree = my_bst.traverse(BinarySearchTree.TreeTraversalOrder.POST_ORDER) print(ordered_tree) my_alpha_bst = BinarySearchTree.Tree() my_alpha_bst.add('A') my_alpha_bst.add('B') my_alpha_bst.add('C') my_alpha_bst.add('D') my_alpha_bst.add('F') my_alpha_bst.add('K') my_alpha_bst.add('G') my_alpha_bst.add('L') my_alpha_bst.add('J') my_alpha_bst.add('I') my_alpha_bst.add('H') my_alpha_bst.add('E') ordered_tree = my_alpha_bst.traverse(BinarySearchTree.TreeTraversalOrder.IN_ORDER) print(ordered_tree) print("\n\n") ordered_tree = my_alpha_bst.traverse(BinarySearchTree.TreeTraversalOrder.PRE_ORDER) print(ordered_tree) print("\n\n") ordered_tree = my_alpha_bst.traverse(BinarySearchTree.TreeTraversalOrder.POST_ORDER) print(ordered_tree)
b01f947373fef89cea302a1fe27707786798950e
iswetha522/Plural_Sight
/corepy/shallow_and_deep_copy.py
294
4.125
4
a = [[1, 2], [3, 4]] b = a[:] print(a is b) print( a == b) print("------------") print(a[0]) print(b[0]) print(a[0] is b[0]) print("----------") a[0] = [8, 9] print(a[0]) print(b[0]) print("----------") a[1].append(5) print(a[1]) print(b[1]) print("------") print(a) print(b) print('-------')
b17a9c1c7d19acdf93befb1f536690336fc96186
cbymar/pyspark-databricks
/mllib00.py
1,311
3.5625
4
import math import numpy as np # http://spark.apache.org/docs/latest/ml-guide.html ### Quick aside on entropy/information gain def entropy(lst): entropysum = 0 for _ in lst: entropysum += _ * np.log2(_) return -1 * entropysum lst = [0.25, 0.75] entropy(lst) # this is our baseline entropy, which is being sent to zero. So that's the info gain. entropy([0.75]) entropy([0.25]) # algebraically, we an express the information gain as the prob-weighted sum of the log2 of the # two probabilities. It's a weighted sum of the uncertainties that are disappearing. # Cross-entropy is the average bit length of the message that contains the elimination of uncertainty lst = [0.35, 0.35, 0.1, 0.1, 0.04, 0.04, 0.01, 0.01] entropy(lst) # Entropy is higher now. # if avg bit length of the uncertainty-eliminating message is higher than the baseline entropy, # that's the cross-entropy loss. # algebraically, it's the probability[true dist]-weighted sum of the log2(probabilities[predicted dist]) def crossentropy(lst1, lst2): crossentropysum = 0 for a, b in zip(lst1, lst2): crossentropysum += a * np.log2(b) return -1 * crossentropysum lst2 = list(reversed(lst)) lst2, lst crossentropy(lst,lst2) # relative entropy. crossentropy(lst,lst2) - entropy(lst) # kl-divergence
67b5f8aec76efd743e50dbe324ac3564bac99ef7
nuxion/python_2021_thu
/exercises/301.py
943
3.828125
4
""" Siguiendo el ejemplo del ejercicio 301, guardar estos valores en una tabla de sqlite3: 2020-04-08;95.5;140.0,44.5 2020-04-09;95.5;140.0,43.5 Cada columna significa lo siguiente: fecha;dolar_blue;dolar_oficial;diferencia Como ayuda uno de los lugares donde se puede tomar informacion es de: https://www.dolarsi.com/api/api.php?type=valoresprincipales """ import requests url = "https://www.dolarsi.com/api/api.php?type=valoresprincipales" response = requests.get(url) dolar_data = response.json() try: valor_oficial = dolar_data[0]['casa']['venta'] valor_blue = dolar_data[1]['casa']['venta'] print(f'Valor oficial: {valor_oficial}, valor blue: {valor_blue}') except KeyError: print("La respuesta del servidor no es valida") #for x in range(0, len(dolar_data)): # print(dolar_data[x]) # #n = 0 #while n < len(dolar_data): # print(dolar_data[n]) # n += 1 for x in dolar_data: print(x)
cc9df3a4b3bd61d3afda75cac49e14555e72b12b
rohitx/DS_and_Algo_in_Python
/Chapter3/R_3_4.py
409
3.84375
4
''' R-3.4: Give an example of a function that is plotted the same on a log-log scale as it is on the standard scale. Answer: the linear function: f(n) = n is an example of a function that is the same on a log-log scale and on the standard scale. ''' import numpy as np import matplotlib.pyplot as plt x = np.arange(0, 100, 0.1) y = x plt.plot(x, y, 'r-') #plt.yscale('log') #plt.xscale('log') plt.show()
acf7461cbc23e1fc7ea0cd86f331a2c2822ab7d3
MrHamdulay/csc3-capstone
/examples/data/Assignment_5/djgway001/mymath.py
334
3.65625
4
#calculate number of k-permutations of n items #wayne de jager #15 april 2014 def get_integer(n): s=input("Enter "+n+":\n") while not s.isdigit(): s=input("Enter "+n+":\n") n=eval(s) return n def calc_factorial(n): factorial=1 for i in range(1,n+1): factorial*=i return factorial
9f4739372dbf2806999b5b898b3bed07ff66dfea
nonatalies/second_one
/1.py
272
4.0625
4
name = input('Введите имя: ') surname = input('Введите фамилию: ') birth = int(input('Введите год рождения: ')) print(name, surname, birth, sep = '_') name, surname = surname, name print(name, surname, birth + 60, sep = '_')
d30c731283a81dfa66c95971f44909e0b919c212
omatveyuk/interview
/HackerRank/bigger_is_greater.py
1,984
4.15625
4
"""Given a word W, rearrange the letters of W to construct another word S in such a way that S is lexicographically greater than W. In case of multiple possible answers, find the lexicographically smallest one among them. >>> bigger_is_greater('ab') 'ba' >>> bigger_is_greater('bb') 'no answer' >>> bigger_is_greater('hefg') 'hegf' >>> bigger_is_greater('dhck') 'dhkc' >>> bigger_is_greater('dkhc') 'hcdk' """ def bigger_is_greater(word): """Next lexicographical permutation algorithm.""" word_lst = [char for char in word] length = len(word_lst) # 1. Find largest index i such that array[i-1] < array[i] # (If no such i exists, then this is already the last permutation.) # print word_lst # print "Find largest index i such that array[i-1] < array[i]" index = None for i in xrange(1, length): if word_lst[i] > word_lst[i-1]: index = i # print 'i:', index if index is None: return "no answer" # print "Find largest index j such that j >= i and array[j] > array[i-1]" pivot = None # 2. Find largest index j such that j >= i and array[j] > array[i-1] for j in xrange(index, length): if word_lst[j] > word_lst[index-1]: pivot = j # print "j:", pivot # print "Swap array[j] and array[i-1]" # 3. Swap array[j] and array[i-1] word_lst[pivot], word_lst[index-1] = word_lst[index-1], word_lst[pivot] # print word_lst # print "Reverse the suffix starting at array[i]" # 4. Reverse the suffix starting at array[i] middle = (length - index) / 2 # print "middle:", middle for i in xrange(middle): word_lst[index+i], word_lst[length-1-i] = word_lst[length-1-i], word_lst[index+i] # print word_lst return ''.join(word_lst) if __name__ == "__main__": from doctest import testmod if testmod().failed == 0: print "********** All Tests are passed. *************"
1d0a441ebf6eb3ee04f8c5fbfcf7921510864cb3
maxwell-martin/txst-cis3389-spring2020
/class_practice/on_campus/10_dictionaries_03042020.py
1,983
4.34375
4
# Dictionaries # Create a dictionary Dic1 = { 1:34, 2:45, 3:89 } print(Dic1) # Get value from dictionary print(Dic1[2]) print(Dic1.get(2)) # Error thrown when key does not exist #print(Dic1[4]) # No error thrown when key does not exist; returns None instead print(Dic1.get(4)) print(Dic1.get(4, "Default message")) # Calculate number of elements in dictionary print(len(Dic1)) # Add key value pair to dictionary Dic1[4] = 67 print(Dic1) # Change value of a kvp Dic1[3] = 100 print(Dic1) # Delete kvp from dictionary #del Dic1[3] #print(Dic1) # Delete all key value pairs from dictionary #Dic1.clear() #print(Dic1) # Keys() method for key in Dic1.keys(): print(key) for key in Dic1: # Does the same thing as Dic1.keys() print(key) # Values() method for value in Dic1.values(): print(value) # Items() method for i in Dic1.items(): print(i) # Pop() method #Dic1.pop(2) #print(Dic1) # Popitem() method Dic1.popitem() print(Dic1) # Exercise 7 ##school = { "CIS3389":["Aindrila Chakraborty", 40], ## "CIS3380":["Kevin Jetton", 120], ## "CIS3325":["Mayur Mehta", 30] } ##course_num = input("Enter a course number: ") ##if course_num in school.keys(): ## print(school.get(course_num)[0], "-", school.get(course_num)[1]) ##else: ## print(course_num, "is not a course.") # Exercise 8 school = { "CIS3389":["Aindrila Chakraborty", 40], "CIS3380":["Kevin Jetton", 120], "CIS3325":["Mayur Mehta", 30] } for key in school.keys(): print(key, ";", school[key]) #OR for k, v in school.items(): print(k, ";", v) # Exercise 9 - Sort dictionary Dic2 = { 1:34, 3:45, 2:89 } for key in sorted(Dic2.keys()): print(key) for key in sorted(Dic2.keys(), reverse = True): print(key) # Exercise 10 dic1={1:10, 2:20} dic2={3:'texas', 4:'mexico'} dic3={5:'ny',6:'45'} dic4 = {} for dic in (dic1, dic2, dic3): dic4.update(dic) print(dic4) # Exercise 11 matrix = [["NY", "New York"], ["CA", "California"], ["TX", "Texas"]] dict5 = dict(matrix) print(dict5)
79f6b69a7a32844df700de3a2ae02bb5c72fd357
Vakonda-River/Stanislav
/lesson3_4_0.py
291
4.125
4
#x^(-y)=1/x^y x_1 = float(input('Введите действительное положительное число: ')) y_1 = int(input('Введите целое отрицательное число: ')) def step(x,y): res = x ** y return (res) print(step(x_1,y_1))
8e05628afd61456dc02449fcb543cbe6162eaf26
crisgrim/python-oop
/Kata3-Student.py
1,974
3.90625
4
class Student(): # Properties name = '' last_name = '' dni = '' age = 0 subjects = [] # Constructor def __init__(self, name, last_name, dni, age): self.name = name self.last_name = last_name self.dni = dni self.age = age # Methods def greet(self): print(f'Hello, my name is {self.name}') def increment_age(self): self.age += 1 def add_subjet(self, subject): self.subjects.append(subject) class Subject(): # Properties name = '' grade = '' # Constructor def __init__(self, name): self.name = name # Methods def add_grade(self, grade): if 0 <= grade <= 10: self.grade = grade class Group(): teacher = None students = [] subjects = [] def __init__(self, teacher, students, subjects): self.load_students(students) self.load_subjects(subjects) def show_group(self): for student in self.students: print(student.name) for subject in self.subjects: print(subject.name) def load_subjects(self, subjects): for subject in subjects: new_subject = Subject(subject) self.add_subject(new_subject) def add_subject(self, subject): self.subjects.append(subject) def remove_subject(self, subject): self.subjects.remove(subject) def load_students(self, students): for student in students: new_student = Student(student, '', '', 0) self.add_student(new_student) def add_student(self, student): self.students.append(student) def remove_student(self, student): self.students.remove(student) student1 = Student('Cristina', 'Ponce', '34124312Z', 18) student1.greet() student1.increment_age() students = ['Cristina', 'Adrián'] subjects = ['Lengua', 'Inglés'] group = Group('Isabel', students, subjects) group.show_group()
a36714242e5be77a93e8734b0c5e29df5b662dad
soumyaevan/PythonProgramming
/CodeSignal/FixMessage.py
209
3.6875
4
""" Implement a function that will change the very first symbol of the given message to uppercase, and make all the other letters lowercase. """ def fixMessage(message): return message.lower().capitalize()
4ecc50191ded5b9cfdfd8bf3b415e0604ea17739
swalgocoder/holbertonschool-higher_level_programming
/0x0B-python-input_output/0-read_file.py~
158
3.78125
4
#!/usr/bin/python3 """ Read a text file (UTF8) and prints it to stdout. """ def read_file(filename=""): print((open(filename, 'r').read()), end="")
b715e6c5e2de0d5daf4eeface1b8aa9b1b9a3263
AnandD007/Amazing-Python-Scripts
/Restoring-Divider/script.py
3,750
3.78125
4
def main(): A = "" Q = int(input("Enter the Dividend => ")) M = int(input("Enter the Divisor => ")) Q = bin(Q).replace("0b", "") M = bin(M).replace("0b", "") size = 0 """ This part makes the initialisation of required for the Restoring Division to occur. Which includes: 1) Setting an extra to M compared to A 2) Filling up A with zeroes 3) Setting the size """ if len(M) == len(Q): M = "0" + M else: if len(Q) > len(M): how = len(Q) - len(M) for i in range(0, how, 1): M = "0" + M else: how = len(M) - len(Q) for i in range(0, how - 1, 1): Q = "0" + Q for i in range(0, len(M), 1): A = "0" + A size = len(M) """ The Calculation and Line by Line Display begins from here """ A = "0" + A M = "0" + M M2 = twos_complement(M) print("Solution=>") print("A=", A) print("Q=", Q) print("M=", M) print("M2=", M2) printer = "A\t\tQ\t\tSize\t\tSteps" print(printer) # Printing the Initialisation step printer = A + "\t\t" + Q + "\t\t" + str(size) + "\t\tInitialization" print(printer) """ The division will be taking place until the size of the Divisor becomes zero """ for i in range(size, 0, -1): """ Left Shift Operation """ A = A[1:len(A)] + Q[0] Q = Q[1:len(Q)] printer = A + "\t\t" + Q + "\t\t" + str(size) + "\t\tLeft Shift" print(printer) """ Subtraction """ A = add(A, M2) printer = A + "\t\t" + Q + "\t\t" + str(size) + "\t\tSubtraction" print(printer) """ Bit Checking and AAddition if required """ if A[0] == '0': Q = Q + "1" else: Q = Q + "0" A = add(A, M) printer = A + "\t\t" + Q + "\t\t" + str(size) + "\t\tBit Checking" print(printer) """ Decreasing Size """ size = size - 1 printer = A + "\t\t" + Q + "\t\t" + str(size) print(printer) def twos_complement(n): a = "" c = "" """ Performing 1's Complement by changing all zeroes to one """ for i in range(0, len(n)): if n[i] == '1': a = a + "0" else: a = a + "1" """ Performing 2's complement by adding 1 to the 1's complement """ d = "" for i in range(0, len(a) - 1): d = d + "0" d = d + "1" c = add(a, d) return c def add(x, y): """ Binary Adddition bing carried out """ carry = "" result = "" carry = "0" for i in range(len(x) - 1, -1, -1): a = carry[0] b = x[i] c = y[i] if a == b and b == c and c == '0': result = "0" + result carry = "0" elif a == b and b == c and c == '1': result = "1" + result carry = "1" else: if a == '1' and b == c and c == '0': result = "1" + result carry = "0" elif a == '0' and b == '1' and c == '0': result = "1" + result carry = "0" elif a == '0' and b == '0' and c == '1': result = "1" + result carry = "0" elif a == '0' and b == '1' and c == '1': result = "0" + result carry = "1" elif a == '1' and b == '0' and c == '1': result = "0" + result carry = "1" elif a == '1' and b == '1' and c == '0': result = "0" + result carry = '1' return result main()
afcaaff5b072d1b3ec4829aa9034f5d32019b839
MrBean1512/bioinformatics_collection
/32_code.py
855
3.578125
4
# open a file to get the input file = open("32_input.txt", 'r') lines = [] for line in file: lines.append("{}".format(line.strip())) file.close() k = int(lines[0]) dna = lines[1] def deBruijnGraph(k, dna): #this is the main function kDict = {} for i in range(0, len(dna) - k + 1): print(dna[i:i+k-1]) if dna[i:i+k-1] not in kDict: kDict[dna[i:i+k-1]] = [dna[i+1:i+k]] else: kDict[dna[i:i+k-1]].append(dna[i+1:i+k]) return kDict def parse(kDict): parse = [] for key, value in kDict.items(): parsedList = ",".join(str(x) for x in value) parse.append(key + " -> " + parsedList) parse.sort() return parse answer = parse(deBruijnGraph(k, dna)) print(answer) fileout = open('32_sub.txt', 'w') for i in answer: fileout.write(i + "\n") fileout.close()
768729b88ecdd415555fdc5d45a8d48db10d4a51
OlgaLevshina/BL_Python
/homework_1/task_2.py
529
4.375
4
# 2. Пользователь вводит время в секундах. # Переведите время в часы, минуты и секунды и выведите в формате чч:мм:сс. # Используйте форматирование строк. ''' second = str() while second.isdigit() == False: second = input("Введите время в секундах ") second = int(second) h = second//3600 m = (second % 3600)//60 s = (second % 3600) % 60 second = f"{h:02}:{m:02}:{s:02}" print(second)
1a887c9e1c06f2e3c1c4a8833d7de31f56b79d0f
MarthaSamuel/foundation
/palindromic.py
593
4.28125
4
# Author: Dimgba Martha O # @martha_samuel_ # 35 this code checks if a string is palindromic. Spaces and letters are ignored. # A palindrome is a string that can be equally read from left to right or right to left, # omitting blank spaces, and ignoring capitalization def palindrome(input_string): new_string = input_string.casefold() new_string = ''.join(new_string.split()) reverse_string = reversed(new_string) if list(new_string)==list(reverse_string): return True return False print(palindrome('Never Odd or Even')) print(palindrome('abc')) print(palindrome('kayak'))
812b8c29ab1c6ebc96b6a8ab6157639ae184b591
JackieBinya/Bootcamp_
/Prime-numbers/prime_numbers_list.py
437
4.09375
4
def primes(n): #creates a function primes prime = [] #initializes the list if type(n) is int: #only takes integers if n < 2: #n starts from 2 return [] elif n > 1: for num in range(2, n+1): # from 0 to n if all(num % i != 0 for i in range(2, num)): prime.append(num) return prime else: raise TypeError("use an integer not a string") #raises error when a string is used
cda43b29ee498693446f2a64245c4c350dd09318
ayushchauhan09/My-Codes
/Codes/Python/Two-vs-Ten.py
165
3.625
4
T = int(input()) for _ in range(T): num = int(input()) if num%10==0: print(0) elif num%5==0: print(1) else: print(-1)
a558f1376e5dc4e5f58e2de1dc03d4433239b5d5
zhjw8086/MagikCode
/第二季/Turtle_project/house.py
404
3.546875
4
import turtle import time t = turtle.Pen() t.color('green','red') t.hideturtle() t.begin_fill() for x in range(3): t.forward(100) t.left(180-60) t.forward(10) t.right(90) t.end_fill() t.color('green','brown') t.begin_fill() for x in range(3): t.forward(80) t.left(90) t.end_fill() t.penup() t.goto(30,-80) t.pendown() for x in range(3): t.right(90) t.forward(40) time.sleep(20)
26083a8ecb1611301d329536516c2c4ba9b6e9fd
LuccasTraumer/pythonRepositorio
/CursoPython/Exercicios/Ex034.py
597
3.890625
4
'''Escreva um programa que pergunte o salário de um funcionário e calcule o valor do seu aumento. Para salários superiores a R$1250,00, calcule um aumento de 10%. Para os inferiores ou iguais, o aumento é de 15%''' salar = float(input('Digite o Salário R$: ')) calc15 = (salar*15)/100 calc10 = (salar*10)/100 if salar <= 1250: print('Seu Salario erá \033[33m {} \033[m R$ a com o aumento é \033[35m {} \033[m R$'.format(salar,salar+calc15)) if salar >= 1250: print('Seu Salario é de \033[33m {} \033[m R$ e com o Aumento será \033[35m {} \033[m R$'.format(salar,calc10+salar))
189824b9b04c087071c07838e4e4d50c41367944
harrietty/python-katas
/katas/replace_chars.py
1,340
4.09375
4
''' In input string word(1 word): replace the vowel with the nearest left consonant. replace the consonant with the nearest right vowel. P.S. To complete this task imagine the alphabet is a circle (connect the first and last element of the array in the mind). For example, 'a' replace with 'z', 'y' with 'a', etc.(see below) The below constants are preloaded ''' alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] consonants = ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z'] vowels = ['a','e','i','o','u'] def replace_chars(strng): if not strng: return '' def prevCon(ch): con = None ch_index = alphabet.index(ch) while con == None: ch_index -= 1 if alphabet[ch_index] in consonants: con = alphabet[ch_index] return con def nextVowel(ch): vowel = None ch_index = alphabet.index(ch) while vowel == None: ch_index = 0 if ch_index == len(alphabet)-1 else ch_index + 1 if alphabet[ch_index] in vowels: vowel = alphabet[ch_index] return vowel return ''.join([prevCon(ch) if ch in vowels else nextVowel(ch) for ch in list(strng)]) # Alternative: Use maketrans: # TR = str.maketrans('abcdefghijklmnopqrstuvwxyz', 'zeeediiihooooonuuuuutaaaaa')
76c735fe149a3cd12f1bd050c8f659adbe51368b
jubic/RP-Misc
/System Scripting/Problem09/files/func3.py
220
3.828125
4
def combine(strlist): string = "" for item in strlist: string = string+"<"+str(item)+">" return string if __name__ == "__main__": print combine(["one", "two"]) # prints "<one><two>"
514f41727105045ab95ccda845cf7aa328e48e0c
rafaelperazzo/programacao-web
/moodledata/vpl_data/386/usersdata/268/83572/submittedfiles/ep1.py
113
3.8125
4
# -*- coding: utf-8 -*- n= int(input('Digite o numero de equações: ')) cont=0 while(cont<n): #ENTRADA
54d21bb5584ca82161bdc74fd517c8a36e1ff3e4
afahad0149/How-To-Think-Like-A-Computer-Scientist
/Chapter 11 (LISTS)/exercises/problem_3.py
97
3.96875
4
a = [1, 2, 3] b = a[:] # b is a clone of a b[0] = 5 print(a) # [1, 2, 3] print(b) # [5, 2, 3]
f932662d9bff8a6635aaae9984c653ec635a5f00
barcern/python-crash-course
/chapter5/5-1_conditional_tests.py
1,534
4.09375
4
# -*- coding: utf-8 -*- """ Created on Sat May 9 11:07:41 2020 @author: barbora """ # Write a series of conditional tests. Print a statement describing each test # and your prediction for the results of each test. Create at least 10 tests. fave_animals = ['alpaca', 'duck', 'flying squirrel', 'goldcrest'] print("Test 1: Is alpaca in fave_animals? I predict True.") print('alpaca' in fave_animals) print("Test 2: Is cockroach in fave_animals? I predict False.") print('cockroach' in fave_animals) print("Test 3: Is goose not in fave_animals? I predict True.") print('goose' not in fave_animals) print("Test 4: Is duck not if fave_animals? I predict False.") print('duck' not in fave_animals) print("Test 5: Are flying squirrel and goldcrest in fave_animals? I predict" " True.") print(('flying squirrel' in fave_animals) and ('goldcrest' in fave_animals)) print("Test 6: Are flying squirrel and shark in fave_animals? I predict" " False.") print(('flying squirrel' in fave_animals) and ('shark' in fave_animals)) print("Test 7: Are flying squirrel or shark in fave_animals? I predict" " True.") print(('flying squirrel' in fave_animals) or ('shark' in fave_animals)) print("Test 8: Are mouse or shark in fave_animals? I predict False.") print(('mouse' in fave_animals) or ('shark' in fave_animals)) plant = 'easter cactus' print("Test 9: Is plant = 'easter cactus'? I predict True.") print(plant == 'easter cactus') print("Test 10: Is plant = 'kalanchoe'? I predict False.") print(plant == 'kalanchoe')
23b5b3851d4ed02bfb0608aa61fd1f121803a209
semi-cheon/programmers
/level2/201217_programmers_압축.py
670
3.71875
4
# python 코딩 테스트 연습 # 작성자: 천세미 # 작성일: 2020.12.17.T # 문제: 압축 # 문제 url: https://programmers.co.kr/learn/courses/30/lessons/17684 def solution(msg): total = [chr(i) for i in range(65,91)] answer = [] temp = '' for i in msg: temp += i if temp not in total: total.append(temp) answer.append(total.index(temp[:-1])) temp = temp[len(temp)-1:] if temp: answer.append(total.index(temp)) return [i+1 for i in answer] if __name__ == "__main__" : # for i in range(len(n)) : print(solution('TOBEORNOTTOBEORTOBEORNOT')) print("")
48b4a8366bdd570864d6b4b7c09e394bbd36c506
cligraphy/cligraphy
/staging/commands/misc/sets.py
965
3.890625
4
#!/usr/bin/env/python """Print the intersection or union of two line-delimited data sets """ OPERATIONS = { 'union': lambda left, right: left.union(right), 'inter': lambda left, right: left.intersection(right), 'ldiff': lambda left, right: left - right, 'rdiff': lambda left, right: right - left, } def read_dataset(filename): result = set() with open(filename, 'r') as fpin: while True: line = fpin.readline() if not line: break result.add(line[:-1]) return result def configure(parser): parser.add_argument('-o', '--operation', help='Set operation', choices=OPERATIONS.keys(), default='inter') parser.add_argument('left', help='Left-side data set') parser.add_argument('right', help='Right-side data set') def main(args): left = read_dataset(args.left) right = read_dataset(args.right) print '\n'.join(OPERATIONS[args.operation](left, right))
da3f9a2e24fb8eb0f5dd5644bb39e6bca8c6c46c
bhavyakamboj/Programming-101-Python-2020-Spring
/week09/03.SQL-and-Python/demo/setup_users_database_with_plain_text_passwords.py
938
3.734375
4
import sqlite3 def create_users_table(): connection = sqlite3.connect('users_with_plain_passwords.db') cursor = connection.cursor() query = ''' CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY AUTOINCREMENT, username VARCHAR(50), password VARCHAR(100) ) ''' cursor.execute(query) connection.commit() connection.close() def populate_users_table(): users_data = [] for i in range(100): users_data.append( f'("user_{i}", "password_{i}")' ) connection = sqlite3.connect('users_with_plain_passwords.db') cursor = connection.cursor() query = f''' INSERT INTO users (username, password) VALUES {','.join(users_data)} ''' cursor.execute(query) connection.commit() connection.close() def main(): create_users_table() populate_users_table() if __name__ == '__main__': main()
2886c188ac6576efc20fd1ac6a5cb7e28a008e68
daks001/py102
/7/Lab7b_Prog3.py
1,887
4.125
4
# By submitting this assignment, I agree to the following: # “Aggies do not lie, cheat, or steal, or tolerate those who do” # “I have not given or received any unauthorized aid on this assignment” # # Name: DAKSHIKA SRIVASTAVA # Section: 532 # Assignment: LAB 7b PROGRAM 3 # Date: 10 OCTOBER 2019 print("This program sorts a list and finds the median value.") a = (input("Enter numbers separated by spaces: ")).split() # a = [67, 78, 34, 90, 1, 6, 34, 9, -9, 23] #a hard-coded list for i in range(len(a)): a[i]=int(a[i]) aa = a a.sort() #sorting the list using python's in-built function length = len(a) if length%2 == 0: #for even number of elements in the list med = (a[length // 2] + a[(length // 2) - 1]) / 2 else: #for odd number of elements in the list med = a[length // 2] print("The median value using python's sort function is:", med) a = aa b = [] #new list to have sorted values m = None mi = 0 while len(a) > 0: m = None for i in range(len(a)): #finding the minimum element in the remaining list if m == None: #b is empty m = a[i] mi = i elif m!=None and a[i] < m: #b has some elements so need to find minimum m = a[i] mi = i b.append(m) #adding the minimmum element to the new list del a[mi] #deleting the minimum element from original list 'a' r = [] #to store the reverse of the sorted list length = len(b) i = length-1 while i>=0: r.append(b[i]) #adding last element of b in a way to make it the first element of r i -= 1 if length%2 == 0: # for even number of elements in the list med = (b[length // 2] + b[(length // 2) - 1]) / 2 else: # for odd2 number of elements in the list med = b[length // 2] print("The median value using fake sort is:", med) print("The sorted list using fake sort is:",b) print("The reverse of the sorted list is:",r)
7ae81472b265f376b29fd0637536c505919ca441
shrutisingh15/Udacity_Data_Analyst_Nanodegree
/Project P5/Intro to Machine learning/ud120-projects-master/datasets_questions/explore_enron_data.py
3,344
3.59375
4
#!/usr/bin/python """ Starter code for exploring the Enron dataset (emails + finances); loads up the dataset (pickled dict of dicts). The dataset has the form: enron_data["LASTNAME FIRSTNAME MIDDLEINITIAL"] = { features_dict } {features_dict} is a dictionary of features associated with that person. You should explore features_dict as part of the mini-project, but here's an example to get you started: enron_data["SKILLING JEFFREY K"]["bonus"] = 5600000 """ import pickle enron_data = pickle.load(open("../final_project/final_project_dataset.pkl", "r")) poi_num = 0 persons = ["SKILLING JEFFREY K","LAY KENNETH L","FASTOW ANDREW S"] total=0 whichone ="" quantified_salary_persons=0 quantified_emails=0 NaN_total_payments=0 poi_NaN_payments = 0 for p in enron_data: if enron_data[p]['poi'] == 1: poi_num +=1 if enron_data[p]["total_payments"] == "NaN": poi_NaN_payments += 1 if enron_data[p]['salary'] != "NaN": quantified_salary_persons +=1 if enron_data[p]['email_address'] != "NaN": quantified_emails += 1 if enron_data[p]["total_payments"] == "NaN": NaN_total_payments += 1 for person in persons: if total<enron_data[person]["total_payments"]: total=enron_data[person]["total_payments"] whichone = person NaN_percentage= (NaN_total_payments/float(len(enron_data))) poi_NaN_percentage = (poi_NaN_payments/float(poi_num)) print "How many data points(people) are in the dataset?\n+ %r" %len(enron_data) print "For each person how many features are available? \n+ %r" %len(enron_data['SKILLING JEFFREY K']) print "How many POIs are there in E+F dataset? \n+ %r" % poi_num print "How many POIs were there in total? \n+ %r" % 35 ## look at the no of POIs in the poi_names.txt file in the final_project folder print "What is the total value of stocks belonging to James Prentice? \n+ %r" % enron_data['PRENTICE JAMES']['total_stock_value'] print "How many email messages do we have from Wesley Colwell to persons of interest? \n+ %r" % enron_data['COLWELL WESLEY']['from_this_person_to_poi'] print "Whats the value of stock options exercised by Jeffrey Skilling? \n+ %r" % enron_data['SKILLING JEFFREY K']['exercised_stock_options'] print "of these three individuals(Lay,Skilling and Fastow) who took home the most money(largest value of total payments feature)? \n+ %r %r" %(total,whichone) print "How many folks in the dataset have quantified salary?How about their email addresses? \n+ %r %r" %(quantified_salary_persons,quantified_emails) print "What percentage of people in the dataset have NaN as their total_payments and how many are they? \n+ %r %r" %(NaN_percentage,NaN_total_payments) print "What percentage of POIs have NaN as their total_payments and how many are they? \n+ %r %r" %(poi_NaN_percentage,poi_NaN_payments) print "if a machine learning algorithm were to use total_payments as a feature,would you expect it to associate a NaN value with POIs or non-POIs?\n+ %r" % "Non-POIs" print "If you added 10 more data points which were all POIs and put NaN for the total payments for these folks.What would be the new number of people of the dataset? What would be the new number of folks with NaN for total payments? \n+ %r %r" % (156 , 31) print "What is the new number of POIs in the dataset? What is the new number of POIs with NaN for total payments? \n+ %r %r" %(28,10)
e596a6ede88bd112b726df5d05923aa31f97ceb4
mutoulovegc/gaochuang123
/桌面/day.4/xingxing.py
552
4.34375
4
#完成5行内容的简单输出 #分析每一行应该如何处理?每行显示的星星和所在的行数是一致的 #嵌套一个循环,专门处理每一行列的星星显示 #定义一个行号确认当前我在那一行 row = 1 while row <= 5: #假设Python中没有字符串拼接这个功能 #每一行显示的星星和当前的行数要是一致的 # #列数 col = 1 while col <= row: print("*", end="") col = col +1 #完成每一行输出增加一个换行 print(" ") row = row + 1
8ad96578c5f5503b000c46812666a77de4db6b08
Disherence/Python_study
/new.py
529
3.5625
4
import math try: a = eval(input("请输入a边长:")) b = eval(input("请输入b边长: ")) c = eval(input("请输入c边长: ")) except NameError: print("请输入正数数值") if str.isdigit(a) == True: print("输输字") elif a < 0 or b < 0 or c < 0: print("数据不可以为负数") elif a+b <= c or a+c <= b or b+c <= a: print("不符合两边之和大于第三边原则") else: p = (a+b+c)/2 s = math. sqrt(p * (p-a) * (p-b)*(p-c)) print("三角形的面积是(:.2f)". format(s))
b4a6c7edf7affd3f22221652f850f08af0099e33
Sathvickm07/My-captain-assignment
/student_adminstration_My Captain.py
1,408
3.953125
4
# school administration tool import csv def write_into_csv (student_info): with open('student_info.csv', 'a', newline='') as csv_file: writer = csv.writer(csv_file) if csv_file.tell() == 0: writer.writerow( ["Name", "Age", "Contact Number", "E-Mail ID"]) writer.writerow(student_info) if __name__ == "__main__": condition = True student_num=1 while(condition): student_info =input("Enter student information for student #{} in the following format (Name Age Contact Number E-mail_ID): ".format(student_num)) #split student_info_list= (student_info.split(' ')) print("\nThe entered information is -\nName: \nAge: \nContact number: {}\E-Mail ID: {}" .format(student_info_list[0], student_info_list[1], student_info_list[2], student_info_list[3])) choice_check =input("Is the entered information correct? (yes/ no): ") if choice_check == "yes": write_into_csv(student_info_list) condition_check=input("Enter (yes/no) if you want to enter information for another student: ") if condition_check == "yes": condition = True student_num= student_num +1 elif condition_check == "no": condition = False elif choice_check == "no": print("\nPlease re-enter the values!")
f22b08b574dfe38d2ba3e2c77217df7999322135
FelixMayer/functions_basic_2
/functions_basic_2.py
1,783
4.25
4
# 1 Countdown - Create a function that accepts a number as an input. Return a new list that counts down by one, from the number (as the 0th element) down to 0 (as the last element). def countdown(num): count = [] for i in range(num, -1, -1): count.append(i) return count x = countdown(5) print(x) # 2 Print and Return - Create a function that will receive a list with two numbers. Print the first value and return the second. def print_return(num1, num2): print(num1) return num2 print_return(5, 19) # 3 First Plus Length - Create a function that accepts a list and returns the sum of the first value in the list plus the list's length. def first_length(x): answer = x[0] + len(x) return answer y = first_length([1, 2, 3, 4]) print(y) # 4 Values Greater than Second - Write a function that accepts a list and creates a new list containing only the values from the original list that are greater than its 2nd value. # Print how many values this is and then return the new list. If the list has less than 2 elements, have the function return False def greater_than_second(x): newList = [] if len(x) < 2: return False for i in x: if i > x[1]: newList.append(i) print(len(newList)) return newList first = greater_than_second([5,2,3,2,1,4]) print(first) second = greater_than_second([3]) print(second) # 5 This length, that value - Write a function that accepts two integers as parameters: size and value. # The function should create and return a list whose length is equal to the given size, and whose values are all the given value. def length_value(size, value): newList = [] for i in range(size): newList.append(value) return newList a = length_value(4,7) print(a)
8b404b33ae8035a7cd017f5f6908933ebf6ae454
gan3i/Python_second
/Exceptions/Iteration and iterable/itertools.py
396
3.796875
4
from itertools import count, islice d = [1,2,3,4,4,4,3,3,2,2,5] c = islice(d,2) print(c) print(any([True,False,True,False])) print(all([False,False,False,False])) #for Synchronized iteration through two or more iterables, a = ["hey", "grus", "bitta"] b = ["Pal!","gott","shoun"] def print_zip(): for item in zip(a,b): print(item) print_zip() # itertol is worth looking at.
5af78ceff2661b9f79853be4abbba099776acc97
Jane11111/Leetcode2021
/022_3.py
665
3.53125
4
# -*- coding: utf-8 -*- # @Time : 2021-07-07 17:14 # @Author : zxl # @FileName: 022_3.py class Solution: def recGenerate(self,left_count,right_count,n,s,ans): if len(s) == 2*n: ans.append(s) return if left_count == right_count: self.recGenerate(left_count+1,right_count,n,s+'(',ans) else: self.recGenerate(left_count,right_count+1,n,s+')',ans) if left_count < n: self.recGenerate(left_count+1, right_count, n, s + '(', ans) def generateParenthesis(self, n: int) : ans = [] self.recGenerate(0,0,n,'',ans) return ans
1f2be3871e84cd9dabf34b121620920e5fa558d6
saisai/tutorial
/python/techiedelight_com/backtracking/minisudo.py
1,920
4.125
4
''' if the board contains no invalid cells, ie.cells that violate the rules: if it is also completely filled out then return true for each cell in the board if the cell is empty for each number in {1,2,3} replace the current cell with number if solve(board) and the board is valid return true else backtrack return false ''' from itertools import * from copy import copy def is_distinct( array ): """ axuilary function to is_solved checks if all elements in a array are distinct (ignores 0s though) """ used = [] for i in array: if i == 0: continue if i in used: return False used.append(i) return True def is_valid( brd ): """Check if a 3x3 mini sudoku is valid.""" for i in range(3): row = [brd[i][0], brd[i][1], brd[i][2]] if not is_distinct(row): return False col = [brd[0][i], brd[1][i], brd[2][i]] if not is_distinct(col): return False return True def solve(brd, empties=9): """ solve a mini sudoku brd is the board empty is the number of empty cells """ if empties == 0: # base case return is_valid(brd) for row, col in product(range(3), repeat=2): # run through every cell cell = brd[row][col] if cell != 0: # if its not empty jump continue brd2 = copy(brd) for test in [1,2,3]: brd2[row][col] = test if is_valid(brd2) and solve(brd2, empties-1): return True # backtrack brd2[row][col] = 0 return False Board = [ [ 0 , 0 , 0 ], [ 1 , 0 , 0 ], [ 0 , 3 , 1 ] ] solve( Board , 9 - 3 ) for row in Board: print(row)
2aebbcc2981ae488c0a134e034dd5cea7f3c2b8d
onegules/Number-Guessing-Game
/NumberGuessGame/NumberGuess.py
501
3.625
4
import numpy as np class NumberGuess: def __init__(self,high=101): ''' Initialize the function and generates a random number based on the optional argument''' self.number = np.random.randint(1,high=high) self.high = high def result(self,guess): '''Calculates the result of a guess''' if guess < self.number: return "Too low." elif guess > self.number: return "Too high." else: return True
9cec2c1ddc458fe3d2299b54737b69513f2a5225
Gangadhar454/Leet-code-solutions
/Maximum sum of two numbers.py
650
4
4
import collections ##Given an array A consisting of N integers, returns the maximum sum of two numbers whose digits add up to an equal sum. ##if there are not two numbers whose digits have an equal sum, the function should return -1. def MaximumSum(A): table = collections.defaultdict(list) for a in A: num = a s = 0 while num: s += num % 10 num //= 10 table[s].append(a) maxSum = -1 for val in table.values(): if len(val) > 1: maxSum = max(maxSum, sum(sorted(val)[-2:])) return maxSum print(MaximumSum([51, 71, 17, 42]))
5910a1169441c6793996230536c5d9c7db53d11b
AyumiizZ/grad-school-work
/01204512-algorithm/implement-for-midterm/find-smallest.py
757
4.09375
4
""" File name: find-smallest.py Author: AyumiizZ Date created: 2020/10/24 Python Version: 3.8.5 About: find smallest number in decreasing and increasing sequence """ def find_smallest(arr): n = len(arr) if (n == 1): return arr[0] if (arr[1] > arr[0]): # increase only return arr[0] if arr[n-1] < arr[n-2]: # decrese only return arr[n-1] lower = 1 upper = n-2 while (lower <= upper): mid = (lower+upper)//2 if ((arr[mid] < arr[mid-1]) and (arr[mid] < arr[mid+1])): ans = arr[mid] break elif((arr[mid - 1] < arr[mid]) and (arr[mid] < arr[mid + 1])): upper = mid - 1 else: lower = mid + 1 return ans
409a509905021c502bae0b5a8b74e37980070a83
nazaninsbr/Queue
/reverse_using_stack.py
1,015
3.921875
4
class Stack: def __init__(self): self.values = [] def push(self, x): self.values.append(x) def top(self): if len(self.values)==0: return -1 return self.values[-1] def isEmpty(self): return len(self.values)==0 def pop(self): if len(self.values)==0: return -1 x = self.values[-1] del self.values[-1] return x class Queue: def __init__(self): self.values = [] def enqueue(self, val): self.values.append(val) def isEmpty(self): if len(self.values)==0: return True return False def dequeue(self): if not self.isEmpty(): val = self.values[0] del self.values[0] return val else: return -1 def reverse(self): tempStack = Stack() while not self.isEmpty(): tempStack.push(self.dequeue()) while not tempStack.isEmpty(): self.enqueue(tempStack.pop()) if __name__ == '__main__': q = Queue() q.enqueue(12) q.enqueue(2) q.enqueue(1) q.enqueue(32) q.enqueue(14) q.enqueue(-10) print(q.values) q.reverse() print('reverse: ', q.values)
a5bfaac1466344b8ae5048a80e29fe7e9d3f2f6e
MAPLE-Robot-Subgoaling/IPT
/data/HW3/hw3_221.py
852
4.15625
4
def main(): degreesNum = float(input("please enter the temperature of the water: ")) degreesType = str(input("what type of measurement is that temperature in? ")) if degreesType == "K" and degreesNum >= 373.0: print("at this temperature, water is a gas") if degreesType == "K" and degreesNum <= 273.0: print("at this temperature, water is a solid") if degreesType == "K" and degreesNum < 373.0 and degreesNum > 273.0: print("at this temperature, water is a liquid") if degreesType == "C" and degreesNum >= 100.0: print("at this temperature, water is a gas") if degreesType == "C" and degreesNum <= 0.0: print("at this temperature, water is a solid") if degreesType == "C" and degreesNum < 100.0 and degreesNum > 0.0: print("at this temperature, water is a liquid") main()
ebad80400781ed92bf01cd38f3c042d287ea3941
Hoch3007/practisepython_org
/exercise20.py
599
3.765625
4
##### practicepython.org: Exercise 20 # Binary Search import random liste = random.sample(range(1,100,1), 99) liste.sort() n = 55 def binary_search(liste, n): while len(liste)>1: l = len(liste) if n<liste[l/2]: liste = liste[0:l/2] else: liste = liste[l/2:] if len(liste)==1: if n == liste[0]: print "Element ist in der Liste." print True else: print "Element ist nicht in der Liste." print False binary_search(liste, n)
44e537375be7879105d4c0a834e56878ba1e966c
rpachauri/connect4
/connect_four/problem/group.py
3,373
3.625
4
from connect_four.game import Square from enum import Enum from connect_four.problem.problem import Problem class GroupDirection(Enum): horizontal = 0 up_right_diagonal = 1 vertical = 2 up_left_diagonal = 3 # Maps (row_diff, col_diff) to a Group Direction. # Note that the mappings are counter-intuitive because # we're mapping the unit-differences between the start and end square of a Group. # e.g. (1, 0) maps to the Vertical direction because there is a difference in row but not column. ROW_COL_DIFFS_TO_group_DIRECTION = { (1, 0): GroupDirection.vertical, (1, 1): GroupDirection.up_left_diagonal, (0, 1): GroupDirection.horizontal, (-1, 1): GroupDirection.up_right_diagonal, (-1, 0): GroupDirection.vertical, (-1, -1): GroupDirection.up_left_diagonal, (0, -1): GroupDirection.horizontal, (1, -1): GroupDirection.up_right_diagonal, } class Group(Problem): """A Group is a group of squares in a line on a TwoPlayerGameEnv state. Each Group belongs to a specific player (0 or 1). All four of the squares must be in a line. In order to specify a group, a client only needs to specify: 1. Which player the Group belongs to. 2. The start and end of the group (since the group must consist of 4 squares in a line). """ def __init__(self, player: int, start: Square, end: Square): # Perform validation on player. if not (player == 0 or player == 1): raise ValueError("player must be 0 or 1. player =", player) self.player = player self.start = start self.end = end # Perform validation on start and end of group. row_diff = end.row - start.row col_diff = end.col - start.col # Should be a vector in one of the 8 acceptable directions. if row_diff != 0 and col_diff != 0: assert abs(row_diff) == abs(col_diff) # max_abs_diff is the number of squares in the group - 1. max_abs_diff = max(abs(row_diff), abs(col_diff)) if max_abs_diff not in {2, 3}: # For now, only support lengths of 3 and 4 for Tic-Tac-Toe and ConnectFour. raise ValueError("Group length", max_abs_diff + 1, "not in {3, 4}") # Derive the squares of the group from the start and end squares. row_diff, col_diff = row_diff // max_abs_diff, col_diff // max_abs_diff square_list = [start] for _ in range(max_abs_diff): next_square = Square(square_list[-1].row + row_diff, square_list[-1].col + col_diff) square_list.append(next_square) assert square_list[-1] == end self.squares = frozenset(square_list) assert len(self.squares) == max_abs_diff + 1 self.direction = ROW_COL_DIFFS_TO_group_DIRECTION[(row_diff, col_diff)] def __eq__(self, other): if isinstance(other, Group): return self.player == other.player and self.squares == other.squares return False def __hash__(self): return self.squares.__hash__() + self.player def __str__(self): return ("[" + str(self.player) + " -> " + "(" + str(self.start.row) + "," + str(self.start.col) + ")-" + "(" + str(self.end.row) + "," + str(self.end.col) + ")]" ) def __repr__(self): return self.__str__()
17fd3bfea6ab550b9927e0bf6e0b105746ba2aa7
MzBrownie/CTI110
/M3T1_AreasOfRectangles_PatriceBrowne.py
749
4.34375
4
# Calculate the area of rectangles # 12 June 2017 # CTI-110 M3T1 - Areas of Rectangles # Patrice Browne # # Area of rectangle is length * width first_rectangle_length = int (input ("First Rectangle Length? ")) first_rectangle_width = int (input ("First Rectangle Width? ")) second_rectangle_lenth = int (input ("Second Rectangle Length? ")) second_rectangle_width = int (input ("Second Rectangle Width? ")) first_area = first_rectangle_length * first_rectangle_width second_area = second_rectangle_lenth * second_rectangle_width if (first_area > second_area): print ("First Rectangle is Bigger." ) elif (first_area < second_area): print ("Second Rectangle is Bigger.") else: print ("They are equal!") print ("Done.")
5839a036f3937e85236bde57744a70916d21ca70
mdhiebert/minichess
/minichess/games/atomic/pieces/multipiece.py
1,066
3.5
4
from typing import List from minichess.games.abstract.piece import AbstractChessPiece, PieceColor import numpy as np class MultiPiece(AbstractChessPiece): ''' A piece that keeps track of itself and 8 other non-pawn pieces surrounding it (up to 9 in total). This piece keeps track of its pieces with a queue. First in, first out. ''' def __init__(self, pieces: List[AbstractChessPiece], position: tuple, value: int) -> None: super().__init__(PieceColor.WHITE, position, value) self.pieces = pieces def _onehot(self): return np.array([-1, 0, -1, 0, -1, 0]) def push(self, piece): self.pieces.append(piece) def pop(self): return self.pieces.pop(0) @property def captured_piece(self): assert len(self) == 9, 'Cannot call captured_piece() mid-construction.' return self.pieces[4] def __len__(self): return len(self.pieces) def __iter__(self): for piece in self.pieces: yield piece def __str__(self): return '*'
55929c51b5c30771926148837fe528d4b12c169b
frankieliu/problems
/leetcode/python/623/sol.py
1,233
3.78125
4
Can my solution be improved? [Python] https://leetcode.com/problems/add-one-row-to-tree/discuss/232356 * Lang: python3 * Author: anonymous36 * Votes: 0 ``` class Solution(object): def addOneRow(self, root, v, d): """ :type root: TreeNode :type v: int :type d: int :rtype: TreeNode """ def addLevel(node, depth): if node == None: return else: if depth + 1 == d: left = node.left node.left = TreeNode(v) node.left.left = left right = node.right node.right = TreeNode(v) node.right.right = right else: addLevel(node.left, depth+1) addLevel(node.right, depth+1) if d == 1: new_root = TreeNode(v) new_root.left = root return new_root else: addLevel(root, 1) return root ``` Time-Complexity: O(n) where n is the number of nodes. Space-Complexity: O(h) where h is the height of three.
6280163355e13b3b00f243661017262d7189a4d1
FaisalAhmed64/Python-Basic-Course
/User input.py
257
4.03125
4
name_is = input("what is your name? ") print("hi " + name_is) name = input("What is your name? ") Color = input("what is your favourite color? ") print(name + " likes " + Color) birth_date = input("birth year: ") Age = 2021 - int(birth_date) print(Age)
7daad8fd4ff333f49954a4b26e8a9b8aff7647e7
fallcreek/open-edx
/solutions/Week6/p1.py
720
3.6875
4
import random def answer(seed): random.seed(seed) a = random.randint(1,5); b = random.randint(6,10); # Solutions with variables converted to string # Make sure you name the solution with part id at the end. e.g. 'solution1' will be solution for part 1. solution1 = "{0}*(1+1/2+1/3+1/4+1/5)".format(a) solution2 = "{0}*(1+1/4+1/9+1/16+1/25)".format(b) solution3 = "{0}*(1-1/2+1/3-1/4+1/5)".format(a) solution4 = "{0}*(1+1/4+1/9+1/16+1/25)".format(b) solution5 = "{0}*(1-2/2+1/3-2/4+1/5)".format(a) solution6 = "{0}*(1+1/9+1/25) +{0}*4*(1/4+1/16)".format(b) # Group all solutions into a list solutions = [solution1,solution2,solution3,solution4,solution5,solution6] return solutions
4fe9d7b1d738012d552b79fb4dc92a3c65fa7e53
akhileshsantoshwar/Python-Program
/Programs/P08_Fibonacci.py
804
4.21875
4
#Author: AKHILESH #This program calculates the fibonacci series till the n-th term def fibonacci(number): '''This function calculates the fibonacci series till the n-th term''' if number <= 1: return number else: return (fibonacci(number - 1) + fibonacci(number - 2)) def fibonacci_without_recursion(number): if number == 0: return 0 fibonacci0, fibonacci1 = 0, 1 for i in range(2, number + 1): fibonacci1, fibonacci0 = fibonacci0 + fibonacci1, fibonacci1 return fibonacci1 if __name__ == '__main__': userInput = int(input('Enter the number upto which you wish to calculate fibonnaci series: ')) for i in range(userInput + 1): print(fibonacci(i),end=' ') print("\nUsing LOOP:") print(fibonacci_without_recursion(userInput))
f649c1141a33f2faebe8ba4b882cb4671c92b13a
gschen/sctu-ds-2020
/1906101040-吴云康/作业3/03.py
392
3.734375
4
class Person(): def __init__(self): self.name = "吴云康" self.age = 20 self.gender = "male" self.college = "信息与工程学院" self.professional = "信息管理与信息系统" def personInfo(self): return "name:{},age:{},gender:{},college:{},professional:{}".format(self.name,self.age,self.gender,self.college,self.professional)
bf2ad03f6c974e1f32a6ad959387267ff8377990
MaxSchmitz/online_translater_practice
/Problems/The median of three/main.py
826
4.25
4
def choose_median(start, middle, end): # finish the method for finding the median pivot = [start, middle, end] pivot.sort() return pivot[1] def partition(lst, pivot, start, end): # add necessary modifications # don't forget to print the result of the partition! pivot = lst.index(pivot) print(f'index of pivot is {pivot}') j = start for i in range(start, end): if lst[i] <= lst[pivot]: j += 1 lst[i], lst[j] = lst[j], lst[i] lst[start], lst[j] = lst[j], lst[start] return j # read the input list # and call the methods lst = [int(n) for n in '3 6 5 2 4'.split()] my_pivot = choose_median(lst[0], lst[len(lst) // 2], lst[len(lst)-1]) print(f'pivot is {my_pivot}') partition(lst, my_pivot, 0, len(lst) - 1) print(f'list after partion {lst}')
7e6c4038aa4740a1ce2d5b97e1863998e164ea68
alisonbelow/ctci_py_cpp
/py/sorting/insertionsort.py
1,198
4.28125
4
from sorter import Sorter import time ''' Time Complexity: O(n^2) Space Complexity: O(1) Divide into sorted and unsorted parts Iterate over unsorted segment, insert the element viewed into correct position of sorted list Comparing unsorted to sorted elem 'x'. Move unsorted elem to correct position then first elem last ''' class InsertionSort(Sorter): def __init__(self, input: list): super().__init__(input) self.name = 'InsertionSort' def sort(self): # Start with second elem for idx in range(1, len(self.numbers)): num_to_insert = self.numbers[idx] idx2 = idx - 1 # Move larger elem later in list if larger than item to insert while idx2 >= 0 and self.numbers[idx2] > num_to_insert: # Move self.numbers[idx2 + 1] = self.numbers[idx2] idx2 -= 1 # Insert item in correct place self.numbers[idx2 + 1] = num_to_insert sorter = InsertionSort([6,7,8,3,1,4,2,4,5]) begin_time = time.time() sorter.sort() elapsed = (time.time() - begin_time) * 1e3 sorter.print_results(sorter.name) print("\tDuration = {} ms".format(elapsed))
63688571fbf63611e25d9ca0227f5b19e503a0a1
LingB94/Target-Offer
/19正则表达式匹配.py
792
3.71875
4
def match(L, pattern): if(not L or not pattern): return False return matchCore(L, pattern) def matchCore(L, pattern): if(L == pattern): return True if( L != '' and pattern == ''): return False if(len(pattern) >= 2 and pattern[1] == '*'): if(L[0] == pattern[0] or (pattern[0] == '.' and L[0] != '')): return matchCore(L[1:], pattern[2:]) or\ matchCore(L, pattern[2:]) or\ matchCore(L[1:], pattern) else: return matchCore(L, pattern[2:]) elif(L[0] == pattern[0] or (pattern[0] == '.' and L[0] != '')): return matchCore(L[1:], pattern[1:]) return False if __name__ == '__main__': a = 'aaa' b = 'a*a' print(match(a,b))
7c24fddcb94099b611dea79c5066809b14d9bc84
pandre-lf/Python-ads41
/Lista-I/Ex25_invertermetades.py
361
4.09375
4
''' 25 - Faça uma função que receba uma lista e exiba os elementos da última metade na frente dos elementos da primeira metade. ''' import math lista_teste=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] def inverter_metades(lista): print(lista[int(len(lista)/2):len(lista)] + lista[0:int(len(lista)/2)]) print(f"Lista invertida: ") inverter_metades(lista_teste)
cd4a6d95e996ef9c08c44f8c6853acb90fe4a03b
davestudin/Projects
/Euler Problems/Euler Problems/Question 1.py
325
3.578125
4
from math import * max=1000 def func1(max): a=0 while a<max: yield a a = a+3 def func2(max): b,c=0,0 while b<max: yield b b = b+5 diff=0 for n in func2(max): if n%3==0 and n%5==0: diff = diff +n c = sum(func1(max)) d = sum(func2(max)) print c+d-diff
b8c200f89e7e086c17d049c8c50c382cebbcec95
sdvinay/advent_of_code
/2019_01.py
1,078
3.9375
4
INPUT_FILE='input/input_2019_01.txt' TEST_INPUTS=[4, 12, 14, 1969, 100756] #inputs provided in problem # fuel burned to transport mass (Part 1) def fuel_burned(mass): return ((int(mass/3)-2) if mass >= 6 else 0) # fuel_required accounts iteratively for including the fuel in the mass (Part 2) def fuel_required(mass): total_fuel = 0 incremental_fuel = fuel_burned(mass) while (incremental_fuel>0): total_fuel += incremental_fuel incremental_fuel = fuel_burned(incremental_fuel) return total_fuel # these are the test inputs provided in the problem # TODO: Actually check the outputs, rather than just print them def test(): for input in TEST_INPUTS: print(fuel_burned(input), fuel_required(input)) test() # The instructions explicitly say to compute fuel requirements on an item-by-item # basis (including on fuel amounts in Part 2), rather than on total mass :shrug: total1 = 0 total2 = 0 with open(INPUT_FILE) as f: lines = f.readlines() for line in lines: mass = int(line) total1 += fuel_burned(mass) total2 += fuel_required(mass) print(total1, total2)
c4055ff67f8d60a10bc5f0e3b42482d9b70257b5
zihuaweng/leetcode-solutions
/leetcode_python/136.Single_Number.py
793
3.53125
4
# https://leetcode.com/problems/single-number/ # 第二种方法解释: # Approach 4: Bit Manipulation # Concept # If we take XOR of zero and some bit, it will return that bit # a \oplus 0 = aa⊕0=a # If we take XOR of two same bits, it will return 0 # a \oplus a = 0a⊕a=0 # a \oplus b \oplus a = (a \oplus a) \oplus b = 0 \oplus b = ba⊕b⊕a=(a⊕a)⊕b=0⊕b=b # So we can XOR all bits together to find the unique number. class Solution: def singleNumber_1(self, nums) -> int: hash_table = {} for i in nums: try: hash_table.pop(i) except: hash_table[i] = 1 return hash_table.popitem()[0] def singleNumber_2(self, nums): a = 0 for i in nums: a ^= i return a
b63b8e22e69d6c0b108327c77a4779ca459b5131
ramdanks/RandomDataGenerator
/Random Data Generator/Array.py
1,390
3.59375
4
class Array : def __init__( self,size ) : self.arr = [ int ] * size self.size = int( size ) self.index = 0 self.set( None ) def print( self ) : for i in range( self.size ) : if ( self.arr[i] != None ) : if ( i+1 < self.size ) and ( self.arr[i+1] != None ) : print( self.arr[i],end=',' ) else : print( self.arr[i],end=' ' ) print() def __eq__( self,value ) : for i in range( self.size ) : if ( value != self.arr[i] ) : return False return True def exist( self,value ) : for i in range( self.size ) : if ( value == self.arr[i] ) : return True return False def set( self,value ) : for i in range( self.size ) : self.arr[i] = value if ( value != None ) : self.index = self.size def push( self,value ) : if ( self.index < self.size ) : self.arr[self.index] = value self.index += 1 def pop( self,value = 1 ) : for i in range( int( value ) ) : if ( self.index != 0 ) : self.arr[self.index - 1] = None self.index -= 1 def sort( self ) : for i in range( self.size ) : check = self.arr[i] if ( self > self.arr[i] ) : temp = self.arr[i] self.arr[i] = self.arr[j] self.arr[j] = temp def refreshIndex( self ) : temp = 0 for i in range( self.size ) : if ( self.arr[i] != None ) : temp += 1 self.index = temp
2bb76007c295563fe5efc218134415ee1af42e57
s-gulzar/python
/recursive.py
309
3.984375
4
def factorial(x): if x == 1: return 1 else: return x * factorial(x - 1) a= 5 print("Factorial of ", a ," is:", factorial(a)) def naturalnum(x): if x == 1: return 1 else: return x + naturalnum(x - 1) b = 6 print("Sum of ",b, "Natural Numbers:",naturalnum(b))
bf76f247531a62b0acdddbb55c46761042c87ea8
triplowe/CSV_Project
/sitka4.py
1,445
3.515625
4
import csv import matplotlib.pyplot as plt from datetime import datetime open_file = open("death_valley_2018_simple.csv", "r") csv_file = csv.reader(open_file,delimiter=",") header_row = next(csv_file) print(type(header_row)) for index, column_header in enumerate(header_row): print(index, column_header) #testing to convert date from string #mydate = datetime.strptime("2018-07-01", "%Y-%m-%d") highs = [] lows = [] dates = [] for row in csv_file: try: theDate = datetime.strptime(row[2], "%Y-%m-%d") high = int(row[4]) low = int(row[5]) except ValueError: print(f"Missing Data for {theDate}") else: dates.append(theDate) lows.append(int(row[5])) highs.append(int(row[4])) #print(highs) #print(dates) #print(lows) fig = plt.figure() plt.title("Daily high temperatures, July 2018", fontsize = 16) plt.xlabel("", fontsize = 12) plt.ylabel("Temperatures (F)", fontsize = 12) plt.tick_params(axis = "both", which = "major", labelsize = 12) plt.plot(dates, highs, c = "red", alpha = 0.5) plt.plot(dates, lows, c = "blue", alpha = 0.5) plt.fill_between(dates, highs, lows, facecolor = "blue", alpha = 0.1) fig.autofmt_xdate() plt.show() #plt.subplot(row,col,index) plt.subplot(2,1,1) plt.plot(dates,highs,c="red") plt.title("Highs") plt.subplot(2,1,2) plt.plot(dates,lows,c="blue") plt.title("Lows") plt.suptitle("Highs and Lows of Sitka Alaska") plt.show()
75fc083ef3621707afbc1faec5355db5b7b0bbf1
linahammad/CodeAcademy
/python/BattleShip.py
1,964
4.3125
4
# Import function to generate a random integer from random import randint # Create the playing board board = [] for x in range(5): board.append(["O"] * 5) def print_board(board): for row in board: print " ".join(row) # Welcome and print the playing field print "Let's play Battleship!" print_board(board) def random_row(board): #generate a random list index (row) for the playing board return randint(0, len(board) - 1) def random_col(board): #generate a random list index (column) for the playing board return randint(0, len(board[0]) - 1) # Determine a random location for the ship in the game in reference to a playing board location ship_row = random_row(board) ship_col = random_col(board) #for testing #print ship_row #print ship_col # Allow 4 turns or guesses as to the location of the ship for turn in range(4): # Notify user of the current Turn print "Turn", turn + 1 # Accept the user's input/guess data guess_row = int(raw_input("Guess Row:")) guess_col = int(raw_input("Guess Col:")) # If the guess is correct, indicate and end the game if guess_row == ship_row and guess_col == ship_col: print "Congratulations! You sunk my battleship!" break # Else the guess is incorrect: else: # Check data validity - indicate the problem if out-of-limits guess, if (guess_row < 0 or guess_row > 4) or (guess_col < 0 or guess_col > 4): print "Oops, that's not even in the ocean." # Check if guess was already made at that location elif(board[guess_row][guess_col] == "X"): print "You guessed that one already." # Indicate a missed guess and print the board else: print "You missed my battleship!" board[guess_row][guess_col] = "X" print_board(board) # Check to see if the game is over if turn == 3: print "Game Over"
1913c3d09fc2d44a269fc972b8a2027e5345b72d
PVyukov/algorithms
/L1_intro/L1_web/task_1.py
732
3.90625
4
# https://drive.google.com/file/d/1bjjsw9tzi4cuL5vQPTmOcL6MHGtmpfbH/view?usp=sharing # Начало # Вывод("Введите два чисал") # Ввод(Первое число) # Ввод(Второе число) # Если Второе число != 0 # То Частное = Первое число / Второе число # Вывод(Частное) # Иначе Вывод("Нет решений") # Конец print('Введите два числа') a = int(input('Введи целое число один: ')) b = int(input('Введи целое число два: ')) if b != 0: c = a / b print(f'{c=}') else: print('Нет решений') print(f'Текст {c} снова текст {a=}')
ba6c648dbe1f6b8cc65b474f4542c44555293a47
andresmiguel39/languages
/python/findHypotenuse/solution.py
596
3.796875
4
from typing import List from math import sqrt class Hypotenuse: def findHypotenuse(self, hickA: List[int], hickB: List[int]) -> List[int]: hypot = [] result = 0.0 if not hickA or not hickB: return [] if len(hickA) == len(hickB): for a in range(0, len(hickA)): for b in range(0, len(hickB)): if a == b: result=(hickA[a]*hickA[a])+(hickB[b]*hickB[b]) hypot.append(sqrt(result)) else: return [] return hypot
1267efb8f752ed1f5a6f99d5893a2ef1d3ce0427
heartcored98/COMET-pytorch
/model.py
11,218
3.5
4
import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.autograd import Variable import math #===== Activation =====# def gelu(x): """ Ref: https://github.com/huggingface/pytorch-pretrained-BERT/blob/master/pytorch_pretrained_bert/modeling.py Implementation of the gelu activation function. For information: OpenAI GPT's gelu is slightly different (and gives slightly different results): 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3)))) """ return x * 0.5 * (1.0 + torch.erf(x / math.sqrt(2.0))) ACT2FN = {"gelu": gelu, "relu": torch.nn.functional.relu} class Attention(nn.Module): def __init__(self, input_dim, output_dim, num_attn_head, dropout=0.1): super(Attention, self).__init__() self.num_attn_heads = num_attn_head self.attn_dim = output_dim // num_attn_head self.projection = nn.ModuleList([nn.Linear(input_dim, self.attn_dim) for i in range(self.num_attn_heads)]) self.coef_matrix = nn.ParameterList([nn.Parameter(torch.FloatTensor(self.attn_dim, self.attn_dim)) for i in range(self.num_attn_heads)]) self.tanh = nn.Tanh() self.relu = nn.ReLU() self.dropout = nn.Dropout(p=dropout) self.param_initializer() def forward(self, X, A): list_X_head = list() for i in range(self.num_attn_heads): X_projected = self.projection[i](X) attn_matrix = self.attn_coeff(X_projected, A, self.coef_matrix[i]) X_head = torch.matmul(attn_matrix, X_projected) list_X_head.append(X_head) X = torch.cat(list_X_head, dim=2) X = self.relu(X) return X def attn_coeff(self, X_projected, A, C): X = torch.einsum('akj,ij->aki', (X_projected, C)) attn_matrix = torch.matmul(X, torch.transpose(X_projected, 1, 2)) attn_matrix = torch.mul(A, attn_matrix) attn_matrix = self.dropout(self.tanh(attn_matrix)) return attn_matrix def param_initializer(self): for i in range(self.num_attn_heads): nn.init.xavier_normal_(self.projection[i].weight.data) nn.init.xavier_normal_(self.coef_matrix[i].data) ##################################################### # ===== Gconv, Readout, BN1D, ResBlock, Encoder =====# ##################################################### class GConv(nn.Module): def __init__(self, input_dim, output_dim, attn, act=ACT2FN['relu']): super(GConv, self).__init__() self.attn = attn if self.attn is None: self.fc = nn.Linear(input_dim, output_dim) self.act = act nn.init.xavier_normal_(self.fc.weight.data) def forward(self, X, A): if self.attn is None: x = self.act(self.fc(X)) x = torch.matmul(A, x) else: x = self.attn(X, A) return x, A class Readout(nn.Module): def __init__(self, out_dim, molvec_dim): super(Readout, self).__init__() self.readout_fc = nn.Linear(out_dim, molvec_dim) nn.init.xavier_normal_(self.readout_fc.weight.data) def forward(self, output_H): molvec = self.readout_fc(output_H) molvec = torch.mean(molvec, dim=1) return molvec class BN1d(nn.Module): def __init__(self, out_dim, use_bn=True): super(BN1d, self).__init__() self.use_bn = use_bn self.bn = nn.BatchNorm1d(out_dim) def forward(self, x): if not self.use_bn: return x origin_shape = x.shape x = x.view(-1, origin_shape[-1]) x = self.bn(x) x = x.view(origin_shape) return x class ResBlock(nn.Module): def __init__(self, in_dim, out_dim, use_bn, use_attn, dp_rate, sc_type, n_attn_head=None, act=ACT2FN['relu']): super(ResBlock, self).__init__() self.use_bn = use_bn self.sc_type = sc_type attn = Attention(in_dim, out_dim, n_attn_head) if use_attn else None self.gconv = GConv(in_dim, out_dim, attn) self.bn1 = BN1d(out_dim, use_bn) self.dropout = nn.Dropout2d(p=dp_rate) self.act = act if not self.sc_type in ['no', 'gsc', 'sc']: raise Exception if self.sc_type != 'no': self.bn2 = BN1d(out_dim, use_bn) self.shortcut = nn.Sequential() if in_dim != out_dim: self.shortcut.add_module('shortcut', nn.Linear(in_dim, out_dim, bias=False)) if self.sc_type == 'gsc': self.g_fc1 = nn.Linear(out_dim, out_dim, bias=True) self.g_fc2 = nn.Linear(out_dim, out_dim, bias=True) self.sigmoid = nn.Sigmoid() def forward(self, X, A): x, A = self.gconv(X, A) if self.sc_type == 'no': # no skip-connection x = self.act(self.bn1(x)) return self.dropout(x), A elif self.sc_type == 'sc': # basic skip-connection x = self.act(self.bn1(x)) x = x + self.shortcut(X) return self.dropout(self.act(self.bn2(x))), A elif self.sc_type == 'gsc': # gated skip-connection x = self.act(self.bn1(x)) x1 = self.g_fc1(self.shortcut(X)) x2 = self.g_fc2(x) gate_coef = self.sigmoid(x1 +x2) x = torch.mul(x1, gate_coef) + torch.mul(x2, 1.0-gate_coef) return self.dropout(self.act(self.bn2(x))), A class Encoder(nn.Module): def __init__(self, args): super(Encoder, self).__init__() self.bs = args.batch_size self.molvec_dim = args.molvec_dim self.embedding = self.create_emb_layer([args.vocab_size, args.degree_size, args.numH_size, args.valence_size, args.isarom_size], args.emb_train) self.out_dim = args.out_dim # Graph Convolution Layers with Readout Layer self.gconvs = nn.ModuleList() for i in range(args.n_layer): if i== 0: self.gconvs.append( ResBlock(args.in_dim, self.out_dim, args.use_bn, args.use_attn, args.dp_rate, args.sc_type, args.n_attn_heads, ACT2FN[args.act])) else: self.gconvs.append( ResBlock(self.out_dim, self.out_dim, args.use_bn, args.use_attn, args.dp_rate, args.sc_type, args.n_attn_heads, ACT2FN[args.act])) self.readout = Readout(self.out_dim, self.molvec_dim) # Molecular Vector Transformation self.fc1 = nn.Linear(self.molvec_dim, self.molvec_dim) self.fc2 = nn.Linear(self.molvec_dim, self.molvec_dim) self.fc3 = nn.Linear(self.molvec_dim, self.molvec_dim) self.bn1 = BN1d(self.molvec_dim) self.bn2 = BN1d(self.molvec_dim) self.act = ACT2FN[args.act] self.dropout = nn.Dropout(p=args.dp_rate) def forward(self, input_X, A): x, A, molvec = self.encoder(input_X, A) molvec = self.dropout(self.bn1(self.act(self.fc1(molvec)))) molvec = self.dropout(self.bn2(self.act(self.fc2(molvec)))) molvec = self.fc3(molvec) return x, A, molvec def encoder(self, input_X, A): x = self._embed(input_X) for i, module in enumerate(self.gconvs): x, A = module(x, A) molvec = self.readout(x) return x, A, molvec def _embed(self, x): list_embed = list() for i in range(5): list_embed.append(self.embedding[i](x[:, :, i])) x = torch.cat(list_embed, 2) return x def create_emb_layer(self, list_vocab_size, emb_train=False): list_emb_layer = nn.ModuleList() for i, vocab_size in enumerate(list_vocab_size): vocab_size += 1 emb_layer = nn.Embedding(vocab_size, vocab_size) weight_matrix = torch.zeros((vocab_size, vocab_size)) for i in range(vocab_size): weight_matrix[i][i] = 1 emb_layer.load_state_dict({'weight': weight_matrix}) emb_layer.weight.requires_grad = emb_train list_emb_layer.append(emb_layer) return list_emb_layer #################################### # ===== Classifier & Regressor =====# #################################### class Classifier(nn.Module): def __init__(self, out_dim, molvec_dim, classifier_dim, in_dim, dropout_rate=0.3, act=ACT2FN['relu']): super(Classifier, self).__init__() self.in_dim = in_dim self.out_dim = out_dim self.molvec_dim = molvec_dim self.classifier_dim = classifier_dim self.fc1 = nn.Linear(self.molvec_dim + self.out_dim, self.classifier_dim) self.fc2 = nn.Linear(self.classifier_dim, self.classifier_dim // 2) self.fc3 = nn.Linear(self.classifier_dim // 2, self.in_dim) self.bn1 = BN1d(self.classifier_dim) self.bn2 = BN1d(self.classifier_dim // 2) self.act = act self.dropout = nn.Dropout(p=dropout_rate) self.param_initializer() def forward(self, X, molvec, idx_M): batch_size = X.shape[0] num_masking = idx_M.shape[1] molvec = torch.unsqueeze(molvec, 1) molvec = molvec.expand(batch_size, num_masking, molvec.shape[-1]) list_concat_x = list() for i in range(batch_size): target_x = torch.index_select(X[i], 0, idx_M[i]) concat_x = torch.cat((target_x, molvec[i]), dim=1) list_concat_x.append(concat_x) concat_x = torch.stack(list_concat_x) pred_x = self.classify(concat_x) pred_x = pred_x.view(batch_size * num_masking, -1) return pred_x def classify(self, concat_x): x = self.dropout(self.bn1(self.act(self.fc1(concat_x)))) x = self.dropout(self.bn2(self.act(self.fc2(x)))) x = self.fc3(x) return x def param_initializer(self): nn.init.xavier_normal_(self.fc1.weight.data) nn.init.xavier_normal_(self.fc2.weight.data) class Regressor(nn.Module): def __init__(self, molvec_dim, classifier_dim, num_aux_task, dropout_rate=0.3, act=ACT2FN['relu']): super(Regressor, self).__init__() self.molvec_dim = molvec_dim self.classifier_dim = classifier_dim self.fc1 = nn.Linear(self.molvec_dim, self.classifier_dim) self.fc2 = nn.Linear(self.classifier_dim, self.classifier_dim // 2) self.fc3 = nn.Linear(self.classifier_dim // 2, num_aux_task) self.bn1 = nn.BatchNorm1d(self.classifier_dim) self.bn2 = nn.BatchNorm1d(self.classifier_dim // 2) self.dropout = nn.Dropout(p=dropout_rate) self.act = act self.param_initializer() def forward(self, molvec): x = self.dropout(self.bn1(self.act(self.fc1(molvec)))) x = self.dropout(self.bn2(self.act(self.fc2(x)))) x = self.fc3(x) return torch.squeeze(x) def param_initializer(self): nn.init.xavier_normal_(self.fc1.weight.data) nn.init.xavier_normal_(self.fc2.weight.data) nn.init.xavier_normal_(self.fc3.weight.data)
bab636919505d7343174748045be495955649be3
Afroderrell/Coin-Counter
/cash.py
682
3.921875
4
from cs50 import get_float money = get_float("How much money is owed?") while (money < 0): print("Value must be a dollar amount greater than 0") money = get_float("How much money is owed?") if money > 0: break cents = round(money *100) coin = 0 quarters = 25 dimes = 10 nickels = 5 pennies = 1 while cents > 0: if cents >= quarters: coin += 1 cents = cents - quarters elif cents >= dimes: coin +=1 cents = cents - dimes elif cents >= nickels: coin +=1 cents = cents - nickels elif cents >= pennies: coin +=1 cents = cents - pennies else: print("Number of coins:", coin)
b4eac7c3bcdbd4abc4190a75c0b560887b77825d
yesmkaran/Target-Game
/settings.py
1,142
3.5
4
class Settings: """A class to store all settings for Target.""" def __init__(self): """Initialize the game's static settings.""" # Screen settings self.screen_width = 1000 self.screen_height = 650 self.bg_color = (239, 222, 205) # Ship settings self.ship_left = 3 # Bullet settings self.bullet_height = 3 self.bullet_width = 15 self.bullet_color = (60, 60, 60) self.bullet_allowed = 3 # How quickly the block point values increase self.score_scale = 1.5 # How quickly the game speeds up self.speedup_scale = 1.1 self.initialize_dynamic_settings() def initialize_dynamic_settings(self): """Initialize settings that change throughout the game.""" self.block_speed = 3.0 self.ship_speed = 2.0 self.bullet_speed = 5.5 # Block direction of 1 represents down and -1 otherwise. self.block_direction = 1 # Scoring self.block_points = 20 def increase_speed(self): """Increase speed settings.""" self.block_speed *= self.speedup_scale self.ship_speed *= self.speedup_scale self.bullet_speed *= self.speedup_scale self.block_points = int(self.block_points * self.score_scale)
f6d85ebf342624fd80b1008bfe26c1590471a404
tberhanu/RevisionS
/revision/15.py
486
4.375
4
""" 15. Check if string starts/ends with certain symbols Replace or substitute sth in the middle of the statement """ string = "#starts with the hash!" print(string.startswith("#")) print(string.startswith("#s")) print(string.endswith("!")) print(string.endswith("hash!")) print(string.endswith("@")) print(string.startswith("###")) print(string.startswith("hash")) statement = "Here we go! We just ---- OLD OLD OLD ----- started the game!" print(statement.replace("OLD", "NEW"))
4e457e9e9b7f0b14929b55be130857de1810f4de
nagask/Interview-Questions-in-Python
/UnionFind/FriendsCircle.py
1,660
3.734375
4
class Union: friends = None def __init__(self, i): if isinstance(i, list): self.friends = i else: self.friends = [i] def mergeFriendCircle(self, b): return Union(self.friends + b.friends) def findFriendCircleOf(i, friend_circles): for circle in friend_circles: if i in circle.friends: return circle return None def friendCircles( friends): friend_circles = [] #Putting each person in their own friend circle for i in xrange(len(friends)): friend_circles.append(Union(i)) for i,friendships in enumerate(friends): friend_circle = findFriendCircleOf(i, friend_circles) #Checking who the current person is linked to for j, friend in enumerate(friendships): if i != j: if friend == 'Y': new_friend_circle = findFriendCircleOf(j, friend_circles) #If i and j are not already in the same friend circle, #we merge their friend circles if friend_circle != new_friend_circle: merged_circle = friend_circle.mergeFriendCircle(new_friend_circle) friend_circles.remove(friend_circle) friend_circles.remove(new_friend_circle) friend_circles.append(merged_circle) return len(friend_circles) friends = ['YYNN', 'YYYN', 'NYYN', 'NNNY'] print(friendCircles(friends)) friends = ['YNNNN', 'NYNNN', 'NNYNN', 'NNNYN','NNNNY'] print(friendCircles(friends))
6dbf47f82f0b2ae6dd0673f29fc3956ee8b549ac
andrepadial/Phyton
/SegundaMenorNota/SegundaMenorNota.py
1,597
3.546875
4
from statistics import mean, median, mode, stdev class Aluno: def __init__(self, nome, nota): self.nome = nome self.nota = nota def populaLista(qtd): lista = list() contador = 0 while(contador <= qtd - 1): nome = str(input('Informe o nome do ' + str(contador + 1) + 'o aluno: ')) nota = float(input('Informe a nota do ' + str(contador + 1) + 'o aluno: ')) lista.append(Aluno(nome, nota)) contador += 1 return lista def imprimeAlunos(lista): for al in lista: print(al.nome + ' - ' + str(al.nota)) def removeMenorNota(lista): al = min(lista, key=lambda x: x.nota) listaAux = list() listaAux = filter(lambda x: x.nota != al.nota, lista) return listaAux def getMenor2aNota(lista): menor2 = min(lista, key=lambda z: z.nota) listaAux = list() listaAux = filter(lambda m2: m2.nota == menor2.nota, listAluno) return listaAux def imprimeDados(lista): print('Soma: ' + str(sum(aluno.nota for aluno in lista))) print('Média: ' + str((sum(aluno.nota for aluno in lista) / len(lista)))) data_points = [float(aluno.nota) for aluno in lista] mode([x for x in data_points]) listAluno = list() qtd = int(input('Informe a quantidade de alunos: ')) listAluno = populaLista(qtd) print('Alunos e notas:') imprimeAlunos(listAluno) print('Alunos com a 2a menor nota:') imprimeAlunos(getMenor2aNota(removeMenorNota(listAluno))) print('Estatísticas ') imprimeDados(listAluno)
0d3129e6e20382c80658d210693faa63201b445d
taketakeyyy/atcoder
/abc/131/c4.py
528
3.546875
4
# -*- coding:utf-8 -*- import sys from fractions import gcd def f(a, x): """1以上a以下で、xで割り切れるものの数""" return a // x def lcm(a, b): """ aとbの最小公倍数を返す """ return a*b // gcd(a, b) def solve(): A, B, C, D = list(map(int, sys.stdin.readline().split())) A -= 1 # CでもDでも割り切れないもの b = B - f(B, C) - f(B, D) + f(B, lcm(C, D)) a = A - f(A, C) - f(A, D) + f(A, lcm(C, D)) print(b-a) if __name__ == "__main__": solve()
bbcbb0ea67f34692c049687636d1765b1c562d82
priyancbr/PythonProjects
/StringOperations.py
156
3.59375
4
Word = "I am a python developer" print(Word) Neelam = len(Word) print(f"length of the string word is {Neelam}") print('{lang} rules'.format(lang='Python'))
a0ddcc79ee0c9337bc6630e949312a7b688c8832
Pogotronic/practicepython
/E13 Fibonacci.py
310
4.125
4
times = int(input('How many fibonacci numbers?')) def make_fib(num): fib = [1, 1] if num == 0: fib = [] if num == 1: fib = [1] if num > 1: for i in range(num -2): fib.append(fib[-1] + fib[-2]) print(fib) return fib make_fib(times)
9d0902193024debaee848865586cd84f1fba80c2
xushubo/learn-python
/module-collections.py
1,843
3.609375
4
from collections import namedtuple from collections import deque from collections import defaultdict from collections import OrderedDict from collections import Counter #namedtuple是一个函数,它用来创建一个自定义的tuple对象, #并且规定了tuple元素的个数,并可以用属性而不是索引来引用tuple的某个元素。 Point = namedtuple('Point', ['x', 'y']) p = Point(1, 2) print(p.x, p.y) print(isinstance(p, Point)) print(isinstance(p, tuple)) rectangle_cube = namedtuple('rectangle_cube', ['x', 'y', 'z']) r = rectangle_cube(4, 3, 6) print(r.x, r.y, r.z) #deque是为了高效实现插入和删除操作的双向列表,适合用于队列和栈: q = deque(['x', 'y', 'z']) q.append('a') q.appendleft('b') print(q) print(isinstance(q, deque)) print(isinstance(q, list)) q.pop() print(q) q.popleft() print(q) #使用dict时,如果引用的Key不存在,就会抛出KeyError。如果希望key不存在时,返回一个默认值,就可以用defaultdict: dd = defaultdict(lambda: 'N/A') #注意默认值是调用函数返回的,而函数在创建defaultdict对象时传入。 dd['key1'] = 'abc' print(dd['key1']) print(dd['key2']) print(isinstance(dd, defaultdict)) print(isinstance(dd, dict)) d = dict([('a', 1), ('b', 2), ('c', 3)]) print(d) # dict的Key是无序的 #如果要保持Key的顺序,可以用OrderedDict: od = OrderedDict([('a', 1), ('b', 2), ('c', 3)]) print(od) print(isinstance(od, dict)) #注意,OrderedDict的Key会按照插入的顺序排列,不是Key本身排序: od1 = OrderedDict() od1['z'] = 1 od1['x'] = 2 od1['y'] = 3 print(od1) print(list(od1.keys())) #Counter是一个简单的计数器,例如,统计字符出现的个数: c = Counter() for ch in 'programming': c[ch] = c[ch] + 1 print(c) print(isinstance(c, Counter)) print(isinstance(c, dict))