blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
6e690536e0f66b664e0429851826bdb68eeb4507
hirani/pydec
/pydec/pydec/dec/info.py
1,615
3.625
4
""" DEC data structures ============= Docs should follow this format: Scipy 2D sparse matrix module. Original code by Travis Oliphant. Modified and extended by Ed Schofield and Robert Cimrman. There are four available sparse matrix types: (1) csc_matrix: Compressed Sparse Column format (2) csr_matrix: Compressed Sparse Row format (3) lil_matrix: List of Lists format (4) dok_matrix: Dictionary of Keys format To construct a matrix efficiently, use either lil_matrix (recommended) or dok_matrix. The lil_matrix class supports basic slicing and fancy indexing with a similar syntax to NumPy arrays. To perform manipulations such as multiplication or inversion, first convert the matrix to either CSC or CSR format. The lil_matrix format is row-based, so conversion to CSR is efficient, whereas conversion to CSC is less so. Example: Construct a 10x1000 lil_matrix and add some values to it: >>> from scipy import sparse, linsolve >>> from numpy import linalg >>> from numpy.random import rand >>> A = sparse.lil_matrix((1000, 1000)) >>> A[0, :100] = rand(100) >>> A[1, 100:200] = A[0, :100] >>> A.setdiag(rand(1000)) Now convert it to CSR format and solve (A A^T) x = b for x: >>> A = A.tocsr() >>> b = rand(1000) >>> x = linsolve.spsolve(A * A.T, b) Convert it to a dense matrix and solve, and check that the result is the same: >>> A_ = A.todense() >>> x_ = linalg.solve(A_ * A_.T, b) >>> err = linalg.norm(x-x_) Now we can print the error norm with: print "Norm error =", err It should be small :) """ postpone_import = 1
f5617054ec164da96fe6c2d4b638c9889060bbf0
hirani/pydec
/pydec/pydec/math/parity.py
2,695
4.15625
4
__all__ = ['relative_parity','permutation_parity'] def relative_parity(A,B): """Relative parity between two lists Parameters ---------- A,B : lists of elements Lists A and B must contain permutations of the same elements. Returns ------- parity : integer The parity is 0 if A differs from B by an even number of transpositions and 1 otherwise. Examples -------- >>> relative_parity( [0,1], [0,1] ) 0 >>> relative_parity( [0,1], [1,0] ) 1 >>> relative_parity( [0,1,2], [0,1,2] ) 0 >>> relative_parity( [0,1,2], [0,2,1] ) 1 >>> relative_parity( ['A','B','C'], ['A','B','C'] ) 0 >>> relative_parity( ['A','B','C'], ['A','C','B'] ) 1 """ if len(A) != len(B): raise ValueError("B is not a permutation of A") # represent each element in B with its index in A and run permutation_parity() A_indices = dict(zip(A,range(len(A)))) if len(A_indices) != len(A): raise ValueError("A contains duplicate values") try: perm = [A_indices[x] for x in B] except KeyError: raise ValueError("B is not a permutation of A") return permutation_parity(perm, check_input=False) def permutation_parity(perm, check_input=True): """Parity of a permutation of the integers Parameters ---------- perm : list of integers List containing a permutation of the integers 0...N Optional Parameters ------------------- check_input : boolean If True, check whether the input is a valid permutation. Returns ------- parity : integer The parity is 0 if perm differs from range(len(perm)) by an even number of transpositions and 1 otherwise. Examples -------- >>> permutation_parity( [0,1,2] ) 0 >>> permutation_parity( [0,2,1] ) 1 >>> permutation_parity( [1,0,2] ) 1 >>> permutation_parity( [1,2,0] ) 0 >>> permutation_parity( [2,0,1] ) 0 >>> permutation_parity( [0,1,3,2] ) 1 """ n = len(perm) if check_input: rangen = range(n) if sorted(perm) != rangen: raise ValueError("Invalid input") # Decompose into disjoint cycles. We only need to # count the number of cycles to determine the parity num_cycles = 0 seen = set() for i in range(n): if i in seen: continue num_cycles += 1 j = i while True: assert j not in seen seen.add(j) j = perm[j] if j == i: break return (n - num_cycles) % 2
013436bd90e2eea1b08a5a1036b5d0bcf27b0eb2
bryan-l-serrano/orps
/createGameTable.py
596
3.53125
4
#!/usr/bin/python import sqlite3 import os conn = sqlite3.connect('/orps/orps.db') print('opened database') cursor = conn.cursor() cursor.execute("DROP TABLE IF EXISTS GAME") sqlCommand = '''CREATE TABLE GAME( gameID CHAR(20) PRIMARY KEY NOT NULL, player1ID CHAR(20) NOT NULL, player2ID CHAR(20) NOT NULL, winPlayerID CHAR(20) NOT NULL, status CHAR(20) NOT NULL, player1Throw CHAR(15) NOT NULL, player2Throw CHAR(15) NOT NULL, round INT NOT NULL, player1WinCount INT NOT NULL, player2WinCount INT NOT NULL )''' cursor.execute(sqlCommand) conn.commit() print('created table') conn.close()
928075c697bfcaa849fb2e399858ca45653a3263
t00n/DiscoveryTripToMusic
/src/memoize.py
1,300
3.78125
4
import collections import functools class memoized(object): '''Decorator. Caches a function's return value each time it is called. If called later with the same arguments, the cached value is returned (not reevaluated). ''' def tuplize(self, something): if isinstance(something, list) or isinstance(something, tuple): something = tuple([self.tuplize(elem) for elem in something]) return something def __init__(self, func): self.func = func self.cache = {} def __call__(self, *args): args = self.tuplize(args) if not isinstance(args, collections.Hashable): # uncacheable. a list, for instance. # better to not cache than blow up. return self.func(*args) if args in self.cache: # print("Using memoized %s with args %s" % (self.func.__name__, str(args))) return self.cache[args] else: # print("Memoizing %s with args %s" % (self.func.__name__, str(args))) value = self.func(*args) self.cache[args] = value return value def __repr__(self): '''Return the function's docstring.''' return self.func.__doc__ def __get__(self, obj, objtype): '''Support instance methods.''' return functools.partial(self.__call__, obj)
9a45a3d526d8619fd9b3a9203d316ee80e7bdf37
Zferi/new-project
/Задания евгения евтушенко/lesson 1/second tusk.py
222
3.546875
4
a = int(input("Enter your second: ")) h = str(a // 3600) m = (a // 60) % 60 s = a % 60 if m < 10: m = '0' + str(m) else: m = str(m) if s < 10: s = '0' + str(s) else: s = str(s) print(h + ':' + m + ':' + s)
03514eee4dc6b2a770d4521e6bd79a031ea33714
IulianStave/demosqlpy
/tkint.py
856
3.765625
4
# Tkinter widgets, states from tkinter import * def convert_from_kg(): grams = 1000 * float(e1_value.get()) t1.delete("1.0", END) t1.insert(END, grams) pounds = 2.20462 * float(e1_value.get()) t2.delete("1.0", END) t2.insert(END, pounds) ounces = 35.274 * float(e1_value.get()) t3.delete("1.0", END) t3.insert(END, ounces) window = Tk() b1 = Button(window, text = "Convert", command = convert_from_kg) b1.grid(row = 0, column = 2) l1 = Label(window, text = "Kg") l1.grid(row = 0, column = 0) e1_value = StringVar() e1 = Entry(window, textvariable=e1_value) e1.grid(row = 0, column = 1) t1 = Text(window, height = 1, width = 20) t1.grid(row=1, column =0) t2 = Text(window, height = 1, width = 20) t2.grid(row=1, column =1) t3 = Text(window, height = 1, width = 20) t3.grid(row=1, column =2) window.mainloop()
c350c7a32906c9097098cdf949251fa03acbb4c0
panghu-art/Sandwich-pie
/列表推导式小实验.py
158
3.734375
4
list1=[] for x in range(10): for y in range(10): if x % 2 ==0: if y % 2 != 0: list1.append((x,y)) print(list1)
609b238fdd5e689ec20cddb76b4569f15298efef
panghu-art/Sandwich-pie
/字符串中子字符串出现的次数.py
516
3.515625
4
def findstr(str1,str2): '''这是一个寻找字符串中子字符串出现次数的函数''' k=0 if len(str2) != 2: print('不好意思,第二个参数长度必须为2,请重新调用!') else: for b in range(len(str1)): if str1[b]==str2[0]: if str1[b+1]==str2[1]: k += 1 return k print(findstr('fashljkfhasjkfhasjkldfhashfasdhfjklhasjklf','as'))
fbb2a15911d7c8821bc9fd9fa4bd6b9ed0e18fbd
panghu-art/Sandwich-pie
/十进制转化为二进制参数.py
488
3.703125
4
def bind(num): '''这是一个将十进制转化为二进制的函数 if num in(0,1): d=str(num) else: d='' while num not in (0,1): d=(str(num%2))+d num=num//2 d=str(num)+d return(d) print(bind(8))''' y=1 z=[] b='' while y != 0: y=num//2 z.append(num%2) num=y z.reverse() for i in z: b=b+str(i) return(b) print(bind(100))
c9e763d504810d7bc5e305f45c5c519040de90f3
lauraromerosantos/TarefaExtra_Algoritmos_Programacao_I
/tarefa_extra.py
5,611
4.0625
4
agenda = {'ivonei':['1111'], 'maria':['2222'], 'pedro': ['3333'],'aaa':['999991111','999992222','999993333']} def ler_telefone(telefones = []): def entrar_outro_numero(): resposta = input('Entrar outro número? s/n: ') if resposta.upper() == 'S': return True return False """ Na função acima é criado a lista 'telefones', e pergunta se o usuário quer adicionar outro numero de telefone, se a resposta for sim ele executa o código abaixo: """ telefone = input(' Entre o Telefone: ') if len(telefone) == 9: if telefone.isnumeric(): telefones.append(telefone) if entrar_outro_numero(): return ler_telefone(telefones) else: return telefones else: input(' Número deve conter apenas dígitos numéricos. [Enter] ') else: input(' Número deve ter 9 dígitos. [Enter] ') return ler_telefone() """ No código acima pede-se para digitar o numero de telefone, se houver 9 digitos, verifica se é numérico e adiciona o numero em 'telefone', perguntar se deseja adicionar outro numero, se sim retorna para a função 'ler_telefone', se não, mostra os telefones. Se não for numerico e nao tiver 9 digitos sai da função. """ def insere(): # print('- - - Insere nome na Agenda - - -') print('Insere nome na Agenda'.center(35,'-')) while True: print('[Enter] finaliza o cadastro') nome = input('Nome: ') if nome: if nome not in agenda: agenda[nome] = ler_telefone() else: input(' Nome Já cadastrado na Agenda. [Enter] ') else: break """ Na função acima pede-se para adicionar nome na agenda, se o nome ainda nao estiver na agenda, executa 'ler_telefone' caso ja tenha o nome na agenda aparece mensagem que já está cadastrado. """ def alterar_nome_telefone(): resposta = input(''' -------------------------- O que você deseja alterar: -------------------------- 1 - Nome 2 - Telefone Escolha: ''') if resposta not in ('1','2'): return alterar_nome_telefone return resposta """ Função para alterar o nome ou telefone """ def alterar_nome(nome): novo_nome = input('...[Enter] - Retorna\n...Digite o nome correto: ') if novo_nome: if novo_nome in agenda: input('...Este nome já consta na agenda! ') else: agenda[novo_nome] = agenda[nome] del(agenda[nome]) """ Para alterar o nome, digitar o novo nome se já estiver na agenda aparece mensagem que já consta na agenda se não adiciona o novo nome na agenda """ def alterar_telefone(nome): print('...Escolha o telefone: ') telefones = agenda[nome] for ind,fone in enumerate(telefones): print(f'...{ind} - {fone}') escolha = int(input(' Escolha pelo indice: ')) if escolha >= 0 and escolha <= len(telefones): telefones.pop(escolha) agenda[nome] = ler_telefone(telefones) print(agenda) """ Para alterar o telefone, verifica o numero na agenda escolhe o telefone pelo indice, se a escolha for maior ou igual a zero e a quantidade(telefones) executa a alteração abaixo """ def alterar(): print('Altera Agenda'.center(35,'-')) while True: print('[Enter] finaliza a alteração') nome = input('Nome para alterar: ') # se for digitado enter. o conteúdo é nulo if nome: # nome é válido if nome in agenda: # nome está na agenda? if alterar_nome_telefone() == '1': # Alterar Nome alterar_nome(nome) else: alterar_telefone(nome) print(agenda) else: input('Nome não consta na agenda. [Enter]') else: # nome NÃO válido break def excluir(): print('Excluir'.center(35,'-')) nome = input('Nome para excluir: ') if nome in agenda: confirma = input(f'...Confirma a exclusão {nome}? s/n: ') if confirma.upper() == 'S': del(agenda[nome]) input('...Nome Excluido...[Enter]') else: input('Nome não consta na agenda. [Enter]') print(agenda) """ Na função acima, digitar o nome para excluir, verifica se o nome consta na agenda, confirma a exclusão com sim ou não se S, excluir o nome. Se o nome nao consta na agenda, aparece mensagem e mostra agenda """ def menu(): resposta = input(''' +---------------------------------+ | Menu Principal | +---------------------------------+ | 0 - Finalizar | | 1 - Inserir Dados na Agenda | | 2 - Alterar Telefone | | 3 - Excluir Pessoa na Agenda | | 4 - Mostrar Agenda | +---------------------------------+ Escolha: ''') if resposta in ('0','1','2','3','4'): return resposta input('Escolha incorreta. [Enter] - Tente Novamente.') return menu() def imprime_agenda(): print('Agenda'.center(35,'-')) for nome,fones in agenda.items(): telefones = str(fones).strip("[]").replace("'","") print(f' {nome.ljust(15,".")} - {telefones}') ##################################### # Programa Principal # while True: escolha = menu() if escolha == '1': insere() elif escolha == '2': alterar() elif escolha == '3': excluir() elif escolha == '4': imprime_agenda() else: break print('Fim')
2ef55f75319d760f4fc37ff6512faab00ef15507
Dididoo12/Dominos
/Domino GUI.py
28,682
4.46875
4
# Date: November 14, 2017 # Author: Edward Tang # Purpose: This program is designed to display a set of dominoes with different properties. # Input: Mouse and/or Keyboard # Output: Screen, Console and/or GUI # ========================================================================================== from tkinter import * import random # Date: November 14, 2017 # Author: Edward Tang # Purpose: This class is intended to be used to edit (through randomization, flippin or programmer/user input) # domino values, and display them through text or a GUI interface. # Field Data: # value - Correlates to the combined value of the two halves of the domino # size - Correlates to the size of one half of the domino # diameter - Correlates to the diameter of one dot on the domino # gap - Correlates to the gap distance between each dot on the domino, and each dot from the domino's sides # orientation - Correlates to the angle of the domino (either horizontal or vertical) # faceup - Correlates to the shown face of the domino (either the blank or dotted side) # Methods: # __str__() - This method is designed to return the domino's "value" field as a string. # getValue() - This method is designed to receive an integer value from the user, ensure it would create a valid domino and return the value. # setValue() - This method is designed to receive an integer and set the domino object's "value" field to it if the value would create a valid domino. Otherwise, "value" is set to 0. # flip() - This method is designed to swap the "left" and "right" values of the domino object (1-5 -> 5-1). # setOrientation() - This method is designed to receive an orientation value and set the domino object's "orientation" field to it if it is either "horizontal" or "vertical" (defaults to "horizontal"). # setSize() - This method is designed to receive a size value and set the domino object's "size", "diameter" and "gap" fields based on it if it is between 30 and 100 (default 30). # setFace() - This method is designed to receive a faceup value and set the domino object's "faceup" field to it if it is a boolean (default True) # randomize() - This method is designed to set the domino object's "value" field to a random valid value. # drawDots() - This method is designed to receive a num value and create an array of dot positions based on it. # It will then create the dots of the domino object based on X and Y parameters and the domino # object's "diameter" and "gap" fields. # draw() - This method is designed to display the two halves of the domino object, drawing the dots on them if # the object's "faceup" field is True or colouring them gray if the object's "faceup" value is False. # drawDominoVariations() - This method is designed to delete all shapes in the Canvas widget and display the domino object, # its flipped version, its vertical version and its facedown version. # getValidInteger() - This method is designed to ask the user for an integer and perform checks to make sure the integer is within a certain range. # orderAscending() - This method is designed to return the the Domino object value arranged to be ascending. # __add__() - This method is designed to return the sum of the Domino object value and a second Domino object value, both ascending. # __sub__() - This method is designed to return the difference of the Domino object value and a second Domino object value, both ascending. # __mul__() - This method is designed to return the product of the Domino object value and a second Domino object value, both ascending. # __gt__() - This method is designed to determine whether or not the Domino object value is greater than a second Domino object's value, with both values ascending. # __lt__() - This method is designed to determine whether or not the Domino object value is less than a second Domino object's value, with both values ascending. # __ge__() - This method is designed to determine whether or not the Domino object value is greater than or equal to a second Domino object's value, with both values ascending. # __le__() - This method is designed to determine whether or not the Domino object value is less than or equal to a second Domino object's value, with both values ascending. # __eq__() - This method is designed to determine whether or not the Domino object value is equal to a second Domino object's value, with both values ascending. # __ne__() - This method is designed to determine whether or not the Domino object value is unequal to a second Domino object's value, with both values ascending. # ============================================================================================================================================================================================================= class Domino: def __init__(self,value=random.randint(0,66),size=30,orientation="horizontal",faceup=True): while value%10 > 6 or value//10 > 6: value = random.randint(0,66) self.value = value if size < 30 or size > 100: self.size = 30 else: self.size = size self.diameter = self.size / 5 self.gap = self.diameter / 2 if orientation != "horizontal" and orientation != "vertical": self.orientation = "horizontal" else: self.orientation = orientation if faceup != True and faceup != False: faceup = True else: self.faceup = faceup # Date: November 14, 2017 # Author: Edward Tang # Purpose: This method is designed to return the domino's "value" field as a string. # Input: N/A # Output: [STRING] The domino's value # =================================================================================== def __str__(self): return str(self.value) # Date: November 14, 2017 # Author: Edward Tang # Purpose: This method is designed to receive an integer value from the user, ensure it # would create a valid domino and return the value. # Input: Keyboard # Output: Console/Screen, [INTEGER] A valid value for the domino # =============================================================================================== def getValue(self): tempValue = self.getValidInteger("Enter the value of the domino","0","66") while tempValue%10 > 6 or tempValue//10 > 6: print("Neither digit can be greater than 6! Please try again.") print() tempValue = self.getValidInteger("Enter the value of the domino","0","66") return tempValue # Date: November 14, 2017 # Author: Edward Tang # Purpose: This method is designed to receive an integer and set the domino object's "value" field to # it if the value would create a valid domino. Otherwise, "value" is set to 0. # Input: [INTEGER] A number value # Output: Console/Screen # ============================================================================================================ def setValue(self,num): if num%10 <= 6 and num//10 <= 6: self.value = num else: self.value = 0 # Date: November 14, 2017 # Author: Edward Tang # Purpose: This method is designed to swap the "left" and "right" values of the domino object (1-5 -> 5-1). # Input: N/A # Output: N/A # ========================================================================================================== def flip(self): self.value = self.value % 10 * 10 + self.value // 10 # Date: November 14, 2017 # Author: Edward Tang # Purpose: This method is designed to receive an orientation value and set the domino object's "orientation" # field to it if it is either "horizontal" or "vertical" (defaults to "horizontal"). # Input: [STRING] Orientation value # Output: Console/Screen # =========================================================================================================== def setOrientation(self,value="horizontal"): if value == "horizontal" or value == "vertical": self.orientation = value else: self.orientation = "horizontal" # Date: November 14, 2017 # Author: Edward Tang # Purpose: This method is designed to receive a size value and set the domino object's "size", "diameter" and # "gap" fields based on it if it is between 30 and 100 (default 30). # Input: [INTEGER] Size value # Output: Console/Screen # ============================================================================================================ def setSize(self,value=30): if value >= 30 and value <= 100: self.size = value else: self.size = 30 self.diameter = self.size / 5 self.gap = self.diameter / 2 # Date: November 14, 2017 # Author: Edward Tang # Purpose: This method is designed to receive a faceup value and set the domino object's "faceup" field to it # if it is a boolean (default True) # Input: [BOOLEAN] Faceup value # Output: Console/Screen # ============================================================================================================ def setFace(self,value=True): if value == True or value == False: self.faceup = value else: self.faceup = True # Date: November 14, 2017 # Author: Edward Tang # Purpose: This method is designed to set the domino object's "value" field to a random valid value. # Input: N/A # Output: N/A # ============================================================================================================ def randomize(self): self.value = random.randint(0,66) while self.value%10 > 6 or self.value//10 > 6: self.value = random.randint(0,66) # Date: November 14, 2017 # Author: Edward Tang # Purpose: This method is designed to receive a num value and create an array of dot positions based on it. # It will then create the dots of the domino object based on X and Y parameters and the domino # object's "diameter" and "gap" fields. # Input: [INTEGER] Num, X and Y values # Output: Screen (GUI), console # References: Canvas widget # =========================================================================================================== def drawDots(self,num,x,y,canvas): if num >= 0 and num <= 6: dotNums = [] if num == 1: dotNums = [5] elif num == 2 and self.orientation == "horizontal": dotNums = [1,9] elif num == 2 and self.orientation == "vertical": dotNums = [3,7] elif num == 3 and self.orientation == "horizontal": dotNums = [1,5,9] elif num == 3 and self.orientation == "vertical": dotNums = [3,5,7] elif num == 4: dotNums = [1,3,7,9] elif num == 5: dotNums = [1,3,5,7,9] elif num == 6 and self.orientation == "horizontal": dotNums = [1,2,3,7,8,9] elif num == 6 and self.orientation == "vertical": dotNums = [1,4,7,3,6,9] elif num == 7 and self.orientation == "horizontal": dotNums = [1,2,3,5,7,8,9] elif num == 7 and self.orientation == "vertical": dotNums = [1,4,7,5,3,6,9] elif num == 8: dotNums = [1,2,3,4,6,7,8,9] elif num == 9: dotNums = [1,2,3,4,5,6,7,8,9] position1 = self.gap position2 = self.gap*2 + self.diameter position3 = self.gap*3 + self.diameter*2 if 1 in dotNums: canvas.create_oval(x+position1,y+position1,x+position1+self.diameter,y+position1+self.diameter,fill="black") if 2 in dotNums: canvas.create_oval(x+position2,y+position1,x+position2+self.diameter,y+position1+self.diameter,fill="black") if 3 in dotNums: canvas.create_oval(x+position3,y+position1,x+position3+self.diameter,y+position1+self.diameter,fill="black") if 4 in dotNums: canvas.create_oval(x+position1,y+position2,x+position1+self.diameter,y+position2+self.diameter,fill="black") if 5 in dotNums: canvas.create_oval(x+position2,y+position2,x+position2+self.diameter,y+position2+self.diameter,fill="black") if 6 in dotNums: canvas.create_oval(x+position3,y+position2,x+position3+self.diameter,y+position2+self.diameter,fill="black") if 7 in dotNums: canvas.create_oval(x+position1,y+position3,x+position1+self.diameter,y+position3+self.diameter,fill="black") if 8 in dotNums: canvas.create_oval(x+position2,y+position3,x+position2+self.diameter,y+position3+self.diameter,fill="black") if 9 in dotNums: canvas.create_oval(x+position3,y+position3,x+position3+self.diameter,y+position3+self.diameter,fill="black") # Date: November 14, 2017 # Author: Edward Tang # Purpose: This method is designed to display the two halves of the domino object, drawing the dots on them if # the object's "faceup" field is True or colouring them gray if the object's "faceup" value is False. # Input: [INTEGER] X and Y values # Output: Screen (GUI) # References: Canvas widget # ================================================================================================================ def draw(self,x,y,canvas): if self.faceup == True: dominoA = canvas.create_rectangle(x,y,x+self.size,y+self.size,fill="white") self.drawDots(self.value//10,x,y,canvas) if self.orientation == "horizontal": dominoB = canvas.create_rectangle(x+self.size,y,x+self.size*2,y+self.size,fill="white") self.drawDots(self.value%10,x+self.size,y,canvas) else: dominoB = canvas.create_rectangle(x,y+self.size,x+self.size,y+self.size*2,fill="white") self.drawDots(self.value%10,x,y+self.size,canvas) else: if self.orientation == "horizontal": dominoA = canvas.create_rectangle(x,y,x+self.size*2,y+self.size,fill="#e0e0e0") else: dominoA = canvas.create_rectangle(x,y,x+self.size,y+self.size*2,fill="#e0e0e0") # Date: November 14, 2017 # Author: Edward Tang # Purpose: This method is designed to delete all shapes in the Canvas widget and display the domino object, # its flipped version, its vertical version and its facedown version. # Output: Screen (GUI) # References: Canvas widget # ========================================================================================================== def drawDominoVariations(self,canvas): canvas.delete(ALL) self.setSize(sliderSize.get()) self.setFace(True) self.orientation = "horizontal" self.draw(10,10,canvas) self.flip() self.draw(dom.size*2 + 30,10,canvas) self.flip() self.orientation = "vertical" self.draw(dom.size*4 + 50,10,canvas) self.setFace(False) self.draw(dom.size*5 + 70,10,canvas) # Date: November 10, 2017 # Author: Edward Tang # Purpose: This method is designed to ask the user for an integer and perform checks to make sure the integer # is within a certain range. # Input: Keyboard, [STRING] The input prompt phrase, [INTEGER] the lowest possible value and the highest # possible value # Output: Console/Screen, [INTEGER] The user-inputted number # ============================================================================================================= def getValidInteger(self, prompt="Enter an integer", low = "", high = ""): if low.isdigit() and high.isdigit(): low = int(low) high = int(high) intUserInput = low - 1 while intUserInput < low or intUserInput > high: strUserInput = "" while not strUserInput.isdigit(): strUserInput = input(prompt + " between " + str(low) + " and " + str(high) + ": ") print() if not strUserInput.isdigit(): print("[ERROR] You did not enter a valid integer! Please try again.") print() intUserInput = int(strUserInput) if intUserInput < low or intUserInput > high: print("[ERROR] You did not enter an integer between " + str(low) + " and " + str(high) + ". Please try again.") print() return intUserInput elif low.isdigit() and not high.isdigit(): low = int(low) intUserInput = low - 1 while intUserInput < low: strUserInput = "" while not strUserInput.isdigit(): strUserInput = input(prompt + " of at least " + str(low) + ": ") print() if not strUserInput.isdigit(): print("[ERROR] You did not enter a valid integer! Please try again.") print() intUserInput = int(strUserInput) if intUserInput < low: print("[ERROR] You did not enter an integer of at least " + str(low) + ". Please try again.") print() return intUserInput # Date: December 10, 2017 # Author: Edward Tang # Purpose: This method is designed to return the the Domino object value arranged to be ascending. # Input: N/A # Output: [INTEGER] A value for the Domino Object # ================================================================================================================================ def orderAscending(self): value = self.value if self.value//10 > self.value%10: value = self.value%10*10 + self.value//10 return value # Date: December 10, 2017 # Author: Edward Tang # Purpose: This method is designed to return the sum of the Domino object value and a second Domino object value, both ascending. # Input: A second Domino object name # Output: [INTEGER] The sum of the two Domino object values # ================================================================================================================================ def __add__(self,secondObject): return self.orderAscending() + secondObject.orderAscending() # Date: December 10, 2017 # Author: Edward Tang # Purpose: This method is designed to return the difference of the Domino object value and a second Domino object value, both ascending. # Input: A second Domino object name # Output: [INTEGER] The difference of the two Domino object values # ======================================================================================================================================= def __sub__(self,secondObject): return self.orderAscending() - secondObject.orderAscending() # Date: December 10, 2017 # Author: Edward Tang # Purpose: This method is designed to return the product of the Domino object value and a second Domino object value, both ascending. # Input: A second Domino object name # Output: [INTEGER] The product of the two Domino object values # ==================================================================================================================================== def __mul__(self,secondObject): return self.orderAscending() * secondObject.orderAscending() # Date: December 10, 2017 # Author: Edward Tang # Purpose: This method is designed to determine whether or not the Domino object value is greater than a # second Domino object's value, with both values ascending. # Input: A second Domino object name # Output: [BOOLEAN] True or False depending on whether or not the Domino object's value is greater than # that of the second # ================================================================================================================================ def __gt__(self,secondObject): isGreater = False if self.orderAscending() > secondObject.orderAscending(): isGreater = True return isGreater # Date: December 10, 2017 # Author: Edward Tang # Purpose: This method is designed to determine whether or not the Domino object value is less than a # second Domino object's value, with both values ascending. # Input: A second Domino object name # Output: [BOOLEAN] True or False depending on whether or not the Domino object's value is less than # that of the second # ===================================================================================================== def __lt__(self,secondObject): isLesser = False if self.orderAscending()< secondObject.orderAscending(): isLesser = True return isLesser # Date: December 10, 2017 # Author: Edward Tang # Purpose: This method is designed to determine whether or not the Domino object value is greater than or # equal to a second Domino object's value, with both values ascending. # Input: A second Domino object name # Output: [BOOLEAN] True or False depending on whether or not the Domino object's value is greater than # or equal to that of the second # ========================================================================================================= def __ge__(self,secondObject): isGreaterOrEqual = False if self.orderAscending()>= secondObject.orderAscending(): isGreaterOrEqual = True return isGreaterOrEqual # Date: December 10, 2017 # Author: Edward Tang # Purpose: This method is designed to determine whether or not the Domino object value is less than or # equal to a second Domino object's value, with both values ascending. # Input: A second Domino object name # Output: [BOOLEAN] True or False depending on whether or not the Domino object's value is less than # or equal to that of the second # ========================================================================================================= def __le__(self,secondObject): isLesserOrEqual = False if self.orderAscending() <= secondObject.orderAscending(): isLesserOrEqual = True return isLesserOrEqual # Date: December 10, 2017 # Author: Edward Tang # Purpose: This method is designed to determine whether or not the Domino object value is equal to # a second Domino object's value, with both values ascending. # Input: A second Domino object name # Output: [BOOLEAN] True or False depending on whether or not the Domino object's value is equal to # that of the second # ================================================================================================== def __eq__(self,secondObject): isEqual = False if self.orderAscending() == secondObject.orderAscending(): isEqual = True return isEqual # Date: December 10, 2017 # Author: Edward Tang # Purpose: This method is designed to determine whether or not the Domino object value is unequal to # a second Domino object's value, with both values ascending. # Input: A second Domino object name # Output: [BOOLEAN] True or False depending on whether or not the Domino object's value is unequal to # that of the second # ==================================================================================================== def __ne__(self,secondObject): notEqual = False if self.orderAscending() != secondObject.orderAscending(): notEqual = True return notEqual # Date: November 17, 2017 # Author: Edward Tang # Purpose: This program is designed to create a window with six labels and a close button. # Input: Title name, six string values and the width and height of the window # Output: Screen # ======================================================================================================== def window6Labels(title,text1,text2,text3,text4,text5,text6,width,height): window = Toplevel(main) window.title(title) window.resizable(False,False) window.config(width=width,height=height,bg="#fcfcfc") ws = main.winfo_screenwidth() hs = main.winfo_screenheight() x = (ws/2) - (width/2) y = (hs/2) - (height/2) window.geometry('%dx%d+%d+%d' % (width, height, x, y)) window.grab_set() Label(window,text=text1,font=("Arial",12,"bold"),bg="#fcfcfc").place(x=5,y=5) Label(window,text=text2,font=("Arial",10,"normal"),bg="#fcfcfc").place(x=5,y=30) Label(window,text=text3,font=("Arial",10,"normal"),bg="#fcfcfc").place(x=5,y=55) Label(window,text=text4,font=("Arial",10,"normal"),bg="#fcfcfc").place(x=5,y=80) Label(window,text=text5,font=("Arial",10,"normal"),bg="#fcfcfc").place(x=5,y=105) Label(window,text=text6,font=("Arial",10,"normal"),bg="#fcfcfc").place(x=5,y=130) Button(window,text="Close",font=("Arial",10,"bold"),relief=FLAT,cursor="hand2",command=lambda:window.destroy(),bg="tomato2").place(x=width-60,y=height-40) #MAIN CODE dom = Domino(value=12) main = Tk() main.title("Domino Generator") display = Canvas(main,width=680,height=223,relief=FLAT) display.place(x=210,y=20) sliderSize = IntVar() sliderSize.set(100) #"Size" Label Label(main,text="Size",font=("Arial",12,"bold"),fg="white",bg="gray").place(x=85,y=45) #"Size" Slider Scale(main,variable=sliderSize,command=lambda _:dom.drawDominoVariations(display),font=("Arial",11,"bold"),orient="horizontal",cursor="hand2",bg="gray",fg="white",troughcolor="light gray",bd=0,highlightthickness=0,length=180,sliderlength=30,from_=30,to=100).place(x=15,y=70) #"Randomize" Button Button(main,text="Randomize (R)",width=17,cursor="hand2",font=("Arial",12,"bold"),relief=FLAT,bg="chartreuse3",command=lambda:(dom.randomize(),dom.drawDominoVariations(display))).place(x=15,y=135) #"Exit" Button Button(main,text="Exit (F4)",width=17,font=("Arial",12,"bold"),bg="#ce3e1a",relief=FLAT,command=lambda:main.destroy()).place(x=15,y=180) menu = Menu(main) #"File" Menu fileMenu = Menu(menu) fileMenu.add_command(label="Clear Display (C)",command=lambda:display.delete(ALL)) fileMenu.add_command(label="Exit (F4)",command=lambda:main.destroy()) menu.add_cascade(label="File", menu=fileMenu) #"Help" Menu helpMenu = Menu(menu,tearoff=0) helpMenu.add_command(label="About",command=lambda:window6Labels("About","Domino Generator","Version: 1.0","Author: Edward Tang","E-Mail: 335433173@gapps.yrdsb.ca","","",300,110)) helpMenu.add_command(label="Hotkeys",command=lambda:window6Labels("Hotkeys","Hotkeys:","R = Randomize Domino Value","Left/Right Arrow = Adjust Domino Size by 1","Up/Down Arrow = Adjust Domino Size by 10","C = Clear Display","F4 = Exit Program",300,160)) menu.add_cascade(label="Help", menu=helpMenu) main.config(width=915,height=267,bg="gray",menu=menu) main.bind("<r>",lambda _:(dom.randomize(),dom.drawDominoVariations(display))) main.bind("<Left>",lambda _:(sliderSize.set(sliderSize.get()-1),dom.drawDominoVariations(display))) main.bind("<Right>",lambda _:(sliderSize.set(sliderSize.get()+1),dom.drawDominoVariations(display))) main.bind("<Down>",lambda _:(sliderSize.set(sliderSize.get()-10),dom.drawDominoVariations(display))) main.bind("<Up>",lambda _:(sliderSize.set(sliderSize.get()+10),dom.drawDominoVariations(display))) main.bind("<c>",lambda _:display.delete(ALL)) main.bind("<F4>",lambda _:main.destroy()) mainloop()
02da3a9e84fd015751a88d76edc96fc231581ffa
wu-wen-chi/Python-first-midtern
/52.py
255
3.671875
4
n=int(input('輸入n值:')) a={} for i in range(1,n+1): name=input('請輸入姓名:') mail=input('請輸入電子郵件:') a[name]=mail s=input('請輸入要查詢電子郵件的姓名:') if s in a: print('電子郵件帳號為:',a[name])
3aeaabc50c9b318eadfc1414006c36c83ad3cff2
wu-wen-chi/Python-first-midtern
/21.py
459
3.546875
4
n=int(input("輸入查詢組數n為:")) for i in range(1,n+1): a,b=input("帳號 密碼:").split() if a=="123" and b=="456": print("9000") elif a=="456" and b=="789": print("5000") elif a=="789" and b=="888": print("6000") elif a=="336" and b=="558": print("10000") elif a=="775" and b=="666": print("12000") elif a=="556" and b=="221": print("7000") else: print("error")
9dfa89305cf8368a3b6ab59f26050b2de56cbc36
wu-wen-chi/Python-first-midtern
/44.py
136
3.671875
4
m=int(input("月:")) d=int(input("日:")) s=(m*2+d)%3 if s==0: print("普通") elif s==1: print("吉") else: print("大吉")
1442f234e5cffc65736b2bf937468d04653c46d1
ashwynh21/rnn
/declarations/memory.py
1,142
3.796875
4
""" We define this class to store the (state, action reward, next) of a particular move """ from collections import deque from typing import List from random import sample from declarations.experience import Experience class Memory: __memory: deque __size: int def __init__(self, batch: int): self.__batch = batch self.__size = batch * 2 self.__memory = deque(maxlen=self.__size) def remember(self, experience: Experience): # first we check if the memory isnt full. if len(self.__memory) == self.__size - 1: # the we pop the end and push to the front. for s in sample(self.__memory, self.__batch): self.__memory.remove(s) return self.__memory.append(experience) def recall(self, size: int) -> List[Experience]: # this function is to sample the memory of the deque object. return sample(self.__memory, size) def size(self) -> int: return len(self.__memory) def maxsize(self) -> int: return self.__batch def isready(self) -> bool: return len(self.__memory) >= self.__batch
617951a21854ea31108f421afa9ebd16738c0282
ashwynh21/rnn
/declarations/action.py
646
3.671875
4
""" We define the class Action to allow us to abstract functions into the action made by our models. """ from typing import List import numpy as np from sklearn.preprocessing import MinMaxScaler scalar = MinMaxScaler() class Action(object): probabilities: List[List[List[List[float]]]] random: bool def __init__(self, action: List[List[List[List[float]]]], random=True): self.probabilities = action self.action = np.argmax(action) self.random = random def normalize(self) -> np.array: return [[[scalar.fit_transform(np.array(self.probabilities[0][0][0]).reshape(-1, 1)).flatten().tolist()]]]
831bc88da89c2c351ed109ae13eb4ea26393cc0a
Itamar-S/Connect-4
/main.py
16,113
3.6875
4
# Importing the colored function from the termcolor libery for multicolored board # Then importing the choice function from the random libery for the Random player # Finally importing the inf const from the math library for the Alpha Beta Pruning (to economize the maximum and minimum score calculation) from termcolor import colored from random import choice from math import inf class Board: """ A class used to represent a board ... Methods ------- clone() Returns a copy of the board to_string() Returns the board as a multicolored string place_mark(marker, col) Placing a marker in the board at the given column legal_move(col) Returns a boolean value indicating whether the move is legal is_winner(marker) Returns a boolean value indicating whether the given marker is a winner check_lines(marker, n) Returns the number of lines that complex from the given marker in length of n is_draw() Returns a boolean value indicating whether there is a tie get_score(player) Returns an integer value indicating the score of the board for the given player """ def __init__(self): """The constructor method creates an empty board using list comprehension""" self.board = [['_' for j in range(6)] for i in range(7)] def clone(self): """The clone method returns a copy of the board""" # Creating a new empty Board object clone = Board() # Using a nested loop every cell in the new board accepts the value of the original board's cell for col in range(7): for row in range(6): clone.board[col][row] = self.board[col][row] return clone def to_string(self): """Returns a string representation of the board""" # Creating the top row of the board board_string = '_____________________________\n' # Using nested loop for every row the loop going through all the columns for row in range(6): for col in range(7): if self.board[col][row] == '_': """In case the cell is empty If the cell is empty (represented by a underscore) we add to the board_string a vertical bar, a starting underscore, the empty cell's sign (another underscore) and a ending underscore. """ board_string += '|___' else: """ Otherwise we add to the board_string a vertical bar, a starting underscore, a circle ('●') that colored (with the colored function) in red if the marker is 'X' else yellow and a ending underscore. """ board_string += '|_' + colored('●', 'red' if self.board[col][row] == 'X' else 'yellow') + '_' # In the end of every row we add to the board_string a vertical bar # and a new line sign ('\n') except if it is the last row. board_string += '|\n' if row < 5 else '|' return board_string def place_mark(self, marker, col): """Adding to the given column the given marker. Parameters ---------- marker : str The marker that will be placed col : int The column to which the marker will be added Raises ------ ValueError If the given column is not in the range of 0-6. Returns ------- boolean a boolean value indicating if the marker's owner winned """ if col < 0 or col > 6: raise ValueError() # The lopp is going from the bottom of the column to the to the top for row in range(5, -1, -1): # For every cell in column, if the cell is empty we set his value to the given marker and break the loop if self.board[col][row] == '_': self.board[col][row] = marker break return self.is_winner(marker) def legal_move(self, col): """Check if there is an empty cell in the given column Parameters ---------- col : int The column that need to check legality Returns ------- boolean a boolean value indicating if there is an empty cell in the given column """ # The method checks by checking the top cell in column, if it is empty, the move is legal. return self.board[col][0] == '_' def is_winner(self, marker): """Checks if the given marker is a winner Parameters ---------- marker : str The marker that we check to see if he is a winner Returns ------- boolean a boolean value indicating if the given marker is a winner """ # The method checks using the check_lines method (that count lines), # that get the given marker and 4 (the length of a winning streak). return self.check_lines(marker, 4) def check_lines(self, marker, n): """Checks the number of lines of a given marker in length of n Parameters ---------- marker : str The marker that will be checked in the method n: int The length of the lines that will search Raises ------ IndexError If the search index is negative. Returns ------- int the number of lines found of the given marker in length of n """ # Creating a nested tuple of four directions (right, down, right-down, left-down) directions = (((0, 0), (1, 0), (2, 0), (3, 0)), ((0, 0), (0, 1), (0, 2), (0, 3)), ((0, 0), (1, 1), (2, 2), (3, 3)), ((0, 0), (-1, 1), (-2, 2), (-3, 3))) num_of_lines = 0 # Using a nested loop that iterates over all the cells for col in range(7): for row in range(6): # For every cell in the board, we are going through all the directions for direction in directions: # We creating a list of the cells in the current direction markers_list = [] # For every cell in the direction, we are adding it to the list for i in range(4): try: current_col = col + direction[i][0] current_row = row + direction[i][1] # If the cell is negative, we exit from the loop if current_col < 0 or current_row < 0: raise IndexError markers_list.append(self.board[current_col][current_row]) except IndexError: # If the cell index is invalid (e.g. column 9), we exit from the loop break else: """Checking list of cells If all the cells are valid, we check the number of given marker apparitions, if the number of apparitions is equal to n and there isn't any opponent marker in the list we add to the num_of_lines variable one. """ if markers_list.count(marker) == n and markers_list.count(marker) + markers_list.count('_') == 4: num_of_lines += 1 return num_of_lines def is_draw(self): """Checks if there is a legal move in the board Returns ------- boolean returns a boolean value indicating whether there is a legal move in the board """ # Using a loop the method checks if there is a legal move in the board for col in range(7): if self.legal_move(col): return False return True def get_score(self, player): """Returns the score of the board for a given player Parameters ---------- player : Player The player that will receive the score of the board for him Returns ------- int an integer value representing the score of the board for the given player """ board_score = 0 # Adding two points for every line in length of 2, of the given player board_score += self.check_lines(player.marker, 2) * 2 # Adding five points for every line in length of 3, of the given player board_score += self.check_lines(player.marker, 3) * 5 # Subtract two points for every line in length of 2, of the opponent player board_score += self.check_lines(player.opponent_marker, 2) * -2 # Subtract hundred points for every line in length of 3, of the opponent player board_score += self.check_lines(player.opponent_marker, 3) * -100 return board_score class Player: """ A class used to represent a player ... Attributes ---------- name : str the name of the player marker : str the marker of the player opponent_marker : str the marker of the opponent player Methods ------- make_move(board) Asking the player to make a legal move """ def __init__(self, name, marker, opponent_marker): """ Parameters ---------- name : str the name of the player marker : str the marker of the player opponent_marker : str the marker of the opponent player """ self.name = name self.marker = marker self.opponent_marker = opponent_marker def make_move(self, board): """Asks the player to make a move Parameters ---------- board : Board the current board Returns ------- int the column that the player selected """ # Asking the player to make a move move = input(f'This is the current board, {self.name} please make a move 1-7\n') # If the player wrote AI, so the computer helps him in the game if move.lower() == 'ai': # We creates a temporary computer object to do a move for the player computer_player = Computer(self.name, self.marker, self.opponent_marker) return computer_player.make_move(board) else: # Otherwise, we return the move that the human player wrote move = int(move) - 1 while True: # If the move is legal, so the method returns it. if board.legal_move(move): return move # Otherwise, the method asks the player again, until he returns a valid answer. else: # Like before, the method asks the player to make a move, and the player can answer 'AI' move = input('Illegal move, please try again.\n') if move.lower() == 'ai': computer_player = Computer(self.name, self.marker, self.opponent_marker) return computer_player.make_move(board) else: move = int(move) - 1 class Random(Player): """ A class used to represent a player that make random moves (inheritor the Player object) ... Attributes ---------- name : str the name of the random player marker : str the marker of the random player opponent_marker : str the marker of the opponent player Methods ------- make_move(board) Makes a random move using the choice function from the random library """ def __init__(self, name, marker, opponent_marker): """ Parameters ---------- name : str the name of the player marker : str the marker of the player opponent_marker : str the marker of the opponent player """ Player.__init__(self, name, marker, opponent_marker) def make_move(self, board): """Choosing a random move Parameters ---------- board : Board the current board """ options = [_ for _ in range(7) if board.legal_move(_)] return choice(options) class Computer(Player): """ A class used to represent a computer player (inheritor the Player object) ... Attributes ---------- name : str the name of the random player marker : str the marker of the random player opponent_marker : str the marker of the opponent player depth : int how many steps the computer will think ahead (default value is 4) Methods ------- score_move(board, i, depth, alpha, beta, turn = True) Score a move using the Minimax algorithm and Alpha Beta Pruning make_move(board) Makes a move by scroing all the colums using the score_move method """ def __init__(self, name, marker, opponent_marker, depth = 4): """ Parameters ---------- name : str the name of the player marker : str the marker of the player opponent_marker : str the marker of the opponent player depth : int, optional how many steps the computer will think ahead (default value is 4) """ Player.__init__(self, name, marker, opponent_marker) self.depth = depth def score_move(self, board, i, depth, alpha, beta, turn=True): """Returns the score of given move Parameters ---------- board : Board the current board i : int the column that will placed a marker into it depth : int The number of moves the computer will think ahead alpha : int, float The minimum score that achieved beta : int, float The minimum score that achieved turn : boolean, optional the current player (True mean current player and False mean opponent player) Returns ------- intger a intger value indicating the score of the board for the current player """ # Creating a copy of the board new_board = board.clone() # Place a mark at column i in the board clone new_board.place_mark(self.marker if turn else self.opponent_marker, i) # Checking winning and tie if new_board.is_winner(self.marker): return inf elif new_board.is_winner(self.opponent_marker): return -inf elif new_board.is_draw(): return 0 # If the depth is 0, the method return a score of the board elif depth == 0: return new_board.get_score(self) else: # Otherwise, the method think move ahead # The method creates a list of possible moves options = [] # The method iterates over all the columns for i in range(7): if new_board.legal_move(i): # Just if the move is legal the method add to the options list the score of the move # In the recursive call the depth is subtract by one and the turn flips over test = self.score_move(new_board, i, depth - 1, alpha, beta, not turn) # If the move is in the middle column, we add to the score 4 points if i == 3: test += 4 options.append(test) # Alpha Beta Pruning if not turn: if max(options) >= beta: return max(options) if max(options) > alpha: alpha = max(options) else: if min(options) <= alpha: return min(options) if min(options) < beta: beta = min(options) # Returns the minimum score if turn, otherwise returns the maximum score return min(options) if turn else max(options) def make_move(self, board): """Searches for the best move Parameters ---------- board : Board the current board Returns ------- int the column that gives the maximum score """ # Creating a possible moves list moves = [] # Iterating all the columns for i in range(7): if board.legal_move(i): # If the move is legal, then we add a tuple of the score of the move # and the column to the moves list if i == 3: # If the column is the middle column, we add 4 points to the score moves.append((self.score_move(board, i, self.depth, -inf, inf) + 4, i)) else: moves.append((self.score_move(board, i, self.depth, -inf, inf), i)) # By sorting the list we get a list that sorted from the lowest to highest score # then we choose the the highest score column return sorted(moves)[-1][1] def main(): """The main function that runs the game""" # Setting the first player turn = False # Creating a board object board = Board() # Creating a list of players players = [Player('Bob', 'X', 'O'), Computer('Alice', 'O', 'X')] while True: # Setting the current player using the turn variable current_player = players[int(turn)] # Prints the board as a string print(board.to_string()) print('\n') # The current player makes a move move = current_player.make_move(board) # Place a mark in the board is_winning = board.place_mark(current_player.marker, move) # If someone won or there is a tie, then the game is over (using break, to exit the loop) if is_winning or board.is_draw(): break # The turn variable flips over turn = not turn # When the game is over, if nobody winned (there is a tie) if board.is_draw(): print('No one wins:') # Otherwise, we prints a message saying who did winned else: print(f'Congratulations {current_player.name}, you win:') # Finally, we print the final board print(board.to_string()) if __name__ == "__main__": main()
305659ca00c20cd2c345989846a699ebe8db33fc
breitbarth/pys-list
/main.py
1,504
3.59375
4
import requests from bs4 import BeautifulSoup html_link = input("Please enter a CraigsList page: ") page = requests.get(html_link) soup = BeautifulSoup(page.text, 'html.parser') class_list = set() # First we need to get the span tags spanTag = {tag.name for tag in soup.find_all('span')} listOfResults = set() sum = 0 spanList = soup.findAll('span', {'class': 'result-price'}) for span in spanList: listOfResults.add(" ".join(span)) price = span.get_text().replace('$', '').replace(',', '') print(price) sum += (int(price)) # class_list.add(" ".join(span)) # if "result-price" in span.attrs.get("class"): # class_list.add(" ".join(span)) print(listOfResults) print(sum / len(listOfResults)) print("This is the amount of results we found:", len(listOfResults)) # print(class_list) # # price_classes = soup.find(class_='result-row') # # all_price_classes = price_classes.find_all('span') # # print(all_price_classes) # splinter # This is a sample Python script. # Press Shift+F10 to execute it or replace it with your code. # Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings. # # def print_hi(name): # # Use a breakpoint in the code line below to debug your script. # print(f'Hi, {name}') # Press Ctrl+F8 to toggle the breakpoint. # # # # Press the green button in the gutter to run the script. # if __name__ == '__main__': # print_hi('PyCharm') # See PyCharm help at https://www.jetbrains.com/help/pycharm/
21dcf23d21a973299992e8c7eae11cae9b455b04
ikisler/udacity-algorithms-projects
/problem_5.py
3,235
3.984375
4
## Represents a single node in the Trie class TrieNode: def __init__(self): ## Initialize this node in the Trie self._is_word = False self._children = {} def set_is_word(self): self._is_word = True def get_is_word(self): return self._is_word def get_children(self): return self._children def insert(self, char): ## Add a child node in this Trie if self._children.get(char) is None: self._children[char] = TrieNode() def suffixes(self, suffix = ''): ## Recursive function that collects the suffix for ## all complete words below this point result = [] for char, child in self._children.items(): if child.get_is_word(): result.append(suffix + char) if child.get_children(): result.extend(child.suffixes(suffix + char)) return result def __repr__(self): out = "Word ending: " + str(self._is_word) + "\n" out += "Children: " + str(self._children) return out ## The Trie itself containing the root node and insert/find functions class Trie: def __init__(self): ## Initialize this Trie (add a root node) self._root = TrieNode() def insert(self, word): ## Add a word to the Trie if len(word) <= 0: # Do not add empty word return current = self._root for char in word: current.insert(char) current = current.get_children()[char] current.set_is_word() def find(self, prefix): ## Find the Trie node that represents this prefix current = self._root for char in prefix: if char not in current.get_children(): return False current = current.get_children()[char] return current # Create Trie and add some words words = [ "ant", "anthology", "antonym", "fact", "factual", "fun", "function", "trie", "trigger", "trigonometry", "tripod" ] trie = Trie() for word in words: trie.insert(word) # Tests # Find a node found = trie.find("ant") print(found) """ Returns output of: Word ending: True Children: {'h': Word ending: False Children: {'o': Word ending: False Children: {'l': Word ending: False Children: {'o': Word ending: False Children: {'g': Word ending: False Children: {'y': Word ending: True Children: {}}}}}}, 'o': Word ending: False Children: {'n': Word ending: False Children: {'y': Word ending: False Children: {'m': Word ending: True Children: {}}}}} """ # Show possible options from suffix print() print(found.suffixes()) # Returns ['hology', 'onym'] # Find empty string print() found = trie.find("") print(found) # Find the root node and prints the whole tree # Show all possible words print() print(found.suffixes()) # Returns ['ant', 'anthology', 'antonym', 'fact', 'factual', 'fun', 'function', 'trie', 'trigger', 'trigonometry', 'tripod'] # Add an empty string to the trie -- ensure that it adds no nodes print(len(found.get_children())) # Returns 3 (for a, f, t) trie.insert("") found = trie.find("") print(len(found.get_children())) # Returns 3 (for a, f, t)
72af6a140f9a896b058998fa1fa65c035104cce4
ebukari/exercism-python-solutions
/solns/atbash_cipher.py
646
3.6875
4
import string import re CIPHERTEXT = 'zyxwvutsrqponmlkjihgfedcba' + string.digits PLAINTEXT = string.ascii_lowercase + string.digits def encode(str_): str_ = re.sub('\W', '', str_).lower() return_str = '' count = 1 for letter in str_: return_str += CIPHERTEXT[PLAINTEXT.index(letter)] # letter if letter.isdigit() else if count == 5: return_str += ' ' count = 0 count += 1 return ' '.join(return_str.split()) def decode(cipher): cipher = re.sub('\W', '', cipher) return_str = '' for letter in cipher: return_str += PLAINTEXT[CIPHERTEXT.index(letter)] return return_str
fb11cc3de9d42cd18037132fdc7fe95b8b06d55c
ngd-b/python-demo
/second.py
2,256
3.6875
4
#!/usr/bin/python # -*- coding:utf-8 -*- print("hello world") # [:] names = list(range(11)) print(names[1:6]) # [::] print(names[1:6:2]) # 判断当前数据是否可以进行迭代 from collections.abc import Iterable print(isinstance(names,Iterable)) # enumerate names = enumerate(names) for k,v in names: print(k,v) # [] nums = [n*n for n in [2,4,8]] print(nums) # 多层操作 nums = [n*m for n in [2,4,8] for m in [1,3,6]] print(nums) # generator names=(n*n for n in [2,4,8]) for val in names: print("for-",val) # print(next(names)) # 判断当前数据类型是否为迭代对象 from collections.abc import Iterator print(isinstance(nums,Iterator)) print(isinstance(names,Iterator)) print(isinstance(iter(nums),Iterator)) # 匿名函数 total = lambda val:val*3 print(total(4),total.__name__) # 装饰器 @ def log(fn): def wrapper(*arg,**oth): print("------操作--------",fn.__name__,"---------操作用户名称---------",arg[0]) return fn(*arg,**oth) return wrapper @log def login(user): print("欢迎登陆:"+user) login("admin") # 装饰器传入自定义参数 import functools def log(bool): def decorator(fn): @functools.wraps(fn) def wrapper(*arg,**oth): print("------操作--------",fn.__name__,"---------操作用户名称---------",arg[0]) if bool: print("2019-10-06") return fn(*arg,**oth) return wrapper return decorator @log(True) def login(user): print("欢迎登陆:"+user) login("test") # 设定函数默认值 def info(name,flag = True): adorn = "" if flag: adorn = "尊贵的" print("欢迎"+adorn+"客人:",name) info("admin",False) info("test",False) # 通过 functools.partial() 设置处理 info_ = functools.partial(info,flag=False) info_("admin") info_("test") # 模块使用 from logs.info import print_log import user.info print_log() print(user.info._Author_) # re 模块 正则表达式 import re print(re.match(r".+lo","hello")) print(re.split(r"l+","hello")) # groups ('h', 'lo') print(re.match(r"^([a-z]+)el([a-z]+)$","hello").groups()) # 对表达式及进行编译, reg_ = re.compile(r"(\d+)\+(\d+)"); print(reg_.match("2233+123").group(1))
86cf7138e283cf83d7c9fdd30cb139857468f433
ngd-b/python-demo
/four/four.py
701
3.6875
4
#!/usr/bin/python # -*- coding:utf-8 -*- print("hello world") # print(a) try: print(a) except NameError as e: print("变量未声明,请检查") finally: print("继续执行!") print(2) # logging 记录日志 import logging try: print(10/0) except ZeroDivisionError as e: logging.exception(e) print(0/10) # 自定义错误类型 class ConflictValueError(ValueError): pass name = input("please input your name \n") try: if name == "admin": raise ConflictValueError("you can't use this name") except ConflictValueError as e: logging.exception(e) print("ok") # 断言 import pdb # assert name!="test","测试" # pdb.set_trace() print("大神,你好")
b7c06bf9cad593102eca103ad43cf8abfbeddb1c
cheriesyb/cp1404practicals
/prac_02/numbering.py
337
3.609375
4
output_file = open("numbers.txt", 'r') number_1 = int(output_file.readline()) number_2 = int(output_file.readline()) print(number_1 + number_2) output_file.close() # extended activity output_file = open("numbers.txt", 'r') total = 0 for line in output_file: number = int(line) total += number print(total) output_file.close()
328b35992c50915e95c2ededde477a066cf9a99f
rafaelols/learn-python3-the-hard-way
/ex48/ex48/lexicon.py
351
3.765625
4
WORD_TYPES = { 'north': 'direction', 'south': 'direction', 'east': 'direction', 'west': 'direction', 'go': 'verb', 'kill': 'verb', 'eat': 'verb' } def scan(sentence): words = sentence.split() result = [] for word in words: tuple = (WORD_TYPES[word], word) result.append(tuple) return result
e3f3da252345a8e54f3e7bff4d6c695d379b5e42
grupy-sanca/dojos
/039/2.py
839
4.53125
5
""" https://www.codewars.com/kata/55960bbb182094bc4800007b Write a function insert_dash(num) / insertDash(num) / InsertDash(int num) that will insert dashes ('-') between each two odd digits in num. For example: if num is 454793 the output should be 4547-9-3. Don't count zero as an odd digit. Note that the number will always be non-negative (>= 0). >>> verificaImpares(23543) '23-543' >>> verificaImpares(2543) '2543' >>> verificaImpares(454793) '4547-9-3' >>> verificaImpares(353793) '3-5-3-7-9-3' """ def verificaImpares(numero): impar = "13579" res = "" anterior_impar = False for letter in str(numero): if letter in impar: if anterior_impar: res += "-" anterior_impar = True else: anterior_impar = False res += letter return res
25869ac8273d09c17f88c59828573e9ba7ba6de4
grupy-sanca/dojos
/027/ex1.py
863
3.609375
4
""" Problema: https://www.urionlinejudge.com.br/judge/pt/problems/view/1234 Entrada: 'This is a dancing sentence' Saída: 'ThIs Is A dAnCiNg SeNtEnCe' Entrada: ' This is a dancing sentence' Saída: ' ThIs Is A dAnCiNg SeNtEnCe' Entrada: aaaaaaaaaaa Saída AaAaAaAaAaA >>> dancing_string('This is a dancing sentence') 'ThIs Is A dAnCiNg SeNtEnCe' >>> dancing_string(' This is a dancing sentence') ' ThIs Is A dAnCiNg SeNtEnCe' >>> dancing_string('aaaaaaaaaaa') 'AaAaAaAaAaA' """ def dancing_string(sentence): response = '' dancing_flag = True for letter in sentence: if letter.isalpha(): response += letter.upper() if dancing_flag else letter.lower() dancing_flag = not dancing_flag else: response += ' ' return response
d353c66f391a8b05404ee48aafa409e2bcfbe5c0
grupy-sanca/dojos
/011/magic_numbers.py
1,244
3.796875
4
""" Validador de Quadrados Mágicos 3x3 https://www.codewars.com/kata/magic-square-validator/ Recebe da entrada padrão uma matriz de tamanho 3x3... [[1, 2, 3], [4, 5, 6], [7, 8, 9]] >>> matriz = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] >>> checar_linha([1, 2, 3]) False >>> checar_linha([4, 9, 2]) True >>> transpor(matriz) [[1, 4, 7], [2, 5, 8], [3, 6, 9]] >>> transpor(transpor(matriz)) [[1, 2, 3], [4, 5, 6], [7, 8, 9]] >>> checar_diagonais(matriz) True >>> checar_diagonais(transpor(matriz)) True >>> is_magical(matriz) False >>> matriz_magica = [[4,9,2], [3,5,7], [8,1,6]] """ from copy import deepcopy def checar_linha(linha): return sum(linha) == 15 def transpor(matriz): tam = len(matriz) return [[matriz[i][j] for i in range(tam)] for j in range(tam)] def checar_diagonais(matriz): tam = len(matriz) diagonal1 = [matriz[i][i] for i in range(tam)] diagonal2 = [matriz[i][tam - 1 - i] for i in range(tam)] return sum(diagonal1) == 15 and sum(diagonal2) == 15 def is_magical(quadrado): linhas = [checar_linha(linha) for linha in quadrado] colunas = [checar_linha for linha in transpor(quadrado)] return not all(linhas) and not all(colunas) and checar_diagonais(matriz)
40081353479ae657ee72bb8f6e37b99be0a5dab8
grupy-sanca/dojos
/036/3.py
1,158
3.515625
4
""" https://www.codewars.com/kata/5aceae374d9fd1266f0000f0 Given two times in hours, minutes, and seconds (ie '15:04:24'), add or subtract them. This is a 24 hour clock. Output should be two digits for all numbers: hours, minutes, seconds (ie '04:02:09'). >>> sum('00:00:00', '00:00:00') '00:00:00' >>> sum('01:02:03', '02:02:02') '03:04:05' >>> sum('00:40:00', '00:40:02') '01:20:02' >>> sum('23:40:59', '00:40:02') '00:21:01' >>> sub('03:04:05', '01:01:01') '02:03:04' >>> sub('00:04:05', '01:01:01') '23:03:04' >>> sub('00:00:00', '01:01:01') '22:58:59' """ def sum(t1, t2): h1, m1, s1 = [int(i) for i in t1.split(':')] h2, m2, s2 = [int(i) for i in t2.split(':')] s = (s1 + s2) m = (m1 + m2) h = (h1 + h2) h = (h % 24 + (m//60)) % 24 m = (m % 60 + (s//60)) % 60 s = s % 60 # # return f"{h:02d}:{m:02d}:{s:02d}" def sub(t1,t2): h1, m1, s1 = [int(i) for i in t1.split(':')] h2, m2, s2 = [int(i) for i in t2.split(':')] h = h1 - h2 m = m1 - m2 s = s1 - s2 h = (24 + h) % 24 m = (60 + m - (s + 60)//60) % 60 s = (60 + s) % 60 return f"{h:02d}:{m:02d}:{s:02d}"
7a25ea6ece6b85b2c4e4737cce1a035517207e05
grupy-sanca/dojos
/006/rangeparser.py
964
3.765625
4
""" >>> range_parser('1') [1] >>> range_parser('1,2,3,10,50') [1, 2, 3, 10, 50] >>> range_parser('3-8') [3, 4, 5, 6, 7, 8] >>> range_parser('1,2,3-8') [1, 2, 3, 4, 5, 6, 7, 8] >>> parse_range('1-3') [1, 2, 3] >>> parse_range('1-3:2') [1, 3] >>> range_parser('1-10,14, 20-25:2') [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 14, 20, 22, 24] >>> range_parser('1-10,14, 20-25:2, 1000-5000:1000') [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 14, 20, 22, 24, 1000, 2000, 3000, 4000, 5000] """ def clean(string): return string.replace("'", '') def range_parser(string): l = [] for elem in clean(string).split(','): # 1-10, 15, 20, 30-40:3 if '-' in elem: l.extend(parse_range(elem)) else: l.append(int(elem)) return l def parse_range(interval): step = 1 if ':' in interval: interval, step = interval.split(':') start, stop = [int(e) for e in interval.split('-')] return list(range(start, stop + 1, int(step)))
7d780b6baa6ca0b9149a8265ddd657d2303f9483
grupy-sanca/dojos
/003/sequence.py
669
3.9375
4
""" Um inteiro positivo n é dado. O objetivo do problema é construir a menor sequencia de inteiros que termina com N de acordo com as seguintes regras: 1. o primeiro elemento da sequencia é 1; A[0] = 1 2. os proximos elementos são gerados pela multiplicação do elemento anterior por 2 ou somando 1; A[i] = A[i-1] * 2 ou A[i] = A[i-1] + 1 para i >= 1. """ def sequence(length): """ >>> sequence(1) 1 >>> sequence(18) 6 >>> sequence(36) 7 >>> sequence(109) 11 """ count = 0 while length > 0: if length % 2: length -= 1 else: length /= 2 count += 1 return count
4fd23931962dd3a22a5a168a9a49bc68fd8eadd6
grupy-sanca/dojos
/028/ex2.py
1,416
4.40625
4
""" A newly opened multinational brand has decided to base their company logo on the three most common characters in the company name. They are now trying out various combinations of company names and logos based on this condition. Given a string, which is the company name in lowercase letters, your task is to find the top three most common characters in the string. -> Print the three most common characters along with their occurrence count. -> Sort in descending order of occurrence count. -> If the occurrence count is the same, sort the characters in alphabetical order. -> ordena a string inicial -> garante que o dicionário tá ordenado -> cria outra função que roda 3 vezes, e antes do for chama letter_count_func Example: * input: aabbbccde * output: [("b": 3), ("a": 2), ("c": 2)] >>> main('aaabbc') [('a', 3), ('b', 2), ('c', 1)] >>> main('aaabbcdef') [('a', 3), ('b', 2), ('c', 1)] >>> main('aaabbbcccdef') [('a', 3), ('b', 3), ('c', 3)] >>> main('abcccdddeffff') [('f', 4), ('c', 3), ('d', 3)] """ def letter_count_func(string): letter_count = {} for letter in string: letter_count[letter] = letter_count.get(letter, 0) + 1 return letter_count def sort_values(x): return [-x[1], x[0]] def main(string): letter_count = letter_count_func(string) letter_count = sorted(letter_count.items(), key=sort_values, reverse=True) return letter_count[-1:-4:-1]
6592fd4409614e36f71eafb4eb5c0477566876bb
grupy-sanca/dojos
/001/lista.py
2,965
4.0625
4
"""Dojo Grupy Sanca - 27/07/2016 """ class Node: """ >>> Node(1) Node(1) >>> no = Node('abc') >>> no Node('abc') """ next = None def __init__(self, value): self.value = value def __repr__(self): return 'Node({!r})'.format(self.value) class List: """ >>> lista = List() >>> lista List() >>> no = Node(1) >>> no.next >>> lista.head """ head = None def __repr__(self): return 'List()' def insert(self, value): """ >>> lista = List() >>> lista.insert('ab') >>> lista.print() ab >>> lista.insert('cd') >>> lista.print() ab cd >>> lista.insert('ef') >>> lista.print() ab cd ef """ new_node = Node(value) node = self.head if node is None: self.head = new_node return while node.next is not None: node = node.next node.next = new_node def print(self): """ >>> lista = List() >>> lista.insert(2) >>> lista.print() 2 """ node = self.head while node is not None: print(node.value) node = node.next def pop(self): """ >>> lista = List() >>> lista.insert('ab') >>> lista.insert('cd') >>> lista.insert('ef') >>> lista.pop() Node('ef') >>> lista.print() ab cd >>> lista.pop() Node('cd') >>> lista.print() ab """ last = self.head penult = None while last is not None: if last.next is None: break penult = last last = last.next if penult: penult.next = None else: self.head = None return last def remove(self, value): """ >>> lista = List() >>> lista.insert('ab') >>> lista.insert('cd') >>> lista.remove('ab') >>> lista.print() cd >>> lista = List() >>> lista.insert(1) >>> lista.insert(2) >>> lista.insert(3) >>> lista.insert(4) >>> lista.remove(1) >>> lista.print() 2 3 4 >>> lista.remove(3) >>> lista.print() 2 4 >>> lista.remove(4) >>> lista.print() 2 >>> lista.remove(2) >>> lista.print() """ node = self.head penult = None while node is not None: if node.value == value: if node == self.head: self.head = node.next elif node.next is None: penult.next = None else: penult.next = node.next break penult = node node = node.next
cdf1b64ca2565e5ed195b57cda9e2a94421665f1
Joseph-L-Hayes/CS188-projects
/P0/speed/quickSort2.py
685
3.9375
4
import time def quickSort(list, pivot=0): if pivot > len(list) - 1: pivot = 0 if len(list) <= 1: return list before = [x for x in list[:pivot]] after = [x for x in list[pivot + 1:]] smaller = [x for x in before if x < list[pivot]] larger = [x for x in before if x >= list[pivot]] smaller += [x for x in after if x < list[pivot]] larger += [x for x in after if x >= list[pivot]] return quickSort(smaller) + [list[pivot]] + quickSort(larger) # Main Function if __name__ == '__main__': lst = [2, 4, 5, 1, 12, 100, 2, 4, 6, 9, 10] start = time.time() print(quickSort(lst)) end = time.time() print(end - start)
1a538c87e392c12466367fb9df19ed7de14eb9ba
lynnanni/Netflix-SDET-project
/Modules/Pages/ComputerPage.py
3,353
3.5625
4
from Modules.Pages.BasePage import Page from Modules.Library.locators import ComputerPageLocators as locators from selenium.webdriver.support.ui import Select import logging class ComputerPage(Page): """ This is the page that appears when a user attempts to add or edit a computer """ logging.basicConfig(level=logging.INFO) def __init__(self, driver, url="http://computer-database.herokuapp.com/computers/new"): super(ComputerPage, self).__init__(driver, "add_computer_page", url=url) def create_computer(self, name=None, introduced_date=None, discontinued_date=None, company=None, cancel=False): logging.info(f"Creating computer with params: name={name}, introduced_date={introduced_date}, " f"discontinued_date={discontinued_date}, company={company}") if name: name_input = self.driver.find_element_by_id(locators.computer_name) name_input.send_keys(name) if introduced_date: introduced_input = self.driver.find_element_by_id(locators.introduced_date) introduced_input.send_keys(introduced_date) if discontinued_date: discontinued_input = self.driver.find_element_by_id(locators.discontinued_date) discontinued_input.send_keys(discontinued_date) if company: company_dropdown = Select(self.driver.find_element_by_id(locators.company)) company_dropdown.select_by_visible_text(company) if cancel: cancel_button = self.driver.find_element_by_xpath(locators.cancel_button) cancel_button.click() else: create_button = self.driver.find_element_by_xpath(locators.create_computer_button) create_button.click() def edit_computer(self, name=None, introduced_date=None, discontinued_date=None, company=None, cancel=False): logging.info(f"Editing computer with params: name={name}, introduced_date={introduced_date}, " f"discontinued_date={discontinued_date}, company={company}") if name: name_input = self.driver.find_element_by_id(locators.computer_name) name_input.clear() name_input.send_keys(name) if introduced_date: introduced_input = self.driver.find_element_by_id(locators.introduced_date) introduced_input.clear() introduced_input.send_keys(introduced_date) if discontinued_date: discontinued_input = self.driver.find_element_by_id(locators.discontinued_date) discontinued_input.clear() discontinued_input.send_keys(discontinued_date) if company: company_dropdown = Select(self.driver.find_element_by_id(locators.company)) company_dropdown.select_by_visible_text(company) if cancel: cancel_button = self.driver.find_element_by_xpath(locators.cancel_button) cancel_button.click() else: save_computer_button = self.driver.find_element_by_xpath(locators.save_computer_button) save_computer_button.click() def delete_computer(self): """ Presses the red "Delete this computer" button """ delete_button = self.driver.find_element_by_xpath(locators.delete_computer_button) delete_button.click()
f17e7bc0acc2e97393a392ffb15e96a3f9f805f2
ayust/controlgroup
/examplemr.py
645
4.28125
4
# A mapper function takes one argument, and maps it to something else. def mapper(item): # This example mapper turns the input lines into integers return int(item) # A reducer function takes two arguments, and reduces them to one. # The first argument is the current accumulated value, which starts # out with the value of the first element. def reducer(accum, item): # This example reducer sums the values return accum+item # You'd run this via the following command: # # some_input_cmd | ./pythonmr.py --auto=examplemr | some_output_command # # or... # # ./pythonmr.py --in=infile.txt --out=outfile.txt --auto=examplemr
5eb04f15805f94fe1cd15b17ae4a9e9c165b43d0
hamzahap/HangmanGame
/Hangman.py
10,671
4
4
from random import randint from tkinter import * import tkinter.ttk as ttk from tkinter.ttk import Progressbar from tkinter import messagebox import time import threading # getInfile() # Gets a text file containing words to be chosen by the Hangman program def getInfile(): try: # First, we check for a file called "wordlist.txt". If it exists in the same directory # as the Hangman program, then we use this file as our word list automatically with open('wordlist.txt', 'r'): infile_name = 'wordlist.txt' except IOError: # If wordlist.txt cannot be found, then we ask the user to specify a text file found_file = False infile_name = input('Please specify a text file containing a list of words for the Hangman game to choose from (include the full file path if the file is in a different directory than the Hangman program): ') # If the user specifies a file name of a file that cannot be found, we keep asking for # a valid input file until a valid one is specified while not(found_file): try: with open(infile_name, 'r'): found_file = True except IOError: infile_name = input('\n{0} was not found!\n\nPlease try again, or specify a different file (include the full file path if the file is in a different directory than the Hangman program): '.format(infile_name)) return infile_name # Chooses a word randomly from the list of words taken from the input file def chooseWord(infile_name, wordLen): infile = open(infile_name, 'r') wordlist = infile.readlines() total_words = len(wordlist) random_num = randint(0, total_words - 1) chosen_word = wordlist[random_num].replace('\n', '') word_len = len(chosen_word) if(wordLen > 0): while(word_len != wordLen): random_num = randint(0, total_words - 1) chosen_word = wordlist[random_num].replace('\n', '') word_len = len(chosen_word) return chosen_word, word_len def timer(gamelabel1, game, hiddenword, progressBar): wordprint = ''; while(gameRunning.get() == True): if(messageBoxOpen.get() == False): if(startTime.get()<=0): start_time = time.time(); startTime.set(10); remainingguesses.set(remainingguesses.get() - 1); showhangman(gamelabel1,remainingguesses) wordprint = "Incorrect Guesses Remaining: " + str(remainingguesses.get()) + "\n" hiddenword.set(wordprint) progressBar["value"] = startTime.get()*10; game.update(); if(remainingguesses.get() <=0): lose(game, word) time.sleep(1); startTime.set(startTime.get()-1); progressBar["value"] = startTime.get()*10; game.update(); def letterguess(guessfield,pointsAvailable, hiddenword,hiddenword1, game, gamelabel1, man): global correctcounter global incorrectcounter global wordarray global guessedletters global word global letters global end i = 0 letterinword = False startTime.set(10); valid = True letter = guessfield.get() letter = letter.lower() guessfield.delete(0, END) ## account for blank input ## if (len(letter) == 0): messagebox.showinfo("Error", "Please enter a letter!") valid = False if(letter in guessedletters): messagebox.showinfo("Error", "Letter has already been guessed"); valid = False if(len(letter) > 1): messagebox.showinfo("Error", "Enter a single charecter!"); valid = False ## check to see if letter is good ## while (i < len(word) and valid): if word[i] == letter[0]: letterinword = True wordarray.pop(2*i) wordarray.insert(2*i, letter[0]) scr.set(scr.get()+1) val.set(str("Score: " + str(scr.get()))); i = i + 1 ## incorrect guess ## if (not letterinword and valid): if guessedletters.count(letter[0]) == 0: guessedletters.append(letter[0]) remainingguesses.set(remainingguesses.get() - 1) ## update label ## wordprint = ''.join(wordarray) + "\n" wordprint = wordprint + "Guessed Letters: " + ', '.join(guessedletters) + "\n" hiddenword1.set(wordprint); wordprint = ''; wordprint = wordprint + "Incorrect Guesses Remaining: " + str(remainingguesses.get()) + "\n" hiddenword.set(wordprint) ## update image ## showhangman(gamelabel1,remainingguesses) ## win condition ## if correctcounter == len(word): win(game, word) ## lose condition ## if remainingguesses.get() <= 0: lose(game, word) ## word guess section ## def wordguess(guessfield, hiddenword, game, man): global word wordguess = guessfield.get() i = 0 match = True if (len(wordguess) == 0): match = False while i < len(wordguess): if word[i] != wordguess[i]: match = False i = i + 1 if len(word) != len(wordguess): match = False if match: win(game, word) else: lose(game, word) ## play the actual game ## def hint(object): messageBoxOpen.set(True); startTime.set(10); for letter in word: if(letter not in guessedletters): messagebox.showinfo("Hint", "The Hint is " + letter); break; startTime.set(10); messageBoxOpen.set(False); object.pack_forget(); def startgame(): global word global wordLen; try: wordLen = int(wordlenfield.get()); except: wordLen = 0; infile_name = getInfile() # Choose a word at random from the acquired word list word, word_len = chooseWord(infile_name,wordLen) if word_len < 1: messagebox.showinfo("Error", "Please enter a word!") startgame() gameRunning.set(True); startTime.set(10); ## lots of variables for actual game ## remainingguesses.set(9); global wordarray global pointsAvailable global guessedletters pointsAvailable = StringVar(); wordarray = [] guessedletters = [] i = 0 while i < word_len: wordarray.append('_') wordarray.append(' ') i = i + 1 global correctcounter global incorrectcounter correctcounter = 0 incorrectcounter = 0 ## end variables ## game = Toplevel() game.wm_title("Hangman") game.minsize(100,100) game.geometry("500x520") man = PhotoImage(file="gallows.gif") hiddenword = StringVar() hiddenword1 = StringVar() gamelabelfiller = Label(game, text = "Timer:") gamelabelfiller.pack() progressBar=ttk.Progressbar(game,length=100,orient='horizontal',mode='determinate') progressBar.pack() gamelabel1 = Label(game, image=man) gamelabel1.image = man gamelabel1.pack() gamelabel3 = Label(game, textvariable=pointsAvailable) gamelabel3.pack() gamelabel4 = Label(game, textvariable=hiddenword) gamelabel4.pack() gamelabel2 = Label(game, textvariable=hiddenword1) gamelabel2.pack() guessfield = Entry(game) guessfield.pack() pointsAvailable.set("Your Total Points : " + str(word_len - correctcounter)); remainingguesses.set(remainingguesses.get() - incorrectcounter) wordprint = ''.join(wordarray) + "\n" wordprint = wordprint + "Guessed Letters: " + ', '.join(guessedletters) + "\n" hiddenword1.set(wordprint); wordprint = ''; wordprint = wordprint + "Incorrect Guesses Remaining: " + str(remainingguesses.get()) + "\n" hiddenword.set(wordprint) t = threading.Timer(0, timer,kwargs={'gamelabel1': gamelabel1,'game':game, 'hiddenword':hiddenword, 'progressBar': progressBar}); t.daemon = True; t.start(); bguessletter = Button(game, text="Guess Letter", width=15, command=lambda: letterguess(guessfield, pointsAvailable, hiddenword, hiddenword1, game, gamelabel1, man)) bguessletter.pack() bhint = Button(game, text="Get Hint", width=15, command=lambda: hint(bhint)) bhint.pack() bguessword = Button(game, text="Guess Word [ONE CHANCE]", width=25, command=lambda:wordguess(guessfield, hiddenword, game, man)) bguessword.pack() game.mainloop() ## quit the game ## def quitnow(): global root messagebox.showinfo("Hangman in Python", "Thanks for playing! See you soon!") root.destroy() def win(game, word): gameRunning.set(False); messagebox.showinfo("Winnerx2-Chicken-Dinner", "You WIN! The word was " + word + "!") game.withdraw() def lose(game, word): gameRunning.set(False); messagebox.showinfo("Loser-Shmooser", "You LOSE! The word was " + word + "!") game.withdraw() def showhangman(gamelabel1,remainingguesses): print("Hangman"); print(str(remainingguesses.get())); if remainingguesses.get() == 9: img = PhotoImage(file="gallows.gif") gamelabel1.configure(image = img) gamelabel1.image = img if remainingguesses.get() == 8: img = PhotoImage(file="head.gif") gamelabel1.configure(image = img) gamelabel1.image = img if remainingguesses.get() == 7: img = PhotoImage(file="noarms.gif") gamelabel1.configure(image = img) gamelabel1.image = img if remainingguesses.get() == 6: img = PhotoImage(file="rightarm.gif") gamelabel1.configure(image = img) gamelabel1.image = img if remainingguesses.get() == 5: img = PhotoImage(file="nolegs.gif") gamelabel1.configure(image = img) gamelabel1.image = img if remainingguesses.get() == 4: img = PhotoImage(file="almostdead.gif") gamelabel1.configure(image = img) gamelabel1.image = img if remainingguesses.get() == 3: img = PhotoImage(file="dead.gif") gamelabel1.configure(image = img) gamelabel1.image = img if remainingguesses.get() == 2: img = PhotoImage(file="deader.gif") gamelabel1.configure(image = img) gamelabel1.image = img if remainingguesses.get() == 1: img = PhotoImage(file="moredead.gif") gamelabel1.configure(image = img) gamelabel1.image = img if remainingguesses.get() == 0: img = PhotoImage(file="deadest.gif") gamelabel1.configure(image = img) gamelabel1.image = img root = Tk() root.wm_title("Hangman in Python") root.minsize(380,380) root.geometry("300x100") title = PhotoImage(file="title.gif") titleLabel = Label(root, image=title) titleLabel.image = title titleLabel.pack() startTime = IntVar(); startTime.set(10); x = Label(root, text="Word Length") x.pack() gameRunning = BooleanVar(); gameRunning.set(True); messageBoxOpen = BooleanVar(); messageBoxOpen.set(False); scr = IntVar(); scr.set(0); val = StringVar(); val.set(str("Score: " + str(scr.get()))); wordlenfield = Entry(root) wordlenfield.pack() remainingguesses = IntVar() score = Label(root, textvariable=val); score.pack(); bplay = Button(root, text="Play", width=10, command=startgame) bplay.pack() bquit = Button(root, text="Quit", width=10, command=quitnow) bquit.pack() mainloop()
da9716a7733d7122453c98faf731b588c5616ec6
JanrichVanHeerden/Sandbox
/oddName.py
243
4
4
"""Janrich van Heerden""" name = input("Enter your name") while name == "": name = input("Enter a NAME") char_list = name count = 1 for each in list(char_list): if count % 2 != 0: print(each) count+=1 else: count+=1
67bf9c85fe99964eb25f6da9c5e8a588673e0c38
SvetlanaGruzdeva/Chess-Dictionary-Validator
/chessvalidator.py
5,635
3.65625
4
#! python3 # chessvalidator - checks if provided chess board is valid import logging logging.basicConfig(filename='chessValidatorLog.txt', level=logging.DEBUG, format=' %(asctime)s - %(levelname)s - %(message)s') # TODO: add validation that no cells appear more than 1 time chess_board = {'1h': 'bpawn', '6c': 'wqueen', '2g': 'bbishop', '5h': 'bqueen', '3e': 'wking', '3f': ''} # Dictionary with invalid items for testing invalid_items = {'10z': '', '': 'wking', '2a': 'zpawn', '3a': 'zqueen'} chess_board.update(invalid_items) def names_check(chess_board): logging.info('Executing NAMES_CHECK') colour_list = ['b', 'w'] pieces_list = ['pawn', 'knight', 'bishop', 'rook', 'queen', 'king'] correct_names_list = [] wrong_names_list = [] axis_x = [1, 2, 3, 4, 5, 6, 7, 8] axis_y = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] correct_board = [] wrong_position_list = [] # Setting list of possible chess pieces for i in colour_list: for m in range(len(pieces_list)): newElement = i + pieces_list[m] correct_names_list.append(newElement) # Setting list of possible positions for i in axis_x: for m in range(len(axis_y)): newElement = str(i) + axis_y[m] correct_board.append(newElement) for key, value in chess_board.items(): # Checking if possition is correct if key not in correct_board: if key == '': wrong_position_list.append('blank field') else: wrong_position_list.append(key) # Checking if piece name is correct if value != '': if value not in correct_names_list: wrong_names_list.append(value) # Error messages if wrong_names_list: logging.debug('piece_name_check False') print(f"Piece names {', '.join(wrong_names_list)} are incorrect") else: logging.info('piece_name_check True') if wrong_position_list: logging.debug('board_check False') print(f"Positions {', '.join(wrong_position_list)} are invalid") else: logging.info('board_check True') # Final output of function if not wrong_names_list and not wrong_position_list: logging.info('NAMES_CHECK is True') return True else: logging.debug('NAMES_CHECK is False') return False def amounts_check(chess_board): logging.info('Executing AMOUNTS_CHECK') b_counter = 0 w_counter = 0 max_amount = 16 #16 bpawn_counter = 0 wpawn_counter = 0 max_pawn_amount = 8 #8 bking_counter = 0 wking_counter = 0 max_king_amount = 1 # if value != '': for value in chess_board.values(): if value != '': if value[0] == 'b': b_counter = b_counter + 1 elif value[0] == 'w': w_counter = w_counter + 1 if value == 'bpawn': bpawn_counter = bpawn_counter + 1 elif value == 'wpawn': wpawn_counter = wpawn_counter + 1 if value == 'bking': bking_counter = bking_counter + 1 elif value == 'wking': wking_counter = wking_counter + 1 if b_counter <= max_amount and w_counter <= max_amount: logging.info('total_amount_check True') else: if b_counter > max_amount: logging.debug('total_amount_check False') print(f'Total amount {b_counter} of black pieces if more than {max_amount}') else: logging.debug('total_amount_check False') print(f'Total amount {w_counter} of white pieces if more than {max_amount}') if bpawn_counter <= max_pawn_amount and wpawn_counter <= max_pawn_amount: logging.info('pawns_check True') else: if bpawn_counter > max_pawn_amount: logging.debug('pawns_check False') print(f'Total amount {bpawn_counter} of black pawns if more than {max_pawn_amount}') else: logging.debug('pawns_check False') print(f'Total amount {wpawn_counter} of white pawns if more than {max_pawn_amount}') if bking_counter <= max_king_amount and wking_counter <= max_king_amount: logging.info('kings_check True') else: if bking_counter > max_king_amount: logging.debug('kings_check False') print(f'Total amount {bking_counter} of black kings if more than {max_king_amount}') else: logging.debug('kings_check False') print(f'Total amount {wking_counter} of white kings if more than {max_king_amount}') if b_counter <= max_amount and w_counter <= max_amount and bpawn_counter <= max_pawn_amount and wpawn_counter <= max_pawn_amount\ and bking_counter <= max_king_amount and wking_counter <= max_king_amount: logging.info('AMOUNTS_CHECK is True') return True else: logging.info('AMOUNT_CHECK is False') return False def is_valid_chess_board(chess_board): logging.info('Executing IS_VALID_CHESS_BOARD') names_check_result = names_check(chess_board) amounts_check_result = amounts_check(chess_board) if names_check_result and amounts_check_result: print('Your board is valid') return True else: print('Your board is invalid') return False # logging.disable(logging.CRITICAL) print(str(is_valid_chess_board(chess_board)))
764c2e9915ec8d6f2091214dfc3a32008327c4e6
lacornichon/twitterPredictor
/twitter_collect/tweet_collect_whole.py
3,187
3.59375
4
from twitter_collect.search import collect """ Generate and return a list of string queries for the search Twitter API from the file file_path_num_candidate.txt :param num_candidate: the number of the candidate :param file_path: the path to the keyword and hashtag files :param type: type of the keyword, either "keywords" or "hashtags" :return: (list) a list of string queries that can be done to the search API independently""" keywords=[] hastag=[] def get_candidate_(num_candidate, file_path): try: file_hashtag_candidate='/Users/valen/Documents/programmation/twitterPredictor/'+str(file_path)+'/hastag_candidate_'+str(num_candidate)+'.txt' file_keywords_candidate='/Users/valen/Documents/programmation/twitterPredictor/'+str(file_path)+'/keywords_candidate_'+str(num_candidate)+'.txt' fichier_hashtag = open(file_hashtag_candidate, "r") fichier_keywords = open(file_keywords_candidate, "r") for line in fichier_hashtag.readlines(): line_str=str(line) hastag=line.split(" ") hastag.pop() #tweets=(collect(line)) #for tweet in tweets: #print(tweet.text) for line in fichier_keywords.readlines(): line_str=str(line) keywords=line.split(" ") keywords.pop() #tweets=(collect(line)) #for tweet in tweets: return keywords, hastag except IOError as error: print(error) print (get_candidate_(1,'CandidateData')) #entrée num-candidate, file_path #sortie : dico de clé:mot clé et associé aux 200 dernier tweets contenant mot clé #rappel, collect renvoi {status, _json} def get_candidate_queries(num_candidate, file_path): try: tweets_keywords={} #dico avec toutes les infos tweets_hastag={} collected_keyword={} #dico avec info utiles collected_hashtag={} queries_hastag=[] #retour brut de collect sous la forme {status, _json} queries_keywords=[] queries_keywords=get_candidate_(num_candidate,file_path)[0] #on séléctionne les keywords queries_hastag=get_candidate_(num_candidate,file_path)[1] #on séléctionne les hashtages for k in queries_keywords: tweets_keywords[k]=collect(k)[1] #Extrait les tweets à l'aide de la fonction collect à partir des keywords du candidats choisi, on recupère un dic for h in queries_hastag: tweets_hastag[h]=collect(h)[1] #Extrait les tweets à l'aide de la fonction collect à partir des hashtags candidat choiisi for tweet in tweets_keywords: collected_keyword[tweet.id]=[tweet.user.name,tweet.text,tweet.retweet_count,tweet.favorite_count] #pour chaque tweet on recup info utiles for hashtag in tweets_hastag: collected_hashtag[tweet.id]=[tweet.user.name,tweet.text,tweet.retweet_count,tweet.favorite_count] return tweets_keywords, tweets_hastag except IOError as error: print(error) print(get_candidate_queries(1,'CandidateData'))
03a2a79eef645a244f623d178933899ed849b58f
ktsun2016/top11
/array_1.py
921
3.671875
4
def most_frequent(s): mp={} for i in s: if i in mp: mp[i] += 1 else: mp[i] = 1 max_times=max(mp.values()) for i, j in mp.items(): if j == max_times: return i s=[1,2,3,4,5,1,2,3,1,1] print(most_frequent(s)) def most_frequent(s): mp={} max_times = 0 max_num = 0 for i in s: if i in mp: mp[i] += 1 if mp[i] > max_times: max_times = mp[i] max_num = i else: mp[i] = 1 return max_num s=[1,2,3,4,5,1,2,3,1,1] print(most_frequent(s)) def most_frequent(s): mp={} max_times = 0 max_num = 0 for i in s: if i in mp: mp[i] += 1 else: mp[i] = 1 if mp[i] > max_times: max_times = mp[i] max_num = i return max_num s=[1,2,3,4,5,1,2,3,1,1] print(most_frequent(s))
624f4f48e466cd470885dbdca5ac79db422af69b
anarchy-muffin/web-spider
/spider.py
2,979
3.609375
4
import HTMLParser import urllib2 import parser #make class LinkParser that inherits methods from #HTMLParser which is why its passed to LinkParser definition. #This is a function that HTMLParser normally has #but we add functionality to it. def handle_starttag(self, tag, attrs): #looking for the beginning of a link # <a href="www.exampleurl.com"></a> if tag == 'a': for (key, value) in attrs: if key == 'href': #grabbing URL(s) and adding #base URL to it. For example: #www.example.com is the base and #newpage.html is the new URL (a relative URL) # #Combining a relative URL with the base HTML page #to create an absolute URL like: #www.example.com/newpage.html newURL = parse.urljoin(self.baseUrl, value) #add it to collection of links: self.links = self.links + [newUrl] #New function to get links that #spider() function will call def get_links(self, url): self.links = [] #Remember base URL which will be important #when creating absolute URLs self.baseUrl = url #use urlopen function from standard Python3 library response = urlopen(url) #Make sure you're looking @ HTML only!! #(No CSS, JavaScript, etc...) if response.getheader('Content-Type')=='text/html': htmlBytes = response.read() #note that feed() handles strings well but not bytes #A change from Python2.x to 3.x htmlString = htmlBytes.decode("utf-8") self.feed(htmlString) return htmlString, self.links else: return "",[] #This is the actual "spider" porton of the webspider (Hooray!) #it takes a URL, a word to find, and a number of pages to search #before giving up. def spider(url, word, maxPages): pagesToVisit = [url] numberVisited = 0 foundWord = False #above is the main loop creates a link parser and grabs all #links on the page, also searching through the page for the #desired quote or string, in getLinks function we return the page. #(helps with where to go next) while numberVisited < maxPages and pagesToVisit != [] and not foundWord: numberVisited = numberVisited +1 #Start from the beginning of our collection of pages url = pagesToVisit[1:] try : print (numberVisited, "Visiting: ", url) parser = LinkParser() data, links = parser.getlinks(url) if data.find(word)>-1: foundWord = True #Adds pages we found to end of the collection #of pages to visit. pagesToVisit = pagesToVisit + links print ("**SUCCESS**") except: print ("**FAILED**") if foundWord: print "The word", word, "was found at:" , url else: print "Word not found."
36444bd3621d0da6aed4b4784e103903b50e873d
Lesikv/python_tasks
/python_practice/nod.py
240
3.890625
4
#usr/bin/env python #coding:utf-8 a = int(input('Введите первое число: ')) b = int(input('Введите второе число: ')) k = a if a < b else b print k while (a % k != 0) or (b % k != 0): k -= 1 print k
88d7bcc2e6596be6ad87fe9a2e27a1217e91088f
Lesikv/python_tasks
/python_practice/diag_matrix.py
495
3.71875
4
#!/usr/bin/env python #coding: utf-8 def diag_matrix(arr): if not arr or len(arr) < 1: return None l_res = len(arr[0]) + len(arr) - 1 res = [[] for i in range(l_res)] i, j = 0, 0 for i in range(len(arr)): while j < len(arr): print 'i = {}, j = {}, res[i+j] = {}, res = {}, arr[i][j] = {}'.format(i, j, res[i+j], res, arr[i][j]) return res if __name__ == '__main__': print diag_matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
732a3d33f2420754f245c12e8de68f0ecd40df0e
Lesikv/python_tasks
/python_practice/binary_tree.py
4,705
3.875
4
#!usr/bin/env python #coding: utf-8 from collections import deque class Node(object): def __init__(self, value): self.value = value self.left = None self.right = None # Creating Fisrt Tree root1 = Node(1) root1.left = Node(3) root1.right = Node(2) root1.left.left = Node(5) root1_1 = Node(1) root1_1.left = Node(3) root1_1.right = Node(2) root1_1.left.left = Node(5) root1_1.right.left = Node(5) # Creating second Tree root2= Node(2) root2.left = Node(1) root2.right = Node(3) root2.left.right = Node(4) root2.right.right = Node(7) # Creating result tree for tests root3 = Node(3) root3.left = Node(4) root3.right = Node(5) root3.left.left = Node(5) root3.left.right = Node(4) root3.right.right = Node(7) def createTree(lst): if not lst: return root = Node(lst[0]) queue = deque([root]) i = 1 while i < len(lst): cur = queue.popleft() if lst[i]: print lst[i], 'LEFT', cur.value cur.left = Node(lst[i]) queue.append(cur.left) i += 1 if i >= len(lst): break if lst[i]: print lst[i], 'RIGHT', cur.value cur.right = Node(lst[i]) queue.append(cur.right) i += 1 return root def compareTree(tree1, tree2): res = {'0':{'first': [], 'second':[]}, '1':{'first':[], 'second':[]}} stack1 = [tree1] stack2 = [tree2] cur1 = None cur2 = None while stack1 and stack2: cur1 = stack1.pop() cur2 = stack2.pop() if cur1.value != cur2.value: res['0']['first'].append(cur1.value) res['0']['second'].append(cur2.value) print res, 'YAHOO1' return False else: res['1']['first'].append(cur1.value) res['1']['second'].append(cur2.value) if cur1.right: stack1.append(cur1.right) if cur1.left: stack1.append(cur1.left) if cur2.right: stack2.append(cur2.right) if cur2.left: stack2.append(cur2.left) print res, stack1, stack2 return not stack1 and not stack2 #def merge(tree1, tree2): # stack1 = [tree1] # stack2 = [tree2] # res = [] # cur1 = None # cur2 = None # i = 0 # while stack1 and stack2: # print i # cur1 = stack1.pop() # cur2 = stack2.pop() # if cur1 and cur2: # new_v = cur1.value + cur2.value # res.insert(i, new_v) # i += 1 # stack1.append(cur1.right) # stack1.append(cur1.left) # stack2.append(cur2.right) # stack2.append(cur2.left) # if not cur1: # if cur2: # res.insert(i, cur2.value) # stack2.append(cur2.right) # stack2.append(cur2.left) # stack1.append(None) # stack1.append(None) # i += 1 # elif not cur2: # res.insert(i, cur1.value) # stack1.append(cur1.right) # stack1.append(cur1.left) # stack2.append(None) # stack2.append(None) # i += 1 # # return res # def check_none(src1, src2): sum_res = 0 if src1: sum_res += src1.value if src2: sum_res += src2.value return sum_res def merge(tree1, tree2): root = Node(check_none(tree1, tree2)) stack1 = [tree1] stack2 = [tree2] stack3 = [root] while stack1 and stack2: cur1 = stack1.pop() cur2 = stack2.pop() cur3 = stack3.pop() cur1_left = cur1 and cur1.left cur2_left = cur2 and cur2.left cur1_right = cur1 and cur1.right cur2_right = cur2 and cur2.right if cur1_left or cur2_left: cur3.left = Node(check_none(cur1_left, cur2_left)) stack1.append(cur1_left) stack2.append(cur2_left) stack3.append(cur3.left) if cur1_right or cur2_right: cur3.right = Node(check_none(cur1_right, cur2_right)) stack3.append(cur3.right) stack1.append(cur1_right) stack2.append(cur2_right) return root def check(): print merge(root1, root2) assert compareTree(merge(root1, root2), root3) #assert compareTree(root1, root1), 'Проверка равенства равных деревьев' #assert compareTree(root1, root2) == False, 'Проверка неравенства разных деревьев' #assert compareTree(root1, root1_1) == False #assert compareTree(root1, createTree([1,3,2,5])) print 'Everything is OK' if __name__ == '__main__': check()
81ef8fcf4248d47775972f2b7f7dfe59afb9240a
Lesikv/python_tasks
/python_practice/loops/l_6_1.py
587
3.953125
4
#!/usr/bin/env python #coding: utf-8 ARRAY = [10, 6, 17, 5, 30, 20, 1, 100, 200] def find_max(arr, n): """ Для массива чисел найти первых два числа таких что, которое больше суммы всех предыдущих (если нет таких, что None) """ sum = 0 res = [] #for k in range(n): for i in range(1, len(arr)): sum += arr[i-1] if arr[i] > sum and len(res) < n: res.append(arr[i]) return res if __name__ == '__main__': print find_max(ARRAY, 3)
41b44b20257c4a5e99ca9af99d7ca7fc7066ed1c
Lesikv/python_tasks
/python_practice/matrix_tranpose.py
654
4.1875
4
#!usr/bin/env python #coding: utf-8 def matrix_transpose(src): """ Given a matrix A, return the transpose of A The transpose of a matrix is the matrix flipped over it's main diagonal, switching the row and column indices of the matrix. """ r, c = len(src), len(src[0]) res = [[None] * r for i in range(c)] for i in range(len(src)): for j in range(len(src[i])): res[j][i] = src[i][j] return res def test_1(): assert matrix_transpose([[1], [2]]) == [[1, 2]] def test_2(): assert matrix_transpose([[1, 2], [3, 4]]) == [[1, 3], [2,4]] if __name__ == '__main__': test_1() test_2()
f21d1ac135f6008ec7acf323c7c075c7ba9577f3
Lesikv/python_tasks
/python_practice/leetcode/list_reverse.py
1,010
3.96875
4
#!usr/bin/env python #coding: utf-8 class Node(object): def __init__(self, val, next=None): self.val = val self.next = next def __repr__(self): if not self.next: return self.val return '{} -> {}'.format(self.val, self.next) def __eq__(self, other): return self.val == other.val and self.next.val == other.next.val n = Node('a', Node('b', Node('c', Node('d')))) print n def list_reverse(lst): prev_n = None next_n = lst.next while True: lst.next = prev_n if not next_n: break prev_n = lst lst = next_n next_n = lst.next print 'prev_n = {}, lst = {}, next_n = {}'.format(prev_n, lst, next_n) return lst def test(): lst_for_check = Node('d', Node('c', Node('b', Node('a')))) #print lst_for_check assert list_reverse(n) == lst_for_check # операция сравнения if __name__ == '__main__': test() #print list_reverse(n)
87a5ddc77570672fe77793c828abaf042573619e
an9wer/socket-exp
/a-web-crawler-with-asyncio-coroutines/simple.py
708
3.5625
4
""" By default, socket operations are blocking: when the thread calls a method like connect or recv, it pauses until the operation completes. """ import socket def fetch(url): sock = socket.socket() sock.connect(("kxcd.com", 80)) request = "GET {} HTTP/1.1\r\nHost: xkcd.com\r\n\r\n".format(url) sock.send(request.encode("ascii")) response = b"" chunk = sock.recv(4096) # it'll block here. because it'll never receive close sign from server side. while chunk: response += chunk chunk = sock.recv(4096) print(chunk) # the following code will never be executed. print(response) sock.close() if __name__ == "__main__": fetch("/")
b79c74407ca0d2547cf55350d985f8e28338fc3d
Oukey/Algoritms
/task_solving/Binary_Search.py
1,060
3.796875
4
# Алгоритм двоичного поиска class BinarySearch: def __init__(self, array): self.array = array self.Left = 0 self.Right = len(array) - 1 self.result = 0 # 0 - поиск, +1 - элемент найден; -1 элемент не найден def Step(self, N): '''Метод выполнения одного шага поиска. Прнимает искомое число (int)''' if self.array[self.Left] > N or self.array[self.Right] < N: self.result = -1 mid = self.Left + (self.Right - self.Left) // 2 if self.result == 0: if self.array[mid] == N: self.result = 1 else: if self.Left == self.Right: self.result = -1 else: if self.array[mid] > N: self.Right = mid - 1 elif self.array[mid] < N: self.Left = mid + 1 def GetResult(self): return self.result
aaa5d1e8b29c70adf1b77239ebd314cb4fa42c4c
eriksandgren/AdventOfCode2018
/day03/day3.py
1,180
3.515625
4
#!/usr/bin/env python import sys def parseInput(): with open ("input.txt", "r") as myfile: myInput = myfile.read() myInput = myInput.split('\n') return myInput def part1and2(): my_input = parseInput() fabric = {} overriddenClaims = set() allClaims = set() for l in my_input: k = l.split() index = int(k[0][1:]) allClaims.add(index) fromLeft = int(k[2].split(',')[0]) fromTop = int(k[2].split(',')[1][:-1]) width = int(k[3].split('x')[0]) height = int(k[3].split('x')[1]) for i in xrange(fromLeft, fromLeft + width): for j in xrange(fromTop, fromTop + height): if (i,j) not in fabric: fabric[(i,j)] = index elif fabric[(i,j)] == 'X': overriddenClaims.add(index) else: overriddenClaims.add(index) overriddenClaims.add(fabric[(i,j)]) fabric[(i,j)] = 'X' doubleBookedSqInches = sum(value == 'X' for value in fabric.values()) print doubleBookedSqInches print allClaims - overriddenClaims part1and2()
92d28d6f3f391537f6903e2bfc196c49cb6aec6d
eriksandgren/AdventOfCode2018
/day01/day1.py
738
3.65625
4
#!/usr/bin/env python import sys def parseInput(): with open ("input.txt", "r") as myfile: myInput = myfile.read() myInput = myInput.split('\n') return myInput def part1(): my_input = parseInput() freq = 0 for l in my_input: if l[0] == '+': freq += int(l[1:]) else: freq -= int(l[1:]) print freq def part2(): my_input = parseInput() freq = 0 freqs = [] while True: for l in my_input: freqs.append(freq) if l[0] == '+': freq += int(l[1:]) else: freq -= int(l[1:]) if freq in freqs: print freq return part1() part2()
9990ff41328f7353af5deb036a45f751499f8cf9
jrantunes/URIs-Python-3
/URIs/URI1828.py
1,343
3.53125
4
#Bazinga! n = int(input()) for i in range(n): e1, e2 = input().split() if e1 == e2: print("Caso #{}: De novo!".format(i + 1)) elif e1 == "tesoura": if e2 == "papel" or e2 == "lagarto": print("Caso #{}: Bazinga!".format(i + 1)) elif e2 == "Spock" or e2 == "pedra": print("Caso #{}: Raj trapaceou!".format(i + 1)) elif e1 == "papel": if e2 == "pedra" or e2 == "Spock": print("Caso #{}: Bazinga!".format(i + 1)) elif e2 == "tesoura" or e2 == "lagarto": print("Caso #{}: Raj trapaceou!".format(i + 1)) elif e1 == "pedra": if e2 == "lagarto" or e2 == "tesoura": print("Caso #{}: Bazinga!".format(i + 1)) elif e2 == "papel" or e2 == "Spock": print("Caso #{}: Raj trapaceou!".format(i + 1)) elif e1 == "lagarto": if e2 == "Spock" or e2 == "papel": print("Caso #{}: Bazinga!".format(i + 1)) elif e2 == "pedra" or e2 == "tesoura": print("Caso #{}: Raj trapaceou!".format(i + 1)) elif e1 == "Spock": if e2 == "tesoura" or e2 == "pedra": print("Caso #{}: Bazinga!".format(i + 1)) elif e2 == "lagarto" or e2 == "papel": print("Caso #{}: Raj trapaceou!".format(i + 1))
16f2303123e1e653761bcd76b2685dc68b5cb682
jrantunes/URIs-Python-3
/URIs/URI2846.py
510
3.71875
4
# Fibonot def fib(n): if n == 1 or n == 2: return False ant = 1 atual = 2 termo = 0 check = True while True: termo = ant + atual ant = atual atual = termo if termo == n: check = False break elif n < termo: break return check x = int(input()) cont = 0 continua = True i = 4 while continua: if fib(i): cont += 1 if x == cont: print(i) continua = not continua i += 1
b0b1a21a1e1f1087488a7b1f1596ba42f911bb63
jrantunes/URIs-Python-3
/URIs/URI1131.py
569
3.515625
4
#Grenais v_i = 0 v_g = 0 empts = 0 grenais = 0 while True: i, g = list(map(int, input().split())) grenais += 1 if i == g: empts += 1 elif i > g: v_i += 1 else: v_g += 1 if int(input("Novo grenal (1-sim 2-nao)\n")) == 2: break else: pass print(grenais, "grenais") print("Inter:{}\nGremio:{}\nEmpates:{}".format(v_i, v_g, empts)) if empts == 1: print("Não houve vencedor") elif v_i > v_g: print("Inter venceu mais") else: print("Gremio venceu mais")
dc67a9ee4f146db344f44d0266db9e77c03a8fbe
jrantunes/URIs-Python-3
/URIs/URI2823.py
219
3.609375
4
#Eearliest Deadline First v = int(input()) sum = 0.0 for i in range(v): c, p = input().split() c = float(c) p = float(p) sum += c / p if sum <= 1.0: print("OK") else: print("FAIL")
99a5cfd9f1daa6b6f13678dbb165c2cd30d4fb37
jrantunes/URIs-Python-3
/URIs/URI1158.py
407
3.53125
4
#Sum of Consecutive Odd Numbers III n = int(input()) for i in range(n): valores = input().split() v1 = int(valores[0]) v2 = int(valores[1]) soma = 0 j = 1 while j <= v2: if v1 % 2 != 0: soma = soma + v1 v1 = v1 + 1 j = j + 1 if v1 % 2 == 0: v1 = v1 + 1 print(soma)
ed9135aa85c66c48840f87ab1ed25960d086d75e
jrantunes/URIs-Python-3
/URIs/URI1045.py
691
3.953125
4
#Triangle Types valores = input().split() v1 = float(valores[0]) v2 = float(valores[1]) v3 = float(valores[2]) nums = [v1, v2, v3] nums.sort() nums.reverse() A = nums[0] B = nums[1] C = nums[2] A_QUAD = A ** 2 BC_QUAD = (B ** 2) + (C ** 2) if A >= B + C: print("NAO FORMA TRIANGULO") exit() else: if A_QUAD == BC_QUAD: print("TRIANGULO RETANGULO") elif A_QUAD > BC_QUAD: print("TRIANGULO OBTUSANGULO") if A_QUAD < BC_QUAD: print("TRIANGULO ACUTANGULO") if A == B == C: print("TRIANGULO EQUILATERO") elif A == B or A == C or B == C: print("TRIANGULO ISOSCELES")
992e74a72343c533ddb451d02a06a9e3241e06e1
jrantunes/URIs-Python-3
/URIs/URI1060.py
167
3.8125
4
#Positive Numbers ctr = 0 for i in range(6): n = float(input()) if n > 0: ctr += 1 else: pass print(ctr, "valores positivos")
723bd68463f045dfd0c5238377c1ed5be7319028
jrantunes/URIs-Python-3
/URIs/URI1180.py
256
3.609375
4
#Lowest Number and Position n = int(input()) vetor = [] nums = list(map(int, input().split())) for i in range(n): vetor.insert(i, nums[i]) print("Menor valor: {}".format(min(vetor))) print("Posicao: {}".format(vetor.index(min(vetor))))
a2429afa5815ad974f8333577a17556f1be5744f
jrantunes/URIs-Python-3
/URIs/URI1253.py
402
3.625
4
#Caesar Cipher abc = 'abcdefghijklmnopqrstuvwxyz' rep = int(input()) for x in range(rep): cifrada = ','.join(input()).lower().split(',') n = int(input()) indices = [] for c in cifrada: indices.append(abc.index(c) - n) palavra = [] for i in indices: palavra.append(abc[i]) resultado = ','.join(palavra).strip('[]').replace(',', '').upper() print(resultado)
c48fb659bcc310e1af9be46ca7f843e104b887fa
jrantunes/URIs-Python-3
/URIs/URI1279.py
733
3.78125
4
#Leap Year or Not Leap Year and … pula_linha = 0 while True: try: ano = int(input()) biss = 0 ordi = 1 if pula_linha: print("") pula_linha = 1 if ano % 4 == 0 and not(ano % 100 == 0) or ano % 400 == 0: print("This is leap year.") biss = 1 ordi = 0 if ano % 15 == 0: print("This is huluculu festival year.") ordi = 0 if ano % 55 == 0 and biss: print("This is bulukulu festival year.") if ordi: print("This is an ordinary year.") except EOFError: break
03bda825834035b06a91c3d876bc06a2269c229c
jrantunes/URIs-Python-3
/URIs/URI1072.py
277
3.59375
4
#Interval 2 in_interval = [] out_interval = [] for i in range(int(input())): x = int(input()) if x in range(10, 21): in_interval.append(x) else: out_interval.append(x) print("{} in\n{} out".format(len(in_interval), len(out_interval)))
8f2e81c5a6eec3157fa16312286e2e8a1582d007
jrantunes/URIs-Python-3
/URIs/URI1018.py
204
3.625
4
#Banknotes notas = [100, 50, 20, 10, 5, 2, 1] n = int(input()) print(n) for nota in notas: qtde = int(n / nota) print("{} nota(s) de R$ {},00".format(qtde, nota)) n -= qtde * nota
9d78bf9b9817518547a0c7c76a17a731b923f389
jrantunes/URIs-Python-3
/URIs/URI1019.py
177
3.734375
4
#Time Conversion N = int(input()) h = 3600 m = 60 hora = N // h min = N // m minutos = min % m segundos = N % m print("{}:{}:{}".format(hora, minutos, segundos))
c7338bfb436b00654b9a30e84308dfb72bfa29b1
eileencuevas/Graphs
/projects/graph/src/graph.py
3,483
4.03125
4
""" Simple graph implementation """ from queue import Queue from stack import Stack class Graph: """Represent a graph as a dictionary of vertices mapping labels to edges.""" def __init__(self): self.vertices = {} def add_vertex(self, vertex_id): self.vertices[vertex_id] = set() def add_edge(self, v1, v2): if v1 in self.vertices and v2 in self.vertices: self.vertices[v1].add(v2) self.vertices[v2].add(v1) else: raise IndexError("That vertex does not exist") def add_directed_edge(self, v1, v2): if v1 in self.vertices and v2 in self.vertices: self.vertices[v1].add(v2) else: raise IndexError("That vertex does not exist") def bft(self, starting_vertex_id): # Breath-First Traversal q = Queue() q.enqueue(starting_vertex_id) visited = set() while q.size() > 0: v = q.dequeue() if v not in visited: print(f"current vertex {v}") visited.add(v) for next_vert in self.vertices[v]: q.enqueue(next_vert) def dft(self, starting_vertex_id): # Depth-First Traversal s = Stack() s.push(starting_vertex_id) visited = set() while s.size() > 0: v = s.pop() if v not in visited: print(f"current vertex {v}") visited.add(v) for next_vert in self.vertices[v]: s.push(next_vert) def dft_recursive(self, starting_vertex_id, visited=None): if visited is None: visited = set() if starting_vertex_id not in visited: visited.add(starting_vertex_id) print(f"current vertex: {starting_vertex_id}") for next_vert in self.vertices[starting_vertex_id]: self.dft_recursive(next_vert, visited) def bfs(self, starting_vertex, target): # Breath-First Search search_queue = Queue() search_queue.enqueue([starting_vertex]) visited = set() while search_queue.size() > 0: current_path = search_queue.dequeue() current_vertex = current_path[-1] if current_vertex not in visited: if current_vertex == target: return current_path visited.add(current_vertex) for next_vert in self.vertices[current_vertex]: new_path = list(current_path) new_path.append(next_vert) search_queue.enqueue(new_path) return f"No route found from {starting_vertex} to {target}" def dfs(self, starting_vertex, target): # Depth-First Search search_stack = Stack() search_stack.push([starting_vertex]) visited = set() while search_stack.size() > 0: current_path = search_stack.pop() current_vertex = current_path[-1] if current_vertex not in visited: if current_vertex == target: return current_path visited.add(current_vertex) for next_vert in self.vertices[current_vertex]: new_path = list(current_path) new_path.append(next_vert) search_stack.push(new_path) # target not found return f"No route found from {starting_vertex} to {target}"
0f4e686cbbf11bda4e773f725caae54413316c6a
Tonguesten36/PersonalRepo
/TonguestenPasswordUtility/PasswordManager/PasswordManager.py
7,688
3.921875
4
import sqlite3 from time import sleep from pip._vendor.distlib.compat import raw_input # For creating a new database def create_new_database(database): # You can add your own database file if you want, as long as you replace the placeholder file "PasswordDatabase.db" connection = sqlite3.connect(database) cursor = connection.cursor() sql_create_table = """CREATE TABLE Password ( website NVARCHAR(50) NOT NULL, accountName NVARCHAR(50) NOT NULL, password NVARCHAR(50) NOT NULL); """ try: cursor.execute(sql_create_table) except sqlite3.DatabaseError: print("Table already exists, sorry about that!") connection.commit() connection.close() # Operation 1: List all passwords available def list_all_password_available(database): connection = sqlite3.connect(database) cursor = connection.cursor() display_password_all = "SELECT * FROM Password" cursor.execute(display_password_all) ans = cursor.fetchall() print("################## Here are the available passwords: #########################") for i in ans: print(f"{i}") connection.close() # Operation 2: Find a password from a specific website def find_password_from_database(database): connection = sqlite3.connect(database) cursor = connection.cursor() print("################ FIND A PASSWORD FROM A SPECIFIC WEBSITE ######################") print("Enter the website that might contains the password you're looking for in the database") web_input = raw_input("Enter here: ") try: # Searching for the password and account based on the associated website select_with_website = "select accountName, password from Password where website = \"{}\";".format(web_input) cursor.execute(select_with_website) # Checking if the website that you're looking for exists in the database web_exist = bool(cursor.fetchall()) if web_exist: # If the website is found select_with_website = "select accountName, password from Password where website = \"{}\";".format(web_input) cursor.execute(select_with_website) return_value = cursor.fetchall() print("\nHere are the accounts for the {} website".format(web_input)) print(return_value) else: # If the website is not found print("Website not found in the database") except sqlite3.OperationalError: # If the user forget to type inside the double quotes print("Are you sure that you're typing the website inside the double quotes?") connection.close() # Operation 3: Create a new password def create_new_password(database): connection = sqlite3.connect(database) cursor = connection.cursor() print("################ CREATE A NEW PASSWORD ######################") # Ask the user how many passwords do they want to add how_many_password = input("How many passwords do you want to add? (enter here) ") # Check if the user is typing in an integer try: if int(how_many_password) > 0: # Asking the user to enter necessary data for the process, # and repeat the process according to their how_many_password input for i in range(int(how_many_password)): new_website = raw_input("Enter the new website: ") new_username = raw_input("Enter the new username: ") new_password = raw_input("Enter the new password: ") param = (new_website, new_username, new_password) # Add the newly entered data into the database cursor.execute("insert into Password values (?, ?, ?)", param) except ValueError: print("Try again.") connection.commit() connection.close() def delete_password_from_database(database): connection = sqlite3.connect(database) cursor = connection.cursor() print("################ DELETE A PASSWORD FROM THE DATABASE ACCORDING TO THE ACCOUNT'S NAME ######################") print("Which account do you want to wipe out from the database?") delete_target = raw_input("Enter the account's name that you wish to delete here (case sensitive): ") try: check_account = "SELECT * FROM Password WHERE accountName = \"?\";" + (str(delete_target)) cursor.execute(check_account) account_exists = bool(cursor.fetchall()) # Check if the target website exists if account_exists: print("Deleting the account {}".format(delete_target)) deleting_password = "DELETE FROM Password WHERE accountName = \"?\";" + (str(delete_target)) cursor.execute(deleting_password) connection.commit() else: print("Cannot found the target account.") except ValueError: print("Try again.") finally: connection.close() def edit_password_info(database): connection = sqlite3.connect(database) cursor = connection.cursor() print("################ EDIT A PASSWORD'S INFO ######################") print("Enter the website's name and the account name to edit a password") website = raw_input("Website: ") account = raw_input("Account: ") new_password = raw_input("Enter your new password here: ") try: check_account_existence = "SELECT password FROM Password WHERE accountName = ?, website = ?" + account cursor.execute(check_account_existence) web_and_account_exists = bool(cursor.fetchall()) if web_and_account_exists: edit_info = "UPDATE Password SET password = ?, accountName = ?" cursor.execute(edit_info, (new_password, website, account)) connection.commit() print("Password successfully updated.") else: print("There is not such website and account in the database.") except sqlite3.OperationalError: print("Something went wrong. The account that you're looking for might not be exists") finally: connection.close() def main_program(): a = 0 while a < 1: print() print("################ PASSWORD MANAGER ######################") print("Welcome to the Password Manager, user. Here is a list of operations you could use in this program:") print("0. Create a new password database (if it's not available already") print("1. List all passwords available") print("2. Find a password with its according website") print("3. Add a new password") print("4. Remove a password") print("5. Edit a password's info") print("6. About this program") print("7. Exit the program") opt = input("Enter here: ") # The database file in the folder database = "PasswordDatabase.db" if opt == "0": create_new_database(database) elif opt == "1": list_all_password_available(database) elif opt == "2": find_password_from_database(database) elif opt == "3": create_new_password(database) elif opt == "4": delete_password_from_database(database) elif opt == "5": edit_password_info(database) elif opt == "7": thank_you = "Thank you for using Password Manager" for i in thank_you: print(f"{i}", end="") sleep(0.1) for i in range(0, 3, 1): print(".", end="") sleep(0.5) a = 1 else: print("Try again.") if __name__ == '__main__': main_program()
7de0c49e2d65108f1c388b51983e5f6e020550b5
LookADonKill/Python
/classes.py
1,015
3.84375
4
nama3 = input("Masukkan nama dari mobil yang ingin anda beli :") brand3 = input("Masukkan merek dari mobil tersebut :") garansi3 = int(input("Masukkan lama garansi yang diinginkan untuk mobil tersebut :")) power3 = int(input("Masukkan banyaknya power yang dimiliki mobil yang diinginkan :")) warna3 = input("Masukkan warna mobil yang diinginkan :") class Otomotif: def __init__(self, nama, brand, garansi, power, warna): self.nama = nama self.brand = brand self.garansi = garansi self.power = power self.warna = warna def info(self): print(f'Mobil ini bernama {self.nama} yang bermerek {self.brand} dan memiliki garansi selama {self.garansi} tahun. Mobil ini memiliki power sebanyak {self.power} cc dan biasanya berwarna {self.warna}.') mobil1 = Otomotif('Mustang', 'Ford', '5 tahun', '3000 cc', 'Biru') mobil2 = Otomotif('Gallardo', 'Lamborghini', '3 tahun', '2500 cc', 'Hitam') mobil3 = Otomotif(nama3, brand3, garansi3, power3, warna3) mobil3.info()
274ecf7c27a5bb87ea374816a9b6f2fc617d1034
LookADonKill/Python
/Gajikerja.py
320
3.71875
4
print("PAYMENT COMPUTATION FOR EMPLOYEE") print("--------------------------------") angka = 10 def gaji(x,y): if Jam > angka: return(200 + (x * y)) elif Jam < angka: return(x * y) Jam = int(input("Enter work hours :")) Rate = int(input("Enter work rate :")) Hasil = gaji(Jam, Rate) print(Hasil)
aec6d7cc480ea842c5b5ae9cf40eeb4f6690dfc9
kathrintravers/Hackerrank
/if_else_loop.py
310
4.0625
4
#!/usr/bin/env python3 if __name__ == '__main__': n = int(input().strip()) if n%2 != 0: print('weird') elif n%2 == 0 and n in range(2,5): print('not weird') elif n%2 == 0 and n in range (6,21): print('weird') elif n>20 and n%2 == 0: print('not weird')
0f8dc99960194214b89becc254e40d383e68bd45
anubhavcu/python-sandbox-
/lists.py
3,156
4.1875
4
# lists are ordered and mutable sequence , allows duplicate members # lists are also heterogenous (can contain int, float,str type together) import random numbers = [1, 2, 3, 4, 5, 6] # numbers1 = list(1, 2, 3, 4, 5) # will generate an error - as list constructor takes 1 argument only numbers1 = list((1, 2, 3, 4, 5)) heterogenous_list = [1, 2, 3, 4, 'abc'] print(heterogenous_list) print('lists on new line ', numbers, '\n', numbers1) fruits = ['apple', 'oranges', 'grapes', 'pears'] print(len(fruits)) print(fruits[1]) # adding to list fruits.append('mangoes') print(fruits) # adding to position fruits.insert(3, 'banana') print(fruits) l1 = [1, 2, 3, 4] l1.insert(2, [7, 8]) print('inserting a list ', l1) # remove elements fruits.remove('pears') print(fruits) # remove with pop fruits.pop(3) fruits.pop() # removes last element if no index is provided print(fruits) # reverse fruits.reverse() print(fruits) # sorting fruits.append('aa') fruits.sort() print(fruits) # reverse sort fruits.sort(reverse=True) print(fruits) # changing values fruits[1] = 'changed value' fruits[len(fruits)-1] = 'blueberries' print(fruits) # some more eg a = [1, 2, 3, 'cat'] # heteregenous list print(len(a)) print(a[-1]) print(a[1]) # * can be used to create multiple concatenated copies of list a = a * 2 print('multiply', a) # in can be used to check for membership ( same as with strings) print('cat' in a) # return true print(3 in a) # true print(4 in a) # false list1, list2 = [1, 2, 3, 4], [5, 6, 7, 8] print(list1, list2) # we can use '+' to concatenate two lists list3 = list1 + list2 print('concatenate two strings ', list1+list2) print(list3) print(a) print(a.index('cat')) # returns the first occurence of the searched element print(a.index(2)) print(a.count('cat')) random_list = [1, 2, 3] print(random_list) random_list[0] = 2 print(random_list) print(random_list[-1] == random_list[len(random_list) - 1]) # unpacking of list elements - make sure to use correct number of parameters on both sides new_list = [1, 2, 3] a, b, c = new_list print(a, b, c) # d, e, f = [1, 2], 15 # will throw an error- either use complete list with exact number of values in list to number of variables value is being assigned to. # d, e, f = [1, 2, 3, 4] # throw an error - too many values to unpack d, e, f = [10, 20, 30] print(d, e, f) # eg x = [1, 2, 3, 4] y = [10, 20, x, 30] z = [10, 20, *x, 30] print('embedding a list', y) print('unpacking a list ', z) # swapping lists l1 = [1, 2, 3] l2 = [5, 6, 7] print('l1', l1) print('l2', l2) l1, l2 = l2, l1 print('l1', l1) print('l2', l2) # slicing of lists, same as with strings numbers_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(numbers_list[:5]) print(numbers_list[:: -1]) # reversed list # to check if present print(8 in numbers_list) # list of lists a = [1, 3, 5, 7, 9] b = [2, 4, 6, 8, 10] c = [a, b] print(c) # 0th element of 0th list and element with index 2 of list with index 1 print(c[0][0], c[1][2]) # list comprehension p = [random.randint(10, 100) for n in range(20)] print(p) l1 = [1, 2, 3, 4, 5] l1 = l1[::-1] # print(l1[::-1]) print(l1)
485fd356a2b3da8cd0db30d1d83714ef64d174f2
anubhavcu/python-sandbox-
/conditionals.py
1,765
4.15625
4
x = 50 y = 50 # if-else: <, >, == # if x > y: # print(f'{x} is greater than {y}') # else: # print(f'{x} is smaller than {y}') if x > y: print(f'{x} is greater than {y}') elif x < y: print(f'{x} is smaller than {y}') else: print("Both numbers are equal") # logical operators - and, or, not x = 5 if x > 2 and x < 10: print(f'{x} is greater than 2 and less than 10') if x > 2 or x <= 10: print(f'{x} is greater than 2 or less than 10') if not(x == y): print(f'{x} is not equal to {y}') # membership operators -not , not in numbers = [1, 2, 3, 4, 5] if x in numbers: print(x in numbers) if y not in numbers: print(y not in numbers) # identity operators - is, is not if x is y: print(x is y) if x is not y: print('x is not y', x is not y) if type(x) is int: print('x is int type') l1 = [] l2 = [] l3 = l1 l4 = l3 + l1 print('l1 == l2', l1 == l2) # true print('l1 is l2', l1 is l2) # false print('l1 == l3', l1 == l3) # true print('l1 is l3', l1 is l3) # true print('l4 is l3', l4 is l3) # false # == and is are slightly different - # == checks if values of both variables are same # is checks whether variable point to the same object # l1 is l2 returns false as two empty lists are at different memory locations , hence l1 and l2 refer to different objects - we can check that by id(l1) and id(l2) # l4 is l3 return false as concatenation of two lists always produce a new list a = 1 f = a print('a', a, id(a)) print('f', f, id(f)) print(f is a) a = 2 print('a', a, id(a)) print('f', f, id(f)) print(f is a) # note when doing f = a, f now refers to the value a is referring to (not a), so when we change value of a,say to 2, then a will refer to 2 but f is referring to 1.
bd63890f1648bf6b2b5e257c939ef5748534df26
gpolaert/cs231n
/assignment1/cs231n/classifiers/softmax.py
4,279
3.953125
4
import numpy as np def softmax_loss_naive(W, X, y, reg): """ Softmax loss function, naive implementation (with loops) Inputs have dimension D, there are C classes, and we operate on minibatches of N examples. Inputs: - W: A numpy array of shape (D, C) containing weights. - X: A numpy array of shape (N, D) containing a minibatch of data. - y: A numpy array of shape (N,) containing training labels; y[i] = c means that X[i] has label c, where 0 <= c < C. - reg: (float) regularization strength Returns a tuple of: - loss as single float - gradient with respect to weights W; an array of same shape as W """ # Initialize the loss and gradient to zero. loss = 0.0 dW = np.zeros_like(W) num_train = X.shape[0] num_classes = W.shape[1] ############################################################################# # TODO: Compute the softmax loss and its gradient using explicit loops. # # Store the loss in loss and the gradient in dW. If you are not careful # # here, it is easy to run into numeric instability. Don't forget the # # regularization! # ############################################################################# for i in range(num_train): f_i = X[i, :].dot(W) # 1xC # Normalization trick to avoid numerical instability, per http://cs231n.github.io/linear-classify/#softmax f_i -= np.max(f_i) sum_i = 0 for j in range(num_classes): sum_i += np.exp(f_i[j]) loss += - f_i[y[i]] + np.log(sum_i) # Compute gradient # dw_j = 1/num_train * \sum_i[x_i * (p(y_i = j)-Ind{y_i = j} )] # Here we are computing the contribution to the inner sum for a given i. for j in range(num_classes): p = np.exp(f_i[j]) / sum_i dW[:, j] += (p - (j == y[i])) * X[i, :] loss /= num_train loss += 0.5 * reg * np.sum(W * W) dW /= num_train dW += reg * W ############################################################################# # END OF YOUR CODE # ############################################################################# return loss, dW def softmax_loss_vectorized(W, X, y, reg): """ Softmax loss function, vectorized version. Inputs and outputs are the same as softmax_loss_naive. """ # Initialize the loss and gradient to zero. loss = 0.0 dW = np.zeros_like(W) num_train = X.shape[0] num_classes = W.shape[1] ############################################################################# # TODO: Compute the softmax loss and its gradient using no explicit loops. # # Store the loss in loss and the gradient in dW. If you are not careful # # here, it is easy to run into numeric instability. Don't forget the # # regularization! # ############################################################################# scores = X.dot(W) # Normalization trick to avoid numerical instability, per http://cs231n.github.io/linear-classify/#softmax scores -= np.max(scores) sums = np.exp(scores).sum(axis=1) correct_class_scores = scores[np.arange(num_train), y] loss = np.sum(- correct_class_scores + np.log(sums)) loss /= num_train loss += 0.5 * reg * np.sum(W * W) scores_norm = np.exp(scores) / (sums[:, np.newaxis]) # My understanding: scores_norm are [0,1]. So subtracting 1 to the correct classes makes it neg # A grad step is self.W -= learning_rate * grad # During the the training update: # - Neg values will reinforce the weights (minus * minus) # - Pos values will penalize the weights (minus * plus) scores_norm[np.arange(num_train), y] -= 1 dW = X.T.dot(scores_norm) dW /= num_train dW += reg * W ############################################################################# # END OF YOUR CODE # ############################################################################# return loss, dW
74abafdf12176b1a10f25c2d687ea19eb4eb6142
AlexanderShulepov/Guillou-Quisquater
/sugar.py
538
3.796875
4
def exgcd(a, b): if a == 0: return (b, 0, 1) else: g, y, x = exgcd(b % a, a) return (g, x - (b // a) * y, y) def inverse_of(a, m): g, x, y = exgcd(abs(a), m) if g != 1: raise Exception('Обратного элемента не существует') else: if a > 0: return x % m else: return -x % m def gcd(a,b): while a!=0 and b!=0: if a > b: a = a % b else: b = b % a return True if a+b==1 else False
87cbc63b1db6b75bb7ea4e539458398ea9944b81
chrisgrimm/fidex_implementation
/instances.py
4,065
3.640625
4
import os, re from typing import List class Instance(object): def __init__(self, all_words : List[str], regex : str): self.all_words = all_words self.regex = regex self.positive_words = [word for word in all_words if re.match(regex, word)] self.negative_words = [word for word in all_words if not re.match(regex, word)] def __repr__(self): return f'Instance({self.regex}, [{",".join(self.positive_words[:3])}, ...], [{",".join(self.negative_words[:3])}, ...])' def __str_(self): return f'Instance({self.regex}, [{",".join(self.positive_words[:3])}, ...], [{",".join(self.negative_words[:3])}, ...])' instances = [ Instance(['cat', 'cats', 'dog', '123', 'goat', 'CAT'], '^cat.*?$'), # startswith cat Instance(['0012', '0021', '1234', 'saufbgaosd', 'AODFI', '00000'], '^\d\d\d\d$'), # 4 digit number Instance(['000', '00', '0', '00000', 'adofioi23', '2oi3jdsf', 'o3qweajfisj'], '^0+?$'), # sequence of zeros Instance(['dogcat', 'catcat', '1234cat', '001234', 'asdf', 'asdfsdf', 'asdf2fe', 'asdfasdf'], '^.*?cat$'), # endswith cat Instance(['cat1', 'cat2', 'cat3', 'cat4', 'dog1', 'dog2', 'dog3', 'dog4'], '^cat.*?$'), # cats not dogs Instance(['Robert M. Smith', 'John E. Doe', 'James F. Franco', 'Wesley W. Weimer', 'John Stuart', 'Jimmy Mcgill', 'Johnny Walker', 'Jeffrey Dahmer'], '^.*?\..*?$') # middle names ] with open('ls_outputs.txt', 'r') as f: lines = f.readlines() all_words = [line.split(' ') for line in lines] instances += [ Instance(all_words[0], '^.*?fidex.*?$'), # contains fidex Instance(all_words[0], '^.*?py$'), # endswith py Instance(all_words[0], '^.*?txt$'), # endswith txt Instance(all_words[0], '^test.*?$'), # startswith test Instance(all_words[1], '^.*?png$'), # ends with png Instance(all_words[1], '^venv.*?$'), # starts with venv Instance(all_words[1], '^Gradly.*?$'), # starts with gradly Instance(all_words[1], '^.*?\d+?.*?$'), # contains numbers Instance(all_words[1], '^.+?\d+?$'), # endswith numbers Instance(all_words[2], '^.*?samples.*?$'), # contains samples Instance(all_words[2], '^.*?image.*?$'), # contains image Instance(all_words[2], '^commence.*?$'), # startswith commence Instance(all_words[2], '^.*?sokoban.*?$'), # contains sokoban Instance(all_words[2], '^.*?png$'), # endswith png Instance(all_words[2], '^[A-Z].*?$'), # startswith uppercase Instance(all_words[2], '^.*?\d+?.*?$'), # contains number Instance(all_words[3], '^all.*?$'), # startswith all Instance(all_words[3], '^.*?sokoban.*?$'), # contains sokoban Instance(all_words[3], '^.*?pacman.*?$'), # contains pacman Instance(all_words[3], '^.*?assault.*?$'), # contains assault Instance(all_words[3], '^.*?py$'), # endswith py Instance(all_words[3], '^grab.*?$'), # startwith grab Instance(all_words[3], '^.*?png$'), # endswith png Instance(all_words[3], '^.*?dqn.*?$'), # contains dqn Instance(all_words[3], '^max\_image\d\.png$'), # matches max_image\d Instance(all_words[3], '^.*?\d.*?$'), # contains numbers Instance(all_words[3], '^.*?metacontroller.*?$'), # contains metacontroller Instance(all_words[4], '^assault.*?$'), # startswith assault Instance(all_words[4], '^.*?vis$'), #endswith vis Instance(all_words[4], '^.*?\d'), # endswith number Instance(all_words[4], '^assault\_traj\_40\_\d$'), # matches assault traj 40 run Instance(all_words[4], '^part\d.*?$'), # startswith part\d Instance(all_words[4], '^.*?sokoban.*?$'), #contains sokoban Instance(all_words[6], '^\d+x.*?$'), #startswith multiplier Instance(all_words[6], '^.*?resets$'), #endswith resets Instance(all_words[6], '^internal.*?$'), #startswith internal Instance(all_words[6], '^\D+?$'), # no digits Instance(all_words[6], '^.*?run.*?'), # contains run Instance(all_words[7], '^.*?py$'), # endswith py Instance(all_words[7], '^gan.*?$'), #startswith gan ] if __name__ == '__main__': for i, instance in enumerate(instances): print(i, instance)
5b468949ae623e6299665ff77feca0857763ead7
benson-w/cf
/codefights/isCryptSolution.py
1,335
3.765625
4
def isCryptSolution(crypt, solution): w1 = crypt[0] w2 = crypt[1] w3 = crypt[2] if (checkFirst(w1, solution) == 1) or (checkFirst(w2, solution) == 1): print("false") return 0 if calculateVal(w1, solution) + calculateVal(w2, solution) == calculateVal(w3, solution): print("true") return 1 else: print("false") return 0 def checkFirst(s, solution): for j in range(0, len(solution)): if (solution[j][0] == s[0]) and (int(solution[j][1]) == 0) and (len(s) != 1): return 1 return 0 def calculateVal(s, solution): total = 0 for i in range(0, len(s)): for j in range(0, len(solution)): if (solution[j][0] == s[i]): total = total + (int(solution[j][1]) * (10 ** (len(s) - i - 1))) return total # solution = [['O', '0'], # ['M', '1'], # ['Y', '2'], # ['E', '5'], # ['N', '6'], # ['D', '7'], # ['R', '8'], # ['S', '9']] # # crypt = ["SEND", "MORE", "MONEY"] # solution = [['O', '1'], # ['T', '0'], # ['W', '9'], # ['E', '5'], # ['N', '4']] # # crypt = ["TEN", "TWO", "ONE"] solution = [["A","0"]] crypt = ["A", "A", "A"] isCryptSolution(crypt, solution)
8c1dafca1b0db6b851a178921d01e5625f2fae12
pranavtotla/polygonlite
/polygonlite/Point.py
3,352
3.890625
4
from .Services import dot import math from .config import THRESHOLD class Point: """ Class for Points. A Point p can be accessed in various ways: 1. p[0], p[1] 2. p.x, p.y 3. p['x'], p['y'] """ def __init__(self, *args, **kwargs): if len(args) == 1: self.point = args[0] self.x = self.point[0] self.y = self.point[1] elif len(args) == 2: self.x = args[0] self.y = args[1] self.point = [self.x, self.y] elif len(args) == 0: self.x = kwargs.get('x') self.y = kwargs.get('y') self.point = [self.x, self.y] def clone(self): """ Returns a new Point object with same parameters as the point. :return: Point """ return Point(self.x, self.y) def square(self): """ Returns a new Point object which has squared x and squared y values. For example: (2,5) -> (4,25) (-2,5) -> (4,25) :return: Point """ return self.__class__(self.x * self.x, self.y * self.y) def sum(self): """ Returns the sum of parameters of x and y of the Point object. For example: (1,2) -> 3 (-1,0) -> -1 :return: """ return self.x + self.y def distance(self, other): """ Returns the distance between two points. For example: distance between (0,2) and (0,5) is 3. :param other: Point :return: float """ return math.sqrt((self - other).square().sum()) def project(self, edge): """ Projects the point on a given Edge. :param edge: Edge :return: Point """ vector = edge.unit_vector() edge_to_point = self - edge.point1 return edge.point1 + (vector * dot(edge_to_point, vector)) def as_array(self): return [self.x, self.y] def __repr__(self): return str([self.x, self.y]) def __getitem__(self, key): if (key == 0) or (key == 'x'): return self.x if (key == 1) or (key == 'y'): return self.y raise KeyError('Invalid key: %s. Valid keys are 0, 1, "x" and "y"' % key) def __setitem__(self, key, value): if (key == 0) or (key == 'x'): self.x = value elif (key == 1) or (key == 'y'): self.y = value raise KeyError('Invalid key: %s. Valid keys are 0, 1, "x" and "y"' % key) def __eq__(self, other): if not isinstance(other, Point): return False if (self.x - other.x) < THRESHOLD: if (self.y - other.y) < THRESHOLD: return True return False def __ne__(self, other): return not self.__eq__(other) def __neg__(self): return self.__class__(-self.x, -self.y) def __add__(self, other): return self.__class__([self.x + other.x, self.y + other.y]) def __sub__(self, other): return self.__class__([self.x - other.x, self.y - other.y]) def __mul__(self, other): return self.__class__([self.x * other, self.y * other]) def __div__(self, other): return self.__class__([self.x / float(other), self.y / float(other)]) def __len__(self): return 2
055abf3d492646cb6c1a38984812814e47dae0cf
HenziKou/Free-Code-Camp
/Python Projects/Budget App/budget.py
4,790
3.65625
4
from typing import List class Category(): def __init__(self, name: str): self.name = name self.ledger = [] def __str__(self): # Using formatted strings: align center, 30 char min, '*' as filler char title = f"{self.name:*^30}" + "\n" items = "" total = "Total: " + str(self.getBalance()) for item in self.ledger: # Formatted strings: right align, 7 char min, 2 rounded decimal places # -------------------------------------------------------------- # | items += f"{item['description'][0:23]:23}" + f"{item['amount']:>7.2f}" + "\n" return title + items + total def deposit(self, amount: int, description = "") -> None: """ A deposit method that accepts an amount and description. If no description is given, it should default to an empty string. The method should append an object to the ledger list in the form of {"amount": amount, "description": description}. """ self.ledger.append( {"amount": amount, "description": description} ) return None def withdraw(self, amount: int, description = "") -> bool: """ A withdraw method that is similar to the deposit method, but the amount passed in should be stored in the ledger as a negative number. If there are not enough funds, nothing should be added to the ledger. This method should return True if the withdrawal took place, and False otherwise. """ if (self.checkFunds(amount)): self.ledger.append( {"amount": (-1 * amount), "description": description} ) return True return False def getBalance(self) -> float: """ A get_balance method that returns the current balance of the budget category based on the deposits and withdrawals that have occurred. """ balance = 0 for item in self.ledger: balance += item["amount"] return balance def transfer(self, amount: int, budget) -> bool: """ A transfer method that accepts an amount and another budget category as arguments. The method should add a withdrawal with the amount and the description "Transfer to [Destination Budget Category]". The method should then add a deposit to the other budget category with the amount and the description "Transfer from [Source Budget Category]". If there are not enough funds, nothing should be added to either ledgers. This method should return True if the transfer took place, and False otherwise. """ transfer_to = "Transfer to" + budget.name transfer_from = "Transfer from" + self.name if (self.checkFunds(amount)): self.withdraw(amount, transfer_to) budget.deposit(amount, transfer_from) return True return False def checkFunds(self, amount: int) -> bool: """ A check_funds method that accepts an amount as an argument. It returns False if the amount is greater than the balance of the budget category and returns True otherwise. This method should be used by both the withdraw method and transfer method. """ if (amount > self.getBalance()): return False return True def getWithdrawals(self) -> float: """ A helper function for createSpendChart(). Returns the withdraw total. """ total = 0 for item in self.ledger: if ( item["amount"] < 0 ): total += item["amount"] return total def truncate(n: float) -> float: """ Helper function for getTotal(). Returns the rounded value. """ multiplier = 10 return int(n * multiplier) / multiplier def getTotal(categories: list) -> List[float]: """ Helper function for createSpendChart(). Returns the total percent spent, rounded down to the nearest tenth. """ total = 0 breakdown = [] for category in categories: # Calculate total amount withdrawn total += category.getWithdrawals() breakdown.append(category.getWithdrawals()) rounded = list( map( lambda x: truncate(x / total), breakdown ) ) return rounded def createSpendChart(categories: list) -> str: result = "Percentage spent by category\n" i = 100 percentages = getTotal(categories) while (i >= 0): # Formatting appropriate bars to their respective percentages spaces = " " for percent in percentages: if (percent * 100 >= i): spaces += "o " else: spaces += " " result += str(i).rjust(3) + "|" + spaces + "\n" i -= 10 line = "-" + ( "---" * len(categories) ) names = [] x_axis = "" for category in categories: names.append(category.name) longest = max(names, key = len) for j in range( len(longest) ): # Print formatting the category name in a vertical line nameStr = " " for name in names: if j >= len(name): nameStr += " " else: nameStr += name[j] + " " # Case handling for extra newline character at the last print line if ( j != len(longest) - 1 ): nameStr += "\n" x_axis += nameStr result += line.rjust( len(line) + 4 ) + "\n" + x_axis return result
c70cbbe6dd0107e74cd408a899dc6bbe77432829
reenadhawan1/coding-dojo-algorithms
/week1/python-fundamentals/selection_sort.py
1,044
4.15625
4
# Selection Sort x = [23,4,12,1,31,14] def selection_sort(my_list): # find the length of the list len_list = len(my_list) # loop through the values for i in range(len_list): # for each pass of the loop set the index of the minimum value min_index = i # compare the current value with all the remaining values in the array for j in range(i+1,len_list): # to update the min_index if we found a smaller int if my_list[j] < my_list[min_index]: min_index = j # if the index of the minimum value has changed # we will make a swap if min_index != i: # we could do the swap like this # temp = my_list[i] # my_list[i] = my_list[min_index] # my_list[min_index] = temp # but using tuple unpacking to swap values here makes it shorter (my_list[i], my_list[min_index]) = (my_list[min_index], my_list[i]) # return our array return my_list print selection_sort(x)
bc064473602c73d97275b8089abe2e6d53cbb59e
Saumonvert/Bootcamp_Python_42AI
/day00/ex04/operations.py
844
3.921875
4
import sys res = sys.argv[1] res2 = sys.argv[2] if len(sys.argv) > 3: print("InputError: too many arguments") elif res.isnumeric() and res2.isnumeric(): arg1 = int(sys.argv[1]) arg2 = int(sys.argv[2]) res1 = arg1 + arg2 sumtxt = "Sum: {}" print(sumtxt.format(res1)) #----------------# res2 = arg1 - arg2 difftxt = "Difference: {}" print(difftxt.format(res2)) #----------------# res3 = arg1 * arg2 prodtxt = "Product: {}" print(prodtxt.format(res3)) #----------------# if arg1 and arg2: res4 = arg1 / arg2 quottxt = "Quotient: {}" print(quottxt.format(res4)) else: print("Quotient: ERROR (div by zero)") #----------------# if arg1 and arg2: res5 = arg1 % arg2 remtxt = "Remainder: {}" print(remtxt.format(res5)) else: print("Remainder: ERROR (modulo by zero)") else: print("InputError: only numbers")
06f2384cd713a2c94b6a0759f1f15f60d482e286
nothingct/BOJ_CodingTest
/소수찾기.py
235
3.71875
4
def isPrime(n): if n < 2 : return False i=2 while i*i <=n : if n % i == 0 : return False i+=1 return True t=int(input()) a=list(map(int,input().split())) cnt=0 for num in a: if isPrime(num) == True: cnt+=1 print(cnt)
5203122ef8d490e781d11968e4573a4d9ad7be11
AgnesHH/RosalindPractices
/iprb.MendelsFirstLaw.py
162
3.640625
4
#!/usr/bin/env python m,n,k=21,15,19 def mendel(m,n,k): S=float(m+n+k)*(m+n+k-1) print (m*(m-1)*0.75 + k*(k-1) + m*n + 2*n*k +2*m*k )/S mendel(m,n,k)
5ecdcd88c08fba99dfa5813145d62dfc6be1b263
yukti99/Computer-Graphics
/LAB-1/dda.py
472
3.71875
4
from graphics import * def dda(p0,p1): win = GraphWin("My Line using DDA", 900, 700) dx = p1[0] - p0[0] dy = p1[1] - p0[1] if (abs(dx) > abs(dy)): steps = abs(dx) else: steps = abs(dy) xi = dx/float(steps) yi = dy/float(steps) x = p0[0] y = p0[1] print(steps) for i in range(0,steps+1): point = Point(x,y) point.draw(win) x += xi y += yi win.getMouse() win.close() def main(): p0 = (50,60) p1 = (788,239) dda(p0,p1) main()
0bc16b1cab5b9b6d0508e343b4855361861f5f68
yukti99/Computer-Graphics
/LAB-2/scanFill.py
2,633
3.578125
4
from graphics import * from graphicLibClass import * from polygon1 import * import math xMin = 0 xMax = 0 yMin = 0 yMax = 0 edgeTable = {} vertex = [] activeTable = [] def ScanLineFilling(n,vertex,color,win): ymin = vertex[0][1] ymax = vertex[0][1] print("ymin = ",ymin) print("ymax = ",ymax) # initial x and y xi = vertex[0][0] yi = vertex[0][1] print("vertex table = ",vertex) # creation of edge table - will not contain horizontal edges for i in range(1,n+1): y1 = vertex[i-1][1] x1 = vertex[i-1][0] y = vertex[i][1] x = vertex[i][0] ymin = min(ymin,y) ymax = max(ymax,y) # we have to ignore horizontal lines if (y1 != y): if (x1 != x): m = (y-y1)/(x-x1) else: # slope is infinity i.e vertical line m = 10**9 if min(y1,y) not in edgeTable: edgeTable[min(y1,y)]=[] if y1<y: edgeTable[min(y1,y)].append([x1,max(y1,y),1/m]) else: edgeTable[min(y1,y)].append([x,max(y1,y),1/m]) print(ymax,ymin) # filling starts from bottom to up so y is incremented by 1 print("edge table = ",edgeTable) for i in range(ymin,ymax): if i in edgeTable: for j in edgeTable[i]: activeTable.append(j) activeTable.sort() #print(activeTable) a = 0 b = 1 while b<len(activeTable): x1 = activeTable[a][0] x2 = activeTable[b][0] c = transformX(math.ceil(x1)) d = transformX(math.floor(x2)) k = transformY(i) line(c,k,d,k,win,color) if(activeTable[b][1]==i+1): activeTable.pop(b) else: activeTable[b][0]+=activeTable[b][2] if (activeTable[a][1]==i+1): activeTable.pop(a) else: activeTable[a][0]+=activeTable[a][2] a+=2 b+=2 return win def main(): win = GraphWin("Scan Line Polygon Filling algorithm",900,900) win.setCoords(-450,-450,450,450) win = drawAxis(win) n = int(input("Enter the no of vertices of the quadrilateral : ")) print("Enter the points in cyclic manner : ") for i in range(n): x = int(input("Enter the x coordinate of the point : ")) y = int(input("Enter the y coordinate of the point : ")) if(i==0): x0,y0 = x,y vertex.append((x,y)) vertex.append((x0,y0)) b_color = input("Enter the boundary color of polygon = ") win = drawPolygon(n,vertex,win,b_color) print("\nVERTEX TABLE : ") print(vertex,"\n") color = input("Enter the color you want to fill in the polygon = ") win = ScanLineFilling(n,vertex,color,win) win.getMouse() win.close() main()
d1d3b0ac7a6f25c1c0b25114c917d0a5694b0837
Bharadwaja92/DataInterviewQuestions
/Questions/Q1_FradulentRetailAccounts.py
1,681
3.5
4
""""""""" Below is a daily table for an active accounts at Shopify (an online ecommerce, retail platform). The table is called store_account and the columns are: Column Name Data Type Description store_id integer a unique Shopify store id date string date status string Possible values are: [‘open’, 'closed’, ‘fraud’] revenue double Amount of spend in USD Here's some more information about the table: The granularity of the table is store_id and day Assume “close” and “fraud” are permanent labels Active = daily revenue > 0 Accounts get labeled by Shopify as fraudulent and they no longer can sell product Every day of the table has every store_id that has ever been used by Shopify Given the above, what percent of active stores were fraudulent by day? """ import mysql.connector host = "localhost" # :3306 username, password, database = "root", "gaian", "DataInterviewQuestions" mydb = mysql.connector.connect(host=host, username=username, passwd=password, database=database) table_name = "Q1_Shopify" my_cursor = mydb.cursor() my_cursor.execute('SELECT COUNT(*) FROM {}'.format(table_name)) # print(my_cursor.fetchall()) # for c in my_cursor: # print(c) QUERY = 'SELECT ' \ 'date, (sum(case when status="fraud" then 1 else 0 end) / count(store_id)) as fraud_rate ' \ 'FROM Q1_Shopify where revenue > 0 GROUP BY date ORDER BY date;' # http://ubiq.co/database-blog/calculate-percentage-column-mysql/#:~:text=To%20calculate%20percentage%20of%20column%20in%20MySQL%2C%20you%20can%20simply,column%20with%20the%20original%20table.&text=If%20you%20want%20to%20add,CROSS%20JOIN%2C%20as%20shown%20below.
249cbda74673f28d7cc61e8be86cdfef2b855e2a
Bharadwaja92/DataInterviewQuestions
/Questions/Q_090_SpiralMatrix.py
414
4.4375
4
""""""""" Given a matrix with m x n dimensions, print its elements in spiral form. For example: #Given: a = [ [10, 2, 11], [1, 3, 4], [8, 7, 9] ] #Your function should return: 10, 2, 11, 4, 9, 7, 8, 1, 3 """ def print_spiral(nums): # 10, 2, 11, 4, 9, 7, 8, 1, 3 # 4 Indicators -- row start and end, column start and end return a = [[10, 2, 11], [1, 3, 4], [8, 7, 9]] print_spiral(a)
8b2af30e0e3e4fc2cfefbd7c7e9a60edc42538c0
Bharadwaja92/DataInterviewQuestions
/Questions/Q_029_AmericanFootballScoring.py
2,046
4.125
4
""""""""" There are a few ways we can score in American Football: 1 point - After scoring a touchdown, the team can choose to score a field goal 2 points - (1) after scoring touchdown, a team can choose to score a conversion, when the team attempts to score a secondary touchdown or (2) an uncommon way to score, a safety is score when the opposing team causes the ball to become dead 3 points - If no touchdown is scored on the possession, a team can attempt to make a field goal 6 points - Awarded for a touchdown Given the above, let's assume the potential point values for American Football are: 2 points - safety 3 points - only field goal 6 points - only touchdown 7 points - touchdown + field goal 8 points - touchdown + conversion Given a score value, can you write a function that lists the possible ways the score could have been achieved? For example, if you're given the score value 10, the potential values are: 8 points (touchdown + conversion) + 2 points (safety) 6 points (only touchdown) + 2x2 points (safety) 7 points (touchdown + field goal) + 3 points (only field goal) 5x2 points (safety) 2x2 points (safety) + 2x3 points (only field goal) """ from collections import Counter # A different version of Coin Change possible_scores = [] def get_possible_ways(score, points, partial=[]): s = sum(partial) if s == score: possible_scores.append(partial) if s >= score: return for i in range(len(points)): p = points[i] remaining = points[i: ] get_possible_ways(score=score, points=remaining, partial=partial+[p]) return 0 points_dict = {2: 'safety', 3: 'only field goal', 6: 'only touchdown', 7: 'touchdown + field goal', 8: 'touchdown + conversion'} points = list(points_dict.keys()) print(points) print(get_possible_ways(10, points)) print(possible_scores) for ps in possible_scores: d = dict(Counter(ps)) sent = ['{} * {} = {} Points'.format(d[v], points_dict[v], v) for v in d] print(sent)
604a4bb01ff02dc0da1ca2ae0ac71e414c5a6afe
Bharadwaja92/DataInterviewQuestions
/Questions/Q_055_CategorizingFoods.py
615
4.25
4
""""""""" You are given the following dataframe and are asked to categorize each food into 1 of 3 categories: meat, fruit, or other. food pounds 0 bacon 4.0 1 STRAWBERRIES 3.5 2 Bacon 7.0 3 STRAWBERRIES 3.0 4 BACON 6.0 5 strawberries 9.0 6 Strawberries 1.0 7 pecans 3.0 Can you add a new column containing the foods' categories to this dataframe using python? """ import pandas as pd df = pd.DataFrame(columns=['food', 'pounds']) df['category'] = df['food'].apply(lambda f: 'fruit' if f.lower() in ['strawberries'] else 'meat' if f.lower() == 'bacon' else 'other')
9d464daf8dc0115ae04613794a46455d1586c3db
Bharadwaja92/DataInterviewQuestions
/Utils/Q20_StringDistances.py
2,112
3.84375
4
""""""""" String Distance Algorithms: Hamming: Number of positions with same symbol in both strings. Only defined for strings of equal length. distance(‘abcdd‘,’abbcd‘) = 3 -> Chars at positions 0, 1, 4 Levenshtein: Minimal number of insertions, deletions and replacements needed for transforming string a into string b. LCS Distance: (Longest Common Substring distance) Minimum number of symbols that have to be removed in both strings until resulting substrings are identical. distance(‘ABCvDEx‘,’xABCyzDE’) = 5 Cosine: 1 minus the cosine similarity of both N-gram vectors. Jaccard: 1 minus the quotient of shared N-grams and all observed N-grams. """ def get_levenshtein_distance(s1: str, s2: str): """ The Levenshtein distance between two strings a and b is given by lev_a,b(len(a), len(b)) where lev_a,b(i, j) is equal to max(i, j) if min(i, j)=0 otherwise: min(leva,b(i-1, j) + 1, leva,b(i, j-1) + 1, leva,b(i-1, j-1) + 1_ai≠bj) where 1_ai≠bj</sub> is the indicator function equal to 0 when ai=bj and equal to 1 otherwise, and leva,b(i, j) is the distance between the first i characters of a and the first j characters of b. :param s1: String 1 :param s2: String 1 :return: Distance calculated using Iterative approach """ rows, cols = len(s1) + 1, len(s2) + 1 dist = [[0 for _ in range(cols)] for __ in range(rows)] for i in range(1, rows): dist[i][0] = i for i in range(1, cols): dist[0][i] = i for col in range(1, cols): for row in range(1, rows): if s1[row - 1] == s2[col - 1]: cost = 0 else: cost = 1 dist[row][col] = min(dist[row - 1][col] + 1, # deletion dist[row][col - 1] + 1, # insertion dist[row - 1][col - 1] + cost) # substitution return dist[row][col]
8d39d540c2a3078ca6fe2a63d3b59ae5cf2f9381
Bharadwaja92/DataInterviewQuestions
/Questions/Q_028_WinningTheLottery.py
807
4.03125
4
""""""""" Suppose you're trying to figure out your chances of winning the lottery. The specific lottery you're interested in has 49 balls, each showing a single number. To win the jackpot you need to match 6 balls to win (note that order does not matter). What is the probability that you can win the jackpot, given you buy 1 ticket? What if you buy 3 lottery tickets? """ from itertools import combinations total_number_of_balls = 49 to_win = 6 # num_possible_combinations = 49C6 num_possible_combinations = len(list(combinations(range(total_number_of_balls), to_win))) print('num_possible_combinations =', num_possible_combinations) prob_winning_1ticket = 1 / num_possible_combinations prob_winning_3tickets = 3 / num_possible_combinations print(prob_winning_1ticket) print(prob_winning_3tickets)
047b133a09b61e045788d629c0442aa8f795c729
Bharadwaja92/DataInterviewQuestions
/Questions/Q_060_ChoosingTwoIceCreams.py
865
4.03125
4
""""""""" Suppose you enter an ice cream store. They sell two types of ice cream: soft serve and frozen yogurt. Additionally, there are 10 flavors of soft serve and 13 flavors of frozen yogurt. You're really hungry, so you decide you can order and eat two ice creams before they melt, but are facing some decision fatigue given the amount of choices. How many ways are there to choose exactly two ice creams from the store? Figuring this out should help quantify that decision fatigue. """ from itertools import combinations """ Num ways to eat 2 icecreams = (1 SS and 1 FY) or (2 SS) or (2FF) """ n1 = len(list(combinations(range(10), 1))) * len(list(combinations(range(13), 1))) n2 = len(list(combinations(range(10), 2))) n3 = len(list(combinations(range(13), 2))) print(n1, n2, n3) num_total_ways = n1 + n2 + n3 print('num_total_ways =', num_total_ways)
d77e79c943a0364efb0b5a3a600f55ffaf783015
Bharadwaja92/DataInterviewQuestions
/Questions/Q_083_SalesByMarketingChannel.py
596
3.546875
4
""""""""" Given the following data set, can you plot a chart that shows the percent of revenue by marketing source? """ import pandas as pd from matplotlib import pyplot as plt pd.set_option('display.max_colwidth', -1) pd.set_option('float_format', '{:f}'.format) pd.set_option('display.max_columns', 500) pd.set_option('display.width', 1000) df = pd.read_csv('../Utils/Sales data.csv') print(df.head(5)) gdf = df.groupby(by=['source'])['purchase_value'].sum().reset_index() plt.pie(x=gdf['purchase_value'], labels=gdf['source'], startangle=90) plt.savefig('../Utils/Q_83.png') plt.show()
913a4d4b373a3265b700971b7b22496a0986599d
aliucrazy/dataStrcutTest
/test_2.1.py
934
3.78125
4
""" """ class LinkedList(object): def __init__(self, data, next: LinkedList): # data--->用于存储放数据元素 self.data = data # next 用来存放该元素的后继 self.next = next def sortArray(La: list, Lb: list) -> list: Lc = list() La_index = 0 Lb_index = 0 while La_index <= len(La)-1 and Lb_index <= len(Lb)-1: if La[La_index] <= Lb[Lb_index]: Lc.append(La[La_index]) La_index += 1 elif La[La_index] > Lb[Lb_index]: Lc.append(Lb[Lb_index]) Lb_index += 1 while La_index <= len(La)-1: Lc.append(La[La_index]) La_index += 1 while Lb_index <= len(Lb)-1: Lc.append(Lb[Lb_index]) Lb_index += 1 return Lc def sortLinked(La: list, Lb: list) -> list: pass if __name__ == "__main__": La = [1, 5, 7, 9] Lb = [2, 4, 6, 10] print(sortArray(La, Lb))
015f6e785a2d2b8f5ebe76197c15b8dd335526cc
code4nisha/python8am
/day4.py
1,594
4.375
4
x = 1/2+3//3+4**2 print(x) # name = 'sophia' # print(name) # print(dir(name)) # print(name.capitalize) # course = "we are learning python" # print(course.title()) # print(course.capitalize()) # learn = "Data type" # print(learn) # learn = "python data types" # print(learn.title()) # data =['ram',123,1.5] # print(data[1]) # negative index # b = "Hello, World!" # print(b[-5:-2]) # Strings # strings in python are single or double quotation marks # print('Hello') # print("Hello") # Multiline Strings # We can use three double quotes # a ="""Lorem ipsum dolor sit amet # consectetur adipiscing alit, # sed do eiusmod tempor incididunt # ut labore et dolore magna aliqua.""" # print(a) # Length string # a = "Hello, World!" # print(len(a)) # slicing # b = "Hello, World!" # print(b[2:5]) # replace string # a = "Hello, World!" # print(a.replace("H", "J")) # format string # age = 36 # txt ="My name is John, and I am {}" # print(txt.format(age)) # we can use %s also in formatting # print("I love %s in %s" % ("programming", "Python")) # 'I love programming in python' # if we have more num then # quantity = 3 # itemno = 567 # price = 49.95 # myorder = "I want {} pieces of item {} for dollars." # print(myorder.format(quantity, itemno,price)) # escape character # the escape charater allows you to use double quotes when you normally would not be allowed # txt = "We are the so-called \"Vikings\" from the north." # print(txt) # text = "I'm fine" # print(text"I'm fine") # tuple # x = ("apple", "banana", "cherry") # y = list(x) # y[1] = "kiwi" # x = tuple(y) # print(x)
b2caa326bde5f346910c1001f1bdf44ed74dccd9
code4nisha/python8am
/day3.py
478
3.75
4
# p = 10 # t = 20 # r =5 # SI = p*t*r/100 # print(SI) # p = float(input("Enter p: ")) # t = float(input("Enter t: ")) # r = float(input("Enter r: ")) # result = p * t * r /100 # print(f"Result: {result}") # name = 'sophia' # print('s' in name) # print('z' not in name) # print('y' in name) a = 9 b = 4 add = a + b sub = a - b mul = a * b div1 = a / b div2 = a // b mod = a % b p = a ** b print(add) print(sub) print(mul) print(div1) print(div2) print(mod) print(p)
dae28a56428b2ba61eb6aacc6c4b8809ae182cc4
christine62/intro-to-computer-science-and-programming-using-python
/hangman/isWordGuessed.py
720
4.0625
4
def isWordGuessed(secretWord, lettersGuessed): ''' secretWord: string, the word the user is guessing lettersGuessed: list, what letters have been guessed so far returns: boolean, True if all the letters of secretWord are in lettersGuessed; False otherwise ''' # FILL IN YOUR CODE HERE... word_list=[] for i in secretWord: word_list.append(i) for letter in word_list[:]: if letter in lettersGuessed: word_list.remove(letter) if len(word_list)==0: return True elif len(word_list)>0: return False ''' or ''' for x in secretWord: if x not in lettersGuessed: return False return True
76d4657cc8a0311f905fb015679df982a3905f67
ChrisAmelia/DataMiningVideoGames
/src/fetchdata.py
3,787
3.71875
4
import urllib.request, json, os from pprint import pprint def fetchAppDetails(appid, write=False): """Returns the fetched data from Steam API. Steam API's format is: https://api.steampowered.com/<interface>/<method>/v<version>/ In this case, it should be: http://store.steampowered.com/api/appdetails/?appids=VALUE&format=json Args: appid (int): Every Steam game has an unique ID called AppID. write (boolean): Set it to True to write the fetched data into a json file Returns: data; a dictionnary containing the fetched data in JSON format. If the data have been correctly fetched then the field data['appid']['success'] should be set to True, else False. """ host = "http://store.steampowered.com" interface = "api" method = "appdetails" get = "?appids=" format = "format=" file_type = "json" request = host + "/" + interface + "/" + method + "/" + get + str(appid) + "&" + format + file_type with urllib.request.urlopen(request) as url: data = json.loads(url.read().decode()) success = data[str(appid)]['success'] if write: if success: f = open(str(appid) + '.json', 'w') json.dump(data, f) else: print('AppID \'' + str(appid) + '\' doesn\'t exist.') return data def _filterData(data): """See method filterData(). Args: data (dict); return value of the method fetchAppDetails() Returns: filtered data """ filtered = {} appid = '' for key in data: appid = key break shorcut = data[appid]['data'] filtered['appid'] = appid filtered['name'] = shorcut['name'] filtered['is_free'] = shorcut['is_free'] filtered['detailed_description'] = shorcut['detailed_description'] filtered['publishers'] = shorcut['publishers'] if 'categories' in shorcut: filtered['categories'] = shorcut['categories'] else: unknown = {} unknown['description'] = 'Unknown' unknown['id'] = -1; l = []; l.append(unknown) filtered['categories'] = l; # filtered['about_the_game'] = shorcut['about_the_game'] # filtered['short_description'] = shorcut['short_description'] return filtered def filterData(): """Returns a dictionnary containing filtered data from given data. The filter is applied on labels that are considered 'important' such as the name, details of the game, categories, etc. See res/label.txt, labels that are considered as important are precede by '>' (relevant) or '>>' (very relevant). Returns: filtered data """ gameList = {} try: current_path = os.getcwd() os.chdir(current_path + "/../res/data/") for filename in os.listdir(os.getcwd()): data = json.load(open(filename)) filtered = _filterData(data) appid = filtered['appid'] gameList[appid] = filtered except Exception as e: raise e finally: os.chdir(current_path) return gameList # To fetch data from Steam API (which authorizes around 200 requests within a short period of seconds). # A Steam game's appID is always a multiple of 10 except if it's a beta-game. # if __name__ == "__main__": # for appid in range(4510, 5001): # if (appid % 10 == 0): # fetchAppDetails(appid, True) # else: # pass # Test filterData() return values # if __name__ == "__main__": # d = filterData() # pprint(d['900']['categories'][0]) # pprint(d['730']['categories'][0]) if __name__ == "__main__": d = filterData() # with open('filtered_data.json', 'w') as fp: # json.dump(d, fp)
3c24d06b8f6c4e4eb380da9c8b7ca94dfee80e51
Mystery01092000/Algorithm_Visualization_tool
/Algorithms_python/BubbleSort.py
466
3.921875
4
from Algorithms_python.Algorithms import Algorithms class BubbleSort(Algorithms): def __init__(self): super().__init__("BubbleSort") def algorithm(self): for i in range(len(self.array)): for j in range(len(self.array)-1-i): if self.array[j] > self.array[j+1]: self.array[j], self.array[j+1] = self.array[j+1], self.array[j] self.update_display(self.array[j], self.array[j+1])
09dd6f8a8ac0b01029e6f8f817e69ef77128eddb
CatonChen/algorithm023
/Week_07/[130]被围绕的区域.py
3,731
4.03125
4
# 给定一个二维的矩阵,包含 'X' 和 'O'(字母 O)。 # # 找到所有被 'X' 围绕的区域,并将这些区域里所有的 'O' 用 'X' 填充。 # # 示例: # # X X X X # X O O X # X X O X # X O X X # # # 运行你的函数后,矩阵变为: # # X X X X # X X X X # X X X X # X O X X # # # 解释: # # 被围绕的区间不会存在于边界上,换句话说,任何边界上的 'O' 都不会被填充为 'X'。 任何不在边界上,或不与边界上的 'O' 相连的 'O' 最终都会被 # 填充为 'X'。如果两个元素在水平或垂直方向相邻,则称它们是“相连”的。 # Related Topics 深度优先搜索 广度优先搜索 并查集 # 👍 471 👎 0 # leetcode submit region begin(Prohibit modification and deletion) # 并查集模板 class UnionFind: def __init__(self): """ 记录每个节点的父节点 """ self.father = {} def find(self, x): """ 查找根节点 路径压缩 """ root = x while self.father[root] is not None: root = self.father[root] # 路径压缩 while x != root: original_father = self.father[x] self.father[x] = root x = original_father return root def merge(self, x, y): """ 合并两个节点 """ root_x, root_y = self.find(x), self.find(y) if root_x != root_y: self.father[root_x] = root_y def is_connected(self, x, y): """ 判断两节点是否相连 """ return self.find(x) == self.find(y) def add(self, x): """ 添加新节点 """ if x not in self.father: self.father[x] = None class Solution: def solve(self, board: List[List[str]]) -> None: """ Do not return anything, modify board in-place instead. """ if not board: return None # 初始化矩阵行列 m, n = len(board), len(board[0]) # 定义node def node(x, y): return x * n + y # 初始化uf uf = UnionFind() # 初始化dummy dummy = m * n uf.add(dummy) # print(uf.father) # 遍历矩阵检查字母O for i in range(m): for j in range(n): if board[i][j] == 'O': # 属于矩阵边界的O if i == 0 or j == 0 or j == n - 1 or i == m - 1: # print(node(i,j)) uf.add(node(i, j)) # 将边界O与dummy连通 uf.merge(node(i, j), dummy) else: # 非边界的O for mx, my in [(i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)]: if 0 <= mx < m and 0 <= my < n and board[mx][my] == 'O': uf.add(node(i, j)) uf.add(node(mx, my)) # 将相互连通的O进行合并 # 与边界O连通的O,最终会连通至dummy uf.merge(node(mx, my), node(i, j)) # # print(uf.father) # 遍历矩阵 for i in range(m): for j in range(n): uf.add(node(i, j)) # 与dummy是同一个祖先 if uf.is_connected(dummy, node(i, j)): board[i][j] = 'O' else: board[i][j] = 'X' # print(uf.father) # leetcode submit region end(Prohibit modification and deletion)
b0aee3c461decf2b2a0f005b3e10efde5042a931
CatonChen/algorithm023
/Week_07/[888]公平的糖果棒交换.py
1,605
3.515625
4
# 爱丽丝和鲍勃有不同大小的糖果棒:A[i] 是爱丽丝拥有的第 i 根糖果棒的大小,B[j] 是鲍勃拥有的第 j 根糖果棒的大小。 # # 因为他们是朋友,所以他们想交换一根糖果棒,这样交换后,他们都有相同的糖果总量。(一个人拥有的糖果总量是他们拥有的糖果棒大小的总和。) # # 返回一个整数数组 ans,其中 ans[0] 是爱丽丝必须交换的糖果棒的大小,ans[1] 是 Bob 必须交换的糖果棒的大小。 # # 如果有多个答案,你可以返回其中任何一个。保证答案存在。 # # # # 示例 1: # # # 输入:A = [1,1], B = [2,2] # 输出:[1,2] # # # 示例 2: # # # 输入:A = [1,2], B = [2,3] # 输出:[1,2] # # # 示例 3: # # # 输入:A = [2], B = [1,3] # 输出:[2,3] # # # 示例 4: # # # 输入:A = [1,2,5], B = [2,4] # 输出:[5,4] # # # # # 提示: # # # 1 <= A.length <= 10000 # 1 <= B.length <= 10000 # 1 <= A[i] <= 100000 # 1 <= B[i] <= 100000 # 保证爱丽丝与鲍勃的糖果总量不同。 # 答案肯定存在。 # # Related Topics 数组 # 👍 155 👎 0 # leetcode submit region begin(Prohibit modification and deletion) class Solution: def fairCandySwap(self, A: List[int], B: List[int]) -> List[int]: sumA, sumB = sum(A), sum(B) diff = (sumA - sumB) // 2 setA = set(A) for y in B: x = y + diff if x in setA: return [x, y] # leetcode submit region end(Prohibit modification and deletion)
ac9c9c6015c2bf76e3d68aa52d0bf63e583a0960
CatonChen/algorithm023
/Week_06/[212]单词搜索 II.py
5,241
3.59375
4
# 给定一个 m x n 二维字符网格 board 和一个单词(字符串)列表 words,找出所有同时在二维网格和字典中出现的单词。 # # 单词必须按照字母顺序,通过 相邻的单元格 内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母在一个单词中不允许被重复使 # 用。 # # # # 示例 1: # # # 输入:board = [["o","a","a","n"],["e","t","a","e"],["i","h","k","r"],["i","f","l" # ,"v"]], words = ["oath","pea","eat","rain"] # 输出:["eat","oath"] # # # 示例 2: # # # 输入:board = [["a","b"],["c","d"]], words = ["abcb"] # 输出:[] # # # # # 提示: # # # m == board.length # n == board[i].length # 1 <= m, n <= 12 # board[i][j] 是一个小写英文字母 # 1 <= words.length <= 3 * 104 # 1 <= words[i].length <= 10 # words[i] 由小写英文字母组成 # words 中的所有字符串互不相同 # # Related Topics 字典树 回溯算法 # 👍 322 👎 0 # leetcode submit region begin(Prohibit modification and deletion) class Solution: def findWords(self, board: List[List[str]], words: List[str]) -> List[str]: # 创建字典树 WORD_KEY = '$' trie = {} for word in words: # 单词 node = trie for letter in word: # 字母 node = node.setdefault(letter, {}) node[WORD_KEY] = word # 单词用$标记出来 # print(node) # print(trie) rownum = len(board) colnum = len(board[0]) matchedWords = [] # 递归回溯 def backtracking(row, col, parent): letter = board[row][col] # print(parent) # print(letter) currnode = parent[letter] # print(currnode) word_match = currnode.pop(WORD_KEY, False) # print(word_match) if word_match: matchedWords.append(word_match) # 将字母标记为#,即已使用 board[row][col] = '#' # 探索当前单元格四周单元格 上右下左 for (x, y) in [(-1, 0), (0, 1), (1, 0), (0, -1)]: new_x, new_y = row + x, col + y if new_x < 0 or new_y < 0 or new_x >= rownum or new_y >= colnum: continue if not board[new_x][new_y] in currnode: continue backtracking(new_x, new_y, currnode) # 回溯,恢复状态 board[row][col] = letter # 剪枝:当前currnode已经遍历过了,从父节点中删除 if not currnode: parent.pop(letter) # 遍历board的所有单元格 for row in range(rownum): for col in range(colnum): if board[row][col] in trie: # print(board[row][col]) backtracking(row, col, trie) return matchedWords # WORD_KEY = '$' # # trie = {} # for word in words: # node = trie # for letter in word: # # retrieve the next node; If not found, create a empty node. # node = node.setdefault(letter, {}) # # mark the existence of a word in trie node # node[WORD_KEY] = word # print(trie) # # rowNum = len(board) # colNum = len(board[0]) # # matchedWords = [] # # def backtracking(row, col, parent): # # letter = board[row][col] # currNode = parent[letter] # # # check if we find a match of word # word_match = currNode.pop(WORD_KEY, False) # if word_match: # # also we removed the matched word to avoid duplicates, # # as well as avoiding using set() for results. # matchedWords.append(word_match) # # # Before the EXPLORATION, mark the cell as visited # board[row][col] = '#' # # # Explore the neighbors in 4 directions, i.e. up, right, down, left # for (rowOffset, colOffset) in [(-1, 0), (0, 1), (1, 0), (0, -1)]: # newRow, newCol = row + rowOffset, col + colOffset # if newRow < 0 or newRow >= rowNum or newCol < 0 or newCol >= colNum: # continue # if not board[newRow][newCol] in currNode: # continue # backtracking(newRow, newCol, currNode) # # # End of EXPLORATION, we restore the cell # board[row][col] = letter # # # Optimization: incrementally remove the matched leaf node in Trie. # if not currNode: # parent.pop(letter) # # for row in range(rowNum): # for col in range(colNum): # # starting from each of the cells # if board[row][col] in trie: # backtracking(row, col, trie) # # return matchedWords # leetcode submit region end(Prohibit modification and deletion)