blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
67f8f51be67c254cbc8715cc7b3d9f967d50eb1f
vkagwiria/thecodevillage
/Python Week 2/Day 4/exercise1.py
200
4.25
4
# print all numbers between 0 and 100 # print "even" instead of the number if a number is even for i in range(0,100+1): if i % 2 ==0: print("even") else: print(i)
c178b8e6c1b65d6387e0154f0b238a838d86a5ef
anuragakella/Algorithms
/karatsuba_multiplaication.py
1,137
4.09375
4
# python function to multiply 2 numbers using the karatsuba algorithm # the example uses 2 - 64 digit strings to perform the operation def karatsuba(m, n): m_l = len(m) n_l = len(n) # length of each number if m_l <= 1 or n_l <= 1: # if the number is a single digit number, just return the product print("iteration " + str(i)) i += 1 return int(m) * int(n) else: # else recursively divide the humber into 2 parts until it reaches length <= 1 a = n[:(n_l//2)] b = n[(n_l//2):] c = m[:(m_l//2)] d = m[(m_l//2):] return(((pow(10, m_l) * int(karatsuba(a, c))) + (pow(10, m_l//2) * (int(karatsuba(a, d)) + int(karatsuba(b, c)))) + int(karatsuba(b, d)))) # the karatsuba formula for numbers "cd" and "ab" -- ((10^n * ac) + (10^n/2 * (ad + bc)) + bd) print("mul: " + str(karatsuba("3141592653589793238462643383279502884197169399375105820974944592", "2718281828459045235360287471352662497757247093699959574966967627"))) # result for those 2 numbers would be # 8539734222673567065463550869546574495034888535765114961879601127067743044893204848617875072216249073013374895871952806582723184
14b30c4ba1fc2e20e7f45f65fc60d9b747c7f15f
RituRaj693/Python-Program
/set_2.py
636
3.59375
4
##############################update the set #thisset = {'kohli','raina'} #thisset.update(['dhoni','tendulkar']) #print(thisset) ######get the lenght of set #thisset = ('raina','dhoni','yuvraj') #print(len(thisset)) ######################### remove item from set #thisset = {'dhoni','raina','jhdav'} #thisset.remove('jhdav') #print(thisset) ####################################remove item from discard method #thisset = ('kohli','raina','dhoni') #thisset.discard('raina') #print(thisset) ###################### pop method in set thisset = {'raian','dhoni','raina','yuvraj'} thisset.pop() print(thisset)
c6e2d36b530c166448f12701ef4017d89b1667b4
ertugrul-dmr/automate-the-boring-stuff-projects
/rockpaperscissors/rockpaperscissors.py
2,665
4
4
# This is a game tries to simulate rock, paper, scissors game. import random import sys def maingame(): # Start's the game if player chooses to play. wins = 0 losses = 0 draws = 0 while True: # Main loop print(f'Wins: {wins}, Losses: {losses}, Draws: {draws}') if wins == 5: print(f'You beat the ai!') break if losses == 5: print(f'Ai has beaten you!') break if draws == 5: print(f'It\'s a draw between you and ai!') break playerMove = str( input('Plese make your move. r(ock),p(aper),s(scissors): ')) aiMove = random.randint(1, 3) # 1 rock, 2 paper, 3 scissor if playerMove == 'r': if aiMove == 1: print('Ai move is: Rock.' + f' Your move was: {playerMove}.') print('Draw') draws += 1 elif aiMove == 2: print('Ai move is: Paper.' + f' Your move was: {playerMove}.') print('Lose') losses += 1 else: print('Ai move is: Scissor.' + f' Your move was: {playerMove}.') print('Win') wins += 1 if playerMove == 'p': if aiMove == 2: print('Ai move is: Paper.' + f' Your move was: {playerMove}.') print('Draw') draws += 1 elif aiMove == 3: print('Ai move is: Scissor.' + f' Your move was: {playerMove}.') print('Lose') losses += 1 else: print('Ai move is: Rock.' + f' Your move was: {playerMove}.') print('Win') wins += 1 if playerMove == 's': if aiMove == 3: print('Ai move is: Scissor.' + f' Your move was: {playerMove}.') print('Draw') draws += 1 elif aiMove == 1: print('Ai move is: Rock.' + f' Your move was: {playerMove}.') print('Lose') losses += 1 else: print('Ai move is: Paper.' + f' Your move was: {playerMove}.') print('Win') wins += 1 k = input(f'Enter R to restart and press Q to quit\nR/Q? ') k.lower() if k == 'r': maingame() else: sys.exit k = input(f'Enter S to restart and press Q to quit\nS/Q? ') k.lower() if k == 's': maingame() else: sys.exit
80d0db9bfc50007ad0200478bf50c162f8014190
HLAvieira/Curso-em-Video-Python3
/Pacote-download/aulas_python_cev/ex_36_avalia_emprestimo.py
634
3.859375
4
print('\033[1;31;40mBem vindo ao avaliador de empréstimo\033[m') sal = float(input('Digite o valor da sua renda mensal: R$ ')) preco = float(input('Digite o valor do empréstimo desejado: R$ ')) num_parcelas = float(input('Digite o número de parcelas mensais que você deseja obter: ')) val_parcela = preco/num_parcelas if val_parcela > 0.3*sal: print('Infelizmente essas condições não são possíveis, entre em contato com nossos atendentes') else: print('Seu empréstimo de {:.2f} foi provado, você paragará {:.0f} parcelas de R${:.2f}'.format(preco, num_parcelas, val_parcela)) print('Obrigado por negociar conosco')
4b6e3679a824b285d52e11d48e9f5da87bca4678
Edvandro-Nogueira/Calculo_Material_Simples
/Calculo_Material_Simples.py
11,600
3.65625
4
#Autor: Edvandro Nogueira de Souza #Este algoritmo simples faz o cálculo de barras necessárias dado n quantidade de peças. #Não leva em consideração um aproveitamento sofisticado, ele apenas ordena os elementos de forma decrescente e tenta alocar na barra com a medida dada. # Imports from copy import deepcopy #arquivoIN = open("/Lista_Material_IN.txt", "r") arquivo = open("/Lista_Corte.txt", "w") #Arquivo de saída 2 arquivo2 = open("/Lista_Material_Simples.txt", "w") #Arquivo de saída 3 arquivo3 = open("/Lista_Pecas.txt", "w") #Declaração de variaveis globais lista_de_pecas = [] i = 1 totalBarra = [] pesoBarrasTotaisServico = 0.0 pesoPecasTotaisServico = 0.0 #Classe de cada material para calculo class Mat: def __init__(self, material, medida_barra_geral, lista_de_pecas): self.material = material self.medida_barra_geral = medida_barra_geral self.lista_de_pecas = lista_de_pecas #print(self.material, self.medida_barra_geral, self.lista_de_pecas) def __del__(self): self.lista_de_pecas = [] #Função de alocação de iteração de duplicadas nas quantidades def add_lista(qtd, medida): if qtd == 1: lista_de_pecas.append(medida) return lista_de_pecas else: lista_de_pecas.append(medida) add_lista((qtd - 1), medida) return lista_de_pecas # Tabela de peso especifico por m2 peso = {"D-069": 0.950, "D-078": 0.795, "78-719": 1.555, "T-095": 0.210, "L-002": 0.076, "GS-034 - 78-1873C": 0.805, "GS-034 - 78-1958D": 0.795, "39-2072C": 0.145, "Cx. Al.": (3.386 + 1.398), "D-079": 0.564, "D-102": 0.625, "TUB-4008": 0.386, "19-375": 0.919, "50-018": 0.263, "U-491": 0.093, "U-425": 0.145, "D-082": 0.349, "U-1048": 1.120, "U-990": 0.827, "VA-203A": 0.292, "Y-120": 0.247, "SU-279": 0.585, "SU-111": 0.620, "SU-108": 0.146, "TUB-4569": 0.595, "L-741": 0.161} #Função de alocação def calc2 (medida_barra, lista, i): medida_barra = int(medida_barra) nbarra = [] lista.sort(reverse=True) lista_temp = deepcopy(lista) medida_barra_temp = deepcopy(medida_barra) for n in lista: if n <= medida_barra_temp: nbarra.append(n) lista_temp.remove(n) medida_barra_temp = medida_barra_temp - n totalBarra.append(nbarra) lista = deepcopy(lista_temp) if lista_temp != []: calc2(medida_barra, lista, i+1) return totalBarra arquivo2.write("LISTA DE MATERIAL NECESSARIO:") arquivo2.write("\n") arquivo3.write("LISTA DE PEÇAS:") arquivo3.write("\n") arquivo3.write("\n") # Função principal def calc(mat, medida_barra, lista, i): medida_barra = int(medida_barra) mat = mat.split(':') mat = mat[1] print('#' * 100) p = ('#' * 100) p = str(p) arquivo.write(p) arquivo.write("\n") arquivo3.write(mat) arquivo3.write("\n") print('Lista de barras de', mat, 'com', medida_barra, 'mm:') p = ('Lista de barras de', mat, 'com', medida_barra, 'mm:') p = str(p) p = p.replace("'", "").replace(",", "", 1).replace(",", "", 2).replace(",", "", -1).replace("(", "").replace(")","") arquivo.write(p) arquivo.write("\n") totalBarra = calc2(medida_barra, lista, i) if len(totalBarra) > 1: print("Total de barras necessárias:",len(totalBarra),"barras") p = ("Total de barras necessárias:",len(totalBarra),"barras") p2 = (len(totalBarra),"barras de",mat,"com",medida_barra,"mm |",round(float((peso[mat]) * (int(len(totalBarra)) * int(medida_barra)) / 1000), 2),"Kg|") p = str(p) p2 = str(p2) p = p.replace("'", "").replace(",", "", 1).replace(",", "", 2).replace(",", "", -1).replace("(", "").replace(")", "") p2 = p2.replace("'", "").replace(",", "", 1).replace(",", "", 2).replace(",", "", -1).replace("(", "").replace(")", "") arquivo.write(p) arquivo2.write(p2) arquivo.write("\n") arquivo2.write("\n") else: print("Total de barras necessárias:", len(totalBarra), "barra") p = ("Total de barras necessárias:",len(totalBarra),"barras") p2 = (len(totalBarra), "barra de", mat, "com", medida_barra, "mm |",round((peso[mat] * (len(totalBarra) * medida_barra) / 1000), 2),"Kg|") p = str(p) p2 = str(p2) p = p.replace("'", "").replace(",", "", 1).replace(",", "", 2).replace(",", "", -1).replace("(", "").replace(")", "") p2 = p2.replace("'", "").replace(",", "", 1).replace(",", "", 2).replace(",", "", -1).replace("(", "").replace(")", "") arquivo.write(p) arquivo2.write(p2) arquivo.write("\n") arquivo2.write("\n") print('-' * 100) p = ('-' * 100) p = str(p) arquivo.write(p) arquivo.write("\n") print('CORTES:') arquivo.write("CORTES:") arquivo.write("\n") for n in range(len(totalBarra)): print("Barra",n+1,":", totalBarra[n], '| Sobra: ',(medida_barra-sum(totalBarra[n]))) p = ("Barra",n+1,":", totalBarra[n], '| Sobra:',(medida_barra-sum(totalBarra[n]))) p = str(p) p = p.replace("'","").replace("(", "").replace(")", "") p = p.replace(",", "", -1) arquivo.write(p) arquivo.write("\n") print('-' * 100) p = ('-' * 100) p = str(p) arquivo.write(p) arquivo.write("\n") print("RELATÓRIO:") arquivo.write("RELATÓRIO:") arquivo.write("\n") sobraTotal = 0 pecas_Totais = 0 for n in range(len(totalBarra)): sobraTotal = sobraTotal + (medida_barra - sum(totalBarra[n])) pecas_Totais = pecas_Totais + sum(totalBarra[n]) print("Aproveitamento:", round(100 - ((sobraTotal * 100) / (len(totalBarra) * medida_barra)), 2), "%") p = ("Aproveitamento:", round(100 - ((sobraTotal * 100) / (len(totalBarra) * medida_barra)), 2), "%") p = str(p) p = p.replace("'", "").replace(",", "", 1).replace(",", "", 2).replace(",", "", -1).replace("(", "").replace(")","") arquivo.write(p) arquivo.write("\n") print("Peso total das", len(totalBarra), "barras:", round((peso[mat] * (len(totalBarra) * medida_barra) / 1000), 2), "Kg") p = ("Peso total das", len(totalBarra), "barras:", round((peso[mat] * (len(totalBarra) * medida_barra) / 1000), 2), "Kg") p = str(p) p = p.replace("'", "").replace(",", "", 1).replace(",", "", 2).replace(",", "", -1).replace("(", "").replace(")","") arquivo.write(p) arquivo.write("\n") global pesoBarrasTotaisServico pesoBarrasTotaisServico = pesoBarrasTotaisServico + (peso[mat] * (len(totalBarra) * medida_barra) / 1000) print("Peso total das peças:", round((pecas_Totais / 1000) * peso[mat], 2), "Kg") p = ("Peso total das peças:", round((pecas_Totais / 1000) * peso[mat], 2), "Kg") p = str(p) p = p.replace("'", "").replace(",", "", 1).replace(",", "", 2).replace(",", "", -1).replace("(", "").replace(")","") arquivo.write(p) arquivo.write("\n") global pesoPecasTotaisServico pesoPecasTotaisServico = pesoPecasTotaisServico + ((pecas_Totais / 1000) * peso[mat]) print(" ") arquivo.write("\n") def conta(lista): lista.sort(reverse=True) listaQualifica = [] listaQtd = [] qtd = 0 for m in lista: for n in lista: if m == n & m not in listaQualifica: listaQualifica.append(m) for m in listaQualifica: for n in lista: if m == n: qtd = qtd + 1 listaQtd.append(qtd) qtd = 0 for m in range(len(listaQtd)): if listaQtd[m] > 1: p = listaQtd[m], "peças de", listaQualifica[m], "mm" p = str(p) p = p.replace("'", "").replace(",", "", 1).replace(",", "", 2).replace(",", "", -1).replace("(","").replace(")", "") arquivo3.write(p) arquivo3.write("\n") #print(m,"peças de",n,"mm") else: #print(m,"peça de",n,"mm") p = listaQtd[m], "peça de", listaQualifica[m], "mm" p = str(p) p = p.replace("'", "").replace(",", "", 1).replace(",", "", 2).replace(",", "", -1).replace("(","").replace(")", "") arquivo3.write(p) arquivo3.write("\n") arquivo3.write("\n") ''' #Este trecho esta sendo substituido pela leitura de dos dados em um .txt # Declarando as peças lista_de_pecas = [] #Limpa a lista de peças mat = "78-719" #Material mat = Mat(mat, 6000, add_lista(1, 2575)) mat.lista_de_pecas = add_lista(1, 2493) mat.lista_de_pecas = add_lista(4, 1834) mat.lista_de_pecas = add_lista(4, 2419) calc(mat.material, mat.medida_barra_geral, mat.lista_de_pecas, i) conta(lista_de_pecas) totalBarra = [] # Declarando as peças lista_de_pecas = [] #Limpa a lista de peças mat = "L-741" #Material mat = Mat(mat, 6000, add_lista(2, 2419)) calc(mat.material, mat.medida_barra_geral, mat.lista_de_pecas, i) conta(lista_de_pecas) totalBarra = [] ''' lista = [] material = [] def gera2(rod, pos, m): mat = m print('alala',index[rod + 1] - index[rod] - 3) for m in range(index[rod + 1] - index[rod] - 3): ad = lista[pos + (m + 3)].split(',') mat.lista_de_pecas = add_lista(int(ad[0]),int(ad[1])) print('gera2',mat.lista_de_pecas) #ad = [] def gera(it, rod): if it > 0: pos = int(index[rod]) #lista_de_pecas = [] mat1 = lista[pos].split(':') mat = str(mat1[1]) mat = str(mat) ad = lista[pos + 2].split(',') mat = Mat(mat, int(lista[pos + 1]), add_lista(int(ad[0]),int(ad[1]))) print('gera', mat.lista_de_pecas) print('chamando a gera2', rod, pos, mat) gera2(rod, pos, mat) #A lista mat.lista_de_pecas não esta sendo apagada, com isso estou ficando com peças repetidas em outras listas #calc(mat.material, mat.medida_barra_geral, mat.lista_de_pecas, i) conta(mat.lista_de_pecas) del mat totalBarra = [] gera(it - 1, rod + 1) with open("/Users/edvandro/Downloads/Fabril - docs/Lista_Material_IN.txt") as f: for line in f: line = line.replace("\n", "") lista.append(str(line)) for m in range(len(lista)): if "Mat" in lista[m]: l = lista[m].split(":") material.append(str(l[1])) index = [] for x in range(len(lista)): if "Mat" in lista[x]: index.append(x) if "FIM" in lista[x]: index.append(x) it = len(index) gera(it - 1, 0) #Término do relatório print('#' * 100) p = ('#' * 100) p = str(p) arquivo.write(p) arquivo2.write(p) arquivo.write("\n") arquivo2.write("\n") print("Peso total de todas as BARRAS do serviço:", round(pesoBarrasTotaisServico,2),"Kg") p = ("Peso total de todas as BARRAS do serviço:", round(pesoBarrasTotaisServico,2),"Kg") p = str(p) p = p.replace("'", "").replace(",", "", 1).replace(",", "", 2).replace(",", "", -1).replace("(", "").replace(")","") arquivo.write(p) arquivo.write("\n") print("Peso total de todas as PEÇAS do serviço:", round(pesoPecasTotaisServico,2),"Kg") p = ("Peso total de todas as PEÇAS do serviço:", round(pesoPecasTotaisServico,2),"Kg") p = str(p) p = p.replace("'", "").replace(",", "", 1).replace(",", "", 2).replace(",", "", -1).replace("(", "").replace(")","") arquivo.write(p) arquivo.write("\n") p2 = ("Peso total de todas as BARRAS do serviço:", round(pesoBarrasTotaisServico,2),"Kg") p2 = str(p2) p2 = p2.replace("'", "").replace(",", "", 1).replace(",", "", 2).replace(",", "", -1).replace("(", "").replace(")","") arquivo2.write(p2) arquivo2.write("\n") #print("Peso todas das peças marcadas com M:") arquivo.close()
bd4c7df02cddc1430b167299adac52818b6fd35d
RobinMelcher/Projects
/PythonPractice2.py
819
3.578125
4
import random def NSidedDie(n): # finish this function randomNumber = random.randint(1, n) return randomNumber def DiceRoller(n, t): # finish this function sum = 0 for i in range(t): sum = sum + NSidedDie(n) return sum ####TESTS - DO NOT MODIFY### def TestDie(n): sum = 0 for i in range(100): sum = sum + NSidedDie(n) sum /= 100 print("Average for " + str(n) + " sided die: " + str(sum)) return abs(sum - (n/2)) <= 1 def RunTests(): print("Test 1: ", "succeded" if TestDie(6) else "failed") print("Test 2: ", "succeded" if TestDie(12) else "failed") print("Test 3: ", "succeded" if TestDie(20) else "failed") #RunTests() input_t = int(input("how many die?:")) print(DiceRoller(20, input_t)/ input_t)
d2aa7e4c549957747b527fbee340608a4f19966d
XiangSugar/Python
/multi_threading.py
1,077
3.84375
4
# coding = utf-8 import time, threading # 新线程执行的代码: def loop(): print('thread %s is running...' % threading.current_thread().name) n = 0 while n < 5: n = n + 1 print('thread %s >>> %s' % (threading.current_thread().name, n)) time.sleep(1) print('thread %s ended.' % threading.current_thread().name) print('thread %s is running...' % threading.current_thread().name) t = threading.Thread(target=loop, name='LoopThread') t.start() t.join() print('thread %s ended.' % threading.current_thread().name) # -------------------------------------------------------------------- # 注意: # 多线程和多进程最大的不同在于,多进程中,同一个变量,各自有一份拷贝存在于每个进程中, # 互不影响,而多线程中,所有变量都由所有线程共享,所以,任何一个变量都可以被任何一个线程修改, # 因此,线程之间共享数据最大的危险在于多个线程同时改一个变量,把内容给改乱了 # 所以后面接着讲如何用lock来保护数据
5d1b4c396a5de96c6e9b6f444dc689f2833c70ec
leodag/adventofcode2020
/12/part2.py
1,293
3.640625
4
def read_file(name): return open(name).read().splitlines() def parse_instructions(lines): instructions = [] for line in lines: instruction = line[:1] amount = int(line[1:]) instructions.append((instruction, amount)) return instructions def move(position, direction, amount): posx, posy = position if direction == 'N': posy -= amount elif direction == 'S': posy += amount elif direction == 'W': posx -= amount elif direction == 'E': posx += amount return posx, posy def navigate(instructions): posx, posy = 0, 0 wayx, wayy = 10, -1 for instruction, amount in instructions: if instruction == 'R': for _ in range(amount % 360 // 90): wayx, wayy = -wayy, wayx elif instruction == 'L': for _ in range(amount % 360 // 90): wayx, wayy = wayy, -wayx elif instruction == 'F': for _ in range(amount): posx, posy = posx + wayx, posy + wayy else: wayx, wayy = move((wayx, wayy), instruction, amount) return abs(posx) + abs(posy) def part2(filename="input"): lines = read_file(filename) instr = parse_instructions(lines) print(navigate(instr))
9a4e4ffc7393acd24cfbbff3ea5e2029eeb23d6b
xiaohuanlin/Algorithms
/Leetcode/108. Convert Sorted Array to Binary Search Tree.py
1,361
4.125
4
''' Given an array where elements are sorted in ascending order, convert it to a height balanced BST. For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. Example: Given the sorted array: [-10,-3,0,5,9], One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST: 0 / \ -3 9 / / -10 5 ''' import unittest # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def sortedArrayToBST(self, nums): """ :type nums: List[int] :rtype: TreeNode """ if nums == []: return None node_index = len(nums)//2 node = TreeNode(nums[node_index]) node.left, node.right = self.sortedArrayToBST(nums[:node_index]), self.sortedArrayToBST(nums[node_index+1:]) return node class TestSolution(unittest.TestCase): def test_sortedArrayToBST(self): examples = ( ) for first,second in examples: self.assert_function(first, second) def assert_function(self, first, second): self.assertEqual(Solution().sortedArrayToBST(*first), second) unittest.main()
0d6ef181fd39fd5e3ca628f7da8a724d3b75e16f
ANatanielK/AI_StrategyGame
/unit.py
4,034
3.5
4
from enum import Enum import random from configuration import * attackClass = {'knight': KnightAttack, 'wizard': WizardAttack} defenseClass = {'knight': KnightDefense, 'wizard': WizardDefense} class Unit: def __init__(self,player,ID,typeOfUnit): '''Constructor: receives the type of The Unit (knight, wizard...) as a String And builds the unit accordingly to the corresponding CSV File''' import csv, sys filename = typeOfUnit + '.csv' with open(filename, newline='') as f: reader = csv.reader(f) try: self.constructor((player,ID)+tuple(row[1] for row in reader)) except csv.Error as e: sys.exit('file {}, line {}: {}'.format(filename, reader.line_num, e)) def constructor(self, player, ID, maxHP, moveRange, isLight, attack, defense): self._player = player self._ID = ID self._maxHP = maxHP self._moveRange = moveRange self._isLight = isLight self._attack = attackClass[attack]() self._defense = defenseClass[defense]() self._experience = 0 def startMatch(self,board,initialLocation): '''To be called at the start of each match''' self._board = board self._location = initialLocation self._HP = self._maxHP self._dead = False #AI strategy purposes def euristica(self): ''' How "strong" is this unit ''' #raise NotImplementedError val = self._HP*weightHP + self._maxHP*weightMaxHP + self._attack.euristica() + self._defense.euristica() + self._experience * weightExperience + self._isLight * weightIsLight + self._moveRange * weightMoveRange return val @property def ID(self): return self._ID @property def player(self): return self._player @property def HP(self): '''Health Points''' return self._HP @HP.setter def HP(self, value): if value < 0: self.dye() else: self._HP = min(self._maxHP, value) @property def moveRange(self): return self._moveRange @property def location(self): return self._location @location.setter def location(self,value): self._location = value @property def cell(self): return self._board.board[self._location] @property def isLight(self): return self._isLight def receiveAttack(self, attacker, attackType, value): '''Attacker is the unit that sends the attack, value is a number indicating the damage in case of success ''' damage = self._defense.receive( attacker, attackType, value) self.HP -= damage return damage def sendAttack(self, target): '''Target is the unit to be attacked''' return self._attack(target, self._location, self._board) def attackRanges(self): return self._attack.ranges def dye(self): self._dead = True def useAbility(self): raise NotImplementedError def earnExperience(self, val): self._experience += val while self._experience > maxExperience: self.levelUP() self._experience -= maxExperience def levelUP(self): self._moveRange *= levelUPProportion self._maxHP *= levelUPProportion self._attack.levelUP() self._defense.levelUp() @property def experience(self): return self._experience def penalty(self,percent = defaultPenaltyPercent): '''Decrease all the the properties by indicated percent% ''' self._attack.penalty(percent) self._defense.penalty(percent) value = 1 - defaultPenaltyPercent / 100 self._maxHP.penalty(percent) self._moveRange *= value self._experience *= value self._HP *= value
3d1fcadfec16c19dc775df87f993fc0918dc1d7d
jcperdomo/182finalproject
/agent.py
2,057
3.78125
4
import operator as op PASS = (0, -1) class Agent(object): """The Agent base class to be overridden with each algorithm.""" def __init__(self, idx, hand): """Initializes an agent with its starting hand.""" self.idx = idx self.hand = hand def firstMove(self): """Plays all 3's (0's in the card encoding) for the first move of the game. :returns: (numThrees, 0) """ numThrees = self.hand[0] return (numThrees, 0) def makeMove(self, node): """Returns the action to be made given a node. :node: The node from which the agent is making the move. :returns: A (numCards, whichCard) action. numCards == 0 represents no action (i.e., a pass). """ raise "not yet defined" def numCardsLeft(self): """Returns number of cards remaining in the hand. :returns: Number of cards left to be played. """ return sum(self.hand.itervalues()) def getAllActions(self, node): """Returns list of all legal actions given a node. :node: The node from which we are considering actions. Must have whosTurn of the current agent. :returns: A list of (numCards, whichCard) actions. """ # corner case: if player is out of cards, return a pass if self.idx in node.finished: return [PASS] # corner case: if it's the initial state, return all 3's if node.isInitialState(): return [self.firstMove()] allPossiblePlays = { (numCards, card) for card, num in self.hand.iteritems() for numCards in xrange(1, num+1) } allPossiblePlays = sorted(allPossiblePlays, key=lambda (n,c): (c,-n)) filterFunc = lambda (n,c): (n == node.topCard[0] and c > node.topCard[1]) if node.topCard is None: return allPossiblePlays else: return [PASS] + filter(filterFunc, allPossiblePlays)
fbc7b9f4f255dd6f0dfa701c91e073f2b92ae4d6
YileC928/CS_sequence_code
/CS_w:_application1/pa3_ngram/basic_algorithms.py
3,969
4.03125
4
""" CS121: Analyzing Election Tweets (Solutions) Algorithms for efficiently counting and sorting distinct `entities`, or unique values, are widely used in data analysis. Functions to implement: - count_tokens - find_top_k - find_min_count - find_most_salient You may add helper functions. """ import math from util import sort_count_pairs ####1.1 def count_tokens(tokens): ''' Counts each distinct token (entity) in a list of tokens Inputs: tokens: list of tokens (must be immutable) Returns: dictionary that maps tokens to counts ''' count_d = {} tokens_no_rep = [] for i in tokens: if i not in tokens_no_rep: tokens_no_rep.append(i) for j in tokens_no_rep: count_d[j] = 0 for i in tokens: if j == i: count_d[j] += 1 return count_d ####1.2 def find_top_k(tokens, k): ''' Find the k most frequently occuring tokens Inputs: tokens: list of tokens (must be immutable) k: a non-negative integer Returns: list of the top k tokens ordered by count. ''' if k < 0: raise ValueError("In find_top_k, k must be a non-negative integer") #Count tokens d_count = count_tokens(tokens) #Convert dict in to list of tuples lst_pairs = [] for key, value in d_count.items(): pair = (key, value) lst_pairs.append(pair) #Sort by count sorted_lst = sort_count_pairs(lst_pairs) #Extract the K tokens lst_top_k = [] for pair in sorted_lst[0:k]: lst_top_k.append(pair[0]) return lst_top_k ####1.3 def find_min_count(tokens, min_count): ''' Find the tokens that occur *at least* min_count times Inputs: tokens: a list of tokens (must be immutable) min_count: a non-negative integer Returns: set of tokens ''' if min_count < 0: raise ValueError("min_count must be a non-negative integer") d_count = count_tokens(tokens) lst_above_min = [] for k, v in d_count.items(): if v >= min_count: lst_above_min.append(k) return set(lst_above_min) ####1.4 def find_tf (doc): ''' Compute tf for one document. Inputs: doc: list of tokens Returns: dictionary mapping tfs to tokens ''' if doc == []: dict_tf = {} else: doc_count = count_tokens(doc) max_t = find_top_k(doc, 1)[0] num_max_t = doc_count[max_t] dict_tf = {} for k, v in doc_count.items(): tf = 0.5 + 0.5 * (v/num_max_t) dict_tf[k] = tf return dict_tf def find_idf(docs): ''' Compute idf for each document. Inputs: docs: list of list of tokens Returns: dictionary mapping tfs to tokens ''' num_docs = len(docs) dict_idf = {} #generate a list of non-repetitive tokens lst_t = [] for doc in docs: for t in doc: if t not in lst_t: lst_t.append(t) #calculate idf for each token in the non-repetitive list for t1 in lst_t: num_occur_t1 = 0 for doc in docs: if t1 in doc: num_occur_t1 += 1 dict_idf[t1] = math.log(num_docs/num_occur_t1) return dict_idf def find_salient(docs, threshold): ''' Compute the salient words for each document. A word is salient if its tf-idf score is strictly above a given threshold. Inputs: docs: list of list of tokens threshold: float Returns: list of sets of salient words ''' dict_idf = find_idf(docs) lst_sa_tokens = [] for doc in docs: dict_tf = find_tf(doc) tf_idf = {} for k, v in dict_tf.items(): tf_idf[k] = v * dict_idf[k] sa_tokens = [] for k1 in tf_idf: if tf_idf[k1] > threshold: sa_tokens.append(k1) lst_sa_tokens.append(set(sa_tokens)) return lst_sa_tokens
7c0e3f24bf9dc548e0bc35a86ff32f44813525aa
jungleQi/leetcode-sections
/classification/data structure/2-array/53-M. Maximum Subarray.py
790
4.21875
4
#coding=utf-8 ''' Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. Example: Input: [-2,1,-3,4,-1,2,1,-5,4], Output: 6 Explanation: [4,-1,2,1] has the largest sum = 6. Follow up: If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle. ''' def maxSubArray(nums): """ :type nums: List[int] :rtype: int """ # 如果当前sum<0而且num<0, 就sum = 0 # maxSum每次curSum更新后,都需要比较更新一次 maxSum = nums[0] curSum = 0 for num in nums: curSum += num maxSum = max(maxSum, curSum) if curSum < 0: curSum = max(0, num) return maxSum
46ecaa0213ee924030dea9accc5c2cbb91d57f78
gramschs/angewandte_informatik
/solutions/week07/aufgabe_07_01.py
511
3.8125
4
''' Aufgabe 7.1 Schreiben Sie Code, der Ihren Vornamen abfragt und anschließend die Länge Ihres Vornamens bestimmt. Dann gibt das Programm den Buchstaben aus, der als erstes im Alphabet vorkommt. Schreiben Sie einmal Ihren Namen komplett klein, also z.B. "alice" und beim zweiten Mal mit großem Anfangsbuchstaben, also z.B. "Alice". Was beobachten Sie? ''' # Eingabe name = input('Wie heißen Sie mit Vornamen? ') # Ausgabe print('Der erste Buchstabe, der im Alphabet vorkommt, ist: {}'.format(min(name)))
554977a2f6c1bb8dc4e3ba03691297879ab2a050
hdert/python-quiz
/unused_components/db_create.py
1,975
3.921875
4
"""See db_create.__doc__.""" from os.path import isfile import sqlite3 from datetime import date db_path = "main.db" def db_create(db_path="main.db"): # noqa: D205, D400 """Check that the database doesn't exist, create the database, create the tables, finally connect to the database. Use os.path.isfile() on the database path to check if the file exists. Connect to the database. Set the conn.isolation_level to None. If the database doesn't exist create the tables leaderboard and score with the columns username, date; and leaderboard_id, and score. Else connect to the database. Args: db_path: Optional; The path to the database file, defaults to main.db. Returns: The connection object and the cursor object. """ if not isfile(db_path): conn = sqlite3.connect(db_path) conn.isolation_level = None c = conn.cursor() c.execute(""" CREATE TABLE leaderboard( username varchar(15) NOT NULL, date date NOT NULL ); """) c.execute(""" CREATE TABLE score( leaderboard_id REFERENCES leaderboard(rowid) NOT NULL, score tinyint(2) NOT NULL ) """) current_date = date.today() users = [['Billy', current_date], ['Eilish', current_date], ['Joel', current_date]] score = [[5, 7, 15], [15, 15, 14], [2, 7, 13]] for i in users: c.execute( """ INSERT into leaderboard (username,date) VALUES (?,?); """, [i[0], i[1]]) user_id = c.lastrowid for i in range(3): c.execute( """ INSERT into score (leaderboard_id,score) VALUES (?,?); """, [user_id, score[users.index(i)][i]]) else: conn = sqlite3.connect(db_path) conn.isolation_level = None c = conn.cursor() return conn, c if __name__ == "__main__": db_create(db_path)
ce55317c2ccbb827b85c34d81b566c8436fd065e
Austin-Bell/PCC-Exercises
/Chapter_7/rental_car.py
211
3.78125
4
# Wrtie a program that ask that user what kind of rental car they would like. prompt = input("What kind of car would you like to rent: ") message = "Let me see what if I can find you a " + prompt print(message)
44f9d77bd8e1aa4cba920a7b90488e833a30ce1f
alinaka/stepik-algorithms-course
/divide_and_conquer/count_sort/__init__.py
661
3.65625
4
import sys def count_sort(numbers, n, M): helper = [0 for _ in range(M + 1)] result = [0 for _ in range(n)] for number in numbers: helper[number] += 1 for i in range(2, len(helper)): helper[i] = helper[i] + helper[i - 1] for j in range(n - 1, -1, -1): result[helper[numbers[j]]-1] = numbers[j] helper[numbers[j]] = helper[numbers[j]] - 1 return result def main(): n = int(sys.stdin.readline().strip()) numbers = list(map(int, sys.stdin.readline().strip().split())) result = count_sort(numbers, n, 10) for i in result: print(i, end=" ") if __name__ == "__main__": main()
9330f5c264f0aba6a604def3c53440b45984c984
daniellehu/pennapps-fall-2015
/db/Python Scipts For Features/healthy_Corner_Stores.py
891
3.546875
4
import json # Reads the corner store data and then creates a dictionary with the zip as # a key and the number of stores as its val def read(file): with open(file) as json_data: data = json.load(json_data) zips = dict() for i in xrange(len(data["features"])): #Reading in the zip code of the corner store location cur = data["features"][i]["properties"]["ZIP"] # Storing it into a dictionary if cur in zips: zips[cur] = zips[cur] + 1 elif cur != None: zips[cur] = 1 return zips # Returns a dict with the zipcode as the key and the number of healthy corner # stores as the value def main(): zips = read("Healthy_Corner_Stores.geojson") with open('healthy_corner_dictionary.geojson', 'w') as outfile: json.dump(zips, outfile) return zips main()
25bd4552dabc3ee6a7e93f5049ea38fb79968140
sowmenappd/ds_algo_practice
/arrays_strings/rearrange_pos_neg_array_with_extra_space.py
509
4.1875
4
print("Program to rearrange positive and negative numbers in an array\n"); # This algorithm doesn't maintain the relative order def rearrange(array): l = len(array) idx = 0 for i in range(l): if array[i] < 0: array[idx], array[i] = array[i], array[idx] idx += 1 p = idx n = 0 while p > 0 and n < l: array[p], array[n] = array[n], array[p] p += 1 n += 2 return array print(rearrange([-1, 2, -3, 4, 5, 6, -7, 8, 9, -1]))
796392b901db215ed053c25269aa0e5d181cd3fe
shashank1094/pythonTutorials
/InterviewBit/subset.py
1,666
3.875
4
# Given a set of distinct integers, S, return all possible subsets. # # Note: # Elements in a subset must be in non-descending order. # The solution set must not contain duplicate subsets. # Also, the subsets should be sorted in ascending ( lexicographic ) order. # The list is not necessarily sorted. # Example : # # If S = [1,2,3], a solution is: # # [ # [], # [1], # [1, 2], # [1, 2, 3], # [1, 3], # [2], # [2, 3], # [3], # ] # ans = [[]] # # # def helper(li, index): # print('lis : {}, index : {}'.format(li, index)) # if index == len(li): # return [[]] # tmp = helper(li, index + 1) # print('before tmp : {}'.format(tmp)) # r = [] # for i in tmp: # t = [li[index]] + i # r.append(t) # print('result : {}'.format(r)) # tmp[1:1] = r # print('after tmp: {}'.format(tmp)) # print('DONE lis : {}, index : {}'.format(li, index)) # return tmp # # # def subsets(l1): # l1.sort() # return helper(l1, 0) # # # t = [1, 2, 3] # ans = subsets(t) # print(ans) class Solution: # @param A : list of integers # @return a list of list of integers def subsets(self, s): res = [] self.subset_helper(res, 0, sorted(s), []) res.sort() return res def subset_helper(self, result, index, s, curr): if index == len(s): result.append(curr) return self.subset_helper(result, index + 1, s, curr + [s[index]]) self.subset_helper(result, index + 1, s, curr) if __name__ == '__main__': print(Solution().subsets([3, 1, 2]))
805f2d795893591bd298cbae8bddda807cbbdea5
BilboSwaggins33/Test
/20.py
703
3.796875
4
#history program; records history in list h #records any undos into r, which allows for redos h = [] r = [] while True: print('Commands: undo, redo, else') choice = input(">>>") if choice == 'undo': try: #pops from history list into redo list x = h.pop(len(h)-1) print(x) r.append(x) except: print('Error: Nothing to undo') elif choice == 'redo': #pops from redo list into history list try: x = r.pop(len(r) - 1) print(x) h.append(x) except: print('Error: Nothing to redo') else: #add input to history h.append(choice)
44518e858ae97ea4cfb096d01c744ce1212cf532
pwildani/Letter-Roller
/roller/testboard.py
623
3.578125
4
""" Generate a board and print it out. """ import board import sys class TermBoardUI: def __init__(self, board): self.board = board def draw(self, out=sys.stdout): for r in range(self.board.rows): print >>out for c in range(self.board.cols): print >>out, self.board.letterAt(r, c), print >>out def main(): rows = cols = 5 if len(sys.argv) > 1: rows = cols = int(sys.argv[1]) if len(sys.argv) > 2: cols = int(sys.argv[2]) print 'Rows: %s, Cols: %s' % (rows, cols) ui = TermBoardUI(board.Board(rows, cols)) ui.draw() if __name__ == '__main__': main()
3ed3fee3cbc9c313eb4eeb0ef83231ccc4846519
vijeeshtp/python22
/inner1.py
365
4.1875
4
def outer (): def add (a,b): return a+b def diff (a,b): return a-b num1 = int(input("Enter num1#")) num2 = int(input("Enter num2#")) opr = input("Enter op::") if (opr== "+"): print (add (num1, num2)) elif (opr== "-"): print (diff(num1, num2)) else : print ("Not supported") outer ()
f6388e57ca4594dcee409bac7ae2afa4265093ac
ElisaMtz/Python_101
/Assignment Python 1-6.py
269
3.765625
4
y = int(input("Please write first number: ")) w = int(input("Please write second number: ")) if y >= w: x = w else: x = y while x > 0: z1 = y % x z2 = w % x if z1 == 0 and z2 == 0: print(x) break x -= 1 ### x = x - 1
d343dd2b8da73751e837c98ec58ec0fb7b734080
AYSEOTKUN/my-projects
/python/hands-on/flask-04-handling-forms-POST-GET-Methods/Flask_GET_POST_Methods_1/app.py
1,011
3.5625
4
# Import Flask modules from flask import Flask,render_template,request # Create an object named app app = Flask(__name__) # Create a function named `index` which uses template file named `index.html` # send three numbers as template variable to the app.py and assign route of no path ('/') @app.route('/') def index(): return render_template('index.html') # calculate sum of them using inline function in app.py, then sent the result to the # "number.hmtl" file and assign route of path ('/total'). # When the user comes directly "/total" path, "Since this is GET # request, Total hasn't been calculated" string returns to them with "number.html" file @app.route('/',methods=["GET","POST"]) def total(): if request.method =="POST": value1 = request.form.get("value1") value2 = request.form.get("value2") value3 = request.form.get("value3") return render_template("number.html") if __name__ == '__main__': #app.run(debug=True) app.run(host='0.0.0.0', port=80)
9078b5157122dc560a42bf76420a1eff12d30e27
nthauvin/sqrt_sum
/sqrt_sum4.py
3,763
4
4
#!/usr/bin/env python3 """ This modules combines neighbours cache and derecursion optimization to solve the Square-sum problem Computes the solutions from N=7 when no argument is passed Computes the solution for N if passed as an argument """ import sys import math import time import concurrent.futures Max = 0 if (len(sys.argv) == 2): Max = int(sys.argv[1]) def gen_squares(N): """ Computes all the perfect squares i*i for i in 1 to N Can be used as a cache for later computations """ squares = set([]) i = 1 while i*i <= N + (N-1) : squares.add(i*i); i = i + 1 return squares def gen_nexts(N, numbers, squares): """ Computes a dictionnary of available moves for each number """ nexts = dict() for i in numbers : for j in range(i+1, N+1): if i+j in squares: nexts[i] = nexts.get(i, []) + [j] nexts[j] = nexts.get(j, []) + [i] return nexts def find_sequence (N, numbers, nexts): """ Find solution sequences for starting numbers Returns (True, sequence) when found of (False, _} otherwise """ if len(numbers) == 0: return (False, []) first = numbers[0] (found, sequence) = solve(N, nexts, [first], [nexts[first]]) if found: return (found, sequence) else: return find_sequence(N, numbers[1:], nexts) def best_candidates (nexts, neighbours, sequence): """ Given a list of possible neighbours, sort them so that next numbers with less edges come first """ if len(neighbours) == 1: return neighbours else: Stats = [] for n in neighbours: Choices = [x for x in nexts[n] if x not in sequence] Count = len(Choices) if Count != 0: Stats.append((len(Choices), n)) Stats.sort() return [x for (count, x) in Stats] def solve (N, nexts, sequence, graphs): """ sequence solver without recursion to preserve Python call stack 'sequence' is the sequence being built, node after node 'Graph' is the corresponding list of still available choice graphs eg : sequence = [3, 1] graphs = [[6, 13], [8], Means that for number 3, available choices are 6 and 13 (sorted by preference) If 3 results in a dead branch, new backtracked state would be: sequence = [1] graphs = [8] leading to sequence = [8, 1] graphs = [] """ while len(sequence) < N and len(sequence) > 0: candidates = graphs[0].copy() # wtf ? corrupts nexts without copy() if candidates == []: sequence.pop(0) graphs.pop(0) else: number = sequence[0] candidate = candidates.pop(0) graphs[0] = candidates neighbours = nexts.get(candidate, []) possible = [x for x in neighbours if x not in sequence] New_candidates = best_candidates(nexts, possible, sequence) sequence.insert(0, candidate) graphs.insert(0, New_candidates) if (len(sequence) == N): return (True, sequence) else: return (False, []) def run(x): """ Computes a valid segment for N """ t0 = round(time.time()*1000) numbers = list(range(1, x+1)) squares = gen_squares(x) nexts = gen_nexts(x, numbers, squares) t1 = round(time.time()*1000) (found, result) = find_sequence(x, numbers, nexts) t2 = round(time.time()*1000) print (x, t1-t0, t2-t1, result, sep=';') return result # Main loop : compute sequence for N if given, otherwise computes from 7 if Max == 0: x=7 while True: run(x) x = x + 1 else: run(Max)
aca927c3aa341664218629744610f80943a30464
GMZDYZ/py-exercise
/base-exercise/guessNum.py
575
4
4
# -*- coding: utf-8 -* """ @Time:2019-12-26 15:02 @Version:1.0.0 @Author:Yincheats @Description:猜数字 """ from random import randint targetNum = randint(1, 10) print("guess a num for your glory 😡") int_yourNum = int(input()) while int_yourNum != targetNum: if int_yourNum < targetNum: print("less;num:", int_yourNum, "😂") if int_yourNum > targetNum: print("bigger;num:", int_yourNum) print("let`s try again,input a num", "😂") int_yourNum = int(input()) continue print("good job! you guessed", "👍👍👍")
c194b55e2baa67361a7d838e047c1856c20e1991
ryancheunggit/tensorflow2_model_zoo
/mnist_mlp_eager.py
5,378
3.546875
4
"""Example program training/inference on digit recognition problem with tensorflow 2.0.""" import argparse import cv2 import os import tensorflow as tf from tensorflow import keras from datetime import datetime # The model here is Multilayer peceptron/Fully connected network with 2 hidden layers. # The encoder/feature_extraction part is (Linear -> BN -> Relu) * 2 # The decoder/classifier part is Linear -> Dropout -> Softmax # It gets to 95% + test accuracy in 1 epoch. # the training loop is in pytorch style with eager execution only. # For Subclassed model like this one, it seems we can not use SavedModel util from tf2.0 # We can only save the weights, the python code is needed to re-construct model to be used for inference BATCH_SIZE = 32 NUM_CLASS = 10 NUM_EPOCHS = 5 LEARNING_RATE = 1e-3 if not os.path.exists('models/mnist_mlp_eager/'): os.mkdir('models/mnist_mlp_eager/') MODEL_FILE = 'models/mnist_mlp_eager/model' class MLP(keras.Model): """MLP model class using tf.Keras API.""" def __init__(self, num_class=NUM_CLASS): super(MLP, self).__init__() self.encoder = keras.Sequential([ keras.layers.Dense(units=128), keras.layers.BatchNormalization(), keras.layers.Activation(activation='relu'), keras.layers.Dense(units=32), keras.layers.BatchNormalization(), keras.layers.Activation(activation='relu') ]) self.decoder = keras.Sequential([ keras.layers.Dense(units=num_class), keras.layers.Dropout(rate=.1), keras.layers.Activation(activation='softmax') ]) def call(self, x, training=True): x = self.encoder(x, training=training) x = self.decoder(x, training=training) return x def train(verbose=0): """Train the model.""" # load dataset mnist = keras.datasets.mnist (x_train, y_train), (x_valid, y_valid) = mnist.load_data() x_train = x_train.reshape(60000, 784).astype('float32') / 255.0 x_valid = x_valid.reshape(10000, 784).astype('float32') / 255.0 train_dataset = tf.data.Dataset.from_tensor_slices((x_train, y_train)).batch(BATCH_SIZE) valid_dataset = tf.data.Dataset.from_tensor_slices((x_valid, y_valid)).batch(BATCH_SIZE) # config model model = MLP() criterion = keras.losses.SparseCategoricalCrossentropy() optimizer = keras.optimizers.Adam(learning_rate=LEARNING_RATE) train_loss = keras.metrics.Mean() train_accuracy = keras.metrics.SparseCategoricalAccuracy() test_loss = keras.metrics.Mean() test_accuracy = keras.metrics.SparseCategoricalAccuracy() # training loop for epoch in range(NUM_EPOCHS): t0 = datetime.now() # train train_loss.reset_states() train_accuracy.reset_states() for idx, (x_batch, y_batch) in enumerate(train_dataset): with tf.GradientTape() as tape: out = model(x_batch, training=True) loss = criterion(y_batch, out) grad = tape.gradient(loss, model.trainable_variables) optimizer.apply_gradients(zip(grad, model.trainable_variables)) train_loss(loss) train_accuracy(y_batch, out) # validate test_loss.reset_states() test_accuracy.reset_states() for idx, (x_batch, y_batch) in enumerate(valid_dataset): out = model(x_batch, training=False) loss = criterion(y_batch, out) test_loss(loss) test_accuracy(y_batch, out) message_template = 'epoch {:>3} time {} sec / epoch train cce {:.4f} acc {:4.2f}% test cce {:.4f} acc {:4.2f}%' t1 = datetime.now() if verbose: print(message_template.format( epoch + 1, (t1 - t0).seconds, train_loss.result(), train_accuracy.result() * 100, test_loss.result(), test_accuracy.result() * 100 )) # it appears that for keras.Model subclass model, we can only save weights in 2.0 alpha model.save_weights(MODEL_FILE, save_format='tf') def inference(filepath): """Reconstruct the model, load weights and run inference on a given picture.""" model = MLP() model.load_weights(MODEL_FILE) image = cv2.imread(filepath, 0).reshape(1, 784).astype('float32') / 255 probs = model.predict(image) print('it is a: {} with probability {:4.2f}%'.format(probs.argmax(), 100 * probs.max())) if __name__ == '__main__': parser = argparse.ArgumentParser(description='parameters for program') parser.add_argument('procedure', choices=['train', 'inference'], help='Whether to train a new model or use trained model to inference.') parser.add_argument('--image_path', default=None, help='Path to jpeg image file to predict on.') parser.add_argument('--gpu', default='', help='gpu device id expose to program, default is cpu only.') parser.add_argument('--verbose', type=int, default=0) args = parser.parse_args() os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu if args.procedure == 'train': train(args.verbose) else: assert os.path.exists(MODEL_FILE + '.index'), 'model not found, train a model before calling inference.' assert os.path.exists(args.image_path), 'can not find image file.' inference(args.image_path)
2b0ac0a91670caa7cd4dff5a4124bca56a6fb9f0
mpralat/notesRecognizer
/staff.py
668
3.734375
4
class Staff: """ Represents a single staff """ def __init__(self, min_range, max_range): self.min_range = min_range self.max_range = max_range self.lines_location, self.lines_distance = self.get_lines_locations() def get_lines_locations(self): """ Calculates the approximate positions of the separate lines in the staff :return: list of approximate positions of the lines """ lines = [] lines_distance = int((self.max_range - self.min_range) / 4) for i in range(5): lines.append(self.min_range + i * lines_distance) return lines, lines_distance
b6d600cefbef4ba2ed03fd103a5fc448a6b39f96
rmanojcse06/java-patterns
/src/main/py/bubbleSort.py
400
4.09375
4
def bubble_sort(arr): if arr: for i in range(len(arr) - 1): for j in range(len(arr) - i - 1): if arr[j+1] < arr[j]: arr[j+1],arr[j] = arr[j],arr[j+1]; return arr; def print_arr(arr): if arr: for e in arr: print(e); myarr=[2,12,4,15,11,13,5,1,6,8,14,7,3,10,9]; bubble_sort(myarr); print_arr(myarr);
bff9ebd79ba241364b9e2b37cfa2bc9d40dd68df
marbibu/node
/SegmentIntersection/LineIntersect.py
3,057
3.734375
4
''' python 2.7 Marek Bibulski 2015 Program implementuje algorytm do sprawdzania czy dwa odcinki na plaszczyznie, przecinaja sie. Pierwsze klikniecie na okno spowoduje utwrzenie pierwszego punktu odcinka, Drugie... drugiego. Dalsze klikniecia od nowa rozpoczna definiowanie punktow rysowanego odcinka. Wyniki przeciecia sa wypsywane w konsoli ''' from Tkinter import Tk,Canvas class Window(object): def __init__(s): #Dane: s.__draw() def __draw(s): s.__master=Tk() s.__master.title("Line intersection") s.__master.geometry("%sx%s+%s+%s"%(600,600,0,0)) s.__C=Canvas(s.__master,highlightthickness=0,bg="gray20") s.__C.pack(side="top",expand=1,fill="both") def __getC(s): return s.__C def loop(s): s.__master.update() s.__master.mainloop() C=property(fget=__getC) class Point(object): __r=6 def __init__(s,C,x,y): #Dane: s.__C=C s.__x,s.__y=x,y #Definicje: s.__draw() def __draw(s): s.__tag=s.__C.create_oval(-s.__r,-s.__r,s.__r,s.__r,fill="gray80",outline="") s.__C.move(s.__tag,s.__x,s.__y) def __getX(s): return s.__x def __getY(s): return s.__y def destroy(s): s.__C.delete(s.__tag) x=property(fget=__getX) y=property(fget=__getY) class Line(object): def __init__(s,C,A,B): #Dane: s.__C=C s.__A,s.__B=A,B #Definicje: s.__draw() def __draw(s): s.__tag=s.__C.create_line(s.__A.x,s.__A.y,s.__B.x,s.__B.y,fill="gray80") def __getA(s): return s.__A def __getB(s): return s.__B def __update(s): s.__C.coords(s.__tag,s.__A.x,s.__A.y,s.__B.x,s.__B.y) def __setA(s,A): s.__A=A s.__update() def __setB(s,B): s.__B=B s.__update() def destroy(s): s.__C.delete(s.__tag) A=property(fget=__getA,fset=__setA) B=property(fget=__getB,fset=__setB) class SegmentIntersection: def __ccw(s,A,B,C): return (C.y-A.y)*(B.x-A.x) > (B.y-A.y)*(C.x-A.x) def intersect(s,A,B,C,D): if s.__ccw(A,C,D) != s.__ccw(B,C,D) and s.__ccw(A,B,C) != s.__ccw(A,B,D): print "przecina sie" else: print "nie przecina sie" class LineCreator: def __init__(s,sesin,C,line): #Dane: s.__sesin=sesin s.__C=C s.__A,s.__B=None,None s.__line=line #Definicje: s.__bind() def __click(s,event): x,y=event.x,event.y s.putCoords(x,y) def putCoords(s,x,y): if s.__A==None and s.__B==None: s.__A=Point(s.__C,x,y) elif s.__A!=None and s.__B==None: s.__B=Point(s.__C,x,y) s.__line0=Line(s.__C,s.__A,s.__B) s.__sesin.intersect(s.__line.A,s.__line.B,s.__line0.A,s.__line0.B) elif s.__A!=None and s.__B!=None: s.__A.destroy() s.__B.destroy() s.__A=Point(s.__C,x,y) s.__B=None s.__line0.destroy() s.__C.update() def __bind(s): s.__C.bind("<1>",s.__click) class Main(): def __init__(s): #Okno z Canvasem win=Window() #Wspolrzedne punktow nieruchomego odcinka x1=100 y1=300 x2=400 y2=100 #Nieruchomy odcinek l1=Line(win.C, Point(win.C,x1,y1), Point(win.C,x2,y2) ) #Linia, ktora bedzie tworzona po kliknieciu na Canvas #wykrywa przeciacia z linia zadana powyzej LineCreator(SegmentIntersection(),win.C,l1) win.loop() Main()
7d16d6aebb2a3e598b03074d8cf64862d66e5334
sanika2106/sanika2106
/guessing game.py
948
4.28125
4
# Now, we will make a game using loops. We will call this game a guessing game. # In this game we take any number, let us suppose this number is number 5. # After this we take any number as an input from the user between 1 to 10. The user tries to guess # this number. # Suppose the user gives 3as an input. We will then check if 3 is equal to 5 or not? # 3 is not equal to 5 so we will ask the user for another input. # Now, we will check if that number is equal to 5 or not. # User will get 5 chances to guess. # If he guessed right within the 5 chances he wins and if he guesses wrong then loses the game. # Hint : # Study about break statement`` in python. # i=1 # while i<=5: # num=int(input("enter the number:")) # if num==5: # print("congratulations!,you win!") # break # else: # print("you loss!") # print(5-i, "chance remain!") # print("try again!") # i+=1 a="shruti" print(a+5)
6304d87b40a414daefaba10adf13ff1442fbf025
zyx124/algorithm_py
/python/sort.py
2,770
4.28125
4
# sort algorithms # The default python sort() method uses merge sort. # Bubble Sort: compare the two adjacent number and make the larger one "float" def bubbleSort(array): if not array: return array for i in range(len(array)): for j in range(len(array) - 1): if array[j] > array[j + 1]: array[j], array[j + 1] = array[j + 1], array[j] return array # Merge Sort: split into two parts and use recursionn O(nlogn) def mergeSort(array): if len(array) == 1: return array n = len(array) left = array[:n // 2] right = array[n // 2:] left = mergeSort(left) right = mergeSort(right) return merge(left, right) def merge(left, right): result = [] while len(left) != 0 and len(right) != 0: if left[0] < right[0]: result.append(left.pop(0)) else: result.append(right.pop(0)) if left: result = result + left if right: result = result + right return result # Insertion Sort: insert the new element into the sorted part. O(n^2) def insertionSort(array): for i in range(1, len(array)): j = i-1 next_element = array[i] while array[j] > next_element and j >= 0: array[j+1] = array[j] j = j - 1 array[j+1] = next_element # Quick Sort: pick a pivot and let the left side smaller than the pivot and the other side larger and repeat for the left side and right side until the the whole array is sorted. O(nlogn) # partition part is usually used in solving array problems like Find Kth Largest Number, it is a quick select method. def quickSort(array, low, high): if low > high: return pivot_location = partition(array, low, high) quickSort(array, low, pivot_location - 1) quickSort(array, pivot_location + 1, high) def partition(array, low, high): pivot = array[high] index = low for i in range(low, high): if array[i] < pivot: array[i], array[index] = array[index], array[i] index = index + 1 array[index], array[high] = array[high], array[index] return index ## version 2 find the kth smallest element def partition(array, start, end, k): if start == end: return array[k] left, right = start, end pivot = array[start + (start - end) // 2] while left <= right: while left <= right and array[left] < pivot: left += 1 while left <= right and array[right] > pivot: right -= 1 if left <= right: array[left], array[right] = array[right], array[left] left += 1 right -= 1 if k <= right: return patition(array, start, right, k) if k >= left: return partition(array, left, end, k) return array[k]
c9282c80fcd12b0762ad10854a8cdb174f262ad7
aditidesai27/wacpythonwebinar
/DAY01/datatype.py
176
3.703125
4
# name = "neeraj sharma" x = 5 #int y = 5.2 #float z = "neeraj sharma" #string str p = '5.5' # q = True / False boolean bool # print("x") # print(x) print(p)
42e95062e5f04bc6b21a80b39ca93c0949b09183
AnkitaPisal1510/assignemt_repository
/pythonpart1.py
224
3.90625
4
user_input=int(input("enter a number:-")) index1=1 print("") while index1<=user_input: print(" ---"*user_input) print(f"| {0} "*user_input+"|") index1+=1 if index1==user_input+1: print(" ---"*user_input)
1db502042c35527194bcbcd7cb402454fdf77eaf
beaupreda/domain-networks
/utils/graphs.py
1,527
4
4
""" functions to make accuracy and loss graphs. author: David-Alexandre Beaupre data: 2020-04-28 """ import os from typing import List import matplotlib.figure class Graph: def __init__(self, savepath: str, fig: matplotlib.figure.Figure, ax: matplotlib.figure.Axes, loss: bool = True): """ represents a graph to show the evolution of the loss and accuracy during training. :param savepath: path to save the images. :param fig: matplotlib figure object. :param ax: matplotlib axis object. :param loss: whether the graph is a loss one or not. """ self.savepath = savepath self.fig = fig self.ax = ax self.loss = loss def create(self, train: List[float], validation: List[float]) -> None: """ creates the accuracy or validation graph in the axis object. :param train: training data (accuracy or loss). :param validation: validation data (accuracy or loss). :return: void. """ self.ax.plot(train) self.ax.plot(validation) self.ax.set_xlabel('epochs') if self.loss: self.ax.set_ylabel('loss') else: self.ax.set_ylabel('accuracy') self.ax.legend(['train', 'validation']) def save(self) -> None: """ writes the graph to a PNG file. :return: void """ graph = 'loss' if self.loss else 'accuracy' save = os.path.join(self.savepath, graph + '.png') self.fig.savefig(save)
5ddddd3c516d93b4412319fde0c497bc178903d7
knparikh/IK
/Strings/palindrome_pairs.py
800
3.78125
4
# Given a list of words, find palindrome pairs # inp: {race, cat, dog, god, car, ma, dam} N, M length # output : {racecar, doggod, madam, goddog} # Brute force : O(n2) combine all words # Approach 2: Hash table: Put every word's reverse in hash table. If word exists # as prefix in hash and its remaining is palindrome, then pair is palindrome. But does not work for race/car, madam # Time complexity: O(N(for all words) * M^2 (to strcmp prefix of length M) + M (palindrome for rest of string)) ~ O(M^2). # Creating hash of reverse words = O(N^2) for each word, reverse and then insert in hash. # Above does not work with ma/dam - for ma, mad does not exist # We also need second hash table with words as it is , and look for reverse # This problem can also be solved with Trie and ReverseTrie # #
296ce0e00c7078c1866a1dc30889dd3138fbbf88
tyrionzt/new_web
/sudoku.py
6,517
3.640625
4
import re from Tkinter import * from collections import defaultdict from random import choice import tkMessageBox as mb class Solution: # judge sudoku is avaiable def isValidSudoku(self, board): for i in range(9): locals()["sudoku" + str(i)] = [] for i in range(9): row = [] col = [] for j in range(9): if board[i][j] and not re.match(r'^[1-9]{1}$', board[i][j]): return False, (i, j) pos = (i // 3) * 3 + j // 3 if board[i][j].isdigit(): if board[i][j] in row: return False, (i, j) row.append(board[i][j]) if board[j][i].isdigit(): if board[j][i] in col: return False, (i, j) col.append(board[j][i]) if board[i][j].isdigit(): if board[i][j] in locals()["sudoku" + str(pos)]: return False, (i, j) locals()["sudoku" + str(pos)].append(board[i][j]) return True class Solution1: def solveSudoku(self, board): """ :type board: List[List[str]] :rtype: return a valid Sudoku board """ def could_place(d, row, col): """ Check if one could place a number d in (row, col) cell """ return not (d in rows[row] or d in columns[col] or d in boxes[box_index(row, col)]) def place_number(d, row, col): """ Place a number d in (row, col) cell """ rows[row][d] += 1 columns[col][d] += 1 boxes[box_index(row, col)][d] += 1 board[row][col] = str(d) def remove_number(d, row, col): """ Remove a number which didn't lead to a solution """ del rows[row][d] del columns[col][d] del boxes[box_index(row, col)][d] board[row][col] = '' def place_next_numbers(row, col): """ Call backtrack function in recursion to continue to place numbers till the moment we have a solution """ # if we're in the last cell # that means we have the solution if col == N - 1 and row == N - 1: sudoku_solved[0] = True # if not yet else: # if we're in the end of the row # go to the next row if col == N - 1: backtrack(row + 1, 0) # go to the next column else: backtrack(row, col + 1) def backtrack(row=0, col=0): """ Backtracking """ # if the cell is empty if not board[row][col]: # iterate over all numbers from 1 to 9 for d in range(1, 10): if could_place(d, row, col): place_number(d, row, col) place_next_numbers(row, col) # if sudoku is solved, there is no need to backtrack # since the single unique solution is promised if not sudoku_solved[0]: remove_number(d, row, col) else: place_next_numbers(row, col) # box size n = 3 # row size N = n * n # lambda function to compute box index box_index = lambda row, col: (row // n) * n + col // n # init rows, columns and boxes rows = [defaultdict(int) for i in range(N)] columns = [defaultdict(int) for i in range(N)] boxes = [defaultdict(int) for i in range(N)] for i in range(N): for j in range(N): if board[i][j]: d = int(board[i][j]) place_number(d, i, j) sudoku_solved = {} sudoku_solved[0] = False backtrack() return board def generate(): board = [["", "", "", "", "", "", "", "", ""] for i in range(9)] for i in range(30): board[choice(range(9))][choice(range(9))] = choice(range(1, 10)) return board main = Tk() main.title("sudoku") board = [["", "", "", "", "", "", "", "", ""] for i in range(9)] main.geometry("430x280") def get_result(): for i in range(9): for j in range(9): board[i][j] = globals()["text_input" + str(i) + str(j)].get() print board res = Solution().isValidSudoku(board) print res if not isinstance(res, tuple): Label(main, text="congratulations!!! you win", bg="green").pack(side=CENTER) print 1111 else: x, y = res[1][0], res[1][1] # error = StringVar(value=board[x][y]) # globals()["text_input" + str(x) + str(y)] = Entry(main, textvariable=error, width=3, bg="red") # globals()["text_input" + str(x) + str(y)].grid(row=x, column=y) mb.showerror(title="error!!!", message="%s row, %s column" % (x+1, y+1), bg="red") # error = Label(main, text="error!!! %s row, %s column" % (x+1, y+1), bg="red") # error.pack(side=BOTTOM) def clean(): for i in range(9): for j in range(9): locals()["vars" + str(i) + str(j)] = StringVar() globals()["text_input" + str(i) + str(j)] = Entry(main, textvariable=locals()["vars" + str(i) + str(j)], width=3) globals()["text_input" + str(i) + str(j)].grid(row=i, column=j) def new(): for i in range(9): for j in range(9): new_board = generate() locals()["vars" + str(i) + str(j)] = StringVar(value=new_board[i][j]) globals()["text_input" + str(i) + str(j)] = Entry(main, textvariable=locals()["vars" + str(i) + str(j)], width=3) globals()["text_input" + str(i) + str(j)].grid(row=i, column=j) def answer(): pass B = Button(main, text="confirm", width=6, command=get_result).grid(row=1, column=13) B1 = Button(main, text="clean", width=6, command=clean).grid(row=3, column=13) B2 = Button(main, text="new", width=6, command=new).grid(row=5, column=13) B3 = Button(main, text="answer", width=6, command=answer).grid(row=7, column=13) main.mainloop()
1856c7327a3fd6e2a4ca7babbadfeb7a10e51e9a
MonCheung/learn_python
/test.py
24,994
4.1875
4
''' def fact(n): print("factorial has been called with n = " + str(n)) if n == 1: return 1 else: res = n * fact(n - 1) print("intermediate result for ", n, " * fact(", n - 1, "): ", res) return res print(fact(20)) ''' ''' #递归算法的实现 def fact(n): result=1 for i in range(2,n+1): result=result*i return result print(fact(1)) print(fact(2)) print(fact(1000)) ''' '''#字符串和编码练习 # -*- coding: utf-8 -*- a=int(input('请输入上次成绩:')) b=int(input('请输入本次成绩:')) r=int(((b-a)/a)*100) print('恭喜成绩提升%.1f%%' % r) ''' ''''#列表练习 # -*- coding: utf-8 -*- L = [['Apple', 'Google', 'Microsoft'],['Java', 'Python', 'Ruby', 'PHP'],['Adam', 'Bart', 'Lisa']] #打印apple print(L[0][0]) #打印python print(L[1][1]) #打印lisa print(L[2][2]) ''' '''#条件判断练习 # -*- coding: utf-8 -*- height = float(input('请输入身高:')) weight = float(input('请输入体重:')) bmi = float((weight/height)**2) if bmi<18.5: print('过轻') elif bmi<=25: print('过重') elif bmi<=32: print('肥胖') else: print('严重肥胖') ''' '''#循环练习 # -*- coding: utf-8 -*- L = ['Bart', 'Lisa', 'Adam'] n = int(len(L)) while n>0: print('Hello,%s' % L[len(L)-n]) n = n-1 ''' '''#循环练习 # -*- coding: utf-8 -*- L = ['Bart', 'Lisa', 'Adam'] for name in L: print('Hello,%s'%name) ''' ''' # -*- coding: utf-8 -*- n1 = 255 n2 = 1000 print(hex(n1)) print(hex(n2)) ''' '''#函数定义练习 # -*- coding: utf-8 -*- import math def quadratic(a, b, c): d=b**2-4*a*c if d==0: x=-b/(2*a) return x elif d>0: x1=(math.sqrt(d)-b)/(2*a) x2=-(math.sqrt(d)+b)/(2*a) return (x1,x2) else: return('无实数解') a=float(input('请输入a:')) b=float(input('请输入b:')) c=float(input('请输入c:')) print(quadratic(a,b,c)) ''' ''' def power(x, n=2): s = 1 while n > 0: n = n - 1 s = s * x return s print(power(188)) ''' '''#函数的参数练习 # -*- coding: utf-8 -*- def product(*L): if len(L)==0: raise TypeError('参数为空') else: n=1 for i in L: n=n*i return n print('product(5) =', product(5)) print('product(5, 6) =', product(5, 6)) print('product(5, 6, 7) =', product(5, 6, 7)) print('product(5, 6, 7, 9) =', product(5, 6, 7, 9)) if product(5) != 5: print('测试失败!') elif product(5, 6) != 30: print('测试失败!') elif product(5, 6, 7) != 210: print('测试失败!') elif product(5, 6, 7, 9) != 1890: print('测试失败!') else: try: product() print('测试失败!') except TypeError: print('测试成功!') ''' ''' def fact(n): if n==1: return 1 return n * fact(n - 1) print(fact(1000)) ''' ''' #递归解决汉诺塔问题 def move(n,a,b,c): if n==1: print(a,'-->',c) else: move(n-1,a,c,b) print(a,'-->',c) move(n-1,b,a,c) print(move(2,'A','B','C')) ''' ''' # -*- coding: utf-8 -*- def trim(s): s=s[1:-1] return s s=str(input('请输入内容:')) print(trim(s)) ''' ''' #切片练习 # -*- coding: utf-8 -*- def trim(s): a=len(s) n=0 m=a-1 while n<a: if s[n]!=' ':#添加空格 break else: n=n+1 while m>0: if s[m]!=' ':#添加空格 break else: m=m-1 #print(n) #输出变量结果 #print(m) #输出变量结果 m=m+1#切片不包含最后一项 return s[n:m] print(trim(' abc ')) if trim(' abc ')=='abc': print('pass') else: print('fail') # 测试: if trim('hello ') != 'hello': print('测试失败!') elif trim(' hello') != 'hello': print('测试失败!') elif trim(' hello ') != 'hello': print('测试失败!') elif trim(' hello world ') != 'hello world': print('测试失败!') elif trim('') != '': print('测试失败!') elif trim(' ') != '': print('测试失败!') else: print('测试成功!') ''' ''' #迭代练习 # -*- coding: utf-8 -*- def findMinAndMax(L): if len(L)==0: return(None,None) elif len(L)==1: return (L[0],L[0]) else: min=L[0] max=L[0] for a in L: if a<min: min=a elif a>max: max=a return (min,max) # 测试 if findMinAndMax([]) != (None, None): print('测试失败!') elif findMinAndMax([7]) != (7, 7): print('测试失败!') elif findMinAndMax([7, 1]) != (1, 7): print('测试失败!') elif findMinAndMax([7, 1, 3, 9, 5]) != (1, 9): print('测试失败!') else: print('测试成功!') ''' ''' #列表生成式练习 # -*- coding: utf-8 -*- L1 = ['Hello', 'World', 18, 'Apple', None] L2 = [s.lower() for s in L1 if isinstance(s,str)==True] # 测试: print(L2) if L2 == ['hello', 'world', 'apple']: print('测试通过!') else: print('测试失败!') ''' ''' # -*- coding: utf-8 -*- def triangles(): L = [1] yield L while True: L.append(0) L = [L[i - 1] + L[i] for i in range(len(L))] yield L # 期待输出: # [1] # [1, 1] # [1, 2, 1] # [1, 3, 3, 1] # [1, 4, 6, 4, 1] # [1, 5, 10, 10, 5, 1] # [1, 6, 15, 20, 15, 6, 1] # [1, 7, 21, 35, 35, 21, 7, 1] # [1, 8, 28, 56, 70, 56, 28, 8, 1] # [1, 9, 36, 84, 126, 126, 84, 36, 9, 1] n = 0 results = [] for t in triangles(): print(t) results.append(t) n = n + 1 if n == 2: break if results == [ [1], [1,1]]: print('测试通过!') else: print('测试失败!') ''' ''' #高级函数练习1 # -*- coding: utf-8 -*- from functools import reduce #第一题字符串大小写转换 def normalize(name): return name[0].upper()+name[:-1].lower() # 测试: L1 = ['adam', 'LISA', 'barT'] L2 = list(map(normalize, L1)) print(L2) #第二题列表乘积 def time(x,y): return x*y def prod(L): return reduce(time,L) # 测试: print('3 * 5 * 7 * 9 =', prod([3, 5, 7, 9])) if prod([3, 5, 7, 9]) == 945: print('测试成功!') else: print('测试失败!') #第三题字符串类型转换 digits={'.':'.','0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9} def chr2num(s): return digits[s] def f(x,y): return x*10+y def str2float(s): l=s.split('.') n=len(l[1]) a=reduce(f,map(chr2num,l[0])) b=reduce(f,map(chr2num,l[1])) return a+b*pow(10,-n) print('str2float(\'123.456789\') =', str2float('123.456789')) if abs(str2float('123.456') - 123.456) < 0.00001: print('测试成功!') else: print('测试失败!') ''' ''' def _odd_iter(): n = 1 while True: n = n + 2 yield n def _not_divisible(n): return lambda x: x % n > 0 def primes(): yield 2 it = _odd_iter() # 初始序列 while True: n = next(it) # 返回序列的第一个数 yield n it = filter(_not_divisible(n), it) # 构造新序列 for n in primes(): if n < 10: print(n) else: break ''' ''' #filter练习 # -*- coding: utf-8 -*- from functools import reduce digits={'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9} def chr2num(s): return digits[s] def fn(x,y): return x*10+y def is_palindrome(n): s=list(str(n)) l=len(s) if l==1: return n else: a=reduce(fn,map(chr2num,s[::-1])) if a==n: return a else: return None # 测试: output = filter(is_palindrome, range(1, 1000)) print('1~1000:', list(output)) if list(filter(is_palindrome, range(1, 200))) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111, 121, 131, 141, 151, 161, 171, 181, 191]: print('测试成功!') else: print('测试失败!') ''' ''' #sorted函数练习 # -*- coding: utf-8 -*- L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)] def by_name(t): return t[0] print(by_name(L))#测试该函数的输出 def by_score(t): return t[1] print(by_score(L))#测试该函数的输出 #升序排序名字和分数 L2 = sorted(L, key=by_name) print(L2) L2 = sorted(L, key=by_score) print(L2) #降序排序名字和分数 L2 = sorted(L, key=by_name, reverse=True) print(L2) L2 = sorted(L, key=by_score, reverse=True) print(L2) ''' ''' #返回函数练习 # -*- coding: utf-8 -*- def createCounter(): x = (x for x in range(1,100)) def counter(): return next(x) return counter # 测试: counterA = createCounter() print(counterA(), counterA(), counterA(), counterA(), counterA()) # 1 2 3 4 5 counterB = createCounter() if [counterB(), counterB(), counterB(), counterB()] == [1, 2, 3, 4]: print('测试通过!') else: print('测试失败!') ''' ''' # -*- coding: utf-8 -*- def is_odd(n): return n % 2 == 1 L = list(filter(is_odd, range(1, 20))) print(L) ''' ''' #匿名函数练习 # -*- coding: utf-8 -*- L = list(filter(lambda n:n%2==1, range(1, 20))) print(L) ''' ''' # -*- coding: utf-8 -*- #装饰器练习 #打印函数执行时间 import time, functools def metric(fn): def wrapper(*args,**kw): print('%s executed in %s ms' % (fn.__name__, 10.24)) return fn(*args,**kw) return wrapper # 测试 @metric def fast(x, y): time.sleep(0.0012) return x + y; @metric def slow(x, y, z): time.sleep(0.1234) return x * y * z; f = fast(11, 22) s = slow(11, 22, 33) if f != 33: print('测试失败!') elif s != 7986: print('测试失败!') else: print('测试成功!') #函数的调用前后输出 def log(func): def wrapper(*args,**kw): print('begin call') c = func(*args,**kw) print('end call') return c return wrapper @log def now(): print('20180905') now() #可自定义输入参数的decorator def logger(*text): def decorator(func): def wrapper(*args,**kw): if str(*text) == '': print('call %s()' % func.__name__) else: print('%s call %s()' % (*text,func.__name__)) return func(*args,**kw) return wrapper return decorator @logger('is test') def f1(): print('2018-09-06') f1() @logger() def f2(): print('2018-09-06') f2() ''' ''' #类和实例练习 # -*- coding: utf-8 -*- class Student(object): def __init__(self,name,sex,age,score): self.name=name self.sex=sex self.age=age self.score=score def get_grade(self): if self.score >= 90: return 'A' elif self.score >= 60: return 'B' else: return 'C' def get_group(self): if self.age >=3 and self.age<=6: return '儿童' elif self.age >=7 and self.age<=14: return '少年' else: return '成年' #测试 lisa = Student('Lisa', 'female',2,99) bart = Student('Bart', 'male',9,59) print(lisa.name, lisa.get_group(), '\'age is %s\''% lisa.age, lisa.get_grade()) print(bart.name, bart.get_group(), '\'age is %s\''% bart.age, bart.get_grade()) ''' ''' #访问限制练习 # -*- coding: utf-8 -*- class Student(object): """docstring for Student.""" def __init__(self, name,gender): self.name=name self.__gender=gender def get_gender(self): return self.__gender def set_gender(self,gender): if gender=='male' or 'female': self.__gender=gender else: raise ValueError('not gender') # 测试: bart = Student('Bart', 'male') if bart.get_gender() != 'male': print('测试失败!') else: bart.set_gender('female') if bart.get_gender() != 'female': print('测试失败!') else: print('测试成功!') ''' ''' #实例属性和类属性 # -*- coding: utf-8 -*- class Student(object): count = 0 def __init__(self, name): self.name = name Student.count += 1 # 测试: if Student.count != 0: print('测试失败!') else: bart = Student('Bart') if Student.count != 1: print('测试失败!') else: lisa = Student('Bart') if Student.count != 2: print('测试失败!') else: print('Students:', Student.count) print('测试通过!') ''' ''' #property属性在类中的应用 # -*- coding: utf-8 -*- class Screen(object): @property def width(self): return self._width @width.setter def width(self,value): self._width = value @property def height(self): return self._height @height.setter def height(self,value): self._height = value @property def resolution(self): return self._width*self._height # 测试: s = Screen() s.width = 1024 s.height = 768 print('resolution = ', s.resolution) if s.resolution == 786432: print('测试通过!') else: print('测试失败!') ''' ''' #错误处理 # -*- coding: utf-8 -*- from functools import reduce def str2num(s): try: return int(s) except Exception as e: return float(s) def calc(exp): ss = exp.split('+') ns = map(str2num, ss) return reduce(lambda acc, x: acc + x, ns) def main(): r = calc('100 + 200 + 345') print('100 + 200 + 345 =', r) r = calc('99 + 88 + 7.6') print('99 + 88 + 7.6 =', r) main() ''' ''' #单元测试练习 # -*- coding: utf-8 -*- import unittest class Student(object): def __init__(self, name, score): self.name = name self.score = score def get_grade(self): n=range(101) if self.score not in n: raise ValueError if self.score >= 80: return 'A' elif self.score >= 60: return 'B' return 'C' class TestStudent(unittest.TestCase): def test_80_to_100(self): s1 = Student('Bart', 80) s2 = Student('Lisa', 100) self.assertEqual(s1.get_grade(), 'A') self.assertEqual(s2.get_grade(), 'A') def test_60_to_80(self): s1 = Student('Bart', 60) s2 = Student('Lisa', 79) self.assertEqual(s1.get_grade(), 'B') self.assertEqual(s2.get_grade(), 'B') def test_0_to_60(self): s1 = Student('Bart', 0) s2 = Student('Lisa', 59) self.assertEqual(s1.get_grade(), 'C') self.assertEqual(s2.get_grade(), 'C') def test_invalid(self): s1 = Student('Bart', -1) s2 = Student('Lisa', 101) with self.assertRaises(ValueError): s1.get_grade() with self.assertRaises(ValueError): s2.get_grade() if __name__ == '__main__': unittest.main() ''' ''' #文档测试练习 # -*- coding: utf-8 -*- def fact(n): '''''' Calculate 1*2*...*n >>> fact(1) 1 >>> fact(10) 3628800 >>> fact(-1) Traceback (most recent call last): ... ValueError ''''''' if n < 1: raise ValueError() if n == 1: return 1 return n * fact(n - 1) if __name__ == '__main__': import doctest doctest.testmod() ''' ''' #实现dir -l输出的练习 # -*- coding: utf-8 -*- from datetime import datetime import os pwd = os.path.abspath('.') print(pwd) print(' Size Last Modified Name') print('------------------------------------------------------------') for f in os.listdir(pwd): fsize = os.path.getsize(f) mtime = datetime.fromtimestamp(os.path.getmtime(f)).strftime('%Y-%m-%d %H:%M') flag = '/' if os.path.isdir(f) else '' print('%10d %s %s%s' % (fsize, mtime, f, flag)) ''' ''' #指定字符串的文件输出的练习(os.walk的用法) # -*- coding: utf-8 -*- import os pwd = os.path.abspath('.') print(pwd) print(os.walk(".")) sr = input('关键字符串:') for path, dirs, files in os.walk("."): for a in files + dirs: if sr in a: print(os.path.join(path, a)) ''' ''' #指定字符串的文件输出的练习(使用递归) # -*- coding: utf-8 -*- import os dir = os.path.abspath('.') def fileFound(seq, filedir): li = os.listdir(filedir) for x in li: path = os.path.join(filedir,x) if os.path.isfile(path) and seq in x: print(os.path.abspath(path).replace(dir,'')) if os.path.isdir(path): fileFound(seq, path) n=input('请输入关键字符串:') fileFound(n,dir) ''' ''' #序列化练习 # -*- coding: utf-8 -*- import json obj = dict(name='小明', age=20) s = json.dumps(obj,ensure_ascii=True)#unicode编码包含ascii编码,故将汉字转为unicode编码 print(s) ''' ''' #正则表达式练习(1) # -*- coding: utf-8 -*- import re def is_valid_email(addr): return re.match(r'^\w+[\.\w]\w+@\w+\.com$',addr) # 测试: assert is_valid_email('someone@gmail.com') assert is_valid_email('bill.gates@microsoft.com') assert not is_valid_email('bob#example.com') assert not is_valid_email('mr-bob@example.com') print('ok') #正则表达式练习(2) # -*- coding: utf-8 -*- import re def name_of_email(addr): return re.match(r'.*?([\w\s]+)',addr).group(1) #'.*?'可以匹配任意长度的字符串(除字符串、数字、空格,可为零) # 测试: assert name_of_email('<Tom Paris> tom@voyager.org') == 'Tom Paris' assert name_of_email('tom@voyager.org') == 'tom' print('ok') ''' ''' #datetime模块练习 # -*- coding:utf-8 -*- import re from datetime import datetime, timezone, timedelta def to_timestamp(dt_str, tz_str): #获取输入时间的datetime dt=datetime.strptime(dt_str,'%Y-%m-%d %H:%M:%S') if '+' in tz_str: #通过正则取出时区,换算为北京时间 n=int(re.match(r'UTC.(0?)(\d+):',tz_str).group(2)) st=dt-timedelta(hours=n-8) return st.timestamp() else: n=int(re.match(r'UTC.(0?)(\d+):',tz_str).group(2)) st=dt+timedelta(hours=n+8) return st.timestamp() # 测试: t1 = to_timestamp('2015-6-1 08:10:30', 'UTC+7:00') print(t1) assert t1 == 1433121030.0, t1 t2 = to_timestamp('2015-5-31 16:10:30', 'UTC-09:00') print(t2) assert t2 == 1433121030.0, t2 print('ok') ''' ''' #base64模块 # -*- coding: utf-8 -*- import base64 def safe_base64_decode(s): if len(s)%4 != 0: s=s+b'=' return safe_base64_decode(s) else: return base64.b64decode(s) # 测试: assert b'abcd' == safe_base64_decode(b'YWJjZA=='), safe_base64_decode('YWJjZA==') assert b'abcd' == safe_base64_decode(b'YWJjZA'), safe_base64_decode('YWJjZA') print('ok') ''' ''' #struct模块打印位图宽高和颜色 # -*- coding: utf-8 -*- import base64, struct bmp_data = base64.b64decode('Qk1oAgAAAAAAADYAAAAoAAAAHAAAAAoAAAABABAAAAAAADICAAASCwAAEgsAAAAAAAAAAAAA/3//f/9//3//f/9//3//f/9//3//f/9//3//f/9//3//f/9//3//f/9//3//f/9//3//f/9//3//f/9/AHwAfAB8AHwAfAB8AHwAfP9//3//fwB8AHwAfAB8/3//f/9/AHwAfAB8AHz/f/9//3//f/9//38AfAB8AHwAfAB8AHwAfAB8AHz/f/9//38AfAB8/3//f/9//3//fwB8AHz/f/9//3//f/9//3//f/9/AHwAfP9//3//f/9/AHwAfP9//3//fwB8AHz/f/9//3//f/9/AHwAfP9//3//f/9//3//f/9//38AfAB8AHwAfAB8AHwAfP9//3//f/9/AHwAfP9//3//f/9//38AfAB8/3//f/9//3//f/9//3//fwB8AHwAfAB8AHwAfAB8/3//f/9//38AfAB8/3//f/9//3//fwB8AHz/f/9//3//f/9//3//f/9/AHwAfP9//3//f/9/AHwAfP9//3//fwB8AHz/f/9/AHz/f/9/AHwAfP9//38AfP9//3//f/9/AHwAfAB8AHwAfAB8AHwAfAB8/3//f/9/AHwAfP9//38AfAB8AHwAfAB8AHwAfAB8/3//f/9//38AfAB8AHwAfAB8AHwAfAB8/3//f/9/AHwAfAB8AHz/fwB8AHwAfAB8AHwAfAB8AHz/f/9//3//f/9//3//f/9//3//f/9//3//f/9//3//f/9//3//f/9//3//f/9//3//f/9//3//f/9//38AAA==') def bmp_info(data): if struct.unpack('<cc', data[:2]) == (b'B', b'M'): return { 'width': struct.unpack('<I', data[18:22])[0], 'height': struct.unpack('<I', data[22:26])[0], 'color': struct.unpack('<H', data[28:30])[0] } return print('not BMP') # 测试 bi = bmp_info(bmp_data) assert bi['width'] == 28 assert bi['height'] == 10 assert bi['color'] == 16 print('ok') ''' ''' #hashlib模块md5验证用户登录的函数 # -*- coding: utf-8 -*- import hashlib db = { 'michael': 'e10adc3949ba59abbe56e057f20f883e', 'bob': '878ef96e86145580c38c87f0410ad153', 'alice': '99b1c2188db85afee403b1536010c2c9' } def login(user, password): md5=hashlib.md5() md5.update(password.encode('utf-8')) password=md5.hexdigest() if user in db: if db[user]==password: return True else: return False else: print('用户不存在') # 测试: assert login('michael', '123456') assert login('bobb', 'abc999') assert login('alice', 'alice2008') assert not login('michael', '1234567') assert not login('bob', '123456') assert not login('alice', 'Alice2008') print('ok') ''' ''' #hashlib模块加盐md5验证用户登录的函数 # -*- coding: utf-8 -*- import hashlib, random def get_md5(s): return hashlib.md5(s.encode('utf-8')).hexdigest() class User(object): def __init__(self, username, password): self.username = username self.salt = ''.join([chr(random.randint(48, 122)) for i in range(20)]) self.password = get_md5(password + self.salt) db = { 'michael': User('michael', '123456'), 'bob': User('bob', 'abc999'), 'alice': User('alice', 'alice2008') } def login(username, password): user = db[username] if user.password == get_md5(password+user.salt): return True else: return False # 测试: assert login('michael', '123456') assert login('bob', 'abc999') assert login('alice', 'alice2008') assert not login('michael', '1234567') assert not login('bob', '123456') assert not login('alice', 'Alice2008') print('ok') ''' ''' #hmac算法验证用户登录 # -*- coding: utf-8 -*- import hmac, random def hmac_md5(key, s): return hmac.new(key.encode('utf-8'), s.encode('utf-8'), digestmod='MD5').hexdigest() class User(object): def __init__(self, username, password): self.username = username self.key = ''.join([chr(random.randint(48, 122)) for i in range(20)]) self.password = hmac_md5(self.key, password) db = { 'michael': User('michael', '123456'), 'bob': User('bob', 'abc999'), 'alice': User('alice', 'alice2008') } def login(username, password): user = db[username] return user.password == hmac_md5(user.key, password) # 测试: assert login('michael', '123456') assert login('bob', 'abc999') assert login('alice', 'alice2008') assert not login('michael', '1234567') assert not login('bob', '123456') assert not login('alice', 'Alice2008') print('ok') ''' ''' #itertools模块计算圆周率序列公式的前N项和 # -*- coding: utf-8 -*- import itertools def pi(N): ' 计算pi的值 ' # step 1: 创建一个奇数序列: 1, 3, 5, 7, 9, ... odd=itertools.count(1,2) # step 2: 取该序列的前N项: 1, 3, 5, 7, 9, ..., 2*N-1. odd_n=itertools.takewhile(lambda a:a<=2*N-1,odd) # step 3: 添加正负符号并用4除: 4/1, -4/3, 4/5, -4/7, 4/9, ... sum=0 for x in odd_n: sum+=4/x*(-1)**(x//2) # step 4: 求和: return sum # 测试: print(pi(10)) print(pi(100)) print(pi(1000)) print(pi(10000)) assert 3.04 < pi(10) < 3.05 assert 3.13 < pi(100) < 3.14 assert 3.140 < pi(1000) < 3.141 assert 3.1414 < pi(10000) < 3.1415 print('ok') ''' ''' #利用urllib读取JSON,将JSON解析为Python对象 # -*- coding: utf-8 -*- from urllib import request import json def fetch_data(url): with request.urlopen(url) as f: data=f.read() return json.loads(data) # 测试 URL = 'https://www.easy-mock.com/mock/5cbec5d8bfb3b05625e96633/dreamlf/urllibTest' data = fetch_data(URL) print(data) assert data['query']['results']['channel']['location']['city'] == 'Beijing' print('ok') ''' ''' #sqlite操作 # -*- coding: utf-8 -*- import os import sqlite3 db_file = os.path.join(os.path.dirname(__file__), 'test.db') if os.path.isfile(db_file): os.remove(db_file) # 初始数据: conn = sqlite3.connect(db_file) cursor = conn.cursor() cursor.execute('create table user(id varchar(20) primary key, name varchar(20), score int)') cursor.execute(r"insert into user values ('A-001', 'Adam', 95)") cursor.execute(r"insert into user values ('A-002', 'Bart', 62)") cursor.execute(r"insert into user values ('A-003', 'Lisa', 78)") cursor.close() conn.commit() conn.close() def get_score_in(low, high): conn = sqlite3.connect(db_file) cursor = conn.cursor() #执行查询语句并且排序 cursor.execute('select * from user where score between ? and ? order by score',(low,high)) values = cursor.fetchall() cursor.close() conn.close() return [value[1] for value in values] # 测试: assert get_score_in(80, 95) == ['Adam'], get_score_in(80, 95) assert get_score_in(60, 80) == ['Bart', 'Lisa'], get_score_in(60, 80) assert get_score_in(60, 100) == ['Bart', 'Lisa', 'Adam'], get_score_in(60, 100) print('Pass') ''' #mysql数据库示例 # -*- coding: utf-8 -*- import mysql.connector import logging usr=input('请输入用户名:') pwd=input('请输入密码:') conn=mysql.connector.connect(host='144.34.158.32',user=usr,password=pwd,database='test') cursor=conn.cursor() #创建user表 try: cursor.execute('create table user (id varchar(20) primary key,name varchar(20))') except Exception as e: print('表已存在') #插入数据 try: cursor.execute('insert into user(id,name)values(%s,%s)',['1','Michael']) except Exception as e: print('id已存在') if cursor.rowcount > 0: print('*********') print('%s行被插入'% (cursor.rowcoun)) print('*********') else: print('没有数据改变') #提交事务 conn.commit() cursor.close() #执行查询 cursor=conn.cursor() cursor.execute('select * from user where id = %s',('1',)) values=cursor.fetchall() print(values) #关闭cursor和数据库连接 cursor.close() conn.close()
2f544a0f0928ce4faef6169ede372c7c4b595b81
Eric-programming/PythonTutorial
/PyBasics/5_collections.py
865
3.875
4
from collections import Counter, OrderedDict, deque # Counter (Count items) my_str = "abcabca" my_counter = Counter(my_str) # {a:3, b:2, c:2} => (dict) most_common_item = my_counter.most_common(1) # (a,3) my_list = [1, 1, 2, 2, 3, 1] my_counter = Counter(my_list) # {1:3, 2:2, 3:1} => (dict) most_common_item = my_counter.most_common(1) # (1,3) # OrderedDict (Know the order of insertion) ordered_dict = OrderedDict() ordered_dict[3] = 1 ordered_dict[2] = 1 ordered_dict[1] = 1 print(ordered_dict) # option 2: dict.popitem() pop the last item that was inserted my_ordered_list = list(ordered_dict.items()) # Deque my_deque = deque([1, 2]) my_deque.append(3) # append right O(1) my_deque.appendleft(0) # append left O(1) my_deque.popleft() # pop first item O(1) my_deque.pop() # pop last item O(1) my_deque.extend([3, 4]) my_deque.extendleft([-1, 0])
629b704f64a414c81083b252fde1b5d79b707764
iamharshverma/APIMicroServiceForWordDocFrequencyCount
/WordsCountCLIVersion.py
4,930
3.578125
4
import os import WordTokanizer import sys # Declaring global dict to be used in program # docToWordsCount : This will store key as docID and value as map of word with frequency # docID_to_absolute_filepath_dict : This stores key as docID i.e filename and value as full absolute path of file, # just in case if we want to display full file name with path(Its a extra feature which can be handled via api call parameter is_full_filepath_needed) # super_words_dict : Dict containing all words with frequencies across all files doc_to_words_count = {} docID_to_absolute_filepath_dict = {} super_words_dict = {} docId_wordCount_map = {} ## Function to process and tokanize each work in given sub filepath def process_file(subfilePath, docId): tokanized_words = WordTokanizer.tokenize(subfilePath) mapWords = WordTokanizer.map_word_count(tokanized_words) doc_to_words_count[docId] = mapWords return doc_to_words_count # Function to print word count from various document id and their frequency in each doc def print_wordDocID_with_count(word, word_from_docIDs_count, is_full_document_path_needed): if (is_full_document_path_needed): tmp_docpath_frequency_dict = {} for key, value in word_from_docIDs_count.items(): key = docID_to_absolute_filepath_dict.get(key) tmp_docpath_frequency_dict[key] = value print('Word: [' + word + '] occurs in full document Path with frequency: ' + str(tmp_docpath_frequency_dict)) print("\n") else: print('Word: [' + word + '] occurs in document IDs with frequency: ' + str(word_from_docIDs_count)) # Helper Function to print total word count of a given word across all files def print_totalCount_for_word(word, total_count): print('Total Count for Word: [' + word + '] is: ' + str(total_count)) # Handles Bonus Conditions which was asked in question # Helper function to provide given list of words as input details , I.e 1. whats the total count of that word across all files, 2. Whats the count with respect to each files with documnet id def word_details(list_of_selected_words): for word in list_of_selected_words: word_from_docIDs_count = {} total_count = super_words_dict.get(word) print_totalCount_for_word(word, total_count) for docID, valueCountMap in docId_wordCount_map.items(): if (valueCountMap.get(word) is not None): count = valueCountMap.get(word) word_from_docIDs_count[docID] = count print_wordDocID_with_count(word, word_from_docIDs_count, False) print_wordDocID_with_count(word, word_from_docIDs_count, True) return word_from_docIDs_count ## Main Program execution start here try: main_file_path = sys.argv[1] except: dir = os.path.dirname(__file__) main_file_path = os.path.join(dir, 'data' ,'maindata.txt') # Main Code to Start Program execution and read main data file mainFile = open(main_file_path, "r") for aline in mainFile: aline = aline.strip(); filePathSplit = os.path.normpath(aline) fileSplitArray = filePathSplit.split(os.sep) docId = fileSplitArray[-1] docID_to_absolute_filepath_dict[docId] = aline docId_wordCount_map = process_file(aline, docId) # Loop to store Map i.e key as doc id with respect to word-count Map as value for k, v in docId_wordCount_map.items(): wordCountMap = v for wordKey, count in wordCountMap.items(): if super_words_dict.get(wordKey) is None: super_words_dict[wordKey] = count else: curr_count = super_words_dict.get(wordKey) curr_count = curr_count + count super_words_dict[wordKey] = curr_count # Creating a super dic of words with overall frequency and displaying it print("\n") print("Displaying Super words Dict with frequencies:") print("\n") print(super_words_dict) print("\n") mainFile.close() # list_of_selected_words : This stores the input word list for that the detailed information needs to be traced list_of_selected_words = list() try: var = input("Provide the input list of words for which detail is required, if only one word then enter input_word else for multiple inputs enter comma separated words") print("\n") input_var = str(var) print("\n") print("You entered " + input_var) if(',' in input_var): input_words = input_var.split(",") for word in input_words: list_of_selected_words.append(word) else: list_of_selected_words.append(input_var) word_details(list_of_selected_words) except: raise Exception("Provide the input list of words for which detail is required in given format: if only one word then enter input_word else for multiple inputs enter comma separated words") # Sample example for word : program and the as input to get their total count and document , frequency count # Function call to process list of input
65b8c519bd6b9516f6766811b034d63404c781bb
iamanobject/Lv-568.2.PythonCore
/HW_6/Andriana_Khariv/Home_Work6_Task_3.py
208
4.21875
4
list_att = input('enter anything: ') def number_of_characters(): for i in list_att: print("Character", i, "included", list_att.count(i), "in a given string", list_att) number_of_characters()
e8e610c321d86bb4c5fffc69eb2271115858fb63
AleByron/AleByron-The-Python-Workbook-second-edition
/chap-5/ex111.py
213
3.703125
4
n = int(input('Enter an integer:')) na = [] na.append(n) for i in na: n = int(input('Enter another integer:')) if n == 0: break na.append(n) na.reverse() for i in na: print(i)
d57162eb524e1f36dad8cb6f67a2a4d88e15f30e
GanSabhahitDataLab/PythonPractice
/python Statement.py
1,940
4.375
4
#!/usr/bin/env python # coding: utf-8 # In[10]: # create a Statement that will print out words that start with 's': st = 'Print only the words that start with s in this sentence' print(st) for elm in st.split() : if elm[0] == 's': print(elm) # In[13]: # print all the even numbers from 0 to 10 for num in range(0,10): if num%2 == 0: print(num) # In[20]: #create a list of all numbers between 1 and 50 that are divisible by 3 myDiv3List = [] for num in range(1,50): if num%3 == 0: myDiv3List.append(num) print(num) # In[25]: #Go through the string below and if the length of a word is even print "even!" st = 'Print every word in this sentence that has an even number of letters' for elem in st.split(): if (len(elem) % 2 == 0): print("Word {0} has even length".format(elem)) else: print("Word {0} has Odd length".format(elem)) # In[30]: # Write a program that prints the integers from 1 to 100. # But for multiples of three print "Fizz" instead of the number, and for the multiples of five print "Buzz". # For numbers which are multiples of both three and five print "FizzBuzz". for elem in range(1,100): if elem % 5 == 0 and elem % 3 == 0: print("Element {0} belongs to FizzBuzz".format(elem)) elif elem % 3 == 0: print("Element {0} belongs to Fizz".format(elem)) elif elem % 5 == 0: print("Element {0} belongs to Buzz".format(elem)) # In[36]: #Create a list of the first letters of every word in the string below st = 'Create a list of the first letters of every word in this string' firstLetterList = [] for elem in st.split(): firstLetterList.append(elem[0]) print(len(firstLetterList)) # In[ ]: print(bin(10)) round(2.345) # Count no of s in string st = "saasahsassdfdf" print(st.count("s")) # Difference of sets s1 = {1,2,3} s2 = {1,2,5} s1.difference(s2)
93e07a3ce41ad717ecfd2785d1f71ae7eaf1cfe3
yangzongwu/leetcode
/archives/leetcode/0005. Longest Palindromic Substring.py
2,032
4.03125
4
''' Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000. Example 1: Input: "babad" Output: "bab" Note: "aba" is also a valid answer. Example 2: Input: "cbbd" Output: "bb" ''' #####################Memory Limit Exceeded #####################Time Limit Exceeded def longestPalindrome(self, s): """ :type s: str :rtype: str """ if not s: return '' max_len=0 rep='' for k in range(len(s)): k_len=self.preLongestPalindrome(s[k:])[0] k_rep=self.preLongestPalindrome(s[k:])[1] if k_len>max_len: max_len=k_len rep=k_rep return rep def preLongestPalindrome(self,s): for k in range(len(s),-1,-1): if s[:k]==s[:k][::-1]: return [k,s[:k]] #################################### class Solution: def longestPalindrome(self, s): """ :type s: str :rtype: str """ if not s: return '' max_len = 0 rep = '' for k in range(len(s)): k_rep = self.preLongestPalindrome(s, k) if len(k_rep) > max_len: max_len = len(k_rep) rep = k_rep return rep def preLongestPalindrome(self, s, k): gap = 0 rep=s[k] rep1,rep2='','' while k - gap >= 0 and k + gap < len(s): if s[k - gap] == s[k + gap]: rep1 = s[k - gap:k + gap + 1] gap += 1 else: break if k + 1 < len(s) and s[k] == s[k + 1]: gap = 0 while k - gap >= 0 and k + 1 + gap < len(s): if s[k - gap] == s[k + 1 + gap]: rep2 = s[k - gap:k + 1 + gap + 1] gap += 1 else: break if len(rep2) > len(rep1): return rep2 else: return rep1
18c2b3d1e330b9174aa2771ca085f1c3f25008a5
swatia-code/data_structure_and_algorithm
/trees/transform_to_sum_tree.py
4,388
4.09375
4
''' PROBLEM STATEMENT ----------------- Given a Binary Tree of size N , where each node has positive and negative values. Convert this to a tree where each node contains the sum of the left and right sub trees in the original tree. The values of leaf nodes are changed to 0. For example, the following tree 10 / \ -2 6 / \ / \ 8 -4 7 5 should be changed to 20(4-2+12+6) / \ 4(8-4) 12(7+5) / \ / \ 0 0 0 0 Input: First line of input contains the number of test cases T. For each test case, there will be only a single line of input which is a string representing the tree as described below: The values in the string are in the order of level order traversal of the tree where, numbers denotes node values, and a character “N” denotes NULL child. For example: For the above tree, the string will be: 1 2 3 N N 4 6 N 5 N N 7 N Output: Inorder traversal of modified tree , printed by driver code. Your Task: You don't need to take input. Just complete the function toSumTree() which accepts root node of the tree as a parameter and modify tree into SumTree. Expected Time Complexity: O(N). Expected Auxiliary Space: O(Height of the Tree). Constraints: 1 <=T<= 100 1 <= N <= 104 Example: Input: 2 3 1 2 10 20 30 40 60 Output: 0 3 0 0 100 0 150 0 LOGIC ----- Do a traversal of the given tree. In the traversal, store the old value of the current node, recursively call for left and right subtrees and change the value of current node as sum of the values returned by the recursive calls. Finally return the sum of new value and value (which is sum of values in the subtree rooted with this node). SOURCE ------ geeksforgeeks CODE ---- ''' ''' # Node Class: class Node: def __init__(self,val): self.data = val self.left = None self.right = None ''' def toSumTree(root) : ''' :param root: root of the given tree. ''' #code here if root == None: return 0 val = root.data root.data = toSumTree(root.left) + toSumTree(root.right) return root.data + val #{ # Driver Code Starts #Initial Template for Python 3 from collections import deque # Tree Node class Node: def __init__(self, val): self.right = None self.data = val self.left = None # Function to Build Tree def buildTree(s): #Corner Case if(len(s)==0 or s[0]=="N"): return None # Creating list of strings from input # string after spliting by space ip=list(map(str,s.split())) # Create the root of the tree root=Node(int(ip[0])) size=0 q=deque() # Push the root to the queue q.append(root) size=size+1 # Starting from the second element i=1 while(size>0 and i<len(ip)): # Get and remove the front of the queue currNode=q[0] q.popleft() size=size-1 # Get the current node's value from the string currVal=ip[i] # If the left child is not null if(currVal!="N"): # Create the left child for the current node currNode.left=Node(int(currVal)) # Push it to the queue q.append(currNode.left) size=size+1 # For the right child i=i+1 if(i>=len(ip)): break currVal=ip[i] # If the right child is not null if(currVal!="N"): # Create the right child for the current node currNode.right=Node(int(currVal)) # Push it to the queue q.append(currNode.right) size=size+1 i=i+1 return root # A utility function to print # inorder traversal of a Binary Tree def printInorder(Node) : if (Node == None) : return printInorder(Node.left) print(Node.data, end = " ") printInorder(Node.right) if __name__=="__main__": t=int(input()) for _ in range(0,t): s=input() root=buildTree(s) toSumTree(root) printInorder(root) print() # } Driver Code Ends
43ad426b59053a8a545cbf6c394517e806797075
dpk3d/HackerRank
/EqualSignalLevel.py
1,652
4.125
4
""" Two signals are generated as part of a simulation. A program monitors the signal. Whenever two signals become equal, then frequency is noted. A record is maintained for maximum simultaneous frequency seen so far. Each time a higher simultaneous frequency is noted this variable maxequal is updated to higher frequency. Note: Both signals start at t=0 , but their duration might be different. In this case the comparision of equality is performed only until the end of shorter signal. If both signals has equal frequency at given time, but the frequency is less than or equal to the current maximum frequency, maxequal is not updated The Running time of both signals are given, denoted by n and m respectively. During the course of simulation how many times is the maxequal variable is updated. Complete the updated times function. """ def updatedTimes(signalOne, signalTwo): updates = 0 maxFrequency = 0 lengthSingal1 = len(signalOne) lengthSingal2 = len(signalTwo) frequencyTaken = min(lengthSingal1, lengthSingal2) - 1 if frequencyTaken > 0: newSignal1 = signalOne[:frequencyTaken] newSignal2 = signalTwo[:frequencyTaken] for one, two in zip(newSignal1, newSignal2): if one == two: if maxFrequency < one: updates = updates + 1 maxFrequency = one return updates else: return 0 signal1 = [1, 2, 3, 3, 3, 5, 4] signal2 = [1, 2, 3, 4, 3, 5, 4] print("Number of times maxequal variable updates is :", updatedTimes(signal1, signal2)) # Number of times maxequal variable updates is : 4
de43274dd497a3017b6fe11683a78495b1dd2de3
rosiehoyem/dsp
/python/advanced_python_dict.py
3,118
3.96875
4
import sys import csv import operator import itertools as it ### Part III - Dictionary ####Q6. Create a dictionary in the below format: ''' faculty_dict = { 'Ellenberg': [['Ph.D.', 'Professor', 'sellenbe@upenn.edu'], ['Ph.D.', 'Professor', 'jellenbe@mail.med.upenn.edu']], 'Li': [['Ph.D.', 'Assistant Professor', 'liy3@email.chop.edu'], ['Ph.D.', 'Associate Professor', 'mingyao@mail.med.upenn.edu'], ['Ph.D.', 'Professor', 'hongzhe@upenn.edu']]} Print the first 3 key and value pairs of the dictionary: ''' def take(n, iterable): #Return first n items of the iterable as a list return list(it.islice(iterable, n)) def dict_sample(dictionary): sample = take(3, dictionary) dictionary_sample = {} for item in sample: dictionary_sample[item] = dictionary[item] return dictionary_sample def create_lastname_dict(csv_file): with open(csv_file) as csvfile: reader = csv.DictReader(csvfile, skipinitialspace=True) fdict = {} for row in reader: last_name = row['name'].split()[-1] if last_name in fdict: fdict[last_name].append([row['degree'], row['title'], row['email']]) else: fdict[last_name] = [] fdict[last_name].append([row['degree'], row['title'], row['email']]) return dict_sample(fdict) ####Q7. The previous dictionary does not have the best design for keys. Create a new dictionary with keys as: ''' professor_dict = {('Susan', 'Ellenberg'): ['Ph.D.', 'Professor', 'sellenbe@upenn.edu'], ('Jonas', 'Ellenberg'): ['Ph.D.', 'Professor', 'jellenbe@mail.med.upenn.edu'], ('Yimei', 'Li'): ['Ph.D.', 'Assistant Professor', 'liy3@email.chop.edu'], ('Mingyao','Li'): ['Ph.D.', 'Associate Professor', 'mingyao@mail.med.upenn.edu'], ('Hongzhe','Li'): ['Ph.D.', 'Professor', 'hongzhe@upenn.edu'] } Print the first 3 key and value pairs of the dictionary: ''' def create_fullname_dict(csv_file): with open(csv_file) as csvfile: reader = csv.DictReader(csvfile, skipinitialspace=True) fdict = {} for row in reader: first_name = row['name'].split()[0] last_name = row['name'].split()[-1] name_key = (last_name, first_name) fdict[name_key] = [] fdict[name_key].append(row['degree']) fdict[name_key].append(row['title']) fdict[name_key].append(row['email']) return dict_sample(fdict) ''' ####Q8. It looks like the current dictionary is printing by first name. Print out the dictionary key value pairs based on alphabetical orders of the last name of the professors ''' def create_sorted_fullname_dict(csv_file): with open(csv_file) as csvfile: reader = csv.DictReader(csvfile, skipinitialspace=True) fdict = {} for row in reader: first_name = row['name'].split()[0] last_name = row['name'].split()[-1] name_key = (last_name, first_name) fdict[name_key] = [] fdict[name_key].append(row['degree']) fdict[name_key].append(row['title']) fdict[name_key].append(row['email']) for item in sorted(fdict, key=operator.itemgetter(0)): print(item) def main(): arg = sys.argv[1] if not arg: print('ERROR: include csv file as argument') sys.exit(1) print(create_lastname_dict(arg)) print("---------------") print(create_fullname_dict(arg)) print("---------------") create_sorted_fullname_dict(arg) if __name__ == '__main__': main()
7a3ce124d254f451bec498aa8c399bf9b1177b39
piketan/pike-s-python
/Python/ex29/ex29.py
421
3.875
4
people = 20 cats = 30 dogs = 15 if people < cats : print("猫太多了世界注定要灭亡") if people > cats : print("没那么多猫这个世界安全了") if people < dogs : print("全世界都垂涎三尺") if people > dogs: print("世界都变干燥了") dogs += 5 if people >= dogs : print("123") if people <= dogs : print("1231212") if people == dogs : print("feerfsefesf")
446750c547062583a671e48711a68bc29ebf82b1
flame4ost/Python-projects
/additional tasks x classes/class Transport.py
2,573
3.609375
4
from __future__ import unicode_literals class Vehicle(object): def __init__(self, speed, max_speed): self.speed = speed self.max_speed = max_speed print('Было создано транспортное средство') def accelerate(self,x): self.speed = self.speed + x if self.speed > self.max_speed: self.speed = self.max_speed def brake(self,x): self.speed = self.speed - x if self.speed < 0: self.speed = 0 def print_status(self): print('Скорость транспортного средства равна {0} км/ч'.format( self.speed)) class Motorcycle(Vehicle): def __init__(self, speed, max_speed): Vehicle.__init__(self, speed, max_speed) # Дополнительные поля self._front_tire_width = 95 self._rear_tire_width = 95 def set_tires_width(self, front, rear): self._front_tire_width = front self._rear_tire_width = rear print('На мотоцикл были установлены новые шины') def print_tire_info(self): print('Ширина передней шины {0} мм'.format(self._front_tire_width)) print('Ширина задней шины {0} мм'.format(self._rear_tire_width)) class Automobile(Vehicle): def __init__(self, speed, max_speed): Vehicle.__init__(self, speed, max_speed) # Дополнительные поля self._gear = 0 self._color = 'синий' def set_gear(self, gear): self._gear = gear def print_status(self): Vehicle.print_status(self) print('Автомобиль переключен на скорость № {0}'.format(self._gear)) print('Автомобиль покрашен в {0} цвет'.format(self._color)) def set_color(self, color): self._color = color def get_color(self): return self._color print('>>> m = Motorcycle(40, 120)') m = Motorcycle(40, 120) print('>>> m.print_status()') m.print_status() print('>>> m.set_tires_width(90, 100)') m.set_tires_width(90, 100) print('>>> m.print_tire_info()') m.print_tire_info() print('\n\n>>> a = Automobile(0, 150)') a = Automobile(0, 150) print('>>> a.accelerate(40)') a.accelerate(40) print('>>> a.set_gear(2)') a.set_gear(2) print('>>> a.print_status()') a.print_status() print(">>> a.set_color('красный')") a.set_color('красный') print('>>> color = a.get_color()') color = a.get_color() print(color)
4096dc72e06ba5465915a513397e564eb0174d8e
cdeanatx/FCC-Projects
/Scientific Computing with Python/boilerplate-budget-app/budget.py
4,417
3.796875
4
import math class Category: #initialize Class with defaults set to empty or 0. def __init__(self, name, ledger = None, credit = 0, debit = 0): if ledger is None: ledger = [] self.name = name self.ledger = ledger self.credit = credit self.debit = debit #Deposits into credit and creates an entry in ledger def deposit(self, amount, description = ""): self.ledger.append({"amount": amount, "description": description}) self.credit += amount #If credit is sufficient, adds to debit and creates a ledger entry with a negative amount def withdraw(self, amount, description = ""): if amount <= self.credit + self.debit: self.ledger.append({"amount": -amount, "description": description}) self.debit -= amount return True else: return False #Get the current balance def get_balance(self): return self.credit + self.debit #Transfers an amount to the TARGET budget category def transfer(self, amount, target): if amount <= self.credit + self.debit: self.withdraw(amount, "Transfer to " + target.name) target.deposit(amount, "Transfer from " + self.name) return True else: return False #Check if an amount is greater than current balance. Returns true or false def check_funds(self, amount): if amount <= self.credit + self.debit: return True else: return False #Create print output def __str__(self): max_len = 30 name_len = len(self.name) num_fill = int((max_len - name_len) / 2) title = "*" * num_fill + self.name + "*" * num_fill + "\n" body = "" for items in self.ledger: len_desc = len(items["description"]) len_amt = len("{:.2f}".format(items["amount"])) if len_desc > 23: trunc_desc = items["description"][0:23] body += trunc_desc + " " * (7 - len_amt) + "{:.2f}".format(items["amount"]) + "\n" else: body += items["description"] + " " * (30 - len_desc - len_amt) + "{:.2f}".format(items["amount"]) + "\n" return title + body + "Total: " + "{:.2f}".format(self.credit + self.debit) def create_spend_chart(categories): #initialize vars rows = 0 finalStr = "" name = [] spent = [] #Find % of each category for category in categories: name.append(category.name) #add category to name array net = 0 #reset net to 0 for each new category #Calculate spending for current category for item in category.ledger: if item["amount"] < 0: net += item["amount"] #Store spending for current category spent.append(net) #calculate total spent across all categories and initialize array to store percentages totalSpent = sum(spent) pCent = [] #Create array containing category spend percentages for item in spent: pCent.append(math.floor(item / totalSpent * 10) * 10) lines = [] pLines = "Percentage spent by category\n" #Create array for numeric percentages on a 10-scale for i in reversed(range(11)): num = i * 10 gLine = " " for p in pCent: if p >= num: gLine += "o " else: gLine += " " lines.append(" " * (3 - len(str(num))) + str(num) + "|" + gLine) for line in lines: pLines += line + "\n" pLines += " " * 4 + "-" * (1 + 3 * len(categories)) #determine longest category name and store in rows var for category in categories: #print("category:",category) rows = max(rows, len(category.name)) #there will be 1 column per category cols = len(categories) #initialize string array with length = rows output = ["" for i in range(rows)] #verticalize the category names for i in range(cols): for j in range(len(name[i])): #print(j,i) while i - len(output[j]) >= 1: output[j] += " " output[j] += name[i][j] #print("output:",output) for i in range(len(output)): finalStr += "\n" + " " * 5 + " ".join(output[i]) + " " #print("i =",i,"finalStr:\n"+finalStr+"|") pLines += finalStr return pLines
b7662bba5e83c6ad11be25a85e7871cc61332e38
sunnyyeti/HackerRank-Solutions
/Algorithms/Interview_Preparation_Kit/Searching/Minimum Time Required.py
2,524
4.46875
4
# You are planning production for an order. You have a number of machines that each have a fixed number of days to produce an item. Given that all the machines operate simultaneously, determine the minimum number of days to produce the required order. # For example, you have to produce items. You have three machines that take days to produce an item. The following is a schedule of items produced: # Day Production Count # 2 2 2 # 3 1 3 # 4 2 5 # 6 3 8 # 8 2 10 # It takes days to produce items using these machines. # Function Description # Complete the minimumTime function in the editor below. It should return an integer representing the minimum number of days required to complete the order. # minimumTime has the following parameter(s): # machines: an array of integers representing days to produce one item per machine # goal: an integer, the number of items required to complete the order # Input Format # The first line consist of two integers and , the size of and the target production. # The next line contains space-separated integers, . # Constraints # Output Format # Return the minimum time required to produce items considering all machines work simultaneously. # Sample Input 0 # 2 5 # 2 3 # Sample Output 0 # 6 # Explanation 0 # In days can produce items and can produce items. This totals up to . # Sample Input 1 # 3 10 # 1 3 4 # Sample Output 1 # 7 # Explanation 1 # In minutes, can produce items, can produce items and can produce item, which totals up to . # Sample Input 2 # 3 12 # 4 5 6 # Sample Output 2 # 20 # Explanation 2 # In days can produce items, can produce , and can produce . #!/bin/python3 import math import os import random import re import sys from collections import Counter # Complete the minTime function below. def minTime(machines, goal): def issuccess(days): return sum(days//m*c for m, c in mac_cnt.items()) >= goal mac_cnt = Counter(machines) up = min(machines)*goal low = 0 while low < up: mid = (low+up)//2 if issuccess(mid): up = mid else: low = mid+1 return up if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') nGoal = input().split() n = int(nGoal[0]) goal = int(nGoal[1]) machines = list(map(int, input().rstrip().split())) ans = minTime(machines, goal) fptr.write(str(ans) + '\n') fptr.close()
d54c73b58e613723a9e8ea78d54c65b85bddc411
rupathouti/SimplePrograms
/fileopen2.py
97
3.53125
4
myfile=open("test.txt","r") for data in myfile.readlines(): print("test.txt contains->", data)
e709bc719728e496dbaae2d165fbce2187428d71
chengjingjing1992/pyone
/test39.py
535
4.125
4
#coding=utf-8 # 给写成这样 string', 'a', 'is', 'it' # str=" it is a string " # list=str.split() # list1=[] # for i in range(1,len(list)+1): # list1.append(list[-i]) # # print(list1) # 对给定的字符串去空格处理 # str="it is a string " # # print(str.replace(" ","")) # 使用一个空字符串合成列表内容生成新的字符串 # str=" def xyz abc !! " # list=str.split() # print(list) # strnew="0" # str3=strnew.join(list) # print(str3) # # print("".join(str.split()))
3dafc00fcdec5f35f5b2faf7172bf7dbd784ead9
MelvinPeepers/Sprint-Challenge--Algorithms
/robot_sort/robot_sort.py
10,573
4.5625
5
""" #### 4. Understand, plan, & implement the Robot Sort algorithm _(6 points)_ You have been given a robot with very basic capabilities: - It can move left or right. - It can pick up an item - If it tries to pick up an item while already holding one, it will swap the items instead. - It can compare the item it's holding to the item in front of it. - It can switch a light on its head on or off. Your task is to program this robot to sort lists using ONLY these abilities. ##### Rules Inside the `robot_sort` directory you'll find the `robot_sort.py` file. Open it up and read through each of the robot's abilities. Once you've understood those, start filling out the `sort()` method following these rules: - You may use any pre-defined robot methods. - You may NOT modify any pre-defined robot methods. - You may use logical operators. (`if`, `and`, `or`, `not`, etc.) - You may use comparison operators. (`>`, `>=`, `<`, `<=`, `==`, `is`, etc.) - You may use iterators. (`while`, `for`, `break`, `continue`) - You may NOT store any variables. (`=`) - You may NOT access any instance variables directly. (`self._anything`) - You may NOT use any Python libraries or class methods. (`sorted()`, etc.) - You may define robot helper methods, as long as they follow all the rules. ##### Hints - Make sure you understand the problem and all of the rules! A solution that breaks the rules will not receive full credit. - If you're unsure if an operator or method is allowed, ask. - Lay out some numbered cards in a line and try sorting them as if you were the robot. - Come up with a plan and write out your algorithm before coding. If your plan is sound but you don't reach a working implementation in three hours, you may receive partial credit. - There is no efficiency requirement but you may lose points for an unreasonably slow solution. Tests should run in far less than 1 second. - We discussed a sorting method this week that might be useful. Which one? - The robot has exactly one bit of memory: its light. Why is this important? Run `python test_robot.py` to run the tests for your `robot_sort()` function to ensure that your implementation is correct. """ """ Plan: Turn on Robot Starting sorting from the left to right (starting at the index 0 moving right!) will need to swap item start at second item, compare (first 2 items) current item to the next item compare if held item is greater or less, if greater move to the right (or keep in current location) of the less card then move on to the next two items if any swaps ar made, robot will need to go through the items again running out of time (sigh) Last step will be to turn off Robot when everything is sorted """ # additional info, using selection sort class SortingRobot: def __init__(self, l): """ SortingRobot takes a list and sorts it. """ self._list = l # The list the robot is tasked with sorting self._item = None # The item the robot is holding self._position = 0 # The list position the robot is at self._light = "OFF" # The state of the robot's light self._time = 0 # A time counter (stretch) # Can Robot move right? def can_move_right(self): """ Returns True if the robot can move right or False if it's at the end of the list. """ return self._position < len(self._list) - 1 # Can Robot move left? def can_move_left(self): """ Returns True if the robot can move left or False if it's at the start of the list. """ return self._position > 0 # then move right def move_right(self): """ If the robot can move to the right, it moves to the right and returns True. Otherwise, it stays in place and returns False. This will increment the time counter by 1. """ self._time += 1 if self._position < len(self._list) - 1: self._position += 1 return True else: return False # then move left def move_left(self): """ If the robot can move to the left, it moves to the left and returns True. Otherwise, it stays in place and returns False. This will increment the time counter by 1. """ self._time += 1 if self._position > 0: self._position -= 1 return True else: return False def swap_item(self): """ The robot swaps its currently held item with the list item in front of it. This will increment the time counter by 1. """ self._time += 1 # Swap the held item with the list item at the robot's position self._item, self._list[self._position] = self._list[self._position], self._item def compare_item(self): """ Compare the held item with the item in front of the robot: If the held item's value is greater, return 1. If the held item's value is less, return -1. If the held item's value is equal, return 0. If either item is None, return None. """ if self._item is None or self._list[self._position] is None: return None elif self._item > self._list[self._position]: return 1 elif self._item < self._list[self._position]: return -1 else: return 0 # Step 1 we need to enable the Robot def set_light_on(self): """ Turn on the robot's light """ self._light = "ON" # Step x when done, turn off Robot - Save energy def set_light_off(self): """ Turn off the robot's light """ self._light = "OFF" # Step 2 if Robot is On: 'Number 5 is ALIVE!' def light_is_on(self): """ Returns True if the robot's light is on and False otherwise. """ return self._light == "ON" def sort(self): """ Sort the robot's list. """ # Fill this out while not self.light_is_on(): # when the light isn't on turn on self.set_light_on() # enable robot Turn on the robot's light # print("Number 5 is ALIVE!") while self.can_move_right(): # print('Move to the right') self.swap_item() # picks up card at index 0 self.move_right() # move to the next card if self.compare_item() == 1: # checks to see if the card is higher then the one being looked at by the robot. If the card is smaller, go to 'else:' # The robot swaps its currently held item with the list item in front of it. This will increment the time counter by 1. self.swap_item() # If the robot can move to the left, it moves to the left and returns True. Otherwise, it stays in place and returns False. This will increment the time counter by 1. self.move_left() # The robot swaps its currently held item with the list item in front of it. self.swap_item() else: # If the robot can move to the left, it moves to the left and returns True. Otherwise, it stays in place and returns False. This will increment the time counter by 1. self.move_left() # The robot swaps its currently held item with the list item in front of it. self.swap_item() # If the robot can move to the right, it moves to the right and returns True. Otherwise, it stays in place and returns False. This will increment the time counter by 1. if card is lower, it's placed down in the original spot. if bigger, the cards are changed self.move_right() # Returns True if the robot can move left or False if it's at the start of the list. while self.can_move_left(): # print('Move to the left') # The robot swaps its currently held item with the list item in front of it. self.swap_item() # If the robot can move to the left, it moves to the left and returns True. Otherwise, it stays in place and returns False. This will increment the time counter by 1. self.move_left() if self.compare_item() == -1: # checks to see if the card is smaller then the one being looked at by the robot self.set_light_off() # Turn off the robot's light # The robot swaps its currently held item with the list item in front of it. self.swap_item() # If the robot can move to the right, it moves to the right and returns True. Otherwise, it stays in place and returns False. This will increment the time counter by 1. self.move_right() # The robot swaps its currently held item with the list item in front of it. self.swap_item() else: # If the robot can move to the right, it moves to the right and returns True. Otherwise, it stays in place and returns False. This will increment the time counter by 1. self.move_right() # The robot swaps its currently held item with the list item in front of it. self.swap_item() # If the robot can move to the left, it moves to the left and returns True. Otherwise, it stays in place and returns False. This will increment the time counter by 1. self.move_left() if __name__ == "__main__": # Test our your implementation from the command line # with `python robot_sort.py` l = [15, 41, 58, 49, 26, 4, 28, 8, 61, 60, 65, 21, 78, 14, 35, 90, 54, 5, 0, 87, 82, 96, 43, 92, 62, 97, 69, 94, 99, 93, 76, 47, 2, 88, 51, 40, 95, 6, 23, 81, 30, 19, 25, 91, 18, 68, 71, 9, 66, 1, 45, 33, 3, 72, 16, 85, 27, 59, 64, 39, 32, 24, 38, 84, 44, 80, 11, 73, 42, 20, 10, 29, 22, 98, 17, 48, 52, 67, 53, 74, 77, 37, 63, 31, 7, 75, 36, 89, 70, 34, 79, 83, 13, 57, 86, 12, 56, 50, 55, 46] t = [9, 11, 7, 17, 29] # my test 7, 9, 11, 17, 29 p = [5, 4, 3, 2, 1] # my test 1, 2, 3, 4, 5 # my test 1, 4, 9, 13, 22, 23, 50, 100, 111 m = [100, 1, 4, 9, 111, 50, 23, 22, 13] z = [0] x = [] robot = SortingRobot(t) # all my little test pass robot.sort() print(robot._list)
464e11cf9934c5254fe1e56f11c50837d7ba47c7
DaehanHong/Algorithmic-Thinking-Part-2-
/Algorithmic Thinking (Part 2)/Week 6/project3.py
6,366
3.96875
4
""" Student template code for Project 3 Student will implement five functions: slow_closest_pair(cluster_list) fast_closest_pair(cluster_list) closest_pair_strip(cluster_list, horiz_center, half_width) hierarchical_clustering(cluster_list, num_clusters) kmeans_clustering(cluster_list, num_clusters, num_iterations) where cluster_list is a 2D list of clusters in the plane """ import alg_cluster def slow_closest_pair(cluster_list): """ from a list of nodes, return distance of the closest pair :param cluster_list: list of nodes :return: tuple(dist, idx1, idx2), idx1<idx2, dist is the distance between the closest pair """ nodelist = list(cluster_list) closest = [float("inf"), -1, -1] for idx1 in range(len(nodelist)): for idx2 in range(len(nodelist)): if idx1 != idx2: dist = nodelist[idx1].distance(nodelist[idx2]) if dist < closest[0]: closest[0] = dist closest[1] = min(idx1, idx2) closest[2] = max(idx1, idx2) return tuple(closest) def fast_closest_pair(cluster_list): """ Compute the distance between the closest pair of clusters in a list (fast) Input: cluster_list is list of clusters SORTED such that horizontal positions of their centers are in ascending order Output: tuple of the form (dist, idx1, idx2) where the centers of the clusters cluster_list[idx1] and cluster_list[idx2] have minimum distance dist. """ nodelist = list(cluster_list) if len(nodelist) <= 3: return slow_closest_pair(nodelist) half = len(nodelist)/2 left = nodelist[0:half] right = nodelist[half:] left_close = fast_closest_pair(left) right_close = fast_closest_pair(right) #re-index right_close right_close = (right_close[0], right_close[1] + half, right_close[2] + half) if left_close[0] < right_close[0]: closest = left_close else: closest = right_close mid = 0.5 * (nodelist[half].horiz_center()+nodelist[half - 1].horiz_center()) pair_strip = closest_pair_strip(cluster_list, mid, closest[0]) if pair_strip[0] < closest[0]: closest = pair_strip return closest def closest_pair_strip(cluster_list, horiz_center, half_width): """ Helper function to compute the closest pair of clusters in a vertical strip Input: cluster_list is a list of clusters produced by fast_closest_pair horiz_center is the horizontal position of the strip's vertical center line half_width is the half the width of the strip (i.e; the maximum horizontal distance that a cluster can lie from the center line) Output: tuple of the form (dist, idx1, idx2) where the centers of the clusters cluster_list[idx1] and cluster_list[idx2] lie in the strip and have minimum distance dist. """ closest = [float("inf"), -1, -1] nodelist = list(cluster_list) s_set = [] for each in nodelist: if abs(each.horiz_center() - horiz_center) < half_width: s_set.append(each) s_set.sort(key = lambda cluster: cluster.vert_center()) if len(nodelist): for idx1 in range(0, len(s_set) - 1): for idx2 in range(idx1 + 1, len(s_set)): dist = s_set[idx1].distance(s_set[idx2]) if dist < closest[0]: closest[0] = dist closest[1] = min(nodelist.index(s_set[idx1]), nodelist.index(s_set[idx2])) closest[2] = max(nodelist.index(s_set[idx1]), nodelist.index(s_set[idx2])) return tuple(closest) ###################################################################### # Code for hierarchical clustering def hierarchical_clustering(cluster_list, num_clusters): """ Compute a hierarchical clustering of a set of clusters Note: the function may mutate cluster_list Input: List of clusters, integer number of clusters Output: List of clusters whose length is num_clusters """ nodelist = list(cluster_list) clusters = list(nodelist) clusters.sort(key = lambda cluster: cluster.horiz_center()) while len(clusters) > num_clusters: closest = fast_closest_pair(clusters) clusters[closest[1]].merge_clusters(clusters[closest[2]]) clusters.remove(clusters[closest[2]]) clusters.sort(key = lambda cluster: cluster.horiz_center()) return clusters ###################################################################### # Code for k-means clustering def kmeans_clustering(cluster_list, num_clusters, num_iterations): """ Compute the k-means clustering of a set of clusters Note: the function may not mutate cluster_list Input: List of clusters, integers number of clusters and number of iterations Output: List of clusters whose length is num_clusters """ nodelist = list(cluster_list) centers = [] nodelist_by_pop = list(nodelist) nodelist_by_pop.sort(key = lambda cluster: cluster.total_population(), reverse=True) # position initial clusters at the location of clusters with largest populations for idx in range(num_clusters): centers.append(alg_cluster.Cluster(set([]), nodelist_by_pop[idx].horiz_center(), nodelist_by_pop[idx].vert_center(), nodelist_by_pop[idx].total_population(), 0)) for idx in range(num_iterations): # set empty list of clusters with clusters = num_clusters results = [alg_cluster.Cluster(set([]), 0, 0, 0, 0) for _ in range(num_clusters)] for each in nodelist: shortest_dist = float("inf") center_position = 0 for center in centers: dist = each.distance(center) if dist < shortest_dist: shortest_dist = dist center_position = centers.index(center) results[center_position].merge_clusters(each) # reset centers centers = list(results) return results
bfc1ccaf6885b4068086057cf0a2d08226b19922
RodrigoPasini/PYTHON
/pythonExercícios/ex013.py
319
3.765625
4
#Exercício Python 13: Faça um algoritmo que leia o salário de um funcionário e mostre seu novo salário, com 15% de aumento. salario=float(input("Informe o salário do funcionário R$ ")) aumento=salario+(salario*(15/100)) print("O novo salário do funcionário com aumento de 15% é de R$ {:.2f}".format(aumento))
0ca90604fba217ba3ffe462a5b79ad8536cf134f
KurnakovMaks/GOST_28147_89_Magma
/gost_28147_89.py
5,860
3.703125
4
def convert_base(num, to_base=10, from_base=10): # first convert to decimal number if isinstance(num, str): n = int(num, from_base) else: n = int(num) # now convert decimal to 'to_base' base alphabet = "0123456789abcdefgABCDEFGHIJKLMNOPQRSTUVWXYZ" if n < to_base: return alphabet[n] else: return convert_base(n // to_base, to_base) + alphabet[n % to_base] plain_text = "81ddb2a8fac76d12" L0 = "81ddb2a8" R0 = "fac76d12" key = ["13a170cf", "4764cb9b", "cf55b828", "08fae737", "e802eee0", "b3eb590a", "77e1b970", "99ca3d21", "13a170cf", "4764cb9b", "cf55b828", "08fae737", "e802eee0", "b3eb590a", "77e1b970", "99ca3d21", "13a170cf", "4764cb9b", "cf55b828", "08fae737", "e802eee0", "b3eb590a", "77e1b970", "99ca3d21", "99ca3d21", "77e1b970", "b3eb590a", "e802eee0", "08fae737", "cf55b828", "4764cb9b", "13a170cf"] '''plain_text = "9a0573bd4b2d295c" L0 = "9a0573bd" R0 = "4b2d295c" key = ["18a75dcf", "2c1ee560", "14621875", "7206bfba", "358ea8f4", "e36ed553", "18fb69db", "0ec9b5b9", "18a75dcf", "2c1ee560", "14621875", "7206bfba", "358ea8f4", "e36ed553", "18fb69db", "0ec9b5b9", "18a75dcf", "2c1ee560", "14621875", "7206bfba", "358ea8f4", "e36ed553", "18fb69db", "0ec9b5b9", "0ec9b5b9", "18fb69db", "e36ed553", "358ea8f4", "7206bfba", "14621875", "2c1ee560", "18a75dcf"]''' S_boxes = ["4a92d80e6b1c7f53", "eb4c6dfa23810759", "581da342efc7609b", "7da1089fe46cb253", "6c715fd84a9e03b2", "4ba0721d36859cfe", "db413f590ae7682c", "1fd057a4923e6b8c"] j = 0 while (j < 32): round_key = key[j] print(f"round key = {round_key}") R_start = R0 round_key_10 = convert_base(round_key, from_base=16, to_base=10) print("round_key in 10 = ", round_key_10) R_10 = convert_base(R_start, from_base=16, to_base=10) print("R = ", R_10) k1 = (int(round_key_10)) + (int(R_10)) print("K1 = ", k1) big = pow(2, 32) k1_mod_2_32 = (int(k1)) % (int(big)) print("R + K mod 2^32 = ", k1_mod_2_32) if len(convert_base(k1_mod_2_32, from_base=10, to_base=2)) < 32: print("0"*(32-len(convert_base(k1_mod_2_32, from_base=10, to_base=2)) ) + convert_base(k1_mod_2_32, from_base=10, to_base=2)) rk_mod_2_32_16 = convert_base(k1_mod_2_32, from_base=10, to_base=16) len_rk_mod_2_32_16 = len(rk_mod_2_32_16) '''print("len_rk_mod_2_32_16 = ", len_rk_mod_2_32_16)''' if len_rk_mod_2_32_16 == 8: rk_mod_2_32_16_10 = rk_mod_2_32_16 elif len_rk_mod_2_32_16 == 7: rk_mod_2_32_16_10 = "0" + rk_mod_2_32_16 elif len_rk_mod_2_32_16 == 6: rk_mod_2_32_16_10 = "00" + rk_mod_2_32_16 '''print("rk_mod_2_32_16_10 = ", rk_mod_2_32_16_10)''' i = 0 '''print(f"S_boxes[{i}] = ", S_boxes[i])''' '''print("len(rk_mod_2_32_16_10) = ", len(rk_mod_2_32_16_10))''' SR = "" for i in range(len(rk_mod_2_32_16_10)): SR += S_boxes[i][int(convert_base(rk_mod_2_32_16_10[i], from_base=16, to_base=10))] '''print("SR = ", SR)''' print("S ( R ) = ", SR) if len(convert_base(SR, from_base=16, to_base=2)) < 32: '''print("SR_2 = ", "0"*(32-len(convert_base(SR, from_base=16, to_base=2))) + convert_base(SR, from_base=16, to_base=2))''' print("\tS ( R ) = ", "0" * (32 - len(convert_base(SR, from_base=16, to_base=2))) + convert_base(SR, from_base=16, to_base=2)) new_data_2 = "" i = 0 for i in range(len(SR)): if len(convert_base(SR[i], from_base=16, to_base=2)) == 4: new_data_2 += convert_base(SR[i], from_base=16, to_base=2) elif len(convert_base(SR[i], from_base=16, to_base=2)) == 3: new_data_2 += "0" + convert_base(SR[i], from_base=16, to_base=2) elif len(convert_base(SR[i], from_base=16, to_base=2)) == 2: new_data_2 += "00" + convert_base(SR[i], from_base=16, to_base=2) elif len(convert_base(SR[i], from_base=16, to_base=2)) == 1: new_data_2 += "000" + convert_base(SR[i], from_base=16, to_base=2) '''print("new_data_2 = ", new_data_2)''' i = 0 new_data_2_x = "" for i in range(len(new_data_2)-11): new_data_2_x += new_data_2[i+11] for i in range(11): new_data_2_x += new_data_2[i] '''print("new_data_2_x = ", new_data_2_x)''' print("Shift = ", new_data_2_x) L = L0 L_2 = convert_base(L, from_base=16, to_base=2) if (len(L_2)) < 32: old_L2 = L_2 L_2 = "" L_2 += "0" * (32 - len(old_L2)) + \ convert_base(L0, from_base=16, to_base=2) L_2_xor_new_data_2_x = "" print(len(new_data_2_x)) print(len(L_2)) for i in range(len(new_data_2_x)): L_2_xor_new_data_2_x += "1" if L_2[i] != new_data_2_x[i] else "0" '''print("L_2_xor_new_data_2_x = ", L_2_xor_new_data_2_x)''' print("L ( + ) F ( R ) = ", L_2_xor_new_data_2_x) new_answer = "" i = 0 new_answer = convert_base(L_2_xor_new_data_2_x, from_base=2, to_base=16) '''print("new_answer = ", new_answer)''' if (len(new_answer)) < 8: old_newans = new_answer new_answer = "" new_answer += "0" * (8 - len(old_newans)) + old_newans '''print("new_answer_R0 = ", R+new_answer)''' print(f"L1 = {R_start} || R1 = {new_answer}") print(f"{R_start} = {convert_base(R_start,10,16)}") print(f"{new_answer} = {convert_base(new_answer,10,16)}") print(f"-{j+1}"*23) j += 1 L0 = R_start R0 = new_answer print("-------------------------------------------------------------------") print("-------------------------------------------------------------------") print("-------------------------------------------------------------------")
ed8677c6b5bd96677480b3339ec31399fe93101b
saidsalihefendic/online-programming-school-2021
/drugo_predavanje/if_kontrolne_strukture.py
720
4.09375
4
""" Konvertovanje prosjek ocjena 5 -> A 4 -> B 3 -> C 2 -> D 1 -> F """ prosjek_ocjena = int(input("Unesite vas prosjek ocjena: ")) print("Vas prosjek ocjena je:", prosjek_ocjena) konvertovani_prosjek_ocjena = None # tip None if prosjek_ocjena == 5: konvertovani_prosjek_ocjena = "A" elif prosjek_ocjena == 4: konvertovani_prosjek_ocjena = "B" elif prosjek_ocjena == 3: konvertovani_prosjek_ocjena = "C" elif prosjek_ocjena == 2: konvertovani_prosjek_ocjena = "D" elif prosjek_ocjena == 1: konvertovani_prosjek_ocjena = "F" else: print("Nije validan prosjek ocjena") if konvertovani_prosjek_ocjena != None: print("Vas konvertovani prosjek ocjena je:", konvertovani_prosjek_ocjena)
b10ca30f5219935902403726120c53cbd0482d65
dhavalKalariya/The-Art-of-Doing-Projects
/Conditionals/Problem17-CoinFlipApp.py
1,056
4.21875
4
#Coin Flip App import random print("Welcome to the Coin Flip App") print("\nI will flip a coin a set number of times.") number = int(input("\nHow many times would you like me to flip the coin: ")) heads = [] tails = [] flips = [] for i in range(1,number+1): #fliping coin using random library flip = random.randint(0,1) if flip == 1: heads.append("Head") print("Head") else: tails.append("Tail") print("Tail") headcount = len(heads) tailcount = len(tails) if headcount == tailcount: print("At "+str(i)+" flips, the number of heads and tails were equal at "+str(i/2)+ " each") #calculate percantages heads_percentage = round(100*headcount/number,2) tails_percentage = round(100*tailcount/number,2) print("Results of Flipping A Coin "+str(number)+" Times:") print("\nSide\t\tCount\t\tPercentage") print("Heads\t\t"+str(headcount)+"/"+str(number)+"\t\t"+str(heads_percentage)+"%") print("Heads\t\t"+str(tailcount)+"/"+str(number)+"\t\t"+str(tails_percentage)+"%")
9bbd5a19586ff1c2c02e2d37d0f8ae388c6392a4
Ran05/basic-python-course
/day3_act2.py
1,009
4.09375
4
#Activity 2 of Day 3: emp_Name = input("Enter employee name: ") yrs_in_service = input("Enter years of service: ") office = input("Enter office: ") o = f""" =======Bunos Form======================== """ print(o) # divider if int(yrs_in_service) >= 10 and office == "it" : print("Hi" + " " + emp_Name + "," + "your bunos is 10000" ) elif int(yrs_in_service) <= 10 and office == "it": print("Hi" + " " + emp_Name + "," + "your bunos is 5000") if int(yrs_in_service) >= 10 and office == "acct" : print("Hi" + " " + emp_Name + "," + "your bunos is 12000" ) elif int(yrs_in_service) <= 10 and office == "acct": print("Hi" + " " + emp_Name + "," + "your bunos is 6000") if int(yrs_in_service) >= 10 and office == "hr" : print("Hi" + " " + emp_Name + "," + "your bunos is 15000" ) elif int(yrs_in_service) <= 10 and office == "hr": print("Hi" + " " + emp_Name + "," + "your bunos is 7500") output = f""" ======================================== """ print(output) # divider
7dff81f1dfaaf68b049d1491baf4932fe27040ec
sauravjain2304/exercism_solutions
/grains/grains.py
161
3.625
4
def square(number): if number <= 0 or number > 64: raise ValueError("error") return 2 ** (number - 1) print(square(64)) def total(): return 2**64 - 1
9af5cb757cb1a736d822dd1b323b167b3cd8a1f8
mtian0415/PythonAndDjangoDepolyment
/conditionals.py
367
3.96875
4
x = 10 y = 13 if x == y: print(f'{x} is equal to {y}') elif x > y: print(f'{x} is greater than {y}') else: print(f'{x} is less than {y}') # not if not(x == y): print(f'{x} is not equal to {y}') numbers = [1,2,3,4,9] if x in numbers: print(x in numbers) if x not in numbers: print(x in numbers) if x is y: print(x is y)
7a20b77e51cbb21904fef20904d21b7dfc5586cc
rodrigobmedeiros/Udemy-Python-Programmer-Bootcamp
/Codes/class_objects.py
489
3.578125
4
# -*- coding: utf-8 -*- """ Created on Thu Mar 12 21:56:03 2020 @author: Rodrigo Bernardo Medeiros """ class people(): specie = 'Human' def __init__(self,name, age,city): self.name = name self.age = age self.city = city def get_details(self): print(f'Infomration: Name: {self.name}, Age: {self.age} and City: {self.city}') rodrigo = people('Rodrigo Bernardo Medeiros', 33, 'Rio de Janeiro') rodrigo.get_details()
fdc5f061cad8dcad1097da2b47b4330f1b29e53a
Surmalumi/homework5
/work6.py
696
3.578125
4
# Необходимо создать (не программно) текстовый файл, где каждая строка описывает учебный предмет и наличие лекционных, практических и лабораторных занятий по этому предмету и их количество. import re dict = {} with open('work6.txt','r', encoding='utf-8') as file: new_file = file.readlines() for discipline in new_file: total_hours = 0 hours = re.findall(r'\d+', discipline) for hour in hours: total_hours += float(hour) dict[discipline.split()[0]] = total_hours print(dict)
c650cd102eb0103092506ffdc22b9bd972f4c19f
vardis/python-algorithms
/src/graph_cycle.py
3,577
3.59375
4
__author__ = 'giorgos' """ Determines if a graph contains a cycle. The graph is expected to be in adjacency list representation. Uses depth first search to explore the graph, if a vertex is visited twice then a cycle exists. Runs in O(n + m) time where n is the number of vertices and m is the number of edges. """ class DirectedCycleDetector: def __init__(self, g): self._G = g self._marked = [False for i in range(g.V())] self._cycle = [] # whenever a vertex is visited it enters this list and it pops off when we have # a DFS for that vertex self._call_stack = [None for i in range(g.V())] # _parentChain[v] = w means that we reached v through w self._parentChain = [None for i in range(g.V())] def has_cycle(self): for v in range(self._G.V()): if not self._marked[v]: self.dfs(v) if self.__has_cycle(): break return self.__has_cycle() def dfs(self, v): self._call_stack[v] = True self._marked[v] = True for w in self._G.edges(v): if self.__has_cycle(): return # support for weighted digraphs if type(w) is list or type(w) is tuple: w = w[0] if not self._marked[w]: self._parentChain[w] = v self.dfs(v, w) elif self._call_stack[w]: # just found a cycle, store the cyclic path self._cycle = [] p = v while True: self._cycle.insert(0, p) p = self._parentChain[p] if p is None or p == w: break self._cycle.insert(0, w) self._cycle.insert(0, v) self._call_stack[v] = False def cycle(self): return self._cycle def __has_cycle(self): return len(self._cycle) > 0 class CycleDetector: def __init__(self, g): self._G = g self._marked = [False for i in range(g.V())] self._cycle = [] # _parentChain[v] = w means that we reached v through w self._parentChain = [None for i in range(g.V())] def has_cycle(self): for v in range(self._G.V()): if not self._marked[v]: self.dfs(-1, v) if self.__has_cycle(): break return self.__has_cycle() def dfs(self, u, v): self._marked[v] = True for w in self._G.edges(v): if self.__has_cycle(): return if not self._marked[w]: self._parentChain[w] = v self.dfs(v, w) elif w != u: # just found a cycle, store the cyclic path self._cycle = [] p = v while True: self._cycle.insert(0, p) p = self._parentChain[p] if p is None or p == w: break self._cycle.insert(0, w) self._cycle.insert(0, v) def cycle(self): return self._cycle def __has_cycle(self): return len(self._cycle) > 0 if __name__ == "__main__": import graph_utils G = graph_utils.load_graph("../data/cyclicG.txt") detector = CycleDetector(G) assert detector.has_cycle() assert [3, 0, 1, 2, 3] == detector.cycle() G = graph_utils.load_graph("../data/tinyG.txt") detector = CycleDetector(G) assert detector.has_cycle() print(detector.cycle())
686ef20781b44c274a597522ffe87897515c31f7
NekoPlusPro/pythonProject
/NCRE/4/PY202.py
658
3.75
4
# 以下代码为提示框架 # 请在...处使用一行或多行代码替换 # 请在______处使用一行代码替换 # # 注意:提示框架代码可以任意修改,以完成程序功能为准 fo = open("PY202.txt","w") data = input("请输入课程名及对应的成绩:") # 课程名 考分 di={} sum=0 while data: t=data.split(' ') di[t[0]]=t[1] sum+=eval(t[1]) data = input("请输入课程名及对应的成绩:") li=list(di.items()) li.sort(key=lambda x:x[1],reverse=True) fo.write("最高分课程是{} {}, 最低分课程是{} {}, 平均分是{:.2f}".format(li[0][0],li[0][1],li[-1][0],li[-1][1],sum/len(li))) fo.close()
dc2432b535d79062ae007417aecbefee9424d4fd
WenyueHu/python
/advance/04-装饰器.py
310
3.578125
4
def w1(func): print('---1---') def inner(): print('---w1---') func() return "w1 + " + func() return inner def w2(func): print('---2---') def inner(): print('---w2---') func() return "w2 + " +func() return inner @w1 @w2 def f1(): print('---f1---') return "hahaha" ret = f1() print(ret)
59c34966ce1f708290dd9627f2b9a58ed6a966c1
stephenjfox/py-scratch
/probability/problem_sets/binomial_distribution_2.py
2,165
3.890625
4
""" Day 4: Binomial Distribution II A manufacturer of metal pistons finds that, on average, 12% of the pistons they manufacture are incorrectly sized. What is the probability that a batch of 10 pistons will contain: 1. No more than 2 rejects? 2. At least 2 rejects? Print the answer to each question on its own line: 1. The first line should contain the probability that a batch of 10 pistons will contain no more than 2 rejects. 2. The second line should contain the probability that a batch of 10 pistons will contain at least 2 rejects. Round both of your answers to a scale of 3 decimal places (i.e., 1.234 format). """ from math import factorial def format_answer(value) -> str: return "{value:0.3f}".format(value=value) def product(i, j) -> int: """Multiply every integer from i -> j inclusive""" out = 1 for x in range(i, j + 1): out *= x return out def n_choose_k(n, k): if n - k > k: divisor = product(n - k + 1, n) denominator = factorial(k) else: divisor = product(k + 1, n) denominator = factorial(n - k) comb = divisor / denominator return comb def binomial_dist(prob_success, prob_fail, trials, choices) -> float: # dist = nCk * p_success^(k) * p_fail^(n-k) coefficient = n_choose_k(trials, choices) positive = prob_success**choices negative = prob_fail**(trials - choices) prob = coefficient * positive * negative return prob if __name__ == '__main__': fails_in_100, batch_count = [int(x) for x in input().split(' ')] # translate the values into probabilities # p = boy, q = girl, because the question is about getting boys fail_rate = fails_in_100 / 100. p = 1 - fail_rate n_trials = batch_count # aliasing # we're seeking after the rate of failures, just treat that as the success criteria binomial_result_2_fails = binomial_dist(fail_rate, p, n_trials, 2) prob_2_rejects = binomial_dist(fail_rate, p, n_trials, 0) +\ binomial_dist(fail_rate, p, n_trials, 1) +\ binomial_result_2_fails prob_at_least_2_rejects = 1 - prob_2_rejects + binomial_result_2_fails print(prob_2_rejects) print(prob_at_least_2_rejects)
8b72ec898d778563abe817c2fb1cedc62ea2cdbf
JosephLevinthal/Research-projects
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/226/users/4476/codes/1747_1531.py
233
3.734375
4
from math import* x = eval(input("digite o numero: ")) k = int(input("digite o numero: ")) soma = 0 i = 0 sinal = +1 while (i<=k-1): soma = soma + sinal * x**(2*i)/factorial(2*i) sinal = - sinal i = i + 1 print(round(soma, 10))
7ace8355b1ae9d55e64e182f9126e1a3df43f575
AbinDaGoat/coding-summer-session2
/notes/week_2/conditional_statements.py
3,235
4.15625
4
""" boolean logic is very necessary in order to better understand how conditional statement works but what are conditional statements? conditional statements are also known as branching statements, and they evaluate a different block of code depending on the boolean expressions that are present NOTE: conditional statements are resolved top-down format of the language: if boolean-expression-1: ... do something ... elif boolean-expression-2: # elif is short for else if ... do something else ... ... elif boolean-expression-n: ... do something else ... else: # default case ... do the default case ... the first if statement is required -- all other statements can be omitted NOTE: conditional statements are mutually exclusive (disjoint) --> if one occurs, then the others do not EXAMPLE 1: coin flip if (heads): do what we need to do for heads else: # tails do what we need to do for tails BAD DESIGN: if (heads): do heads elif (tails): do tails EXAMPLE 2: rock paper scissors if (rock): do rock elif (paper): do paper else: do scissors NOTE: illogical for this case if (rock): do rock if (paper): do paper if (scissor): do scissor EXAMPLE 3: lottery system consider the following situation: there is a lottery system in your county where we have prizes for various categories of winners: 1st place --> 1 million pennies 2nd place --> 2 million dollars 3rd place --> ps5 box with a ps4 inside 4th place --> a high five from the pope if (you are first place): get 1 million pennies elif (you are second place): get 2 million dollars elif (you are third place): get a ps5 box with a ps4 inside elif (you are fourth place): get a high five from the pope EXAMPLE 4: tournament if (you win the tournament): get winner prize NOTE: < and >= are opposite operators > and <= are opposite operators """ x = 5 if x > 0: print("x is positive") elif x < 0: print("x is negative") else: print("x is zero") """ from lines 83 to 88, that is called an if block (specifically its if-elif-else block) """ """ DESIGN: boolean variables should have names that are predicates --> verb phrase examples: 1) is_ugly 2) is_set 3) is_running 4) is_unit_test_passing RECALL: functions also have a naming structure --> they are also verb-like, but not predicates 1) def display_name(): 2) def get_user_age(): 3) def calc_tip(): RECALL: any other kind of variable should be noun-like ALWAYS: examples: 1) tip 2) velocity 3) damage """ """ nested if statements: you can have anything in the block of code dedicated to each if-elif-else block; including other conditional statements!!! NOTE: modulo operator: MATH: n mod m --> divide n by m, and get the remainder ex: 10 mod 5 --> 0 ex: 7 mod 2 --> 1 ex: 26 mod 7 --> 5 CODE: n % m --> divide n by m, and get the remainder ex: 10 % 5 --> 0 ex: 7 mod 2 --> 1 ex: 26 mod 7 --> 5 """ x = 7 if x > 0: # check to see if its positive print("x is positive!!") # now determine if x is even --> use the modulo operator if x % 2 == 0: print("x is even!") else: print("x is odd!") else: print("x is not positive!!")
2d3efdbbb2d181108eff2ccff72e577093dbe8d9
mindful-ai/oracle-june20
/day_02/code/11_understanding_functions_and_modules/project_b.py
386
3.875
4
# Project B # Find all the prime numbers between a user # given range import project_a_new # Inputs start = int(input("Enter the start : ")) end = int(input("Enter the end : ")) # Process primes = [] for num in range(start, end + 1): if(project_a_new.checkprime(num)): primes.append(num) # Output print('-'*40) print("PRIMES:") print(primes)
d781329eb6a8881b329aca7082715d33c35d7740
turo62/exercise
/exercise/sorting_basic.py
586
3.953125
4
def sorting_nums(numbers): print(numbers) N = len(numbers) for i in range(N): for j in range(N - 1): if numbers[j] > numbers[j + 1]: temp = numbers[j + 1] numbers[j + 1] = numbers[j] numbers[j] = temp else: j += 1 return numbers def main(): numbers = sorting_nums([1, 2, 56, 32, 51, 2, 8, 92, 15]) print(numbers) if __name__ == "__main__": main()
ccf7d2989ce67f8d49449c6a9cacc74c98a63b53
bam0/Project-Euler-First-100-Problems
/Problems_41-60/P51_Prime_Digit_Rep.py
5,236
4.4375
4
''' Problem: Find the smallest prime which, by replacing part of the number (not necessarily adjacent digits) with the same digit, is part of an eight prime value family. One of the first things we should try to do in order to solve this problem is narrow down how many digits we need to replace. If we replace 1 or 2 digits, we are guaranteed at least three numbers will not be prime, since they would have to be divisible by 3. We know this because if a number is divisible by 3, the sum of the digits is also divisible by 3. Thus we should be focusing on replacing 3 digits. And we also know that we cannot replace the final digit, because trivially we would get 5 even numbers. Combining these two facts will lead us to a more efficient solution. Before getting started with the rest, let's bring out our prime sieve. ''' def sieve(n): L = [True]*n L[0] = L[1] = False for p, prime in enumerate(L): if prime: yield p for i in range(p*p, n, p): L[i] = False ''' First we'll need a helper function which takes in a prime and lets us know if we have a triple of the same digit. In order to avoid redundant calculations, we save the value of the digit for the triple as well and return it. ''' def triple(p): s, D = str(p), {} # Initialize dictionary of digits for l in s: # Mimic the Counter built-in if l in D: D[l] += 1 else: D[l] = 1 for key, val in D.items(): if val==3 and key!=s[-1]: # Check for triple w/ last digit not included return (True, key) return (False, None) ''' Now we'll create another helper function which checks if a given prime produces an 8+ prime family through substitution of the key digit. It will check for primality using the big set, and keep track of those already checked in the small set. All we need to do is take advantage of the sub function in the regex library. As long as there are not over 2 composite numbers, we know we have found an 8-prime family. ''' import re def is_valid(prime, small_set, big_set, key): count, p_str = 0, str(prime) for i in range(10): p_int = int(re.sub(key, str(i), p_str)) # Substitute key with 0-9 if p_int in big_set and len(str(p_int))==len(p_str): # Checks if number is prime small_set.add(p_int) # and same length as the else: # original number count += 1 if count > 2: # If >2 composite, test is failed return False return True ''' The final part is simple. All we have to do is create a large list of primes with the sieve and check each of them for the above property. ''' def solution1(limit): big_list = list(sieve(limit)) big_set = set(big_list) p_set = set() for prime in big_list: trp = triple(prime) if trp[0]: if prime in p_set: continue if is_valid(prime, p_set, big_set, trp[1]): return prime ''' Next we'll craft a solution very similar to the previous one, but without the use of a prime sieve. First we'll need a simple prime-checker. ''' def is_prime(n): for i in range(3, int(n**0.5)+1, 2): if not n%i: return False return True ''' The next function is almost the same as is_valid, with the sets removed and is_prime implemented instead. ''' def is_good(prime, key): count, p_str = 0, str(prime) for i in range(10): p_int = int(re.sub(key, str(i), p_str)) if is_prime(p_int) and len(str(p_int))==len(p_str): continue count += 1 if count > 2: return False return True ''' Finally we start with 4 digit numbers and work our way up. ''' def solution2(limit): cur = 1001 while cur < limit: if is_prime(cur): trp = triple(cur) if trp[0] and is_good(cur, trp[1]): return cur cur += 2 ''' Lastly, we make a slight optimization over the previous solution by using a smaller prime sieve than solution 1 coupled with a dynamic primality check. ''' def dynamic_check(lst, num): root = num ** 0.5 # Get the square root for prime in lst: if prime > root: # No more checks needed break if not num % prime: return False return True ''' And finally we take advantage of the fact that all primes after 3 can be written as 6k+/-1 for integers k. Now we have made a hybrid of the first two solutions, giving the most efficient solution of the three. ''' def solution3(limit): prime_list = list(sieve(int(limit**0.5))) cur = 1002 while cur < limit: if dynamic_check(prime_list, cur-1): # Check 6k-1 trp = triple(cur-1) if trp[0] and is_good(cur-1, trp[1]): return cur-1 if dynamic_check(prime_list, cur+1): # Check 6k+1 trp = triple(cur+1) if trp[0] and is_good(cur+1, trp[1]): return cur+1 cur += 6 print('Smallest prime:', solution3(1000000)) # Smallest prime: 121313
25f6613cb81b58f1c87d087cfe4bbaf8532d20d7
yaHaart/hometasks
/Module21/06_deep_copy/main.py
1,240
3.5
4
from copy import deepcopy site = { 'html': { 'head': { 'title': 'Куплю/продам телефон недорого' }, 'body': { 'h2': 'У нас самая низкая цена на телефон', 'div': 'Купить', 'p': 'Продать' } } } def parsing_dict(struct, telephone_name): key1_to_find = 'title' key2_to_find = 'h2' title_to_change = 'Куплю/продам ' + telephone_name + ' недорого' h2_to_change = 'У нас самая низкая цена на ' + telephone_name if key1_to_find in struct: struct[key1_to_find] = title_to_change if key2_to_find in struct: struct[key2_to_find] = h2_to_change for value in struct.values(): if isinstance(value, dict): result = parsing_dict(value, telephone_name) if result: break else: result = None return result number_of_sites = 2 for _ in range(number_of_sites): telephone = input('Название телефона ') site_copy = deepcopy(site) parsing_dict(site_copy, telephone) print(site_copy) # print(site) # зачёт! 🚀
686fa642a5c45545bc4ff53f5c42c588e409581c
RevathiM25/python-programming
/beginner/hello.py
68
3.84375
4
n=int(input("enter")) for i in range(n): i="hello" print(i)
997b82e5511470dee620e58c0ad3c027ab62a1e6
Yao-Phoenix/TrainCode
/listtest.py
297
3.765625
4
#!/usr/bin/env python3 import sys if __name__ == '__main__': a_list=[] b_list=[] for argv in sys.argv[1:]: if len(argv) <= 3: a_list.append(argv) elif len(argv) > 3: b_list.append(argv) print(' '.join(a_list)) print(' '.join(b_list))
78b230ce7f3cb10fe2025c299f0e4433ac85adaf
WenzheLiu0829/Extreme_computing
/assignment2/task2/reducer.py
701
3.53125
4
#!/usr/bin/python import sys import heapq #create heap queue top_10_question = [ ] heapq.heapify(top_10_question) for line in sys.stdin: # for ever line in the input from stdin line = line.strip() # Remove trailing characters id, value = line.split("\t", 1) value = int(value) # populate into heapqueue heapq.heappush(top_10_question, (value, id)) if len(top_10_question) > 10: # more than 10 rows heapq.heappop(top_10_question) #reverse the heap queue and print the result for value, id in reversed([heapq.heappop(top_10_question) for x in range (len(top_10_question))]): id = id.strip(",") print("{0}\t{1}".format(value, id))
010255f865f36158408d94aa34f431e40122afe7
niqaabi01/Intro_python
/Week7/Support.py
1,072
3.90625
4
#creating an automated tech response to single inputs = key words #Saaniah Blankenberg #2020/06/17 def intro(): print('Welcome to the automated technical support system.') print('Please describe your problem.') def add_input(): return input().capitalize() def main(): intro() problem = add_input() responses = { "Crashed" : "Are the drivers up to date", "Blue" : "Ah, the blue screen of death. And then what happened?", "Hacked" : "You should consider installing and anti-virus software.", "Bluetooth" : "Have you tried mouthwash?", "Windows" : "Ah, I think I see your problem.What version?", "Apple" : "You mean the computer kind?", "Spam" : "You should see if your mail client can filter messages", "Connection" : "Telkom"} while problem != "Quit": if problem not in responses: print("Curious, Tell me more") problem = add_input() if problem in responses: print(responses.get(problem)) problem = add_input() print(main()) if __name__ == '__main__': main()
f77eaf310c9d0bb9b2ac30dec25fe254af61a69f
matthewschaub/ToPL
/P5/check.py
3,349
3.828125
4
from lang import * # Implements the typing relation e : T, which # is to say that every expression e has some type # T. If not, the expression is ill-typed (or # sometimes ill-formed). # The (only) boolean type boolType = BoolType() # The (only) integer type intType = IntType() def is_bool(x): # Returns true if x either is boolType (when # x is a Type) or if x has boolType (when x # is an expression). The latter case will # recursively compute the the type of the # expression as a "convenience". if isinstance(x, Type): return x == boolType if isinstance(x, Expr): return is_bool(check(x)) def is_int(x): # Same as above, but for int. if isinstance(x, Type): return x == intType if isinstance(x, Expr): return is_int(check(x)) def is_same_type(t1, t2): # Returns true if t1 and t2 are the same # type (if both are types). # Quick reject. t1 and t2 are not objects # of the same type. if type(t1) is not type(t2): return False if type(t1) is BoolType: return True if type(t1) is IntType: return True assert False def has_same_type(e1, e2): # Returns true if e1 and e2 have the # same type (recursively computing the # types of both expressions.) return is_same_type(check(e1), check(e2)) def check_bool(e): # -------- T-Bool # b : Bool return boolType def check_int(e): # -------- T-Int # n : Int return intType def check_and(e): # e1 : Bool e2 : Bool # --------------------- T-And # e1 and e2 : Bool if is_bool(e1) and is_bool(e2): return boolType raise Exception("invalid operands to 'and'") def check_add(e): # e1 : Int e2 : Int # ------------------- T-Add # e1 + e2 : Int if is_int(e.lhs) and is_int(e.rhs): return intType raise Exception("invalid operands to '+'") def check_sub(e): # e1 : Int e2 : Int # ------------------- T-Sub # e1 - e2 : Int if is_int(e.lhs) and is_int(e.rhs): return intType raise Exception("invalid operands to '-'") def check_eq(e): # e1 : T1 e2 : T2 # ----------------- T-Eq # e1 == e2 : Bool if has_same_type(e.lhs, e.rhs): return boolType raise Exception("invalid operands to '=='") def do_check(e): # Compute the type of e. assert isinstance(e, Expr) if type(e) is BoolExpr: return check_bool(e) if type(e) is AndExpr: return check_and(e) if type(e) is OrExpr: return check_or(e) if type(e) is NotExpr: return check_not(e) if type(e) is IfExpr: return check_if(e) if type(e) is IntExpr: return check_int(e) if type(e) is AddExpr: return check_add(e) if type(e) is SubExpr: return check_sub(e) if type(e) is MulExpr: return check_mul(e) if type(e) is DivExpr: return check_div(e) if type(e) is RemExpr: return check_rem(e) if type(e) is NegExpr: return check_neg(e) if type(e) is EqExpr: return check_eq(e) if type(e) is NeExpr: return check_ne(e) if type(e) is LtExpr: return check_lt(e) if type(e) is GtExpr: return check_gt(e) if type(e) is LeExpr: return check_le(e) if type(e) is GeExpr: return check_ge(e) assert False def check(e): # Accepts an expression and returns its type. # If we've computed the type already, return it. if not e.type: e.type = do_check(e) return e.type
16794e14b0b22a43d25e81f71957a94abea14908
kinsei/Learn-Python-The-Hard-Way
/ex19-1.py
315
3.703125
4
# This was written for python 2.7 # This is a part of Learning Python The Hard Way exercise 19 # The pourpose of this exercise is is to write a function and run it 10 different ways start_number = int(raw_input("Enter PC NUM:")) def add_number(start_number): print start_number + 1 add_number(start_number)
7cf73f2928c0ec9032b67a26a08ccf46b3664ac0
serhiistr/Python-test-telegram
/classmethod.py
1,581
4.0625
4
# Class # Название класса пишутся с большой буквы class Dog(): # __init__ специальный метод, который автоматически выполняется при создании # каждого нового экземпляра класса. Т.е. отвечает за базовый функционал, # который будет отрабатываться каждый раз при создании нашего обьекта (собака :)) # self - указывает, что мы работаем конкретно с экземпляром класса Dog # self нужен только внутри класса, а при создании обьекта мы его не указываем def __init__(self, name, age): #Инициализируем аттрибуты имя и возраст self.name = name self.age = age print("Собака", name, "создана") def sit(self): print(self.name.title() + " села на место") def jump(self): print(self.name.title() + " подпрыгнула") # Теперь создаем обьект по инструкции нашей (class Dog()). Этот обьект называется экземпляр класса my_dog_1 = Dog('archi', 5) # это создали экземпляр класса Dog my_dog_2 = Dog('ben', 2) my_dog_1.sit() # обращаемся напрямую к методу, через точку my_dog_2.jump() # print(my_dog.age)
1fa0d64ee01cc9e19651b695e80bbcb816c41d52
mike171001/ALLESVANPYCHARM
/Al het huiswerk/4. Functie met if 2.0.py
245
3.75
4
def new_password(oldpassword, newpassword): if len(newpassword) <6: print(True) newpassword = input("What will be your new password?") oldpassword = input("what was your old password? ") new_password(oldpassword,newpassword)
e8e4bdeb81de49ade6793c0dfbb215736c75804e
gabrielponto/eletronics
/main.py
1,668
3.734375
4
#!/usr/bin/python # -*- coding: utf-8 -*- import sys num1 = sys.argv[1] num2 = sys.argv[2] def get_bin_string(number): return bin(int(number)).replace('0b', '') bin_num_1 = get_bin_string(num1) bin_num_2 = get_bin_string(num2) def portAND(input1, input2): return '1' if int(input1) and int(input2) else '0' def portXOR(input1, input2): return '1' if (int(input1) or int(input2)) and int(input1) != int(input2) else '0' print(u"O primeiro numero em binário é: %s" % bin_num_1) print(u"O Segundo número em binário é: %s" % bin_num_2) # Iguala o número de zeros nos dois max_length = len(bin_num_1) if len(bin_num_2) > max_length: max_length = len(bin_num_2) bin_num_1 = bin_num_1.zfill(max_length) bin_num_2 = bin_num_2.zfill(max_length) print(u"Número 1: %s" % bin_num_1) print(u"Número 2: %s" % bin_num_2) result = [] for index in range(max_length): # pass the numbers on logical gates if index == 0: bit = portAND(bin_num_1[index], bin_num_2[index]) print(u"[AND] Primeira posição. Adicionando bit %s - De %s e %s" % (bit, bin_num_1[index], bin_num_2[index])) result.append(bit) bit = portXOR(bin_num_1[index], bin_num_2[index]) print(u"[XOR] Adicionando bit %s - De %s e %s" % (bit, bin_num_1[index], bin_num_2[index])) result.append(bit) result_string = ''.join(result) result_string_decimal = int(result_string, 2) correct_decimal_result = int(num1) + int(num2) print(u"Resultado de %s + %s = %s" % (bin_num_1, bin_num_2, result_string)) print(u"Resultado em decimal do cálculo binário: %s" % result_string_decimal) print(u"Resultado esperado: %s" % correct_decimal_result)
629d01e074ffd1d5c7278775f3d75870016e4f40
vedantshr/python-learning
/practice/Doubly_Linked_List.py
2,349
4.125
4
class Node: def __init__(self, data=None): self.next = None self.prev = None self.data = data class doublylinkedlist: def __init__(self): self.head = None def Insert(self, newdata): NewNode = Node(newdata) if self.head is None: self.head = NewNode else: NewNode.next = self.head self.head.prev = NewNode self.head = NewNode # def Append(self, newdata): # NewNode = Node(newdata) # NewNode.next = None # if self.head is None: # NewNode.prev = None # self.head = NewNode # return # last = self.head # while (last.next is not None): # last = last.next # last.next = NewNode # NewNode.prev = last # return def Append(self, newdata): NewNode = Node(newdata) NewNode.next = None if self.head is None: NewNode.prev = None self.head = NewNode return last = self.head while (last.next is not None): last = last.next last.next = NewNode NewNode.prev = last return def Push(self, prev_node, newdata): if prev_node is None: return NewNode = Node(newdata) NewNode.next = prev_node.next #This is the step where we are mentioning that next node of previous node is now the next node of newnode. prev_node.next = NewNode NewNode.prev = prev_node if NewNode.next is not None: NewNode.next.prev = NewNode def Print(self): currentnode = self.head while currentnode is not None: print(currentnode.data, end=" ") currentnode= currentnode.next print("Null") if __name__ == "__main__": dll = doublylinkedlist() n = int(input("Number of elements: ")) for i in range(n): newdata = int(input("Enter data: ")) dll.Insert(newdata) dll.Print() m = int(input("Number of elements: ")) for i in range(m): newdata = int(input("Enter data: ")) dll.Append(newdata) dll.Print() a = int(input("after how many digits would you like to add: ")) b = dll.head for i in range(a): b = b.next dll.Push(b, "20") dll.Print()
78f4f464de53e50f6eda9b803ad99d3f80304132
pabloApoca/PYTHON-COURSE
/functions.py
341
3.90625
4
def hello(name="Person"): print("Hello world " + name) hello("Pablo") hello("Martin") hello() def add(n1, n2): return n1 + n2 print(add(10, 30)) print(len("Hello")) # lambda son funciones anonimas que resiben un numero de argunmento pero que solo resiven una expresion add = lambda num1, num2: num1 + num2 print(add(10,50))
3ab1e960084727d2c8d4d34b992529cdc33bba10
HanSeokhyeon/Baekjoon-Online-Judge
/code/9663_n-queen.py
994
3.75
4
def n_queen(chess, case, n): if n == 0: case.append(1) return for i, row in enumerate(chess): for j, v in enumerate(row): if v == 0: place_queen(chess, j, i) n_queen(chess, case, n-1) pass def place_queen(chess, x, y): for i, row in enumerate(chess): chess[i][x] = 1 for j, v in enumerate(chess[y]): chess[y][j] = 1 if x < y: small = x else: small = y y_now = y - small x_now = x - small while not (y_now == len(chess) or x_now == len(chess)): chess[y_now][x_now] = 1 y_now += 1 x_now += 1 y_now = y + x x_now = 0 while not (y_now == -1 or x_now == len(chess)): chess[y_now][x_now] = 1 y_now -= 1 x_now += 1 return if __name__ == '__main__': k = int(input()) l = [[0 for _ in range(k)] for _ in range(k)] case = [] n_queen(l, case, k) print(case)
5a5a5b1783811e8f35bda9114c4a663a015d99e3
M4573R/udacity-1
/cs262/problems/exam/problem5.py
3,458
3.734375
4
__author__ = 'dhensche' # Turning Back Time # # Focus: Units 1, 2 and 3: Finite State Machines and List Comprehensions # # # For every regular language, there is another regular language that all of # the strings in that language, but reversed. For example, if you have a # regular language that accepts "Dracula", "Was" and "Here", there is also # another regular language that accepts exactly "alucarD", "saW" and # "ereH". We can imagine that this "backwards" language is accepted by a # "backwards" finite state machine. # # In this problem you will construct that "backwards" finite state machine. # Given a non-deterministic finite state machine, you will write a # procedure reverse() that returns a new non-deterministic finite state # machine that accepts all of the strings in the first one, but with their # letters in reverse order. # # We will use same the "edges" encoding from class, but we # will make the start and accepting state explicit. For example, the # regular expression r"a(?:bx|by)+c" might be encoded like this: edges1 = {(1, 'a'): [2], (2, 'b'): [3, 4], (3, 'x'): [5], (4, 'y'): [5], (5, 'b'): [3, 4], (5, 'c'): [6]} accepting1 = 6 start1 = 1 # For this problem we will restrict attention to non-deterministic finite # state machines that have a single start state and a single accepting # state. Similarly, we will not consider epsilon transitions. # # For the example above, since the original NFSM accepts "abxc", the NFSM # you produce must accept "cxba". Similarly, since the original accepts # "abxbyc", the NFSM you produce must accept "cybxba", and so on. # # Your procedure "reverse(edges,accepting,start)" should return a tuple # (new_edges,new_accepting,new_start) that defines a new non-deterministic # finite state machine that accepts every string in the language of the # original ... reversed! # # Vague Hint: Draw a picture, and then draw all the arrows backwards. def reverse(edges, accepting, start): rev = {} for ((star, char), ends) in edges.iteritems(): for end in ends: path = (end, char) rev[path] = rev.get(path, []) + [star] return rev, start, accepting # write your code here ... # We have included some testing code to help you check your work. Since # this is the final exam, you will definitely want to add your own tests. # # Recall: "hello"[::-1] == "olleh" def nfsmaccepts(edges, accepting, current, string): if string == "": return current == accepting letter = string[0] rest = string[1:] if (current, letter) in edges: for dest in edges[(current, letter)]: if nfsmaccepts(edges, accepting, dest, rest): return True return False r_edges, r_accepting, r_start = reverse(edges1, accepting1, start1) for s in ["abxc", "abxbyc", "not", "abxbxbxbxbxc", ""]: # The original should accept s if-and-only-if the # reversed version accepts s_reversed. print nfsmaccepts(edges1, accepting1, start1, s) == nfsmaccepts(r_edges, r_accepting, r_start, s[::-1]) # r"a+b*" edges2 = {(1, 'a'): [2], (2, 'a'): [2], (2, 'b'): [2]} accepting2 = 2 start2 = 1 r_edges2, r_accepting2, r_start2 = reverse(edges2, accepting2, start2) for s in ["aaaab", "aabbbbb", "ab", "b", "a", "", "ba"]: print nfsmaccepts(edges2, accepting2, start2, s) == \ nfsmaccepts(r_edges2, r_accepting2, r_start2, s[::-1])
7f675cd84ec04f14c559fcf77178a070b466f155
dharmit01/competitve_coding
/110A.py
110
3.59375
4
s = input() li = (4,7) for str in s: if str not in li: print("NO") exit print("YES")
af26b72bee59c984337d6b52d3792cd0960c3c70
Peng-Zhanjie/The-CP1404-Project
/Work4/list_exercises.py
1,157
3.9375
4
usernames = ['jimbo', 'giltson98', 'derekf', 'WhatSup', 'NicolEye', 'swei45', 'BaseInterpreterInterface', 'BaseStdIn', 'Command', 'ExecState', 'InteractiveConsole', 'InterpreterInterface', 'StartServer', 'bob'] def main(): numbers=[] Count=0 read=True while (read!=False): try: number=int(input("Please enter number{}:".format(Count+1))) except ValueError: print("ValueError") continue if(number>=0): numbers.append(number) Count+=1 else: print("Input finished") read=False print("The first number is {}".format(numbers[0])) print("The last number is {}".format(numbers[-1])) print("The smallest number is {}".format(min(numbers))) print("The biggest number is {}".format(max(numbers))) Average=sum(numbers)/len(numbers) print("The average of the numbers is {}".format(Average)) loop=True while(loop==True): name=input("Please enter your name:") if name not in usernames:print("Access denied") else: print("Access granted") loop=False main()
54b1293e0f16953bb35739c1a9998dd07d3314b0
LiaoU3/CodeWars
/4kyu/VigenèreCipherHelper.py
1,374
3.515625
4
# https://www.codewars.com/kata/52d1bd3694d26f8d6e0000d3/train/python class VigenereCipher(object): def __init__(self, key, alphabet): self.key = key self.alphabet = alphabet def encode(self, text): key_string = '' encoded = '' num = 26 if self.alphabet[0] == 'a' else 46 for pos in range(len(text)): key_string += self.key[pos % len(self.key)] for pos in range(len(text)): if text[pos] not in self.alphabet: encoded += text[pos] else: encoded += self.alphabet[(self.alphabet.find(text[pos]) + self.alphabet.find(key_string[pos])) % num] return encoded def decode(self, text): key_string = '' decoded = '' num = 26 if self.alphabet[0] == 'a' else 46 for pos in range(len(text)): key_string += self.key[pos % len(self.key)] for pos in range(len(text)): if text[pos] not in self.alphabet: decoded += text[pos] else: decoded += self.alphabet[(self.alphabet.find(text[pos]) - self.alphabet.find(key_string[pos])) % num] return decoded abc = "abcdefghijklmnopqrstuvwxyz" key = "カタカナ" c = VigenereCipher(key, abc) print(c.encode('タモタワ')) print(c.encode('CODEWARS')) print(c.decode('yiuzsrzhot'))
e2a9f38f5ee7fbe4dd84bd999714333d8000fa1f
fantastic001/fluidsim
/lib/draw.py
468
3.734375
4
def draw_from_function(grid, n, m, func, params={}): """ Draws boundary if func(x,y) is True, then it will be solid, fluid otherwise """ for i in range(n): for j in range(m): grid[i][j] = func(j,i,n,m, **params) def border_draw(grid,n,m): """ Draws solid borders """ for i in range(n): for j in range(m): if i == 0 or j == 0 or i == n-1 or j == m-1: grid[i][j] = True
fac8c470e62413e1766aca7408c9643c73abaaef
vrublevskiyvitaliy/verification
/ordered tests/stack.py
811
3.921875
4
class Stack(): def __init__(self): self.__items = [] self.__index = 0 def __len__(self): return self.__index @property def is_empty(self): return self.__index == 0 def peek(self): if self.is_empty: raise IndexError("Cannot peek from an empty stack!") return self.__items[self.__index - 1] def pop(self): if self.is_empty: raise IndexError("Cannot pop from an empty stack!") self.__index -= 1 item = self.__items[self.__index] self.__items[self.__index] = None return item def push(self, item): if len(self.__items) == self.__index: self.__items.append(item) else: self.__items[self.__index] = item self.__index += 1
03b7d925d78d284e5b32fae30d825c40dcfcb5ec
nbiadrytski-zz/python-training
/p_advanced_boiko/visibility/closure_example.py
345
4
4
def maker(N): # outer function that generates and returns a nested function, without calling it def action(X): return X + N return action nested_func = maker(3) # nested_func is actually action() returned by maker(); pass 3 to arg N print(nested_func(2)) # pass 2 to X, N remembers 3: 2 + 3 = 5 print(nested_func(10)) # 13
269a283f1f9ea9f1955064eceb19929c89ae6d02
dodieboy/Np_class
/PROG1_python/coursemology/Mission51-VitalityPoints.py
1,887
4.125
4
#Programming I ####################### # Mission 5.1 # # Vitality Points # ####################### #Background #========== #To encourage their customers to exercise more, insurance companies are giving #vouchers for the distances that customers had clocked in a week as follows: ###################################################### # Distance (km) # Gift # ###################################################### # Less than 25 # $2 Popular eVoucher # # 25 <= distance < 50 # $5 Cold Storage eVoucher # # 50 <= distance < 75 # $10 Starbucks eVoucher # # More than 75 # $20 Subway eVoucher # ###################################################### #Write a Python program to check and display the gift that customer will recieve. #The program is to prompt user for the total distance he had travelled (by walking or running) #in a week and check which gift he will get and display the information to him. #The return value of the function is the eVoucher value (e.g., 2 for the Popular eVoucher) #Important Notes #=============== #1) Comment out ALL input prompts before submitting. #2) You MUST use the following variables # - distance # - gift # - value #START CODING FROM HERE #====================== #Prompt user for the total distance travelled (either by walking or running). #Check gifts to be given to customer def check_gift(distance): #Check gift to be given if distance < 25: value = 2 elif distance < 50: value = 5 elif distance < 75: value = 10 else: value = 20 print(str(value) + ' eVoucher') #Modify to display gift to be given return value #Do not remove this line #Do not remove the next line check_gift(distance) #input 10 output 2 #input 25 output 5 #input 50 output 10 #input 76 output 20
1d47cac60cafbd9bc8193419447e19be0a2115ec
raybrightwood/-Python
/homework1-6.py
266
3.84375
4
a = int(input("Введите результат спортсмена за первый день")) b = int(input("Введите необходимый результат спортсмена")) day = 1 while a < b: a = a * 1.1 day = day + 1 print (day)
2f0280abbfe3776ae00d19a37cf50c5824817ddd
bigeyesung/Leetcode
/160. Intersection of Two Linked Lists.py
1,202
3.75
4
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def getIntersectionNode(self, headA, headB) -> ListNode: p1, p2 = headA, headB while p1 != p2: # if p1: # print("p1:",p1.val) # if p2: # print("p2:",p2.val) # print("======") p1 = headB if not p1 else p1.next p2 = headA if not p2 else p2.next # if p1: # print("after p1:",p1.val) # if p2: # print("after p2:",p2.val) # print(p1.val) return p1 def test(var): var[0]+=5 if __name__ == "__main__": apple = [4] test(apple) print(apple) a1 = ListNode(4) a2 = ListNode(1) a3 = ListNode(8) a4 = ListNode(4) a5 = ListNode(5) b1 = ListNode(5) b2 = ListNode(6) b3 = ListNode(1) b4 = ListNode(8) b5 = ListNode(4) b6 = ListNode(5) a1.next=a2 a2.next=a3 a3.next=a4 a4.next=a5 b1.next=b2 b2.next=b3 b3.next=b4 b4.next=b5 b5.next=b6 sol = Solution() sol.getIntersectionNode(a1,b1)
fd0ce75c48c705b16c5a3b3f843a338ecb541db5
JiniousChoi/encyclopedia-in-code
/languages/figuredrawer/circle.py
301
3.75
4
from PIL import Image, ImageDraw SIZE = 256 r = SIZE / 3 image = Image.new("L", (SIZE, SIZE)) d = ImageDraw.Draw(image) for x in range(SIZE): for y in range(SIZE): is_inner = (x - SIZE//2)**2 + (y - SIZE//2)**2 <= r**2 d.point((x,y), is_inner * 255) image.save('./circle.jpg')
ad9acb3c76717a00980265af26c69ea735f5b3ea
asharkova/python_practice
/UdacityAlgorithms/lessons1-3/binarySearchAlgorithm.py
1,196
4.21875
4
"""You're going to write a binary search function. You should use an iterative approach - meaning using loops. Your function should take two inputs: a Python list to search through, and the value you're searching for. Assume the list only has distinct elements, meaning there are no repeated values, and elements are in a strictly increasing order. Return the index of value, or -1 if the value doesn't exist in the list.""" def binary_search(input_array, value): """Your code goes here.""" middle = len(input_array) // 2 lower = 0 upper = len(input_array)-1 while lower < upper: if value > input_array[middle]: lower = middle + 1 middle += len(input_array[lower:]) // 2 + 1 elif value < input_array[middle]: upper = middle - 1 middle = len(input_array[0:middle]) // 2 else: return middle if value == input_array[upper]: return upper elif value == input_array[lower]: return lower return -1 test_list = [1, 3, 9, 11, 15, 19, 29] test_val1 = 25 test_val2 = 9 print(binary_search(test_list, test_val1)) print(binary_search(test_list, test_val2))