blob_id
stringlengths
40
40
repo_name
stringlengths
6
108
path
stringlengths
3
244
length_bytes
int64
36
870k
score
float64
3.5
5.16
int_score
int64
4
5
text
stringlengths
36
870k
3778d1779d42cd18e94218babea4582cd4259b93
simamumu/python_library
/数学/素因数分解.py
780
3.5625
4
# 先にふるってprimesを作る def hurui(N): koho = list(range(2,N)) prime = [] limit = math.sqrt(koho[-1]) while True: p = koho[0] if limit <= p: prime = prime + koho break else: prime.append(p) koho = [e for e in koho if e%p != 0] return prime N = 10000 MAX = 100000 primes = hurui(math.sqrt(MAX)) # N を素因数分解 def factorization(N): ans = defaultdict(int) L = len(primes) pind = 0 while N > 1: p = primes[pind] while N%p == 0: N //= p ans[p] += 1 pind += 1 if pind >= L: ans[N] += 1 break return ans facs = factorization(N) for p,n in facs.items(): print(p,n)
8db2c5b49559d9b3e9d47e21a0181948f987c6f5
carlosvcerqueira/Projetos-Python
/ex032.py
463
3.65625
4
from datetime import date ano = int(input('Que ano quer analisar? Coloque 0 para analisar o ano atual: ')) cores = {'limpa': '\033[m', 'Vermelho': '\033[1:34:31m', 'Roxo': '\033[35:45m', 'amarelo': '\033[33:33m'} if ano == 0: ano = date.today().year if ano % 4 == 0 and ano % 100 != 0 or ano % 400 == 0: print('O ano {}{}{} é BISSEXTO!'.format(cores['Vermelho'], ano, cores['limpa'])) else: print('O ano {} NÃO é BISSEXTO!'.format(ano))
59185a63ac67ccf751b061c314f744c1f628dd6b
danylagacione/Codility
/Lesson2/CyclicRotation.py
1,616
4.28125
4
# CyclicRotation # # Uma matriz A consistindo de N inteiros é fornecida. # A rotação da lista significa que cada elemento é deslocado para a direita por um índice, # e o último elemento da lista é movido para o primeiro lugar. # Por exemplo, a rotação da lista A = [3, 8, 9, 7, 6] é [6, 3, 8, 9, 7] # (os elementos são deslocados para a direita por um índice e 6 é movido para o primeiro lugar). # # O objetivo é girar a matriz A K vezes; isto é, cada elemento de A será deslocado para o K tempo certo. # # Escreva uma função: # # solução def (A, K) # # que, dada uma lista A que consiste em N números inteiros e um número inteiro K, # retorna a lista A girada K vezes. # # Por # exemplo, dado # # A = [3, 8, 9, 7, 6] # K = 3 # # a # função deve retornar[9, 7, 6, 3, 8].Foram realizadas três rotações: # # [3, 8, 9, 7, 6] -> [6, 3, 8, 9, 7] # [6, 3, 8, 9, 7] -> [7, 6, 3, 8, 9] # [7, 6, 3, 8, 9] -> [9, 7, 6, 3, 8] # Por outro exemplo, dado # # A = [0, 0, 0] # K = 1 # a função deve retornar[0, 0, 0] # # Dado # # A = [1, 2, 3, 4] # K = 4 # a função deve retornar[1, 2, 3, 4] #usar o pop para tirar o último item da lista e depois em uma variável o insert para inserir no começo da lista A = [3, 8, 9, 7, 6] def solution(A:list , k): for item in range(k): ultimo = A[-1] restante = A[:-1] A = [ultimo, *restante] return A A = [3, 8, 9, 7, 6] print(solution(A,3)) # def solution(A:list, k): # for item in range(k): # ultimo = A.pop(-1) # inserindo = A.insert(0, ultimo) # A = [ultimo, *inserindo] # return A
13e56e329d324199f27814f9669f4ba7b88c96fd
connormullett/PythonPacman
/pacman.py
882
3.53125
4
class Pacman: def __init__(self): self.total_points = 5000 self.points = 5000 self.lives = 3 self.ghost_multiplier = 200 self.lives_gained = 0 def add_points(self, points): self.points += points self.total_points += points if self.points >= 10000: self.gain_life() self.points -= 10000 def gain_life(self): self.lives += 1 self.lives_gained += 1 def lose_life(self): self.lives -= 1 def ghost_killed(self): self.ghost_multiplier *= 2 self.points += self.ghost_multiplier self.total_points += self.ghost_multiplier fruits = { 'Cherry': 100, 'Strawberry': 300, 'Orange': 500, 'Apple': 700, 'Melon': 1000, 'Galaxian': 2000, 'Bell': 3000, 'Key': 5000 }
c3050b32fdc495a20d31a07266e070fafcd074d0
optimus-kart/python-multithreading
/examples.py
12,887
3.53125
4
class Test: def __init__(self): self.tests = {} def add(self, fn, tests): self.tests[fn] = tests def run(self): for fn, tests in self.tests.items(): for test in tests: self.run_test(fn, test) def run_test(self, fn, test): test.setdefault("args", ()) test.setdefault("kwargs", {}) test.setdefault("returns", None) test.setdefault("raises", None) result = "Testing {}(".format(fn.__qualname__) if test["args"]: s = [str(x) for x in test["args"]] result += ", ".join(s) if test["kwargs"]: if test["args"]: result += ", " records = ["{}={}".format(k, str(v)) \ for k, v in test["kwargs"].items()] result += ", ".join(records) result += ") -> " result += "{}".format(test["raises"] if test["raises"] \ else test["returns"]) try: ret = fn(*test["args"], **test["kwargs"]) if ret == test["returns"]: result += ": ok." else: result += ": *** failed\n (got {})".format(ret) except Exception as e: if type(e) is not type(test["raises"]) or \ str(e) != str(test["raises"]): result += ": *** failed\n (raised {})".format(e) else: result += ": ok." print(result) ----------------------------------------------------- from time import sleep def foo(): for i in range(10): yield sleep(1) print("foo: counting {}".format(i)) def bar(): for i in range(10): yield sleep(1) print("bar: counting {}".format(i)) if __name__ == '__main__': f = foo() b = bar() while True: next(f) next(b) ----------------------------------------------------------- # https://public.etherpad-mozilla.org/p/Advanced_Python from time import sleep def foo(): for i in range(10): sleep(1) print("foo: counting {}".format(i)) def bar(): for i in range(10): sleep(1) print("bar: counting {}".format(i)) if __name__ == '__main__': from threading import Thread f = Thread(target=foo) b = Thread(target=bar) f.start() b.start() print("Two threads created...") ------------------------------------------------------------ # https://public.etherpad-mozilla.org/p/Advanced_Python from itertools import count def foo(): for i in count(): print("foo: counting {}".format(i)) def bar(): for i in count(): print("bar: counting {}".format(i)) if __name__ == '__main__': from threading import Thread f = Thread(target=foo) b = Thread(target=bar) f.start() b.start() for i in count(): print("main: counting {}".format(i)) ------------------------------------------------------------ from time import sleep def foo(): for i in range(7): print("foo: counting {}".format(i)) sleep(1) def bar(): for i in range(20): print("bar: counting {}".format(i)) sleep(1) if __name__ == '__main__': from threading import Thread f = Thread(target=foo) b = Thread(target=bar) f.start() b.daemon = True b.start() for i in range(5): print("main: counting {}".format(i)) sleep(1) ---------------------------------------------------------- from threading import Thread from time import sleep class MyThread(Thread): def __init__(self, name): Thread.__init__(self) self.thread_name = name def run(self): for i in range(10): print("{}: counting: {}".format(self.thread_name, i)) sleep(1) if __name__ == '__main__': t1 = MyThread("test-thread-1") t2 = MyThread("test-thread-2") t1.start() t2.start() ---------------------------------------------------------- """ Exercise: --------- Implement the class - RunPeriodic that allows a function to be executed at periodic intervals in a separate thread. [Available at https://public.etherpad-mozilla.org/p/Advanced_Python ] """ from threading import Thread class RunPeriodic(Thread): pass # TODO: Implement the logic here. if __name__ == '__main__': def print_test(): print("Running print_test...") def hello_world(): print("Hello world....") print_thread = RunPeriodic(5, print_test) print_thread.start() # Execute print_test() function every 5 seconds hello_thread = RunPeriodic(2, hello_world) hello_thread.start() # Execute hello_thread() function every 2 seconds from time import sleep for i in range(40): print("main thread: counting", i) sleep(0.5) # Issue a stop request to both threads after 20 seconds print_thread.stop() hello_thread.stop() # Wait for both threads to finish. print_thread.join() hello_thread.join() print("main thread: finished.") -------------------------------------------------------------- """ Exercise: --------- Implement the class - RunPeriodic that allows a function to be executed at periodic intervals in a separate thread. [Available at https://public.etherpad-mozilla.org/p/Advanced_Python ] """ from threading import Thread class RunPeriodic(Thread): def __init__(self, interval, fn, args=(), kwargs={}): Thread.__init__(self) self.interval = interval self.fn = fn self.fn_args = args self.fn_kwargs = kwargs def run(self): from time import sleep while not hasattr(self, "cancel"): self.fn(*self.fn_args, **self.fn_kwargs) sleep(self.interval) def stop(self): self.cancel = True if __name__ == '__main__': def print_test(): print("Running print_test...") def hello_world(): print("Hello world....") print_thread = RunPeriodic(5, print_test) print_thread.start() # Execute print_test() function every 5 seconds hello_thread = RunPeriodic(2, hello_world) hello_thread.start() # Execute hello_thread() function every 2 seconds from time import sleep for i in range(40): print("main thread: counting", i) sleep(0.5) # Issue a stop request to both threads after 20 seconds print_thread.stop() hello_thread.stop() # Wait for both threads to finish. print_thread.join() hello_thread.join() print("main thread: finished.") ------------------------------------------------------------------ from time import sleep from threading import Thread, current_thread def foo(): current = current_thread() for i in range(20): if hasattr(current, "cancel"): break print("foo: counting {}".format(i)) sleep(1) if __name__ == '__main__': f = Thread(target=foo) f.start() for i in range(5): print("main: counting {}".format(i)) sleep(1) f.join(2) if (f.is_alive()): f.cancel = "True" f.join() print("main: foo joined...") ----------------------------------------------------------------------- from random import random from time import sleep from threading import Thread a = [10, 2, 4, 5, 6, 7] b = [2, 3, 4] def square(coll): for i, v in enumerate(coll): coll[i] = v * v sleep(random()) def cube(coll): for i, v in enumerate(coll): coll[i] = v ** 3 sleep(random()) if __name__ == '__main__': print(a, b) s = Thread(target=square, args=(a,)) c = Thread(target=cube, args=(b,)) threads = [(s, a), (c, b)] s.start() c.start() while threads: t, r = threads.pop() t.join(0.1) if not t.is_alive(): print(r) else: threads.insert(0, (t, r)) ----------------------------------------------------------- from __future__ import print_function from threading import Thread SIZE = 100000 a = list(range(SIZE)) def square_list_item(i): a[i] = a[i] * a[i] def square_list(): for i in range(SIZE): square_list_item(i) if __name__ == '__main__': t1 = Thread(target=square_list) t2 = Thread(target=square_list) # b = a.copy() b = list(a) t1.start() t2.start() t1.join() t2.join() for i, v in enumerate(a): if (b[i] ** 4) != v: print("a[{}] = {} NOT consistent with b[{}] ** 4 = {}".format( i, v, i, b[i] ** 4)) ------------------------------------------------------------------- from __future__ import print_function from threading import Thread, Lock SIZE = 100000 a = list(range(SIZE)) lock = Lock() def square_list_item_old(i): try: lock.acquire() a[i] = a[i] * a[i] finally: lock.release() def square_list_item(i): with lock: a[i] = a[i] * a[i] def square_list(): for i in range(SIZE): square_list_item(i) if __name__ == '__main__': t1 = Thread(target=square_list) t2 = Thread(target=square_list) # b = a.copy() b = list(a) t1.start() t2.start() t1.join() t2.join() for i, v in enumerate(a): if (b[i] ** 4) != v: print("a[{}] = {} NOT consistent with b[{}] ** 4 = {}".format( i, v, i, b[i] ** 4)) ------------------------------------------------------------------------- def access_url(method, url): import requests from time import time if hasattr(requests, method): start = time() response = getattr(requests, method)(url) duration = time() - start output = "{} {} took {} seconds with response code {}" print(output.format(method.upper(), url, duration, response.status_code)) def benchmark_urls(filename): with open(filename) as url_file: for line in url_file: method, url = line.strip().split(" ") access_url(method.lower(), url) if __name__ == '__main__': from argparse import ArgumentParser parser = ArgumentParser() parser.add_argument("filename", help="path to a text file containing list of URLs") args = parser.parse_args() benchmark_urls(args.filename) -------------------------------------------------------------------------------- from threading import Thread, Condition, Lock from time import sleep from random import randint from collections import deque class SimpleQueue: def __init__(self, size=10): self.empty_slots = size self.queue = deque() self.empty = Condition() self.full = Condition() self.lock = Lock() def show(self): with self.lock: r = str(self.queue) return r def put(self, v): with self.full: if not self.empty_slots: self.full.wait() with self.empty: with self.lock: self.queue.append(v) self.empty_slots -= 1 self.empty.notify() def get(self): with self.empty: if len(self.queue) == 0: self.empty.wait() with self.full: with self.lock: v = self.queue.popleft() self.empty_slots += 1 self.full.notify() return v queue = SimpleQueue(10) def producer(): while True: v = randint(1, 100) print("Produced: ", v, "Queue =", queue.show()) queue.put(v) sleep(v / 200) def consumer(): while True: v = queue.get() print("Consumed: ", v, "Queue =", queue.show()) sleep(v / 100) p = Thread(target=producer) c = Thread(target=consumer) p.start() c.start() ----------------------------------------------------- from threading import Thread, Semaphore, Lock from time import sleep from random import randint from collections import deque class SimpleQueue: def __init__(self, size): self.queue = deque() self.reader = Semaphore(0) self.writer = Semaphore(size) self.lock = Lock() def show(self): with self.lock: s = str(self.queue) print(s) def put(self, v): self.writer.acquire() with self.lock: self.queue.append(v) self.reader.release() def get(self): self.reader.acquire() with self.lock: v = self.queue.popleft() self.writer.release() return v queue = SimpleQueue(10) def producer(): while True: v = randint(1, 100) print("Produced: ", v) queue.put(v) # sleep(v/100.0) def consumer(): while True: v = queue.get() print("Consumed: ", v) sleep((v / 100.0) + 0.3) p = Thread(target=producer) c = Thread(target=consumer) p.start() c.start()
d4149e54be8afa247dae476fd8cc5f242cff77f6
sebanazarian/itedes
/modulo1/segmento3/examenFinal/autosABM.py
2,895
3.703125
4
def agregarAutos(autos): auto={} patente = input("Ingrese patente del Auto: ") patenteDuplicada = verificarPatente(patente) while patenteDuplicada=="si": print("Patente Existente ingrese nuevamente") patente = input("Ingrese patente del Auto: ") patenteDuplicada=verificarPatente(patente) auto['patente']= patente auto['marca']=input("Ingrese marca del Auto: ") auto['modelo']=input("Ingrese modelo del Auto: ") auto['color']=input("Ingrese color del Auto: ") autos.append(auto) return autos def verificarPatente(patenteAuto): for auto in autos: if auto['patente']==patenteAuto: return "si" return "no" def modificarAutoxPatente(autos,patenteAuto): i=0 contador=0 for auto in autos: if auto['patente']==patenteAuto: opcionMenuModificar='' while opcionMenuModificar !="0": print("1-Modificar Pantente") print("2-Modificar Marca") print("3-Modificar modelo") print("4-Modificar Color") print("0-Salir") print("") opcionMenuModificar=input("Ingrese la opcion deseada: ") if opcionMenuModificar== "1": patente = input("Ingrese patente del auto: ") patenteDuplicada = verificarPatente(patente) while patenteDuplicada=="si": print("Patente Existente ingrese nuevamente") patente = input("Ingrese patente del Auto: ") patenteDuplicada=verificarPatente(patente) autos[i]['patente'] = patente elif opcionMenuModificar== "2": autos[i]['marca'] = input("Ingrese marca del auto: ") elif opcionMenuModificar=="3": autos[i]['modelo'] = input("Ingrese modelo del auto: ") elif opcionMenuModificar=="4": autos[i]['color'] = input("Ingrese color del auto: ") contador= contador +1 i=i+1 if contador == 0: print("No existe el auto") def eliminarAuto(autos,patenteAuto): contador=0 i=0 for auto in autos: if auto['patente']==patenteAuto: del autos[i] contador= contador +1 i=i+1 if contador == 0: print("No existe el auto") def escribirArchivo(listaAutos): with open('listAutos.txt', 'w') as fileAutos: fileAutos.writelines("%s\n" % lista for lista in listaAutos ) def limpiar(): os.system('clear') #main import os autos=[] opcionMenu='' while opcionMenu !="0": print("1-Cargar Auto") print("2-Modificar Auto") print("3-Baja de Auto") print("4-Mostrar Lista") print("0-Salir") print("") opcionMenu=input("Ingrese la opcion deseada: ") opcion='si' if opcionMenu == "1": while opcion!='no': autos=agregarAutos(autos) limpiar() opcion=input("Desea agregar otro auto: ") escribirArchivo(autos) elif opcionMenu=="2": print("2") patenteAuto=input("Ingresela patente del auto a modificar: ") modificarAutoxPatente(autos,patenteAuto) elif opcionMenu=="3": patenteAuto=input("Ingresela patente del auto a eliminar: ") eliminarAuto(autos,patenteAuto) elif opcionMenu=="4": print(autos)
5b3179b3ae4405bb75a8f7ab5728ff1629a0b717
SingleMaltose/DSP_Optimizing_With_Python
/Loop_Bound_Calc.py
3,801
3.546875
4
# -*- coding: utf-8 -*- """ Created on Tue Aug 27 14:18:53 2019 This is the straight-forward implementation of algorithms in Chaptr 2, "Iteration Bound" of "VLSI Digital Signal Processing Systems". The class 'Graph' contains 2 algorithm for calculating iteration bound of dsp graph, named "Longest Path Matrix(LPM)" and "Minimum Cycle Mean(MCM)" LPM algorithm is O(d^4+de) complexity in which d is the number of delay unit and e is the number of computing unit MCM algorithm is O(de+de') complexity in which e' is the number of side of the dsp graph @author: Singlemaltmaltose """ import numpy as np class Graph(object): def __init__(self,node_calc_time, graph_matrix, graph_delay_matrix): self.node_calc_time = node_calc_time # graph_matrix是以计算单元为节点的图对应的矩阵M, M(i,j)为从第i个计算单元为尾 # 指向第j个计算单元的箭头的延迟数,若不存在i到j的箭头,则M(i,j)=-1 # notes:在后面的章节中对于i到j不存在的箭头将改为M(i,j)=None self.graph_matrix = graph_matrix # graph_delay_matrix是以延迟单元为节点的图对应的矩阵graph_delay_matrix, # graph_delay_matrix(i,j)为从第i个延迟单元为尾,指向第j个延迟单元的箭头, # 且中间不包含其他延迟单元的路径中,最大的总计算时长, # 若不存在i到j且中间无其他延迟单元的箭头,则graph_delay_matrix(i,j)=-1 # notes:在后面的章节中对于i到j不存在的箭头将改为graph_delay_matrix(i,j)=None self.graph_delay_matrix = graph_delay_matrix def print_graph(self): print(self.graph_matrix) def if_looped_graph(self): g_mat = self.graph_matrix w = g_mat.shape[1] for i in range(w): if np.max(g_mat[:,i])<0: g_mat[i,:] = -1 if np.max(g_mat)<0: return g_mat,False else: return g_mat,True def calc_loop_bound_LPM(self): graph_delay_matrix = self.graph_delay_matrix w = graph_delay_matrix.shape[1] L = [graph_delay_matrix] for i in range(1,w): L_temp = np.zeros([w,w],dtype=int) for j in range(w): for k in range(w): L_temp[j][k] = -1 for m in range(w): if L[0][j][m] != -1 and L[i-1][m][k] != -1: if L[0][j][m] + L[i-1][m][k] > L_temp[j][k]: L_temp[j][k] = L[0][j][m] + L[i-1][m][k] L.append(L_temp) bound_candidates=[] for i in range(w): bound_candidates += list(np.diag(L[i])/(i+1)) loop_bound = max(bound_candidates) return loop_bound def calc_loop_bound_MCM(self): graph_delay_matrix = self.graph_delay_matrix w = graph_delay_matrix.shape[1] f0 = 100000 * np.ones([w,1],dtype=int) f0[0] = 0 f = [f0] for i in range(w): f_temp = np.zeros([w,1],dtype=int) for j in range(w): f_temp[j] = int(min([f[i][k]-graph_delay_matrix[k,j] \ for k in range(w) \ if graph_delay_matrix[k,j] >=0])) if f_temp[j] > 10000: f_temp[j] = 100000; f.append(f_temp) bound_candidates=np.concatenate([(f[w]-f[i])/(w-i) for i in range(w)],axis=1) loop_bound = -min(bound_candidates[range(w),np.argmax(bound_candidates,axis=1)]) return loop_bound
3305512104f41a73ce7a94a26c13a232c575bed7
alexganwd/coderdojo
/projects/2019-2020/week2/askforuserinput.py
405
4.3125
4
#Ask user for information operator = input("Introduce an operation\n") number1 = int(input("Introduce your first number\n")) number2 = int(input("Introduce your second number\n")) #Present information back to the user print("The operation selected is " + operator) if operator == '+': result = number1 + number2 print(result) elif operator == '-': result = number1 - number2 print(result)
392c88b63a163b7bc2a569599facfa62f40da343
humachine/AlgoLearning
/leetcode/Done/500_KeyboardRow.py
1,382
4.125
4
#https://leetcode.com/problems/keyboard-row/ '''Given a List of words, return the words that can be typed using letters of alphabet on only one row's of the Qwerty keyboard. Inp: ["Hello", "Alaska", "Dad", "Peace"] Out: ["Alaska", "Dad"] ''' class Solution(object): def findWords(self, words): result = [] TOP, MIDDLE, BOTTOM = 0, 1, 2 # ROWS contains the letters seen in each row of the keyboard ROWS = ['qwertyuiop', 'asdfghjkl', 'zxcvbnm'] for word in words: if word: row = None # We use the first character of the word to determine its intended row. if word[0].lower() in ROWS[TOP]: row = TOP elif word[0].lower() in ROWS[MIDDLE]: row = MIDDLE elif word[0].lower() in ROWS[BOTTOM]: row = BOTTOM # We then check if the rest of the word matches the row of the first letter for char in word[1:]: if char.lower() not in ROWS[row]: break # If all characters belong to the same row (break was not encountered), then append word to result. else: result.append(word) return result s = Solution() print s.findWords(["Hello", "Alaska", "Dad", "Peace"])
7f1bcfa1aee24dd1c195ea05af9c9c3667b497fc
aifulislam/Demo_First_Python_Coding
/program11.py
1,945
4.4375
4
#Inner If Statement-------- if 6>4: if 6>3: if 7>2: print('Hi') if 6<9: if 4<6: if 5<6: if 9<8: print('Hi') else: print('hello') #Lage number find of three numbers----- num1 = 90 num2 = 80 num3 = 50 if num1>num2: if num1>num3: print(num1) else: print(num3) if num2>num1: if num2>num3: print(num2) else: print(num3) #Lage number find of three numbers----- num4 = 50 num5 = 70 num6 = 60 if num4>num5: if num4>num6: print(num4) else: print(num6) else: if num5>num6: print(num5) else: print(num6) #Ternary Operator----- num7 = 50 num8 = 60 ''' if num7>num8: print(num7) else: print(num8) ''' max = num7 if num7>num8 else num8 print('Max = ',max) #Logical operator-----and--or--not--- #Find Large Number---using-and------- ''' num10 = 70 num11 = 80 num12 = 90 if num10>num11 and num10>num12 : print(num10) elif num11>num10 and num11>num12: print(num11) else: print(num12) ''' num10 = 90 num11 = 80 num12 = 60 if num10>num11 and num10>num12: print(num10) elif num11>num10 and num11>num12: print(num11) else: print(num12) #Logical operator-----and--or--not--- #Find Vowel(a,e,i,o,u)---using-or------- ch='a' if ch=='a' or ch=='e' or ch=='i' or ch=='o' or ch=='u' \ or ch=='A' or ch=='E' or ch=='I' or ch=='O' or ch=='U': print('Vowel') else: print('Consonant') #Logical operator-----and------- # Letter Grade Program-----GPA-- mark = 55 if mark>=80 and mark<=100: print('A+') elif mark>=70 and mark<=79: print('A') elif mark>=60 and mark<=69: print('A-') elif mark>=50 and mark<=59: print('B') elif mark>=40 and mark<=49: print('C') elif mark>=33 and mark<=39: print('D') else: print('F')
0c0cbea05af8a9f6ba575e74fe9c9aad540d774f
jcroskrey/csc121
/lab6/chapter9.py
2,806
3.828125
4
# Problem 1 def prob_1(): for i in range(10): print("*", end=" ") # Problem 2 def prob_2(): for i in range(10): print("*", end=" ") print() for i in range(5): print("*", end=" ") print() for i in range(20): print("*", end=" ") print() # Problem 3 def prob_3(): for i in range(10): print() for j in range(10): print("* ", end="") # Problem 4 def prob_4(): for i in range(10): print() for j in range(5): print("* ", end="") # Problem 5 def prob_5(): for i in range(5): print() for j in range(20): print("* ", end="") # Problem 6 def prob_6(): for i in range(10): print() for j in range(10): print(i, end=" ") # Problem 7 def prob_7(): for i in range(10): print() for j in range(10): print(i, end=" ") # Problem 8 def prob_8(): for i in range(10): print() for j in range(i+1): print(j, end=" ") # Problem 9 def prob_9(): for i in range(10): print() for n in range(i): print(" ", end=" ") for j in range(10-i): print(j, end=" ") # Problem 10 def prob_10(): for i in range(10): print() for row in range(10): if i*row < 10: print(" ", end=" ") else: print(" ", end="") print(i*row, end=" ") # Problem 11 def prob_11(): for i in range(10): print() for n in range(10-i): print(" ", end=" ") for row in range(1,1+i): print(row, end=" ") for j in range(i-1,0,-1): print(j, end=" ") # Problem 12 def prob_12(): for i in range(10): print() for n in range(10-i): print(" ", end=" ") for row in range(1,1+i): print(row, end=" ") for j in range(i-1,0,-1): print(j, end=" ") for i in range(10): print() for n in range(i): print(" ", end=" ") for j in range(9-i): print(j+1, end=" ") # Problem 13 def prob_13(): for i in range(10): print() for n in range(10-i): print(" ", end=" ") for row in range(1,1+i): print(row, end=" ") for j in range(i-1,0,-1): print(j, end=" ") for i in range(10): print() for n in range(i+2): print(" ", end=" ") for j in range(1, 9-i): print(j, end=" ") for j in range(7-i, 0, -1): print(j, end=" ") prob_1() prob_2() prob_3() prob_4() prob_5() prob_6() prob_7() prob_8() prob_9() prob_10() prob_11() prob_12() prob_13()
7c7386287f6763affff9ee436cd8af213178f160
applutree/Python-Repo
/practicepython_practice1.py
436
4.15625
4
from datetime import date name = input("What is your name? ") age = int(input("what is your age? ")) current_date = date.today() year_to_100 = (current_date.year - age) + 100 print("Hello " + name + ", you will turn 100 years old in ", year_to_100, " years." ) iter_num = int(input("Enter number of iteration: ")) for i in range(iter_num): print("Hello " + name + ", \nyou will turn 100 years old in ", year_to_100, " years." )
9ff04bf2695a433287aecb4736e27e2d0d3dc216
zerghua/leetcode-python
/N1323_Maximum69Number.py
1,130
4.0625
4
# # Create by Hua on 4/16/22. # """ You are given a positive integer num consisting only of digits 6 and 9. Return the maximum number you can get by changing at most one digit (6 becomes 9, and 9 becomes 6). Example 1: Input: num = 9669 Output: 9969 Explanation: Changing the first digit results in 6669. Changing the second digit results in 9969. Changing the third digit results in 9699. Changing the fourth digit results in 9666. The maximum number is 9969. Example 2: Input: num = 9996 Output: 9999 Explanation: Changing the last digit 6 to 9 results in the maximum number. Example 3: Input: num = 9999 Output: 9999 Explanation: It is better not to apply any change. Constraints: 1 <= num <= 104 num consists of only 6 and 9 digits. """ class Solution(object): def maximum69Number(self, num): """ :type num: int :rtype: int thought: scan from left to right, find the first 6 and change it to 9, and return. 04/16/2022 10:14 Accepted 19 ms 13.5 MB python easy 1 min. string replace """ return str(num).replace("6", "9", 1)
25d68d2472cac4d36be00e2d9217465f17f55196
filipbartek6417/RegexEngine
/Regex Engine/task/regex/regex.py
260
3.84375
4
pair = input().split('|') match = 'True' for index, item in enumerate(pair[0]): try: if item != pair[1][index] and item != '.': match = 'False' break except IndexError: match = 'False' break print(match)
2d041e4fde674f00c30e90ca3c8571de3e7047d2
Graunarmin/Krypto_SS18
/handy_python_stuff/my_lib.py
2,918
3.640625
4
''' Sammlung von nützlichen Funktionen import my_lib ''' def ggT(s,e): ''' ggT von s und e mit dem euklidschen Algorithmus bestimmen ''' tmp = 0 if s < e: tmp = e e = s s = tmp while True: r = s % e if r == 0: break s = e e = r #print (e) return e def mult_inv(x, Z_n): ''' Multiplikatives Inverses von x in Zn bestimmen ''' if ggT(x, Z_n) == 1: for i in range (0, Z_n +1): if ((i * x) % Z_n) == 1: #print(i) return i else: print("Es existiert kein multiplikatives Inverses zu %s in Z_%s." %(x, Z_n)) return(-1) def ordnung(a, p, e): ''' Ordnung des Elements a in Z_p mit neutralem Element e \n ord(a) = {min(n € N | a**n = e), falls existent, sonst unendlich} ''' for n in range(1, p): if ((a ** n) % p) == e : #print(n) return n print("infinitive") return(-1) def generator(p): ''' Generatoren der Gruppe Z_p bestimmen \n wenn in mod n {a, a^2, a^3, ..., a^n} = Z_n, dann ist a Generator von Z_n \n GEHT NUR FÜR PRIMZAHLEN und nur für multiplikative Gruppen! ''' Z_p = [i for i in range(1,p)] print(Z_p) A = [] generators = [] for a in range(0, p): for z in range(0, p*3): x = (a**z) % p if x not in A: A.append(x) A.sort() if A == Z_p: generators.append(a) A = [] if generators: print("Z_%s ist zyklisch und hat folgende(n) Generator(en):" %p) # print(generators) return generators def order_of_gi(g, i, p, e): ''' Ordnung von g^i in Z_p mit neutralem Element e \n ord(g^i) = (ord(g))/ ggT((ord(g)), i) ''' ord_g = ordnung(g, p, e) ord_gi = ord_g / ggT(ord_g, i) return ord_gi def aver_ord(g, n, e): ''' average order of elements is the sum of orders of the groups elements divided by the order of the group \n av_ord(g^ab) = sum(ord(g))/|G| \n g = Generator von Z_n \n n = Primzahl p \n e = neutrales Element \n a,b = zufällige Elemente aus Z_n \n (takes some time! About 20-25 minutes?) ''' sum_ = 0 for a in range (1, n): for b in range(1, n): counter += 1 sum_ += order_of_gi(g, (a*b), n, e) average_order = sum_ / ((n-1)*(n-1)) return average_order
3415154c7002758264b5680b732b61fff43523b7
clouds16/intro-python
/week7/test_roll.py
866
3.875
4
import random as r class Dice: def __init__(self): self.numdice = 2 # number of dice self.numfaces = 6 def rollDice(self): diceRolls = [] for i in range(self.numdice): roll = r.randint[1, self.numfaces] return diceRolls def main(): count = 0 dice = Dice() diceroll = dice.rollDice() usersum = int(input("Roll until what sum")) rolls = [] while True: if usersum < 1*dice.numdice or usersum > 6*dice.numdice: print("please choose a values between 2 and 12") else: break while True: dice = Dice() diceroll = dice.rollDice() if diceroll != usersum: print(diceroll, sum(diceroll)) rolls.append(diceRolls) else: print("done ", len(rolls)) break main()
9f022b590c08cb293c7369dcfd4cd7bca9fed85b
amrithajayadev/misc
/dp/trapping_rain_water.py
889
3.765625
4
def greatest_element_right(nums): output = [nums[-1],] for i in range(len(nums) - 2, -1, -1): output.append(max(nums[i], output[-1])) print(output[::-1]) return output[::-1] def greatest_element_left(nums): output = [] for i in range(len(nums)): if not output: output.append(nums[i]) else: output.append(max(output[i-1], nums[i])) print(output) return output # nums = [2, 1, 5, 6, 2, 3, 2, 2] # [-1, 2, -1, -1, 6, 6,3,2] # nearest_greatest_element_left(nums) def rain_water_trapped(heights): ngl = greatest_element_left(heights) ngr = greatest_element_right(heights) water = 0 for i in range(len(heights)): water += min(ngr[i], ngl[i]) - heights[i] return water heights = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1] # heights = [4,2,0,3,2,5] print(rain_water_trapped(heights))
02eb0671b97df8276f876ff814827f595ae072b0
jorinvo/r
/substitution_cipher/encrypt.py
730
3.65625
4
import argparse import sys default_abc = 'abcdefghijklmnopqrstuvwxyz ' def main(): # Parse ars parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter ) parser.add_argument( 'abc', type=str, help='' ) args = parser.parse_args() abc = args.abc # Validate alphabet if sorted(abc) != default_abc: print('abc has wrong length, illegal characters or duplicates', file=sys.stderr) exit(1) substitutions = dict(zip(default_abc, abc)) substitutions['\n'] = '' for line in sys.stdin: print(''.join(substitutions[c] for c in line)) if __name__ == "__main__": main()
5a67eb8cc78796e1ce82b64c8f08647e1f9857ea
ColeDavis99/BST
/TESTING_creation_insertion_deletion.py
2,767
3.734375
4
import random #File 1 generates a C++ program to test BST values (insertion and deletion) #File 2 generates a listing of numbers I can put into visualgo.com and #See what the BST I just made looks like file1 = open("test1.txt","w") file2 = open("test2.txt","w") file1.write("#include \"header.h\"\n") file1.write("#include \"bst.hpp\"\n") file1.write("#include \"node.hpp\"\n\n") file1.write("int main()\n") file1.write("{\n") ''' L1 stores listing of 1000 random numbers from 1-1000 inclusive in the order they were gen. L2 stores either "None" or 1. The index number represents y/n the number is found in L1 L3 stores the final listing of AT MOST 1000 unique elements numbered 1-1000 inclusive. ''' MAX_NUM_NODES = 20 L1 = [None] * int(MAX_NUM_NODES+1) L2 = [None] * int(MAX_NUM_NODES+1) L3 = [None] * int(MAX_NUM_NODES+1) for a in range(500): L1 = [None] * int(MAX_NUM_NODES+1) L2 = [None] * int(MAX_NUM_NODES+1) L3 = [None] * int(MAX_NUM_NODES+1) #Genereate 100 numbers 1-100 inclusive for i in range(MAX_NUM_NODES): randomNum = random.randint(1,MAX_NUM_NODES) L1[i] = randomNum #print(L1) #print("\n\n") #Store whether or not a number was generated in L2, index # is the # generated for q in range(MAX_NUM_NODES): L2[L1[q]] = 1 #print(L2) #print("\n\n") #Create a unique listing of all numbers generated (Every element in list is unique) ctr = 0; for z in range(MAX_NUM_NODES): if(L2[L1[z]] == 1): L2[L1[z]] = None L3[ctr] = L1[z] ctr += 1 #Chop off the extra "Nones" L3 = L3[:ctr] #print(L3) ''' GENERATED C++ NODE INSERTION CODE BELOW ''' length = len(L3) for k in range(length): #Generate the code that creates the BST with the first # that was generated if(k == 0): file1.write("\n\n\n\n\tBST<int,string> bst"+str(a)+"(Node<int, string> ("+str(L3[k])+", \"RootVal\"));\n") else: file1.write("\tbst"+str(a)+".emplace(Node<int, string>("+str(L3[k])+", \"value\"));\n") #Remove last comma in the number listing if(k == length-1): file2.write(str(L3[k])) else: file2.write(str(L3[k]) + ",") ''' GENERATED C++ NODE DELETION CODE BELOW ''' #Shuffle order of L3 for delete functionality random.shuffle(L3) for n in range(length): file1.write("\n\tbst"+str(a)+".ascend_printout(bst"+str(a)+".getRoot());") file1.write("\n\tbst"+str(a)+".deleteNode(bst"+str(a)+".at("+str(L3[n])+")->getKey());") #file1.write("\n\tbst"+str(a)+".ascend_printout(bst"+str(a)+".getRoot());\n") file1.write("\n\treturn 0;\n}") file1.close() file2.close()
91d7bea7bca7643d173d2f94bde593b13f3687b6
Lujinjian-hunan/python_study
/课堂笔记/day4/文件操作2.py
805
3.65625
4
# f = open('user.txt') # f.close() # with open('user.txt',encoding='utf-8') as f: #文件对象,文件句柄 # for line in f: # print(line) # line = line.strip() # if line: # print(line) #1、读取到文件所有内容 #2、替换 new_str #3、清空原来的文件 #4、写进去新的 #新的 import os # 打开a文件,再以只写的方式新建一个新文件 with open('words.txt') as fr,open('words_new.txt','w') as fw: for line in fr: line = line.strip() if line: # 把读取到的内容替换成大写再写入新文件中 line = line.upper() fw.write(line+'\n') # 用os模块的方法删除原文件再把新文件重命名为a os.remove('words.txt') os.rename('words_new.txt','words.txt')
21660b9a8b185b249efbbabbc41ee99c4dd65da9
trgeiger/algorithms
/hackerrank/2d-array-ds.py
1,879
3.671875
4
""" Context Given a 2D Array, : 1 1 1 0 0 0 0 1 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 We define an hourglass in to be a subset of values with indices falling in this pattern in 's graphical representation: a b c d e f g There are hourglasses in , and an hourglass sum is the sum of an hourglass' values. Task Calculate the hourglass sum for every hourglass in , then print the maximum hourglass sum. Note: If you have already solved the Java domain's Java 2D Array challenge, you may wish to skip this challenge. Input Format There are lines of input, where each line contains space-separated integers describing 2D Array ; every value in will be in the inclusive range of to . Constraints Output Format Print the largest (maximum) hourglass sum found in . Sample Input 1 1 1 0 0 0 0 1 0 0 0 0 1 1 1 0 0 0 0 0 2 4 4 0 0 0 0 2 0 0 0 0 1 2 4 0 Sample Output 19 Explanation contains the following hourglasses: 1 1 1 1 1 0 1 0 0 0 0 0 1 0 0 0 1 1 1 1 1 0 1 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 1 1 0 0 0 0 2 0 2 4 2 4 4 4 4 0 1 1 1 1 1 0 1 0 0 0 0 0 0 2 4 4 0 0 0 0 0 2 0 2 0 2 0 0 0 0 2 0 2 4 2 4 4 4 4 0 0 0 2 0 0 0 1 0 1 2 1 2 4 2 4 0 The hourglass with the maximum sum () is: 2 4 4 2 1 2 4 """ """ SOLUTION """ def getHourglass(arr, i, j): return(arr[i][j]+arr[i][j+1]+arr[i][j+2]+ arr[i+1][j+1]+ arr[i+2][j]+arr[i+2][j+1]+arr[i+2][j+2]) def getLargestHG(arr): maxran = len(arr)-2 # set initial value as first hourglass maxHG = getHourglass(arr, 0, 0) for i in range(maxran): for j in range(maxran): result = getHourglass(arr, i, j) if result > maxHG: maxHG = result return maxHG print(getLargestHG(arr))
fe25dbd68bb8d7d25e650bee1341dd87c7288902
yaoyawei/Python-Learn
/Higher_order_function.py
2,933
4.1875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- print("----函数名----") f = abs print("f=abs,f(-10)=%d)"%f(-10)) #abs = 10 #abs(-10)会报错 #print("abs=10,abs(-10)=%d"%abs(-10)) f = abs def add(x, y, f): return f(x) + f(y) #add(5,-6,abs)=abs(5)+abs(-6)=11 print("add(5,-6,abs)=%d"%add(5,-6,abs)) # map() & reduce() print("----map() & reduce()----") l_map = [1,2,3,4,5,6,7,8,9] def cube(x): return x*x*x print("l_map=%s"%l_map) print("map(cube,l_map)=%s"%map(cube,l_map)) print("map(str,l_map)=%s"%map(str,l_map)) print("map(str,map(cube,l_map)=%s"%map(str,map(cube,l_map))) #reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4) from functools import reduce print("reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)") def sum_reduce(x,y): return x+y l_reduce = [n for n in range(101)] print("l_reduce = %s"%l_reduce) print("reduce(sum_reduce,l_map)=%d"%reduce(sum_reduce,l_reduce)) print("sum(l_reduce)=%d"%sum(l_reduce)) # example:filter() print("----filter()----") def is_prime_num(x): n = 2 while(n < x): if x%n == 0: return False else: n = n+1 #print("%d is a prime nummber."%x) return True # test code of is_prime_num num_test = 5000 # int(input()) #print("%d is a prime nummber:%s"%(num_test,is_prime_num(num_test))) num_test = [n for n in range(num_test)] num_test = filter(is_prime_num,num_test) print("type of num_test is %s"%type(num_test)) # type of filter is <class 'filter'> print("num_test = filter(num_test):%s"%list(num_test)) # example: sorted() print("----sorted()----") print(sorted(['bob', 'about', 'Zoo', 'Credit'])) # 默认按照ASCII的大小比较 print(sorted([36, 5, -12, 9, -21], key=abs)) # print(sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower)) # example:函数作为返回值 print("----函数作为返回值----") def lazy_sum(*args): #...... def sum(): ax = 0 for n in args: ax = ax + n return ax return sum func1 = lazy_sum(1,2,3,4,5) print("type of func1 is %s"%type(func1)) # <class 'function'> print("func1() = %d"%func1()) func2 = lazy_sum(2,3,4,5,6) print("func1 == func2:%s"%(func1==func2)) # func1 不等于 func2 # example: 匿名函数 print("----匿名函数----") print(list(map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9]))) def build(x, y): return lambda: x * x + y * y # 匿名函数作为返回值 func3 = build(3,4) print("type of func3 is %s"%type(func3)) # <class 'function'> print("func3(build(3,4)) = %d"%func3()) # 25 = 3*3 + 4*4 # example: 装饰器(Decorator) print("----decorator----") def today_date(): print("2018-10-06") print("today_date._name_:%s"%today_date.__name__) def log(func): def wrapper(*args, **kw): print('call %s():' % func.__name__) return func(*args, **kw) return wrapper @log def yesterday_date(): print("2018-10-05") yesterday_date()
36c573882bf494deda08fd1a108581afc85e87fc
rkbrian/AirBnB_clone
/models/engine/file_storage.py
1,671
3.5
4
#!/usr/bin/python3 """Module defines a class ``FileStorage`` used to serialize/deserialize python data to/from a JSON file""" import json from models.base_model import BaseModel from models.user import User from models.city import City from models.amenity import Amenity from models.place import Place from models.review import Review from models.state import State class FileStorage(): """object used to store data using a dictionary representation""" __file_path = 'file.json' __objects = {} def __init__(self): """constructor for class object ``FileStorage``""" pass def all(self): """method returns dictionary (string representation of instances)""" return self.__objects def new(self, obj): """method assigns key/pair values to private attribute ``objects``""" key = '{}.{}'.format(obj.__class__.__name__, obj.id) self.__objects[key] = obj def save(self): """method serializes innstances to a JSON file""" easyDict = {} for key, val in self.__objects.items(): easyDict[key] = val.to_dict() with open(self.__file_path, 'w') as JsFile: json.dump(easyDict, JsFile) def reload(self): """method deserializes JSON file to pythonic instances. If JSON file is missing exception is silenced""" try: with open(self.__file_path, 'r') as JsFile: json_obj = json.load(JsFile) for key, val in json_obj.items(): my_dict = '{}(**{})'.format(val['__class__'], val) self.__objects[key] = eval(my_dict) except: pass
ae3a1c03f4ec1d0911ba3bb0802f067f33632360
XIG-DATA/IPO
/ex.py
247
3.71875
4
class Question : answer = None text = None class Add(Question): def __init__(self, num1, num2): self.text = '{} + {}'.format(num1, num2) self.answer = num1 + num2 from ex import Add add1 = Add(1,2) print(add1.text) # print(add1.answer)
79b5eae90926db59af2cde5982f495e7eab1d3d6
aniGevorgyan/python
/homework.py
2,689
3.75
4
#!/usr/bin/python 3.7.2 from math_util import myFactorial # 1. Գրել ֆունկցիա, որը կընդունի 1 պարամետր՝ n, և կվերադարձնի բառարան, որի key-երն են 1-ից մինչև n֊ը, իսկ value֊ները # դրանց համապատասխան ֆակտորիալները։ def getFactorial(n): md = {} for i in range(1, n + 1): md[i] = myFactorial(i) return md # 2. Կատարել հետևյալ քայլերը․ # - Մուտքագրել նախադասություն # - Հաշվել դրա տառերի քանակը /առանց օգտվելու տողի որևիցե ֆունկցիայից/ # - Տպել նախադսությունը, ամբողջությամբ մեծատառերով։ # - Տպել նախադասությունը, որի յուրաքանչյուր բառի վերջին տառը մեծատառ է # - Ստանալ լիստ, որի էլեմենտները տվյալ նախադասության կենտ երկարություն ունեցող բառերն են # - Վերադարձնել նախադասությունում ամենաշատ և ամենաքիչ հանդիպող տառերը/1ական/ # - Դասավորել բառերը ֆայլի մեջ այբբենական կարգով, որոնց դիմաց գրել համապատասխան հակադարձ բառերը /օր․ այո - ոյա/ def getLettersLenth(ms): sLenth = 0 for i in ms: if i in ('abcdefghijklmnopqrstuvwxyzABSDEFGHIJKLMNOPQRSTUVWXYZ'): sLenth += 1 return sLenth def getUpperSentence(ms): sUpper = '' for i in ms: sUpper += i.upper() return sUpper def capitalizeLastLetter(ms): result = "" for word in ms.split(): result += word[:-1] + word[-1].upper() + " " return result def getOdds(ms): listOdd = [] for i in ms.split(): if(len(i)%2 == 1): listOdd.append(i) return listOdd def getMaxAndMinCounts(ms): md = {} for i in ms: if (i.isalpha()): md[i] = ms.count(i) max = 0 min = len(ms) max_key = min_key = "" for k, v in md.items(): if (max < v): max = v max_key = k if (min > v): min = v min_key = k return "Max - " + max_key +":" + str(max), "Min - " + min_key +":" + str(min) def writeInFile(ms): sSorted = sorted(ms.split()) f = open("test.txt", "w") for i in sSorted: f.write(i + " - " + i[::-1] + "\n") return sSorted def main(): ms = input("Your sentence here: ") print(getFactorial(14)) print(getLettersLenth(ms)) print(getUpperSentence(ms)) print(capitalizeLastLetter(ms)) print(getOdds(ms)) print(getMaxAndMinCounts(ms)) writeInFile(ms) if __name__ == "__main__": main()
a4df27d70b1ead5f05ab470fbda720679b7f1d13
Frederick-S/Introduction-to-Algorithms-Notes
/src/chapter_07/stack_optimized_tail_recursive_quick_sort.py
598
3.59375
4
from .quick_sort import partition def stack_optimized_tail_recursive_quick_sort(numbers): stack_optimized_tail_recursive_quick_sort_internal( numbers, 0, len(numbers) - 1) def stack_optimized_tail_recursive_quick_sort_internal(numbers, p, r): while p < r: q = partition(numbers, p, r) if q - p > r - q: stack_optimized_tail_recursive_quick_sort_internal( numbers, q + 1, r) r = q - 1 else: stack_optimized_tail_recursive_quick_sort_internal( numbers, p, q - 1) p = q + 1
3752b08ff2472a5373393bee0a268e968dde0133
vidgit/FAQ
/Maths/DuplicatesXOR.py
283
3.59375
4
def repeatedNumber(A): k=1 i=2 A=list(A) n=len(A) while(i<=n-1): k=k^i i+=1 temp=A[0] for j in range(1,n): temp=temp^A[j] return temp^k A=[1,1,3,4,5] print repeatedNumber(A)
f2ab002d34be50716c362ee13e0453bb1d824bff
1290259791/Python
/leetcode/book/2.4.2.py
634
3.609375
4
def MaxSum(array, n): """ 连续子数组的最大乘积 动态规划 Max=Max{a[i],Max[i-1]*a[i],Min[i-1]*a[i]}Min=Min 创建一维数组 :param array: :param n: :return: """ maxA = [0 for i in range(n)] minA = [0 for i in range(n)] maxA[0] = array[0] minA[0] = array[0] value = maxA[0] for i in range(1, n): maxA[i] = max(array[i], maxA[i - 1] * array[i], minA[i - 1] * array[i]) minA[i] = min(array[i], maxA[i - 1] * array[i], minA[i - 1] * array[i]) value = max(value, maxA[i]) print(value) List = [-2, -3, 8, -5, -2] MaxSum(List, len(List))
59e99feed18c04c2caff685907f85e119f143844
kanthuc/game-of-life
/golengine.py
1,734
3.53125
4
class Cell: neighbors = ((-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)) def __init__(self, x, y): self.x = x self.y = y def __repr__(self): return "(%i, %i)"%(self.x,self.y) def __eq__(self, other): return self.x==other.x and self.y==other.y def __hash__(self): return hash((self.x, self.y)) def get_neighbors(self): for dx, dy in Cell.neighbors: yield Cell(self.x+dx, self.y+dy) class Board: def __init__(self): self.live_cells = set() def __repr__(self): return "{%s}"%", ".join(str(cell) for cell in self.get_live_cells()) def get_live_cells(self): for cell in self.live_cells: yield cell def count_live_neighbors(self, cell): return sum(n in self.live_cells for n in cell.get_neighbors()) def stays_alive(self, cell): return 2 <= self.count_live_neighbors(cell) <= 3 def reproduces(self, cell): return self.count_live_neighbors(cell) == 3 def update(self): live_cells = set() for cell in self.live_cells: if self.stays_alive(cell): live_cells.add(cell) for n in cell.get_neighbors(): if n not in self.live_cells and self.reproduces(n): live_cells.add(n) self.live_cells = live_cells def is_alive(self, cell): return cell in self.live_cells def toggle_cell(self, cell): if cell in self.live_cells: self.live_cells.remove(cell) else: self.live_cells.add(cell) def clear_board(self): self.live_cells.clear()
70e1c716e8a2a52cee4270d1baa06fede0c2707a
liucng/python-2020-study
/第三周/凯撒密码.py
229
3.578125
4
i = str(input()) a = "" for t in i : if "a"<= t <="z": a+=chr(ord("a")+(ord(t)-ord("a")+3)%26) elif "A"<= t <="Z": a+= chr(ord("A") + (ord(t) - ord("A") + 3) % 26) else: a=a+t print(a)
701fab841832779fa67b30f20d72e065cd2ebdd7
HeartFu/LeetCode
/109. Convert Sorted List to Binary Search Tree/Solution.py
1,373
3.875
4
# Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next # Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def sortedListToBST(self, head: ListNode) -> TreeNode: def getLength(head: ListNode) -> int: ret = 0 while head: ret += 1 head = head.next return ret def buildTree(left: int, right: int) -> TreeNode: if left > right: return None mid = (left + right + 1) // 2 root = TreeNode() root.left = buildTree(left, mid - 1) nonlocal head root.val = head.val head = head.next root.right = buildTree(mid + 1, right) return root length = getLength(head) return buildTree(0, length - 1) def buildNodeList(list_pre, i): if i >= len(list_pre): return None newNode = ListNode(list_pre[i]) newNode.next = buildNodeList(list_pre, i + 1) return newNode solution = Solution() list1 = [-10,-3,0,5,9] head_org = buildNodeList(list1, 0) print(solution.sortedListToBST(head_org))
487aa13f4c25a5923263d4aeb5cd2c79e39f42d0
shen-huang/selfteaching-python-camp
/19100203/AustinJiangg/d3_exercise_calculator.py
463
3.90625
4
operator = input("请输入需要进行的运算(加,减,乘,除):") number_one = float(input("请输入第一个参数:")) number_two = float(input("请输入第二个参数:")) if operator == "加": a = number_one + number_two print(a) if operator == "减": b = number_one - number_two print(b) if operator == "乘": c = number_one * number_two print(c) if operator == "除": d = number_one / number_two print(d)
57e82995e134b2c7eefe378172c95b7b1e644051
ppyy-hub/bbbb
/py_ws/day2/e1.py
2,087
3.953125
4
# 从键盘输入一个成绩,根据成绩输出对应的等级 # 90(包含)---100(包含) A # 70(包含)---90(不包含) B # 60(包含)---70(不包含) C # 0(包含)--60(不包含) D # 其它情况,输出“无效的成绩” # score=input("请输入你的成绩") # scores=int(score) # # if scores>=90 and scores<=100: # print('A') # elif scores>=70 and scores<90: # print('B') # elif scores>=60 and scores<70: # print('C') # elif scores>=0 and scores<60: # print('D') # else: # print("其他成绩输入无效的成绩") # ''' # 猜数字游戏: # (1)提示用户“猜数字游戏开始了” # (2)指定一个数字让用户来猜 # (3)提示用户猜一个数字并获取用户猜的数字 # (4)把用户猜的数字和指定的数字进行比较 # 如果猜对了,输入“恭喜你,猜对了,可惜没有奖励!” # 如果猜错了,输出“猜错了,正确答案是 **” # (5)猜完以后输出“游戏结束了,不玩了!” # ''' # print("猜数字游戏开始了") # H=6 # number=input("输入的数字") # number=int(number) # if number == H: # print("恭喜你,猜对了,可惜没有奖励!") # else: # print("猜错了,正确答案是 **") # input("游戏结束了,不玩了!") # '''1)猜错了提示用户,猜大了还是猜小了 # (2)用户可以有3次猜的机会 # (3)猜玩两次以后提示用户"还有最后一次机会" # (4)使用random模块,里面有一个函数randint(),可产生一个随机数 # a、导入模块 # import random # b、产生随机数 # key=random.randint)#参数的意思是产生一个1(1,10-10之间的随机数 # ''' import random print("-------游戏开始了-------") H=random.randint(1,10) a=0 while a<3: b=input("请输入你猜的数字") c=int(b) if c==H: print("回答正确") break else: print("回答错误") a=a+1 if a==2: print("你还有一次机会") print("正确答案是",H)
64608e47e768e3d4a26070a157f5c805c22f63dd
azegun/python_study
/chap07/module_study/module_with.py
1,081
3.53125
4
#파일을 생성하고 + 파일 이름을 변경합니다. import os with open("original.txt", "w") as file: file.write("hello") os.rename("original.txt", "new.txt") #파일을 제거합니다 os.remove("new.txt") std_list = [["1", "김상건", 90, 80, 70], ["2", "이나연", 80, 80, 60]] if not os.path.exists("../std_list.txt"): # if os.path.isfile("std_list.txt"): with open("../std_list.txt", "w", encoding="utf-8") as f: for std in std_list: format_str = "{}, {}, {}, {}, {}\n".format(std[0], std[1], std[2], std[3], std[4]) print(std) f.write(format_str) std_list2 = [] with open("../std_list.txt", "r", encoding="utf-8") as f: for line in f: std = line.strip().split(",") print("std : ", std, type(std)) std = int(std[0]), std[1], int(std[2]), int(std[3]), int(std[4]) #투플에서 리스트로 바꿔줄떄는 list() std_list2.append(list(std)) print("파일로 읽어 들은 std_List[]", std_list2) #시스템 명령어 실행 os.system("dir")
9129d1802695e6d8ef1db2fbff28a6a0cb29e203
JasonCheng1/Sudoku-Game
/Past Versions/PreSudoku.py
2,498
3.890625
4
board = [[5, 3, 0, 0, 7, 0, 0, 0, 0], [6, 0, 0, 1, 9, 5, 0, 0, 0], [0, 9, 8, 0, 0, 0, 0, 6, 0], [8, 0, 0, 0, 6, 0, 0, 0, 3], [4, 0, 0, 8, 0, 3, 0, 0, 1], [7, 0, 0, 0, 2, 0, 0, 0, 6], [0, 6, 0, 0, 0, 0, 2, 8, 0], [0, 0, 0, 4, 1, 9, 0, 0, 5], [0, 0, 0, 0, 8, 0, 0, 7, 9]] def print_board(board: [[int]]) -> None: for i in range(len(board)): if i % 3 == 0 and i != 0: print("_______________________") for j in range(len(board[0])): if j % 3 == 0 and j != 0: print("| ", end="") if j == 8: print(board[i][j]) else: print(str(board[i][j]) + " ", end="") print("\n<_______________________>\n") def find_blank(board: [[int]]) -> (): for i in range(len(board)): for j in range(len(board[0])): if board[i][j] == 0: return (i, j) return None def valid(board, num, pos): return check_row(board, num, pos) and check_col(board, num, pos) and check_box(board, num, pos) def check_row(board, num, pos): for i in range(len(board[0])): if board[pos[0]][i] == num and i != pos[1]: return False return True def check_col(board, num, pos): for i in range(len(board)): if board[i][pos[1]] == num and i != pos[0]: return False return True def check_box(board, num, pos): x = pos[1]//3 y = pos[0]//3 for i in range(3*y, 3*y + 3): for j in range(3*x, 3*x + 3): if board[i][j] == num and (i, j) != pos: return False return True def possible(board, pos) -> []: res = [0] * 10 for i in range(len(board[0])): res[board[pos[0]][i]] += 1 for i in range(len(board)): res[board[i][pos[1]]] += 1 x = pos[1]//3 y = pos[0]//3 for i in range(3*y, 3*y + 3): for j in range(3*x, 3*x + 3): res[board[i][j]] += 1 return res def solve(board: [[int]]): pos = find_blank(board) if not pos: return True plausible = possible(board, pos) for i in range(1, 10): if plausible[i] == 0: if (valid(board, i, pos)): board[pos[0]][pos[1]] = i if(solve(board)): return True board[pos[0]][pos[1]] = 0 return False print_board(board) solve(board) print_board(board)
0ccc50990d10f40e5695365ea19a643a7af14540
Zhenye-Na/leetcode
/python/917.reverse-only-letters.py
1,589
3.8125
4
# # @lc app=leetcode id=917 lang=python3 # # [917] Reverse Only Letters # # https://leetcode.com/problems/reverse-only-letters/description/ # # algorithms # Easy (59.56%) # Likes: 1163 # Dislikes: 47 # Total Accepted: 112.6K # Total Submissions: 185.9K # Testcase Example: '"ab-cd"' # # Given a string s, reverse the string according to the following rules: # # # All the characters that are not English letters remain in the same # position. # All the English letters (lowercase or uppercase) should be reversed. # # # Return s after reversing it. # # # Example 1: # Input: s = "ab-cd" # Output: "dc-ba" # Example 2: # Input: s = "a-bC-dEf-ghIj" # Output: "j-Ih-gfE-dCba" # Example 3: # Input: s = "Test1ng-Leet=code-Q!" # Output: "Qedo1ct-eeLg=ntse-T!" # # # Constraints: # # # 1 <= s.length <= 100 # s consists of characters with ASCII values in the range [33, 122]. # s does not contain '\"' or '\\'. # # # # @lc code=start class Solution: def reverseOnlyLetters(self, s: str) -> str: if not s or len(s) == 0: return s s = [char for char in s] left, right = 0, len(s) - 1 while left < right: while left < right and not s[left].lower().isalpha(): left += 1 while left < right and not s[right].lower().isalpha(): right -= 1 if left < right: print(left, right, s[left], s[right]) s[left], s[right] = s[right], s[left] left += 1 right -= 1 return "".join(s) # @lc code=end
ada59bc04c4ce2767ae2fed7501a66fb7ab579fd
MiroslavPK/Python-OOP
/01 - Defining classes/Exercise/06 - Pokemon/project/trainer.py
1,001
3.703125
4
from project.pokemon import Pokemon class Trainer: def __init__(self, name: str): self.name = name self.pokemon = [] def add_pokemon(self, pokemon: Pokemon): if pokemon in self.pokemon: return 'This pokemon is already caught' self.pokemon.append(pokemon) return f'Caught {pokemon.pokemon_details()}' def release_pokemon(self, pokemon_name: str): pokemon_names = [pokemon.name for pokemon in self.pokemon] if pokemon_name not in pokemon_names: return 'Pokemon is not caught' del self.pokemon[pokemon_names.index(pokemon_name)] return f'You have released {pokemon_name}' def trainer_data(self): trainer_details = [ f'Pokemon Trainer {self.name}', f'Pokemon count {len(self.pokemon)}' ] pokemon_details = [f'- {pokemon.pokemon_details()}' for pokemon in self.pokemon] return '\n'.join(trainer_details + pokemon_details) + '\n'
c0f609852171585583e3c7474350aaf8a42f1f52
MKDevil/Python
/学习/6、第六部分 - 类和OOP/26、类的编写基础/1、类的编写基础.py
2,045
4.4375
4
#!/usr/bin/env python # -*- coding:utf-8 -*- # 示例一、定义类-------------------------------------------------------- class FirstClass(): def setdata(self, value): self.data = value def display(self): print(self.data) x = FirstClass() x.setdata(99) y = FirstClass() y.setdata(88) x.display() y.display() # 可以直接给类实例增加新的没有定义过的属性 x.newvalue = 'New value' print(x.newvalue) # 示例二、类的继承------------------------------------------------------ class SecondClass(FirstClass): def display(self): print('Current value = %s' % self.data) z = SecondClass() z.setdata(77) z.display() # 示例三、运算符重载---------------------------------------------------- class ThirdClass(SecondClass): def __init__(self, data): """重写构造函数""" self.data = data def __add__(self, other): """ 重写 + 运算 只适用于类实例在加号左边,否则会报错 """ return ThirdClass(self.data + other) def __str__(self): """重写 print 的方法""" return 'ThirdClass: %s' % self.data def mul(self, other): self.data *= other a = ThirdClass('abc') a.display() print(a) b = a + 'xyz' # 实例 a 传递给 self,字符串 'xyz' 传递给 other b.display() print(b) a.mul(3) print(a) # 示例四、最简单的类---------------------------------------------------- class rec: pass # 这个类,没有实例,只存在命名空间 rec.name = 'Bob' rec.age = 40 print(rec.name, rec.age) x = rec() print(x.name) print(x.__dict__.keys()) # x 的 name 属性来自于 rec,x 自身并没有额外属性 x.name = 'Tom' print(x.name) print(x.__dict__.keys()) print(x.__class__) print(rec.__dict__.keys()) # 示例五、在类外写方法-------------------------------------------------- def upper(self): return self.name.upper() print(upper(x)) rec.method = upper # 可以将外部写的方法,赋值给类 print(x.method())
ab90c5a180f4a49bbf5c64062f7049add4b3da8f
MakarVS/GeekBrains_Algorithms_Python
/Lesson_3/Check/hw_nekrasov_lesson_3/les_3_task_4_nek.py
1,216
3.65625
4
# -*- coding: utf-8 -*- """ Created on Wed Mar 4 12:01:37 2020 @author: Nekad """ # ============================================================================= # 4. Определить, какое число в массиве встречается чаще всего. #Если искомый элемент(ы) встречается в массиве несколько раз, используйте один любой по вашему выбору. # ============================================================================= import random list_len = 10 min_item = 0 max_item = 10 array = [random.randint(min_item, max_item) for _ in range(list_len)] print(f'\nИсходный массив:\n{array}\n') numbers = dict() for item in array: if item not in numbers: numbers[item] = 1 else: numbers[item] += 1 for i, j in numbers.items(): print(f'Число {i} повторяется {j} раз(а)') max_count = 0 num_max_count = [] for num in numbers: if numbers[num] > max_count: max_count = numbers[num] num_max_count = num print(f'\nОдно из самых чаще всего повторящихся чисел: {num_max_count}')
195df4d2de4aa76a02cbb6f6ace83861e818527c
frankier/apertium
/apertium-tools/scrapers-misc/kkitapNameFixer.py
887
3.65625
4
#!/usr/bin/env python3 import sys import fileinput import sys if len(sys.argv) < 2: files="kaz.bible.kkitap.txt" else: files=sys.argv[1] for line in fileinput.input(files, inplace=True): # for line in lines: #print(lines) i=0 j=0 line=line.strip() if "Патшалықтар 1" in line or "Патшалықтар 2" in line: #line="1 Самуил 1" if i<26: line=line.replace("Патшалықтар 1","Самуил 1").strip() line=line.replace("Патшалықтар 2","Самуил 2").strip() i+=1 elif "Патшалықтар 3" in line or "Патшалықтар 4" in line: line=line.replace("Патшалықтар 3","Патшалықтар 1") line=line.replace("Патшалықтар 4","Патшалықтар 2") print(line) #print("".join(lines))
7037f4717a933499345a69f09222e799bd612ab1
alex-moffat/Python-Projects
/Snippets/SQLITE_assignment.py
8,426
4.09375
4
# PYTHON: 3.8.2 # AUTHOR: Alex Moffat # PURPOSE: The Tech Academy Bootcamp - SQLITE ASSIGNMENT #============================================================================= """ TAGS: SQL, sqlite3.version, error handling, connect, cursor, execute, CREATE, INSERT, SELECT slice, upper, fetchall, executescript, 'with' sqlite3.connect() """ # ============================================================================ #===== IMPORTED MODULES import sqlite3 #========== CONNECT - establish connection to DB and print sqlite3 version def dbConnect(db): conn = None try: conn = sqlite3.connect(db) # creates a db if one does not exist print(sqlite3.version) except ValueError as e: print("DB Connection Error: {}".format(e)) finally: if conn: conn.close() # close db connection if open #========== USE CONNECTION - establish connetion to DB and return open connection def dbUse(db): conn = None try: conn = sqlite3.connect(db) # creates a db if one does not exist except ValueError as e: print("DB Connection Error: {}".format(e)) return conn #========== EXECUTE - can pass SQL statement def sqlExecute(db, statement): conn = dbUse(db) if conn != None: #===== EXECUTE try: cur = conn.cursor() # creates cursor object 'cur' cur.execute(statement) if statement[slice(0,6)].upper() == 'SELECT': #===== SELECT dataset = cur.fetchall() if conn: conn.close() return dataset elif statement[slice(0,6)].upper() == 'UPDATE': #===== UPDATE conn.commit() print(cur.rowcount, " record updated.") elif statement[slice(0,6)].upper() == 'DELETE': #===== DELETE conn.commit() print(cur.rowcount, " record deleted.") except ValueError as e: print("DB Execute Error: {}".format(e)) finally: if conn: conn.close() else: print("DB Connection Error...cannot execute SQL statement") #========== INSERT - can pass SQL db, table statement, values statement (can be single tuple or list of tuples) def sqlInsert(db, statement, iValue): conn = dbUse(db) if conn != None: #===== INSERT try: cur = conn.cursor() # creates cursor object if isinstance(iValue, list): #===== MULTIPLE ROW INSERT cur.executemany(statement, iValue) conn.commit() print(cur.rowcount, " records inserted.") elif isinstance(iValue, tuple): #===== SINGLE ROW INSERT cur.execute(statement, iValue) conn.commit() print(cur.rowcount, " record inserted.") else: print("DB INSERT Error: Values are not formatted correctly - need list or tuple") except ValueError as e: print("DB INSERT Error: {}".format(e)) finally: if conn: conn.close() else: print("DB Connection Error...cannot execute SQL statement") #============================================================= #========== ASSIGNMENT #============================================================= db = "test_database.db" tempDB = ':memory:' # saves to RAM and is gone once connection is closed def assignment(): con1 = sqlite3.connect(db) con2 = sqlite3.connect(tempDB) c1 = con1.cursor() c2 = con2.cursor() #===== create database c1.execute("CREATE TABLE IF NOT EXISTS people (firstName TEXT, lastName TEXT, age INT)") c2.execute("CREATE TABLE IF NOT EXISTS people (firstName TEXT, lastName TEXT, age INT)") #===== insert data c1.execute("INSERT INTO people VALUES ('Ron', 'Obvious', 42)") c2.execute("INSERT INTO people (firstName, lastName, age) VALUES (?, ?, ?)",('Ron', 'Obvious', 42)) con1.commit() con2.commit() #===== select data c1.execute("SELECT * FROM people") c2.execute("SELECT * FROM people") print(c1.fetchall()) print(c2.fetchall()) #===== close connection if con1: con1.close() if con2: con2.close() # database ':memory:' is gone when connection closed #===== USING 'with' to simplify code - changes are commited automatically, but still need to close the connection with sqlite3.connect(db) as con3: # c3 = con3.cursor() c3.execute("INSERT INTO people VALUES ('Alex', 'Moffat', 49)") # no need for commit c3.execute("SELECT * FROM people") # new value 'Alex Moffat' already present in database print(c3.fetchall()) if con3: # this will trigger outside with block print("Connection still open") con3.close() else: print("Connection already closed") #===== OPEN 'with' to drop table --> create table --> insert --> select --> insert --> select with sqlite3.connect(db) as con4: c4 = con4.cursor() #=== executescript() - non-parameterized code - note the comma seperated inserted values c4.executescript(""" DROP TABLE IF EXISTS people; CREATE TABLE people (firstName TEXT, lastName TEXT, age INT); INSERT INTO people VALUES ('Ron', 'Obvious', 42), ('Alex', 'Moffat', 49); """) print("===== Created new table & added 2 records =====") c4.execute("SELECT * FROM people") print(c4.fetchall()) #=== executemany() - parameterized statement that takes a list or tuple of tuples pTuple = (('Luigi', 'Vercotti', 43), ('Arthur', 'Belling', 28)) pList = [('Royal', 'Albert', 12), ('Zuli', 'Kitty', 2)] c4.executemany("INSERT INTO people VALUES (?,?,?)", pTuple) c4.executemany("INSERT INTO people VALUES (?,?,?)", pList) print("===== Insert 2 records in tuple & 2 in list =====") c4.execute("SELECT * FROM people") print(c4.fetchall()) if con4: con4.close() #===== INPUT - get data from user and insert with parameterized insert statement go = True fName = input("Enter your first name: ").title() lName = input("Enter your last name: ").title() while go: age = input("Enter your your age: ") try: age = int(age) go = False except: print('You must enter an integer for age.') data = (fName, lName, age) with sqlite3.connect(db) as con5: c5 = con5.cursor() c5.execute("INSERT INTO people VALUES (?,?,?)", data) c5.execute("UPDATE people SET age=? WHERE firstName=? AND lastName=?", (45, 'Luigi', 'Vercotti')) print("===== select records with last name 'Vercotti' or 'Moffat' =====") c5.execute("SELECT * FROM people WHERE lastName=? OR lastName=?", ('Vercotti', 'Moffat')) print(c5.fetchall()) print("===== select records with input first name =====") c5.execute("SELECT * FROM people WHERE firstName=?", (fName,)) print(c5.fetchall()) if con5: con5.close() #===== SELECT - using fetchall, fetchone, fetchmany with sqlite3.connect(db) as con6: c6 = con6.cursor() pList = [('Peep', 'Chicken', 12), ('Plurp', 'Chicken', 3), ('Papaya', 'Chicken', 3), ('Supreme', 'Chicken', 1)] c6.executemany("INSERT INTO people VALUES (?,?,?)", pList) c6.execute("SELECT firstName, lastName, age FROM people WHERE age < 30 ORDER BY age DESC") #=== NOTE: Each time you fetch a row it is gone from the retrieved dataset print("===== fetchone() =====") for row in c6.fetchone(): print(row) print("===== fetchmany(3) =====") for row in c6.fetchmany(3): print(row) print("===== fetchall() =====") for row in c6.fetchall(): print(row) print("===== count =====") c6.execute("SELECT COUNT(*) FROM people WHERE age < 30") print("The select statement had {} records before each fetch".format(c6.fetchone()[0])) print("===== fetch one row at a time =====") c6.execute("SELECT firstName, lastName, age FROM people WHERE age < 30 ORDER BY age DESC") while True: # infinite loop requires a break row = c6.fetchone() if row is None: break print(row) if con6: con6.close() if __name__ == '__main__': assignment()
487ba07c41449c775970653e3fb4d03f6720caf9
GaneshDesk/Python-Programs
/.history/Python_Basic_Programs/Sum_of_Digits_20200821205105.py
378
4.28125
4
# program to calculate sum of digit of given number. def SumFunction(n): tot = 0 while(n > 0): dig = n % 10 tot = tot+dig n = n//10 return tot if __name__ == '__main__': print("Program for sum of digit of given number") n = int(input("Enter a number:")) ret = SumFunction(n) print("The total sum of digits is:", ret)
f28b0653287a74c0dafea59e344c35ba59b054d8
no4job/WER
/SRC/wer.py
14,202
3.609375
4
# import numpy import time import Levenshtein import re import os from io import StringIO # import csv import csv_tools # import editdistance import collections def wer(r, h): """ Calculation of WER with Levenshtein distance. Works only for iterables up to 254 elements (uint8). O(nm) time ans space complexity. Parameters ---------- r : list h : list Returns ------- int Examples -------- >>> wer("who is there".split(), "is there".split()) 1 >>> wer("who is there".split(), "".split()) 3 >>> wer("".split(), "who is there".split()) 3 """ # initialisation # d = numpy.zeros((len(r)+1)*(len(h)+1), dtype=numpy.uint8) d = numpy.zeros((len(r)+1)*(len(h)+1), dtype=numpy.uint16) # d = numpy.zeros((len(r)+1)*(len(h)+1), dtype=numpy.uint32) d = d.reshape((len(r)+1, len(h)+1)) for i in range(len(r)+1): for j in range(len(h)+1): if i == 0: d[0][j] = j elif j == 0: d[i][0] = i # computation for i in range(1, len(r)+1): for j in range(1, len(h)+1): if r[i-1] == h[j-1]: d[i][j] = d[i-1][j-1] else: substitution = d[i-1][j-1] + 1 insertion = d[i][j-1] + 1 deletion = d[i-1][j] + 1 d[i][j] = min(substitution, insertion, deletion) return d[len(r)][len(h)] def Convert_to_UTF_string(compared,ref): ref_count = 0 # ref_dict = collections.OrderedDict() # compared_dict = collections.OrderedDict() wrd_dict = {} # compared_dict = {} # ref_dict = {} # compared_dict = {} for wrd in ref: wrd_dict[wrd]=chr(ref_count).encode('utf-8') ref_count += 1 for wrd in compared: wrd_dict[wrd]=chr(ref_count).encode('utf-8') ref_count += 1 # utf_code = ref_dict.get(compared_wrd,None) # if not utf_code: # utf_code = chr(ref_count).encode('utf-8') # ref_count += 1 # compared_dict[compared_wrd]= utf_code ref_str = ''.join(str(wrd_dict[wrd], encoding='utf-8') for wrd in ref) compared_str = ''.join(str(wrd_dict[wrd], encoding='utf-8') for wrd in compared) return [compared_str,ref_str] ''' def save_csv(compared,ref,edit_ops,csv_file,append = 0): out_csv = csv_tools.csvLog(csv_file,append) # header_list = sort_headers(list(get_field_type_list(patent_list))) # if append == 0: # out_csv.add_row(header_list) for patent in patent_list: csv_row = [] for header in header_list: value = filter_blank(patent.get(header) or "") value = trim_leading_signes(value) trim_leading_signes csv_row.append(value) out_csv.add_row(csv_row) # if value !=None: # csv_row.append(value) # else: # csv_row.append(value) return out_csv def syncronize_list__(lst_1,lst_2,edit_ops): deletion = [] insertion = [] replacement = [] lst_1_sync = list(lst_1) lst_2_sync = list(lst_2) for op in edit_ops: if op[0] == 'delete': deletion.append(op[1]) if op[0] == 'insert': insertion.append(op[1]) if op[0] == 'replace': replacement.append(op[1]) insertion.sort(reverse=True) for delete_position in deletion: lst_1_sync[delete_position]=">"+lst_1_sync[delete_position]+"<" for replace_position in replacement: lst_1_sync[replace_position]="|"+lst_1_sync[replace_position]+"|" for insert_position in insertion: lst_1_sync.insert(insert_position,'<>') for delete_position in range(len(lst_1_sync)): if re.match('^>[^<>]*<$',lst_1_sync[delete_position]): lst_2_sync.insert(delete_position,'') return lst_1_sync,lst_2_sync ''' def syncronize_list(lst_1,lst_2,edit_ops): deletion = [] insertion = [] replacement = [] lst_1_sync = list( [e,''] for e in lst_1) lst_2_sync = list( [e,''] for e in lst_2) for op in edit_ops: if op[0] == 'delete': deletion.append(op[1]) if op[0] == 'insert': insertion.append(op[1]) if op[0] == 'replace': replacement.append(op[1]) insertion.sort(reverse=True) for delete_position in deletion: # lst_1_sync[delete_position]=">"+lst_1_sync[delete_position]+"<" lst_1_sync[delete_position][1]='delete' for replace_position in replacement: # lst_1_sync[replace_position]="|"+lst_1_sync[replace_position]+"|" lst_1_sync[replace_position][1]='replace' for insert_position in insertion: # lst_1_sync.insert(insert_position,'<>') lst_1_sync.insert(insert_position,['','insert']) for delete_position in range(len(lst_1_sync)): # if re.match('^>[^<>]*<$',lst_1_sync[delete_position]): if lst_1_sync[delete_position][1] == 'delete': lst_2_sync.insert(delete_position,['','skip']) return lst_1_sync,lst_2_sync def get_all_syncronized_list_(ref_file_path,compared_file_dir_path, compared_file_pattern): all_syncronized_list = [] for filename in os.listdir(compared_file_dir_path): if re.match(compared_file_pattern,filename): with open(ref_file_path, 'r', encoding='utf-8') as ref_file, \ open(compared_file_dir_path+filename, 'r', encoding='utf-8') as compared_file: ref_str = ref_file.read().replace('\n', ' ').replace('\r', ' ') compared_str = compared_file.read().replace('\n', ' ').replace('\r', ' ') ref = ref_str.split() compared = compared_str.split() converted_str = Convert_to_UTF_string(compared,ref) compared_str = converted_str[0] ref_str = converted_str[1] edit_ops = Levenshtein.editops(compared_str, ref_str) # compared_sync,ref_sync = syncronize_list(compared,ref,edit_ops) syncronized_list=list(syncronize_list(compared,ref,edit_ops)) syncronized_list.append(filename) syncronized_list.append(os.path.basename(ref_file_path)) if len(ref)>0 : syncronized_list.append(len(edit_ops)/len(ref)) else: syncronized_list.append(None) all_syncronized_list.append(syncronized_list) return all_syncronized_list def get_all_syncronized_list(ref_file_path,compared_file_dir_path, compared_file_pattern): all_syncronized_list = [] for filename in os.listdir(compared_file_dir_path): if re.match(compared_file_pattern,filename): with open(ref_file_path, 'r', encoding='utf-8') as ref_file, \ open(compared_file_dir_path+filename, 'r', encoding='utf-8') as compared_file: all_syncronized_list.append(syncronize_file(ref_file,compared_file)) return all_syncronized_list def syncronize_str(ref_file,compared_str): compared_file = StringIO() compared_file.write(compared_str) result = syncronize_file(ref_file,compared_file) return result def word_count(file): with open(file,'r', encoding='utf-8') as f: str = f.read().replace('\n', ' ').replace('\r', ' ') return len(str.split()) def syncronize_file(ref_file,compared_file): # all_syncronized_list = [] # for filename in os.listdir(compared_file_dir_path): # if re.match(compared_file_pattern,filename): # with open(ref_file_path, 'r', encoding='utf-8') as ref_file, \ # open(compared_file_path, 'r', encoding='utf-8') as compared_file: ref_str = ref_file.read().replace('\n', ' ').replace('\r', ' ') compared_str = compared_file.read().replace('\n', ' ').replace('\r', ' ') ref = ref_str.split() compared = compared_str.split() converted_str = Convert_to_UTF_string(compared,ref) compared_str = converted_str[0] ref_str = converted_str[1] edit_ops = Levenshtein.editops(compared_str, ref_str) # compared_sync,ref_sync = syncronize_list(compared,ref,edit_ops) syncronized_list=list(syncronize_list(compared,ref,edit_ops)) # syncronized_list.append(filename) # syncronized_list.append(os.path.basename(compared_file_path)) syncronized_list.append(os.path.basename(compared_file.name)) syncronized_list.append(os.path.basename(ref_file.name)) if len(ref)>0 : syncronized_list.append(len(edit_ops)/len(ref)) else: syncronized_list.append(None) return syncronized_list # all_syncronized_list.append(syncronized_list) # return all_syncronized_list def syncronize_all(all_syncronized_list): all_skip_num_list =[] max_skip_num_list =[] ref_syncronized_list = [] all_compared_syncronized_list = [] for syncronized_list in all_syncronized_list: skip_num=0 # no_skip_count = 0 skip_num_list = [] for element in syncronized_list[1]: if element[1]=='skip': skip_num+=1 else: skip_num_list.append(skip_num) skip_num = 0 # if skip_num != 0: skip_num_list.append(skip_num) all_skip_num_list.append([skip_num_list,syncronized_list[2]]) for i in range(len(all_skip_num_list[0][0])): max_skip_num_list.append(max(skip_num_list[0][i] for skip_num_list in all_skip_num_list)) # no_skip_number = None no_skip_number = 0 for element in all_syncronized_list[0][1]: if element[1]!='skip': ref_syncronized_list.extend([['','skip'] for x in range(max_skip_num_list[no_skip_number])]) # ref_syncronized_list.append(['','skip']*max_skip_num_list[no_skip_number]) no_skip_number+=1 ref_syncronized_list.append(element) # if len(max_skip_num_list)== no_skip_number+1: ref_syncronized_list.extend([['','skip'] for x in range(max_skip_num_list[no_skip_number])]) ref_syncronized_list=[ref_syncronized_list,all_syncronized_list[0][3],all_syncronized_list[0][4]] for syncronized_list in all_syncronized_list: compared_syncronized_list = [] no_skip_number = 0 skip_number = 0 for element in syncronized_list[0]: # if element[1]!='delete' and element[1]!='insert': if element[1]!='delete': compared_syncronized_list.extend([['','skip'] for x in range(max_skip_num_list[no_skip_number]-skip_number)]) # ref_syncronized_list.append(['','skip']*max_skip_num_list[no_skip_number]) no_skip_number+=1 skip_number = 0 else: skip_number+=1 compared_syncronized_list.append(element) # if len(max_skip_num_list)== no_skip_number+1: compared_syncronized_list.extend([['','skip'] for x in range(max_skip_num_list[no_skip_number]-skip_number)]) all_compared_syncronized_list.append([compared_syncronized_list,syncronized_list[2],syncronized_list[4]]) return ref_syncronized_list,all_compared_syncronized_list def save_csv(ref_syncronized_list,all_compared_syncronized_list,csv_file,append = 0): out_csv = csv_tools.csvLog(csv_file,append) header_list = [ref_syncronized_list[1]] for compared_syncronized_list in all_compared_syncronized_list: header_list.append(compared_syncronized_list[1]) if append == 0: out_csv.add_row(header_list) csv_row = [ref_syncronized_list[2]] for compared_syncronized_list in all_compared_syncronized_list: csv_row.append(compared_syncronized_list[2]) if append == 0: out_csv.add_row(csv_row) for i in range(len(ref_syncronized_list[0])): csv_row = [mark_edit_op(ref_syncronized_list[0][i][0],ref_syncronized_list[0][i][1])] for compared_syncronized_list in all_compared_syncronized_list: csv_row.append(mark_edit_op(compared_syncronized_list[0][i][0],compared_syncronized_list[0][i][1])) out_csv.add_row(csv_row) return out_csv def mark_edit_op(value,edit_op): if edit_op == "skip": return value if edit_op == "delete": return '#'+value if edit_op == "insert": return '<>' if edit_op == "replace": return '@'+ value return value if __name__ == "__main__": CALC_DIR = 1 # import doctest # doctest.testmod() # print (wer("who is there".split(), "who is there 123".split())) REF_FILE_DIR_PATH = '../REF_TXT/' REF_FILE_NAME = 'ref.txt' COMPARED_FILE_DIR_PATH = '../TXT_IN/' COMPARED_FILE_NAME = 'compared.txt' OUT_CSV_FILE_DIR_PATH = '../CSV_OUT/' OUT_CSV_FILE_NAME = 'out.csv' start_time = time.clock() ref_syncronized_list = [] all_compared_syncronized_list = [] if CALC_DIR: all_syncronized_list = get_all_syncronized_list(REF_FILE_DIR_PATH+REF_FILE_NAME,COMPARED_FILE_DIR_PATH, r'^compared_\d+') ref_syncronized_list,all_compared_syncronized_list=syncronize_all(all_syncronized_list) else: with open(REF_FILE_DIR_PATH+REF_FILE_NAME, 'r', encoding='utf-8') as ref_file, \ open(COMPARED_FILE_DIR_PATH+COMPARED_FILE_NAME, 'r', encoding='utf-8') as compared_file: ref_str = ref_file.read().replace('\n', ' ').replace('\r', ' ') compared_str = compared_file.read().replace('\n', ' ').replace('\r', ' ') ref = ref_str.split() compared = compared_str.split() converted_str = Convert_to_UTF_string(compared,ref) compared_str = converted_str[0] ref_str = converted_str[1] edit_ops = Levenshtein.editops(compared_str, ref_str) print (len(edit_ops)) print (edit_ops) compared_sync,ref_sync = syncronize_list(compared,ref,edit_ops) print(ref_sync) print(compared_sync) save_csv(ref_syncronized_list,all_compared_syncronized_list, OUT_CSV_FILE_DIR_PATH+OUT_CSV_FILE_NAME,append = 0) finish_time = time.clock() print("{:.2f}s".format((finish_time-start_time))) exit(0)
265458e9a36ae2ac1ebb2189e2573d3ab9e4db48
deepaksinghcv/self_training_MNIST
/model.py
1,426
3.59375
4
'''contains a NN model for training MNIST''' import torch import torch.nn as nn class MNIST_Model(nn.Module): '''define a custom NN for MNIST''' def __init__(self, num_of_input_channels, num_of_output_channels): '''initialize the model with given channels''' super(MNIST_Model, self).__init__() self.num_of_input_channels = num_of_input_channels self.num_of_output_channels = num_of_output_channels self.create_nn() def create_nn(self): self.l1 = nn.Linear(in_features = self.num_of_input_channels, out_features = 10, bias = True) self.l2 = nn.Linear(in_features = 10, out_features = 10, bias = True) self.l3 = nn.Linear(in_features = 10, out_features = 20, bias = True) self.l4 = nn.Linear(in_features = 20, out_features = 20, bias = True) self.l5 = nn.Linear(in_features = 20, out_features = self.num_of_output_channels, bias = True) self.relu = nn.ReLU() self.softmax = nn.Softmax(dim = 1) def forward(self, x): '''define forward propagation''' x = self.relu(self.l1(x)) x = self.relu(self.l2(x)) x = self.relu(self.l3(x)) x = self.relu(self.l4(x)) x = self.relu(self.l5(x)) # x = self.softmax(x) return x if __name__ == "__main__": model = MNIST_Model(784, 10) x = torch.randn(784) output = model(x) print(output)
41c488b8ff926e02cc567ad7d9ed6724a672782b
Suoivy/RBF-Neural-Network
/RBFModel.py
25,086
3.59375
4
"""" Date:2017.4.27 Neural Network design homework Using 3-phases-RBF NN to regression author:Suo Chuanzhe email: [email protected] """ import numpy as np import time from sklearn.cluster import KMeans from scipy.spatial import distance import matplotlib.pyplot as plt class RBFModel(): # config model value """ Input: data_input(array(IN_value_num,data_num)) data_output(array(OUT_value_num,data_num) hidden_unit_number(N) """ def __init__(self, data_input = np.array([[0],[0]]), data_output = np.array([[0],[0]]), hidden_units_number = 1): self.input = data_input self.output = data_output self.data_number = self.input.shape[1] self.input_units_number = self.input.shape[0] self.hidden_units_number = hidden_units_number self.output_units_number = self.output.shape[0] self.center, self.spread, self.weight, self.bias = np.array([[], [], [], []]) self.radial_basis_input = np.array([]) self.radial_basis_function = self.sigmoid_activation self.radial_basis_function_gradient = self.sigmoid_gradient self.output_activation = self.none_activation self.output_activation_gradient = self.none_gradient self.loss_function = self.L2_loss self.loss_function_gradient = self.L2_loss_gradient self.optimizer = self.BGD_optimizer self.eval_input = np.array([]) self.eval_output = np.array([]) # Initialize values #3-Layers BP """ input: activation_function(function) activation_gradient(function) """ def initialize_parameters(self, radial_basis_function, radial_basis_function_gradient, output_activation, output_activation_gradient): self.center = 8 * np.random.rand(self.hidden_units_number, self.input_units_number) - 4 self.spread = 0.2 * np.random.rand(self.hidden_units_number, 1) + 0.1 self.weight = 0.2 * np.random.rand(self.output_units_number, self.hidden_units_number) - 0.1 self.bias = 0.2 * np.random.rand(self.output_units_number, 1) - 0.1 self.set_activation(radial_basis_function, radial_basis_function_gradient, output_activation, output_activation_gradient) # Set activation function def set_activation(self, radial_basis_function, radial_basis_function_gradient, output_activation, output_activation_gradient): self.radial_basis_function = radial_basis_function self.radial_basis_function_gradient = radial_basis_function_gradient self.output_activation = output_activation self.output_activation_gradient = output_activation_gradient # Cluster hidden unit center using Kmeans def cluster_center(self): estimator = KMeans(n_clusters = self.hidden_units_number) estimator.fit(self.input.T) self.center = estimator.cluster_centers_ alldist = distance.cdist(self.center, self.center, 'euclidean') dist = np.where(alldist == 0, alldist.max()+1, alldist) self.spread = dist.min(axis=1).reshape(self.hidden_units_number, 1) # Set evaluate dataset def set_evaluate_dataset(self, samp_input, samp_output): self.eval_input = samp_input self.eval_output = samp_output # train model """ Input: loss_function(function) loss_gradient(function) optimizer(function) learn_error(float64) max_iteration(int64) """ def train(self, loss_function, loss_gradient, optimizer, learn_error, iteration, evaluate=False, **option_hyper_param): self.loss_function = loss_function self.loss_function_gradient = loss_gradient self.optimizer = optimizer train_losses = [] eval_losses = [] param = [] elapsed_time = 0 # plt.ion() # train_fig = plt.figure() # loss_plt = train_fig.add_subplot(1, 1, 1) # loss_plt.set_title('train_loss') # loss_plt.set_xlable('train_iter') # loss_plt.set_ylable('loss') for iter in range(iteration): last_time = time.time() # Back propagation and Optimizer loss = self.optimizer(param, option_hyper_param) iter_time = time.time() - last_time elapsed_time = elapsed_time + iter_time train_losses.append(loss) # loss_plt.plot(loss, 'b-') # plt.draw() if evaluate: results, eval_loss = self.evaluate(self.eval_input, self.eval_output) eval_losses.append(eval_loss) if iter % 100 == 0: print('train iteration:%d, train loss:%f, iter time:%f, elapsed time:%f' % ( iter, loss, iter_time, elapsed_time)) if loss < learn_error: break # plt.ioff() # plt.show() if evaluate: return train_losses, eval_losses, results else: return train_losses # Forward graph configure network output def _forward(self, input_=np.array([])): if len(input_) == 0: input_ = self.input self.distance = distance.cdist(input_.T, self.center, 'euclidean').T self.radial_basis_input = self.distance / self.spread hidden_output = self.radial_basis_function(self.radial_basis_input) network_output = self.output_activation(self.weight.dot(hidden_output) + self.bias) return hidden_output, network_output # Back graph configure network gradient def _backward(self, hidden_output, network_output): hidden_gradient = self.loss_function_gradient(network_output, self.output) * self.output_activation_gradient( network_output) input_gradient = self.weight.T.dot(hidden_gradient) * self.radial_basis_function_gradient(self.radial_basis_input) delta_weight = hidden_gradient.dot(hidden_output.T) / self.data_number delta_bias = hidden_gradient.dot(np.ones((self.data_number, 1))) / self.data_number ldist = np.tile(self.input, (self.hidden_units_number, 1)) - self.center.reshape(self.input_units_number*self.hidden_units_number, 1) # shape: i*h,n ldist_gradient = (input_gradient / self.spread) / (-self.distance) delta_center = (ldist * ldist_gradient.repeat(self.input_units_number, 0)).sum(axis=1).reshape(self.hidden_units_number, self.input_units_number) / self.data_number delta_spread = (input_gradient * (-self.distance * np.power(self.spread, -2))).dot(np.ones((self.data_number, 1))) / self.data_number return delta_center, delta_spread, delta_weight, delta_bias # evaluate model def evaluate(self, input, output, ): hidden_output, network_output = self._forward(input) loss = self.loss_function(network_output, output) return network_output, loss # predict def predict(self, input): output = self._forward(input) return output ### Optimizer Functions ### # Batch Gradient Descent (BGD) def BGD_optimizer(self, param, hyper_param={'learn_rate': 0.01}): # Initialize variables try: learn_rate = hyper_param['learn_rate'] except: print('BGD_optimizer have no "learn_rate" hyper-parameter') return # Forward propagation hidden_output_, network_output_ = self._forward() # Loss function loss_ = self.loss_function(network_output_, self.output) # Backward propagation delta_center, delta_spread, delta_weight, delta_bias = self._backward(hidden_output_, network_output_) extended_gradient = self.extend_variables(delta_center, delta_spread, delta_weight, delta_bias) extended_variables = self.extend_variables(self.center, self.spread, self.weight, self.bias) # Updata variables extended_delta = learn_rate * extended_gradient extended_variables = extended_variables - extended_delta self.center, self.spread, self.weight, self.bias = self.split_weights(extended_variables) return loss_ # Momentum def Momentum_optimizer(self, param, hyper_param={'learn_rate': 0.01, 'momentum_rate': 0.9}): # Initialize variables if len(param) == 0: param.append(np.zeros(1)) # last delta_weights and delta_biases try: learn_rate = hyper_param['learn_rate'] except: print('Momentum_optimizer have no "learn_rate" hyper-parameter') return try: momentum_rate = hyper_param['momentum_rate'] except: print('Momentum_optimizer have no "momentum_rate" hyper-parameter') return # Forward propagation hidden_output_, network_output_ = self._forward() # Loss function loss_ = self.loss_function(network_output_, self.output) # Backward propagation delta_center, delta_spread, delta_weight, delta_bias = self._backward(hidden_output_, network_output_) extended_gradient = self.extend_variables(delta_center, delta_spread, delta_weight, delta_bias) extended_variables = self.extend_variables(self.center, self.spread, self.weight, self.bias) # Updata variables extended_delta = param[0] extended_delta = momentum_rate * extended_delta + learn_rate * extended_gradient param[0] = extended_delta extended_variables = extended_variables - extended_delta self.center, self.spread, self.weight, self.bias = self.split_weights(extended_variables) return loss_ # Nesterov Accelerated Gradient(NAG) def NAG_optimizer(self, param, hyper_param={'learn_rate': 0.01, 'momentum_rate': 0.9}): # Initialize variables if len(param) == 0: param.append(np.zeros(1)) # last delta_weights and delta_biases try: learn_rate = hyper_param['learn_rate'] except: print('NAG_optimizer have no "learn_rate" hyper-parameter') return try: momentum_rate = hyper_param['momentum_rate'] except: print('NAG_optimizer have no "momentum_rate" hyper-parameter') return # Forward propagation extended_variables = self.extend_variables(self.center, self.spread, self.weight, self.bias) extended_delta = param[0] self.center, self.spread, self.weight, self.bias = self.split_weights( extended_variables - momentum_rate * extended_delta) hidden_output_, network_output_ = self._forward() # Loss function loss_ = self.loss_function(network_output_, self.output) # Backward propagation delta_center, delta_spread, delta_weight, delta_bias = self._backward(hidden_output_, network_output_) extended_gradient = self.extend_variables(delta_center, delta_spread, delta_weight, delta_bias) # Updata variables extended_delta = momentum_rate * extended_delta + learn_rate * extended_gradient param[0] = extended_delta extended_variables = extended_variables - extended_delta self.center, self.spread, self.weight, self.bias = self.split_weights(extended_variables) return loss_ # Adagrad def Adagrad_optimizer(self, param, hyper_param={'learn_rate': 0.01}): # Initialize variables delta = 10e-7 if len(param) == 0: param.append(np.zeros(1)) # accumulated square gradient try: learn_rate = hyper_param['learn_rate'] except: print('Adagrad_optimizer have no "learn_rate" hyper-parameter') return # Forward propagation hidden_output_, network_output_ = self._forward() # Loss function loss_ = self.loss_function(network_output_, self.output) # Backward propagation delta_center, delta_spread, delta_weight, delta_bias = self._backward(hidden_output_, network_output_) extended_gradient = self.extend_variables(delta_center, delta_spread, delta_weight, delta_bias) extended_variables = self.extend_variables(self.center, self.spread, self.weight, self.bias) # Updata variables accumulated_gradient = param[0] accumulated_gradient = accumulated_gradient + extended_gradient * extended_gradient param[0] = accumulated_gradient extended_delta = learn_rate / np.sqrt(accumulated_gradient + delta) * extended_gradient extended_variables = extended_variables - extended_delta self.center, self.spread, self.weight, self.bias = self.split_weights(extended_variables) return loss_ # Adadelta def Adadelta_optimizer(self, param, hyper_param={'decay_rate': 0.9}): # Initialize variables delta = 10e-7 if len(param) == 0: param.append(np.zeros(1)) # accumulated square gradient param.append(np.zeros(1)) # accumulated square delta try: decay_rate = hyper_param['decay_rate'] except: print('Adadelta_optimizer have no "decay_rate" hyper-parameter') return # Forward propagation hidden_output_, network_output_ = self._forward() # Loss function loss_ = self.loss_function(network_output_, self.output) # Backward propagation delta_center, delta_spread, delta_weight, delta_bias = self._backward(hidden_output_, network_output_) extended_gradient = self.extend_variables(delta_center, delta_spread, delta_weight, delta_bias) extended_variables = self.extend_variables(self.center, self.spread, self.weight, self.bias) # Updata variables accumulated_gradient = param[0] accumulated_delta = param[1] accumulated_gradient = decay_rate * accumulated_gradient + ( 1 - decay_rate) * extended_gradient * extended_gradient extended_delta = np.sqrt(accumulated_delta + delta) / np.sqrt(accumulated_gradient + delta) * extended_gradient accumulated_delta = decay_rate * accumulated_delta + (1 - decay_rate) * extended_delta * extended_delta param[0] = accumulated_gradient param[1] = accumulated_delta extended_variables = extended_variables - extended_delta self.center, self.spread, self.weight, self.bias = self.split_weights(extended_variables) return loss_ # RMSProp def RMSProp_optimizer(self, param, hyper_param={'learn_rate': 0.01, 'decay_rate': 0.9}): # Initialize variables delta = 10e-6 if len(param) == 0: param.append(np.zeros(1)) # accumulated square gradient try: learn_rate = hyper_param['learn_rate'] except: print('RMSProp_optimizer have no "learn_rate" hyper-parameter') return try: decay_rate = hyper_param['decay_rate'] except: print('RMSProp_optimizer have no "decay_rate" hyper-parameter') return # Forward propagation hidden_output_, network_output_ = self._forward() # Loss function loss_ = self.loss_function(network_output_, self.output) # Backward propagation delta_center, delta_spread, delta_weight, delta_bias = self._backward(hidden_output_, network_output_) extended_gradient = self.extend_variables(delta_center, delta_spread, delta_weight, delta_bias) extended_variables = self.extend_variables(self.center, self.spread, self.weight, self.bias) # Updata variables accumulated_gradient = param[0] accumulated_gradient = decay_rate * accumulated_gradient + ( 1 - decay_rate) * extended_gradient * extended_gradient param[0] = accumulated_gradient extended_delta = learn_rate / np.sqrt(accumulated_gradient + delta) * extended_gradient extended_variables = extended_variables - extended_delta self.center, self.spread, self.weight, self.bias = self.split_weights(extended_variables) return loss_ # RMSProp_with_Nesterov def RMSProp_Nesterov_optimizer(self, param, hyper_param={'learn_rate': 0.01, 'momentum_rate': 0.9, 'decay_rate': 0.9}): # Initialize variables delta = 10e-6 if len(param) == 0: param.append(np.zeros(1)) # last delta_weights and delta_biases param.append(np.zeros(1)) # accumulated square gradient try: learn_rate = hyper_param['learn_rate'] except: print('RMSProp_Nesterov_optimizer have no "learn_rate" hyper-parameter') return try: decay_rate = hyper_param['decay_rate'] except: print('RMSProp_Nesterov_optimizer have no "decay_rate" hyper-parameter') return try: momentum_rate = hyper_param['momentum_rate'] except: print('RMSProp_Nesterov_optimizer have no "momentum_rate" hyper-parameter') return # Forward propagation extended_variables = self.extend_variables(self.center, self.spread, self.weight, self.bias) extended_delta = param[0] self.center, self.spread, self.weight, self.bias = self.split_weights( extended_variables - momentum_rate * extended_delta) hidden_output_, network_output_ = self._forward() # Loss function loss_ = self.loss_function(network_output_, self.output) # Backward propagation delta_center, delta_spread, delta_weight, delta_bias = self._backward(hidden_output_, network_output_) extended_gradient = self.extend_variables(delta_center, delta_spread, delta_weight, delta_bias) extended_variables = self.extend_variables(self.center, self.spread, self.weight, self.bias) # Updata variables accumulated_gradient = param[1] accumulated_gradient = decay_rate * accumulated_gradient + ( 1 - decay_rate) * extended_gradient * extended_gradient param[1] = accumulated_gradient extended_delta = learn_rate / np.sqrt(accumulated_gradient + delta) * extended_gradient extended_variables = extended_variables - extended_delta self.center, self.spread, self.weight, self.bias = self.split_weights(extended_variables) return loss_ # Adam def Adam_optimizer(self, param, hyper_param={'learn_rate': 0.01, 'decay1_rate': 0.9, 'decay2_rate': 0.999}): # Initialize variables delta = 10e-8 if len(param) == 0: param.append(np.zeros(1)) # accumulated gradient param.append(np.zeros(1)) # accumulated square gradient param.append(0) # train steps try: learn_rate = hyper_param['learn_rate'] except: print('Adam_optimizer have no "learn_rate" hyper-parameter') return try: decay1_rate = hyper_param['decay1_rate'] except: print('Adam_optimizer have no "decay1_rate" hyper-parameter') return try: decay2_rate = hyper_param['decay2_rate'] except: print('Adam_optimizer have no "decay2_rate" hyper-parameter') return # Forward propagation hidden_output_, network_output_ = self._forward() # Loss function loss_ = self.loss_function(network_output_, self.output) # Backward propagation delta_center, delta_spread, delta_weight, delta_bias = self._backward(hidden_output_, network_output_) extended_gradient = self.extend_variables(delta_center, delta_spread, delta_weight, delta_bias) extended_variables = self.extend_variables(self.center, self.spread, self.weight, self.bias) # Updata variables accumulated_gradient = param[0] accumulated_square_gradient = param[1] step = param[2] + 1 accumulated_gradient = decay1_rate * accumulated_gradient + (1 - decay1_rate) * extended_gradient accumulated_square_gradient = decay2_rate * accumulated_square_gradient + ( 1 - decay2_rate) * extended_gradient * extended_gradient param[0] = accumulated_gradient param[1] = accumulated_square_gradient param[2] = step + 1 extended_moment1 = accumulated_gradient / (1 - np.power(decay1_rate, step)) extended_moment2 = accumulated_square_gradient / (1 - np.power(decay2_rate, step)) extended_delta = learn_rate * extended_moment1 / (np.sqrt(extended_moment2) + delta) extended_variables = extended_variables - extended_delta self.center, self.spread, self.weight, self.bias = self.split_weights(extended_variables) return loss_ ### Activation Functions ### # sigmoid def sigmoid_activation(self, input_): output_ = 1 / (1 + np.exp(-input_)) return output_ def sigmoid_gradient(self, input_): output_ = input_ * (1 - input_) return output_ # tanh (Bipolar sigmoid) def tanh_activation(self, input_): output_ = (1 - np.exp(-input_)) / (1 + np.exp(-input_)) return output_ def tanh_gradient(self, input_): output_ = 0.5 * (1 - input_ * input_) return output_ # ReLU def ReLU_activation(self, input_): output_ = np.where(input_ < 0, 0, input_) return output_ def ReLU_gradient(self, input_): output_ = np.where(input_ > 0, 1, 0) return output_ # Softmax def softmax_activation(self, input_): output_ = np.exp(input_ - input_.max(axis=0)) / np.sum(np.exp(input_ - input_.max(axis=0)), axis=0) return output_ def softmax_gradient(self, input_): output_ = input_ * (self.output - input_) return output_ # None Activation def none_activation(self, input_): output_ = input_ return output_ def none_gradient(self, input_): output_ = 1 return output_ # RBF Gaussian Function def Gaussian_basis(self, input_): output_ = np.exp(-np.power(input_, 2)) return output_ def Gaussian_gradient(self, input_): output_ = -2 * input_ * np.exp(-np.power(input_, 2)) return output_ # RBF Reflected sigmoid Function def Reflected_sigmoid_basis(self, input_): output_ = 1 / (1 + np.exp(np.power(input_, 2))) return output_ def Reflected_sigmoid_gradient(self, input_): output_ = -2 * input_ * np.exp(np.power(input_, 2)) / np.power(1 + np.exp(np.power(input_, 2)), 2) return output_ ### Loss Functions ### # output_: Network predict output output: dataset output # L2_loss (RMSE) def L2_loss(self, output_, output): loss = np.sum(0.5 * np.power(output_ - output, 2)) return loss def L2_loss_gradient(self, output_, output): loss_gradient = output_ - output return loss_gradient # cross_entropy loss def cross_entropy_loss(self, output_, output): loss = -np.sum(np.log(output_) * output) return loss def cross_entropy_gradient(self, output_, output): loss_gradient = -output / output_ return loss_gradient # sigmoid_cross_entropy loss # softmax cross_entropy loss ### utilities ### def extend_variables(self, center_, spread_, weight_, bias_): variables = np.concatenate( (center_.reshape(-1), spread_.reshape(-1), weight_.reshape(-1), bias_.reshape(-1))) return variables def split_weights(self, variables): center_mark = self.input_units_number * self.hidden_units_number spread_mark = center_mark + self.hidden_units_number weight_mark = spread_mark + self.hidden_units_number * self.output_units_number center = variables[: center_mark].copy() center = center.reshape(self.hidden_units_number, self.input_units_number) spread = variables[center_mark: spread_mark].copy() spread = spread.reshape(self.hidden_units_number, 1) weight = variables[spread_mark: weight_mark].copy() weight = weight.reshape(self.output_units_number, self.hidden_units_number) bias = variables[weight_mark:].copy() bias = bias.reshape(self.output_units_number, 1) return center, spread, weight, bias def save_model(self, path='model'): np.save(path, [self.center, self.spread, self.weight, self.bias]) def load_model(self, path): parameters = np.load(path) self.center = parameters[0] self.spread = parameters[1] self.weight = parameters[2] self.bias = parameters[3] self.input_units_number = self.center.shape[1] self.hidden_units_number = self.center.shape[0] self.output_units_number = self.weight.shape[0]
955f9fb338854949f7862d18ef9e5a071988d9f2
rafaelperazzo/programacao-web
/moodledata/vpl_data/82/usersdata/233/42998/submittedfiles/decimal2bin.py
119
3.71875
4
# -*- coding: utf-8 -* binario=int(input('Digite um número binário: ')) soma=0 while soma=soma+n*2**i n=binario%10
85be9a41f124a4f914124a1c7bc447eb1812db0d
Yakobo-UG/Python-by-example-challenges
/challenge 48.py
705
4.25
4
#Ask for the name of somebody the user wants to invite to a party. After this, display the message “[name] has now been invited” and add 1 to the count. Then ask if they want to invite somebody else. Keep repeating this until they no longer want to invite anyone else to the party and then display how many people they have coming to the party. repeat = "yes" repeat = "YES" repeat = "Yes" add = 0 while repeat == "yes" or repeat == "Yes" or repeat == "YES" : name =str(input("Enter name to be invited: ")) print (name, "has now been invited") add = add + 1 repeat = str(input("Do you want to add another person?: ")) print(add, "number of peaple have been invited to the party")
fe52f47a23d6a7422475453e86cf9a467ece99c0
hlcr/Leetcode
/48. Rotate Image.py
770
3.765625
4
class Solution(object): def rotate(self, matrix): """ :type matrix: List[List[int]] :rtype: None Do not return anything, modify matrix in-place instead. """ for i in range(len(matrix)): for j in range(i, len(matrix)): matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j] start = 0 end = len(matrix) - 1 while start < end: matrix[i][start], matrix[i][end] = matrix[i][end], matrix[i][start] start += 1 end -= 1 if __name__ == '__main__': r = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]] for k in r: print(k) print() Solution().rotate(r) print() for l in r: print(l)
f70c05721a5d5569d4d229eff43c7046311a1301
jashidsany/Learning-Python
/Codecademy Lesson 5 Loops/L5.3_Infinite_Loops.py
353
3.90625
4
students_period_A = ["Alex", "Briana", "Cheri", "Daniele"] students_period_B = ["Dora", "Minerva", "Alexa", "Obie"] for students in students_period_A: students_period_B.append(students) # if you change students_period_B to students_period_A, it will cause an infinite loop print(students) # temp variable represents elemenets in the lists
f5a6000e29ca7b9c6cb8f2ced47a8899f4871faa
rramosp/20182.python.sols
/utils/student_function/student_PS1_SYNTAX_4.py
212
3.84375
4
## Ejercicio del estudiante def fibonacci(n): f_1=1 f_2=1 suma=0 if(n<3): return 1 for i in xrange(3,n+1): suma=f_1+f_2 f_1=f_2 f_2=suma return suma
3ee568a4bee32affc4766cab773e212fe5a25e8c
EEsparaquia/Python_project
/script31_2.py
960
3.75
4
#! Python3 # Programming tutorial: # Urllib Module import urllib.request # Basicaly go to # 'http://pythonprogramming.net' # and serch basics and filter the # <p></p> tags to extract thr content import urllib.request import urllib.parse import re print(''' ##################### # # # Starting Python3 # # Scripts. # # It's an exciting # # time to be alive # # # ##################### ''') url = 'http://pythonprogramming.net' #values = {'s':'basics', # 'submit':'Search'} #data = urllib.parse.urlencode(values) #data = data.encode('utf-8') #req = urllib.request.Request(url, data) req = urllib.request.Request(url) resp = urllib.request.urlopen(req) respData = resp.read() #print(respData) paragraphs = re.findall('<p>(.*?)</p>',str(respData)) for eachP in paragraphs: print(eachP) input('Press any key to exit!')
9e30b8d24b2b2d73ce039cab05d315a108b8b418
Nep-DC-Exercises/day-7
/frequency_pattern_1.py
785
4.1875
4
# Given two arrays write a function to find out if two arrays have the same frequency of digits. array_1 = [1, 2, 3, 4] array_2 = [1, 2, 3, 4] frequency_1 = {} frequency_2 = {} # populate two dictionaries with key of the number in the array and the value is how frequent it shows up def frequency(arr1, arr2, dict1, dict2): for i in arr1: if i not in dict1: dict1[i] = 1 else: dict1[i] += 1 for i in arr2: if i not in dict2: dict2[i] = 1 else: dict2[i] += 1 frequency(array_1, array_2, frequency_1, frequency_2) if frequency_1 == frequency_2: print("The two arrays have the same frequency of digits.") else: print("The to arrays do not have the same frequency of digits.")
0e3ef14db7711323ea905ba2a031960d7ac21c22
vega28/code_challenges
/codewars/mumbling.py
1,438
3.90625
4
# Mumbling # https://www.codewars.com/kata/5667e8f4e3f572a8f2000039 # Challenge: # Transform any input string by the given pattern: # for each character, multiply by the place in the string, # then capitalize the first one of that character, # then string them together by dashes. # Constraints: # the input string will only contain characters a..z and A..Z. # Code: def accum1(s): """ Build the string according to the pattern. e.g. >>> accum1('abcd') 'A-Bb-Ccc-Dddd' >>> accum1("RqaEzty") 'R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy' >>> accum1("cwAt") 'C-Ww-Aaa-Tttt' """ result = '' for i, char in enumerate(s): if i > 0: result += '-' result += char.upper() + (char.lower())*i return result def accum2(s): """ Build the string according to the pattern. e.g. >>> accum2('abcd') 'A-Bb-Ccc-Dddd' >>> accum2("RqaEzty") 'R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy' >>> accum2("cwAt") 'C-Ww-Aaa-Tttt' """ return '-'.join([c.upper() + c.lower()*i for i, c in enumerate(s)]) ##################################################################### # run doctests if __name__ == "__main__": import doctest print() result = doctest.testmod() if not result.failed: print("ALL TESTS PASSED. NICE!") print()
fe1178387fe03b627620f201c82f27396045ead2
JMH201810/Labs
/Python/p01310a.py
771
4.625
5
##Buffet: A buffet-style restaurant offers only five basic foods. ##Think of five simple foods, and store them in a tuple. ##• Use a for loop to print each food the restaurant offers. ##• Try to modify one of the items, and make sure that Python rejects the change. ##• The restaurant changes its menu, replacing two of the items with different foods. ## Add a block of code that rewrites the tuple, and then use a for loop ## to print each of the items on the revised menu. foods = ('tortilla', 'bean', 'horchata', 'okra', 'milk') print("Foods offered:") for f in foods: print (f) #foods[0] = 'hamburger' foods = ('tortilla', 'bean', 'pepper', 'cream', 'milk') print ("\nRevised food list:") for f in foods: print (f)
9a0cc1ea58eb6b69cd7544588defd5c48b2325b9
MATEO19M/ESPE202011-FP-GEO-3285
/workshops/unit1/WS01HelloWorld/Hello World.py
430
4
4
print("Hello World from Mateo Martinez \n ESPE \n GEO") # input variables addend1 = input(" Enter the first number --> ") addend2 = input(" Enter the second number --> ") # add two numbers sum = float(addend1) + float(addend2) # displaying the sum print("The sum of {0} and {1} is {2}".format(addend1,addend2,sum)) print("The sum is %.1f" %(float(input("Enter first number: "))+float(input("Enter second number: "))))
2bd3d4fce2853e4196a63ee869aae1a8a9198123
alcal3/CSS-301-Portfolio
/problem3.4.5.py
387
4.0625
4
#aleks calderon #5.2.2019 #creating a class w/method that prints greeting and students name class Student: def __init__(self, name, major): self.name = name self.major = major def myfunc(self): print("Good morning, " + self.name) p1 = Student("Aleks", "Communications") p1.myfunc() p1.major = "Criminal Justice" print(p1.major)
8819849347dbc7f6e0eaada57b02a979637d31b8
seansliu/Escape-the-Zombies
/ZombieGame.py
7,410
3.5
4
# Zombie Game GUI # # Michelle Lee, Sean Liu, Sophie Lucy from zombie import * import Tkinter as Tk from PIL import Image, ImageTk class ZombieGame: """Escape the Zombie Game""" def __init__(self): """define the GUI window""" self.main_window = Tk.Tk() self.main_window.title('Escape the Zombies!') # create the window frames self.top_frame = Tk.Frame() self.diff_frame = Tk.Frame() self.mid_frame = Tk.Frame() self.word_frame = Tk.Frame() self.guess_frame = Tk.Frame() self.wrong_frame = Tk.Frame() self.play_frame = Tk.Frame() self.quit_frame = Tk.Frame() self.stats_frame = Tk.Frame() # initialize images self.images = [] for i in range(7): filename = 'images/zombies' + str(i) + '.ppm' self.images.append(ImageTk.PhotoImage(Image.open(filename))) self.game_img = ImageTk.PhotoImage(Image.open('images/zombies.ppm')) self.win_img = ImageTk.PhotoImage(Image.open('images/win.ppm')) self.lose_img = ImageTk.PhotoImage(Image.open('images/lose.ppm')) # initizlize data structures self.wordbank = index_dict('words.txt') self.word = '' self.guess = [] self.guesses = [] self.wrongbox = '' self.mistakes = 0 self.mistakes_total = 0 self.losses = 0 self.wins = 0 # directions frame self.direction = Tk.StringVar() self.dir_label = Tk.Label(self.top_frame, width=60, bg='cyan', \ textvariable=self.direction, font=("Helvetica", 20)) self.dir_label.pack(side='left') # difficulty buttons self.easy_butt = Tk.Button(self.diff_frame, text='Easy', \ font=("Helvetica", 20)) self.easy_butt.pack(side='left') self.medium_butt = Tk.Button(self.diff_frame, text='Medium', \ font=("Helvetica", 20)) self.medium_butt.pack(side='left') self.hard_butt = Tk.Button(self.diff_frame, text='Hard', \ font=("Helvetica", 20)) self.hard_butt.pack(side='left') # gameplay image self.image_label = Tk.Label(self.mid_frame, image=self.game_img) self.image_label.pack(side='top', fill='both', expand='yes') # word display frame self.display = Tk.StringVar() self.word_label = Tk.Label(self.word_frame, width=60, bg='yellow', \ textvariable=self.display, font=("Helvetica", 20)) self.word_label.pack(side='left') # wrong letters bank self.wrong = Tk.StringVar() self.wrong_label1 = Tk.Label(self.wrong_frame, width=60, bg='red', \ text='Incorrectly guessed letters:', font=("Helvetica", 20)) self.wrong_label2 = Tk.Label(self.wrong_frame, width=60, bg='red', \ textvariable=self.wrong, font=("Helvetica", 20)) self.wrong_label1.pack() self.wrong_label2.pack() # input frame self.entry = Tk.Entry(self.guess_frame, width=2, \ font=("Helvetica", 20)) self.guess_butt = Tk.Button(self.guess_frame, text='Guess', \ font=("Helvetica", 20)) self.entry.pack(side='left') self.guess_butt.pack(side='left') # Play and Quit frames. self.replay_butt = Tk.Button(self.play_frame, text='Replay', \ font=("Helvetica", 20)) self.quit_butt = Tk.Button(self.quit_frame, text='Quit', command=self.quit_now, font=("Helvetica", 20)) self.replay_butt.pack(side='left') self.quit_butt.pack(side='right') self.reset() # stat tracking frame. self.stats = Tk.StringVar( \ value='Wins: -, Losses: -, Avg. bad guesses: -') self.stats_label = Tk.Label(self.stats_frame, \ textvariable=self.stats, font=("Helvetica", 20)) self.stats_label.pack(side='left') # pack frames. self.top_frame.pack() self.diff_frame.pack() self.mid_frame.pack() self.word_frame.pack() self.wrong_frame.pack() self.guess_frame.pack() self.stats_frame.pack() self.play_frame.pack(side='left') self.quit_frame.pack(side='right') # Variables needed in play function. self.comp = Tk.StringVar() Tk.mainloop() def start_easy(self): """start game in easy mode""" self.start(0) def start_medium(self): """start game in easy mode""" self.start(1) def start_hard(self): """start game in easy mode""" self.start(2) def start(self, mode): """initialize the game""" # sleep unrelated buttons self.easy_butt.configure(command=self.chill) self.medium_butt.configure(command=self.chill) self.hard_butt.configure(command=self.chill) self.image_label.configure(image=self.images[0]) self.guess_butt.configure(command=self.check_letter) self.replay_butt.configure(command=self.reset) self.direction.set('Save Peach! Please guess a letter below.') self.main_window.bind('<Return>', self.check_letter) self.mistakes = 0 self.word = generate_word(self.wordbank, mode) self.guess = len(self.word) * ['_'] for i in range(len(self.word)): if not self.word[i].isalpha(): self.guess[i] = self.word[i] display = ' '.join(self.guess) self.display.set(display) def reset(self): """resets the game""" # sleep unrelated buttons self.replay_butt.configure(command=self.chill) self.guess_butt.configure(command=self.chill) self.image_label.configure(image=self.game_img) self.easy_butt.configure(command=self.start_easy) self.medium_butt.configure(command=self.start_medium) self.hard_butt.configure(command=self.start_hard) self.guesses = [] self.wrongbox = '' self.wrong.set(self.wrongbox) self.display.set('') intro = 'Peach needs your help! Select a difficulty to begin.' self.direction.set(intro) def check_letter(self, *args): """checks input letter with word""" letter = self.entry.get() if len(letter) != 1 or not letter.isalpha(): self.direction.set('Invalid input. Please enter an letter ONLY.') return letter = letter.lower() # correct guess if (letter in self.word.lower()) and not (letter in self.guesses): self.guesses.append(letter) for i in range(len(self.word)): if self.word[i].lower() == letter: self.guess[i] = self.word[i] display = ' '.join(self.guess) self.display.set(display) self.direction.set('Nice guess. Keep it up!') if self.word == ''.join(self.guess): self.win() self.main_window.unbind('<Return>') return # wrong guess self.mistakes += 1 if letter not in self.wrongbox: self.wrongbox = self.wrongbox + ' ' + letter self.wrong.set(self.wrongbox) if self.mistakes >= 7: self.lose() self.main_window.unbind('<Return>') else: self.image_label.configure(image=self.images[self.mistakes]) self.direction.set('Oops! Wrong letter. Try harder!') def quit_now(self): """quits the game by closing the GUI window""" self.main_window.destroy() def chill(self): """do nothing""" return def win(self): """win state""" self.image_label.configure(image=self.win_img) msg = 'Congratulations, you saved Peach! Hit Replay to play again.' self.direction.set(msg) self.guess_butt.configure(command=self.chill) self.update_stats(win=True) def lose(self): """loss state""" self.image_label.configure(image=self.lose_img) msg = 'Aw, you failed! Your word: %s. Hit Replay to play again.' \ %self.word self.direction.set(msg) self.guess_butt.configure(command=self.chill) self.update_stats(win=False) def update_stats(self, win): """update and displat stats""" self.mistakes_total += self.mistakes if win: self.wins += 1 else: self.losses += 1 stats_msg = 'Wins: %d, Losses: %d, Avg. bad guesses: %.2f' \ %(self.wins, self.losses, \ float(self.mistakes_total)/(self.wins+self.losses)) self.stats.set(stats_msg) z = ZombieGame()
cf9e14be615e4920ace467037c8087728ecb0e6f
arifaulakh/Competitive-Programming
/DMOJ/ship/ship.py
435
3.59375
4
parts = input() full = "BFLTC" if parts == full: print("NO MISSING PARTS") if parts.count("B") >=1 and parts.count("F") >=1 and parts.count("L")>= 1 and parts.count("T") >= 1 and parts.count("C"): print("NO MISSING PARTS") if parts.count("B") == 0: print("B") if parts.count("F") == 0: print("F") if parts.count("C") == 0: print("C") if parts.count("T") == 0: print("T") if parts.count("L") == 0: print("L")
0ffcc2caf7a8e3989abe8d03085f67b10d089744
homutovan/HomeWork2.3
/main.py
5,209
3.6875
4
valid_symbol = {'(': [1], ')': [0], '+': [2, lambda oper1, oper2: oper1 + oper2], '-': [2, lambda oper1, oper2: oper1 - oper2], '*': [3, lambda oper1, oper2: oper1 * oper2], '/': [3, lambda oper1, oper2: oper1 / oper2]} def two_operands(): str_in = input('Введите арифметическое выражение в форме префиксной нотации:\n').split() try: str_in[2] if len(str_in) > 3: a = b valid_symbol[str_in[0]] print(f'Результат вычисления: {valid_symbol[str_in[0]][1](int(str_in[1]), int(str_in[2]))}') except NameError: print('Введенное выражение содержит более 3 символов') except IndexError: print('Введенное выражение содержит менее 3 символов') except KeyError: print('Первая операция отсутствует в списке доступных операций') except ZeroDivisionError: print('Введенное выражение предусматривает деление на 0, проверьте порядок следования операндов') except ValueError: print('В качестве операндов возможно использовать только числа') finally: print('Введите новое выражение:') return None def multiple_operands(): #notation = input('Введите арифметическое выражение в форме префиксной нотации:\n').split() in_string = '- * / 15 - 7 + 1 1 3 + 2 + 1 1' #Пример из Википедии notation = in_string.split() while len(notation) > 1: out_string = [] digit = 0 for symbol in notation: out_string.append(symbol) if symbol.isdigit(): digit += 1 else: digit = 0 if digit == 2: operand2 = out_string.pop() operand1 = out_string.pop() operator = out_string.pop() new_symbol = int(valid_symbol[operator][1](int(operand1), int(operand2))) out_string.append(str(new_symbol)) notation = out_string + notation[(len(out_string) + 2):] break print(f'Результат вычисления: {notation[0]}') return None def symbolic_solution(): #notation = input('Введите арифметическое выражение в форме префиксной нотации:\n').split() in_string = '- * / 15 - 7 + 1 1 3 + 2 + 1 1' #Пример из Википедии #15 / (7 - (1 + 1)) * 3 - (2 + (1 + 1)) notation = in_string.split() while len(notation) > 1: out_string = [] operand2 = [] operand1 = [] digit = 0 for symbol in notation: out_string.append(symbol) if symbol[0].isdigit(): digit += 1 else: digit = 0 if digit == 2: operand2 = out_string.pop() operand1 = out_string.pop() operator = out_string.pop() try: math_symbol = operand1 + operator + operand2 except (IndexError, TypeError): try: math_symbol = operand1 + operator + operand2[1] except (IndexError, TypeError): try: math_symbol = operand1[1] + operator + operand2 except (IndexError, TypeError): math_symbol = operand1[1] + operator + operand2[1] if (valid_symbol[operator][0] < 3) and (len(notation)) != 3: math_symbol = '(' + math_symbol + ')' try: new_symbol = int(valid_symbol[operator][1](int(operand1), int(operand2))) except (IndexError, TypeError): try: new_symbol = int(valid_symbol[operator][1](int(operand1[0]), int(operand2))) except (IndexError, TypeError): try: new_symbol = int(valid_symbol[operator][1](int(operand1), int(operand2[0]))) except (IndexError, TypeError): new_symbol = int(valid_symbol[operator][1](int(operand1[0]), int(operand2[0]))) out_string.append([str(new_symbol), math_symbol]) notation = out_string + notation[(len(out_string) + 2):] break print(f'Результат вычисления:{notation[0][1]} = {notation[0][0]}') return None #two_operands() #multiple_operands() symbolic_solution()
ca497649868b45efab43b9bec158d420fa82276d
jlaframboise/StockPrediction
/util_functions.py
11,393
3.515625
4
import numpy as np import pandas as pd from sklearn.metrics import mean_squared_error import matplotlib.pyplot as plt from sklearn.preprocessing import MinMaxScaler def apply_rolling(stock, trail_size, predict_length, predict_change=False, trend_classify=False): """ A function that takes in a timeseries for a single stock, and reshapes the data for input into an LSTM. It converts (days, features) to (days, trail_size days, features). It will set the yvalue based on the setting parameters, and predict_length. """ x = [] y = [] tickers = [] # for every day for i in range(trail_size, len(stock) + 1 - predict_length): # x is features for last trail_size days x_point = stock.drop(columns=['Date', 'Ticker']).iloc[i-trail_size : i].values # set y value based on settings if trend_classify: y_point = 1 if stock['Close'].iloc[i + predict_length -1] > stock['Close'].iloc[i -1] else 0 elif predict_change: y_point = stock['Close'].iloc[i + predict_length -1] - stock['Close'].iloc[i -1] else: y_point = stock['Close'].iloc[i + predict_length -1] ticker = stock['Ticker'].iloc[i + predict_length -1] # only append datapoints where there is no nan values if np.isnan(x_point).sum() ==0: x.append(x_point) y.append(y_point) tickers.append(ticker) # return the x values, the y values, # and the ticker repeated for every point return np.array(x), np.array(y), np.array(tickers) def split_and_apply_rolling(stock, trail_size, predict_length, hist_features, tech_features): """ A function that will perform the same task as apply_rolling, except it will split the technical indicators into a separate input from the historical data for use in a model with separate input branches. """ xh = [] xt = [] y = [] tickers = [] # for every day for i in range(trail_size, len(stock) + 1 - predict_length): # historical data from t-trail_size to t-1 inclusive xh_point = stock.drop(columns=['Date', 'Ticker']+tech_features).iloc[i-trail_size : i].values # technical data at time t-1 xt_point = stock[tech_features].iloc[i - 1] # label at time t-1 + predict_length y_point = stock['Close'].iloc[i + predict_length -1] ticker = stock['Ticker'].iloc[i + predict_length -1] # check for nan values if np.isnan(xh_point).sum() ==0 and np.isnan(xt_point).sum() ==0: xh.append(xh_point) xt.append(xt_point) y.append(y_point) tickers.append(ticker) # return inputs, outputs, and the ticker return np.array(xh), np.array(xt), np.array(y), np.array(tickers) def split_and_roll_all_stocks(dataset, trail_size, predict_length, hist_features, tech_features): """ A function that will take in a dataset of many stocks, and apply the split_and_apply_rolling function to split each stock into inputs, outputs reshaped for input to LSTM, and will return the concatenation. """ res = dataset.groupby('Ticker').apply(lambda x: split_and_apply_rolling(x, trail_size=trail_size, predict_length=predict_length, hist_features=hist_features, tech_features=tech_features)) xh = [x[0] for x in res.values] xt = [x[1] for x in res.values] y = [x[2] for x in res.values] tickers = [x[3] for x in res.values] return np.concatenate(xh), np.concatenate(xt), np.concatenate(y), np.concatenate(tickers) def roll_all_stocks(dataset, trail_size, predict_length, predict_change=False, trend_classify=False): """ A function that takes in a dataset of stocks, and for each stock it will apply_rolling to reshape it into inputs and outputs for LSTM. It then concatenates the output and returns. """ res = dataset.groupby('Ticker').apply(lambda x: apply_rolling(x, trail_size=trail_size, predict_length=predict_length, predict_change=predict_change, trend_classify=trend_classify)) x = [x[0] for x in res.values] y = [x[1] for x in res.values] tickers = [x[2] for x in res.values] x = np.concatenate(x) y = np.concatenate(y) tickers = np.concatenate(tickers) return x, y, tickers def evaluate_model_rmse(y_preds, y_true, num_features, scaler): """ When performing regression, our model is trained on normalized features (including predicted prices) and so before computing RMSE we need to take the sklearn scaler we used to normalize and inverse the transform so we can consider RMSE in dollars. """ dummies = np.zeros((y_preds.shape[0], num_features-1)) res = np.concatenate([y_preds, dummies], axis=1) pred_dollars = scaler.inverse_transform(res)[:, 0] res2 = np.concatenate([np.expand_dims(y_true, axis=1), dummies], axis=1) true_dollars = scaler.inverse_transform(res2)[:, 0] return np.sqrt(mean_squared_error(true_dollars, pred_dollars)) def plot_loss(history): """ A helper function to make a plot of the loss curve of a network trained with Keras. Style from Jacob's past work. """ plt.figure(figsize=(8,6)) plt.plot(history.history['loss'], 'bo--') plt.plot(history.history['val_loss'], 'ro-') plt.ylabel('Loss') plt.xlabel('Epochs (n)') plt.legend(['Training loss', 'Validation loss']) plt.title("Loss curve for LSTM") plt.show() def plot_acc(history): """ A helper function to make a plot of the loss curve of a network trained with Keras. Style from Jacob's past work. """ plt.figure(figsize=(8,6)) plt.plot(history.history['accuracy'], 'bo--') plt.plot(history.history['val_accuracy'], 'ro-') plt.ylabel('Accuracy') plt.xlabel('Epochs (n)') plt.legend(['Training accuracy', 'Validation accuracy']) plt.title("Accuracy curve for LSTM") plt.show() def norm_per_stock_split(train, valid, test, features, scaler_model): """ Takes in dataframes for train, validation, test with a 'Ticker' column, and will split the dataframes by this ticker, then fit_transform the data in train with a normalizing model specified in place, and transform the data in train and test in place and return the mapping of tickers to scaler models. """ scalers = {} for ticker in train['Ticker'].unique(): scaler = scaler_model() # fit and transform training data train.loc[train['Ticker']==ticker, features] = scaler.fit_transform(train.loc[train['Ticker']==ticker, features]) # only transform training and test, do not fit. valid.loc[valid['Ticker']==ticker, features] = scaler.transform(valid.loc[valid['Ticker']==ticker, features]) test.loc[test['Ticker']==ticker, features] = scaler.transform(test.loc[test['Ticker']==ticker, features]) # save the model that was used for this stock scalers[ticker] = scaler return scalers def load_climate_data(filenames, terms): """ A function to load in the climate google trends data from a list of filenames and a list of corresponding terms. """ # read files dfs = [pd.read_csv(f) for f in filenames] # rename columns, insert the search term string for i in range(len(dfs)): dfs[i].columns = ["Date", "Popularity"] dfs[i].insert(2, "Term", terms[i]) # combine to one df climate_trends_data = pd.concat(dfs).reset_index(drop=True) # convert date col to datetime climate_trends_data['Date'] = pd.to_datetime(climate_trends_data['Date']) # convert the data from long to wide format climate_trends_data = climate_trends_data.pivot(index='Date', columns="Term", values="Popularity").reset_index() return climate_trends_data def performance_stats(model, x, y): """ A function that will take in a LSTM model, and inputs and output and will print some key stats that can indicate performance, but also whether the model is guessing only one class all the time to get that baseline 50% accuracy. """ print("Upward ratio: {:.2%}".format(np.mean(y))) preds = model.predict(x) print("Mean prediction: {:.2%}".format(np.mean(preds))) print("Predicted upward ratio: {:.2%}".format(np.mean(preds>0.5))) print("Accuracy: {:.2%}".format(np.mean( y == [1 if x>0.5 else 0 for x in preds]))) def generate_dataset(stock_data, trends_data, target_stocks, train_end, valid_end, test_end, stock_features, trend_features, trail_size, predict_length, stock_scaler=MinMaxScaler, objective="classification" ): """ A function to generate a dataset to train a LSTM model on stock trend classification. This function will take in the whole dataset of stocks, and dataset of trends data. It will take the end dates of each of the splits, and lists of stock features and trend features. Note, 'Close' must be the first feature in stock_features. it accepts parameters trail_size to be the number of days to look back. predict_length is the number of days ahead to consider the trend. """ # filter data to only target stocks target_stocks_dataset = stock_data[stock_data['Ticker'].isin(target_stocks)].reset_index(drop=True) # filter to only chosen stock features target_stocks_dataset = target_stocks_dataset[['Ticker', 'Date'] + stock_features] # split into training, validation, testing based on provided dates train = target_stocks_dataset.loc[target_stocks_dataset['Date'] < train_end] valid = target_stocks_dataset.loc[(target_stocks_dataset['Date'] > train_end) & (target_stocks_dataset['Date'] < valid_end)] test = target_stocks_dataset.loc[(target_stocks_dataset['Date'] > valid_end) & (target_stocks_dataset['Date'] < test_end)] # normalize data per stock _ = norm_per_stock_split(train, valid, test, stock_features, stock_scaler) # merge in trends data train = train.merge(trends_data[['Date']+trend_features], on=["Date"], how='left') valid = valid.merge(trends_data[['Date']+trend_features], on=["Date"], how='left') test = test.merge(trends_data[['Date']+trend_features], on=["Date"], how='left') if objective=='classification': trend_classify = True else: raise NotImplementedError("No other objectives supported yet!") # reshape dataset for LSTM inputs x_train, y_train, _ = roll_all_stocks(train, trail_size, predict_length, trend_classify=trend_classify) x_valid, y_valid, _ = roll_all_stocks(valid, trail_size, predict_length, trend_classify=trend_classify) x_test, y_test, _ = roll_all_stocks(test, trail_size, predict_length, trend_classify=trend_classify) # confirm shapes are matching assert x_train.shape[0] == y_train.shape[0] assert x_valid.shape[0] == y_valid.shape[0] assert x_test.shape[0] == y_test.shape[0] assert x_train.shape[1:] == x_valid.shape[1:] == x_test.shape[1:] # return the dataset return x_train, y_train, x_valid, y_valid, x_test, y_test
7cb1e76c1cb95f4e34014dd2b5e0f225fcb6e798
JagadeeshMandala/python
/python programms/sum of natural numbers.py
210
4.125
4
num=int(input("enter the number")) if num<0: print("enter the postive numbers only") else: sum=0 while(num>0): sum+=num num-=1 print("The sum is",sum)
e6fdfe1837a9128e853e867bfb6158b7df12361a
DandyCV/SoftServeITAcademy
/L11/L11_HW1_2.py
838
3.890625
4
#Визначте атрибути fullname та email в класі Employee. При заданих first та last names: #- В конструкторі сформуйте fullname звичайним з’єднанням через пробіл first та last name. #В конструкторі сформуйте email з’єднанням first та last name через ‘.’ між ними та приєднуючи # ‘@company.com’ наприкінці. class Employee(): def __init__(self, first, last): self.first_name = first self.last_name = last self.full_name = first + ' ' + last self.email = first.lower() + '.' + last.lower() + '@company.com' def __repr__(self): return '%s your email address: %s' %(self.full_name, self.email) print(Employee('Serhii', 'Velychko'))
e4e87e57536067268168f5db77064b21fc26b1d5
JosephLevinthal/Research-projects
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/225/users/4311/codes/1635_1055.py
389
3.703125
4
# Teste seu código aos poucos. # Não teste tudo no final, pois fica mais difícil de identificar erros. # Use as mensagens de erro para corrigir seu código. from math import* vi = float(input("Velocidade inicial: ")) an = radians(float(input("angulo: "))) d = float(input("distancia horizontal: ")) g = 9.8 R = ((vi**2)*sin(2*an))/g if(abs(R-d)<= 0.1): print("sim") else: print("nao")
6559fafc1963ca91871f8eb37e1a883bf37a8327
millenagena/Python-Scripts
/aula06 - desafio 003 soma.py
148
3.890625
4
n1 = int(input('Informe um número: ')) n2 = int(input('Informe mais um número: ')) print('A soma resultante desses números é {}'.format(n1+n2))
417f6ecaf27ae5b969e5e22a46270f52165e0aed
IceHilda/HallOfGrandmasters
/coding 1.2.3.py
686
3.921875
4
# Create a function that takes in a list of numbers def pwn(numbers=None, art=None): # default set to none # If no list provided, ask the user if numbers == None: numbers = input("What are your numbers (without spaces)? ") #numbers = list(numbers) numbers = [int(x) for x in numbers] if art == None: art = input("What symbol would you like to use? ") for each_number in numbers: # print(art * each_number) for i in range(each_number): print(art, end="") print("\n", end="") # F = 52422 # U = # Use case 1 (give a list): #my_list = [5, 2, 5, 2, 2] #pwn(my_list) # Use case 2 (user input): pwn()
3e5237e2d1f3998ad3b42302e8f11fdcf3e6c13a
michaelverano/PracticeWithPython
/renameDates.py
1,322
3.578125
4
#! python3 # renameDates.py - renames filenames with American MM-DD-YY date formats # to European DD-MM-YY. import shutil, os, re # Create a regex that matches files with the American date format. datePattern = re.compile(r"""(.*?) # all text before the date. ((0|1)?\d)- # one or two digits for month ((0|1|2|3)?\d)- # one or two digits for the day ((19|20)\d\d) # four digits for th year. (.*?)$ # all text after the date. """, re.VERBOSE) # TODO: Loop over the files in the working directory. for amerFilename in os.listdir('.'): mo = datePattern.search(amerFilename) # TODO: Skip files without a date. if mo == None: continue # TODO: Get the different parts of the filename. beforePart = mo.group(1) monthPart = mo.group(2) dayPart = mo.group(4) yearPart = mo.group(6) afterPart = mo.group(8) # Form the European-style filename. euroFilename = beforePart + dayPart + '-' + monthPart + '-' + yearPart + afterPart # Get the full, absolute file paths. absWorkingDir = os.path.abspath('.') amerFilename = os.path.join(absWorkingDir, amerFilename) euroFilename = os.path.join(absWorkingDir, euroFilename) # TODO: Rename the files. print('Rename "%s" to "%s"...' % (amerFilename, euroFilename)) #shutil.move(amerFilename, euroFilename) # uncomment after testingself.
10dc1dd13ed43ece05c4d777de720a35e1f1244d
CoderGustavo/ExerciciosPython
/65.py
628
4.0625
4
vezes = soma = maior = menor = 0 continuar = 'S' while continuar in 'S': valor = int(input('Digite um valor: ')) continuar = str(input('Deseja continuar? [S/N] ')).strip().upper()[0] vezes += 1 soma += valor if vezes == 1: maior = menor = valor else: if valor > maior: maior = valor if valor < menor: menor = valor print('Foram digitados {} numeros'.format(vezes)) print('A soma dos valores é: {}'.format(soma)) print('A média dos valores é: {}'.format(soma/vezes)) print('O maior valor é: {}'.format(maior)) print('O menor valor é: {}'.format(menor))
031d71300bba616925c70adad8e63007e625f47c
samrap/algebrasolver
/config/alg.py
10,915
3.953125
4
from __future__ import division from fractions import Fraction, gcd import math """Algebra calculation module This module takes user input from the algebra.py module and processes calculations based on the function called by the user. Functions in this module should never be called explicitly in this script, aside from testing. Besides testing, these functions are typically called from the algebra.py module. The exception to this is complicated equations that may require multiple functions to be completed. """ # ---------- GLOBAL CALCULATIONS ---------- # def remove_zeros(iterable, replace=1): """Remove zeros from a list. This function is typically used to prevent a ZeroDivisionError when dividing by numbers in a list. By default the number replaced has the value of 1, unless the 'replace' parameter is specified. """ for num in xrange(0, len(iterable)): if iterable[num] == 0: iterable[num] = replace return iterable def check(x): """Return only the sign of an integer x if its value is 1. If its value is greater than 1, return the value. """ if x == -1: return '-' if x == 1: return '' return x def atod(a): """Attempt to convert the data type 'a' to digit d This function is used for converting a string to a digit when the exact type is unknown (i.e. integer or float). If the string cannot be converted, the function returns False. Otherwise, the digit is returned as a float if the decimal is greater than 0 or as an integer if the decimal is equal to 0. Due to the nature of the function, it can also be used to round off floating point numbers whose decimal is equal to 0 (i.e. 3.0 -> 3) """ try: d = float(a) except: return False if d == int(d): # it is an integer return int(d) else: return d # ---------- SPECIFIC CALCULATIONS ---------- # def direct_variation(x, y): """Check if the values of y vary directly with the values of x. Find the constant of variation between the first two x/y values and check the remaining values against that constant. Print if y varies directly with x or not and if it does, include the constant of variaition (k). """ # Check if any value in the x tuple is equal to 0. if any((n == 0 for n in x)): print "Zero division error. Type 'man dv' for more info." return False k = Fraction(y[0], x[0]) if all([Fraction(x[1], x[0]) == k for x in zip(x, y)]): print "Y varies directly with x. k = %s" % (k) else: print "Y does not vary directly with x" def find_slope(set_one, set_two): """Find the slope between two x,y coordinate sets using the equation y2 - y1 / x2 - x1 and return it in simplest form. """ try: print Fraction(set_two[1] - set_one[1], set_two[0] - set_one[0]) except ZeroDivisionError: print "Undefined" def numtype(n): """Print the type of number entered. For example, the number 12 is a real, natural number, the number -2 is a real integer, etc. """ ntype = type(n) if ntype == int: if n > 0: print "%s is a real, natural number" % (n) return if n >= 0: print "%s is a real, whole number" % (n) return if n < 0: print "%s is a real integer" % (n) elif ntype == float: print "%s is a real, rational number" % (n) return else: print "Error: %s is not a number" % (n) return def check_arithmetic_sequence(sequence, n): """Check if the given data, sequence is an arithmetic sequence. If sequence is not an arithmetic sequence, print that it is not and return False. If sequence is an arithmetic sequence, print the common difference as well as n, the nth term, if the flag was specified. A list of numbers is an arithmetic sequence if there is a common difference between each term and its preceding term. If any of the differences do not match, it is not a sequence. """ i, j = 0, 1 # Establish a common difference to check against for all terms diff = sequence[j] - sequence[i] while j < len(sequence): if sequence[j] - sequence[i] != diff: print "Not an arithmetic sequence" return False i += 1; j += 1 else: print "The sequence is an arithmetic sequence. Common difference: %s"\ % (diff) if n: print "Nthterm: %s" % (sequence[0] + (n - 1) * diff) def check_geometric_sequence(sequence, n): """Check if the given data is a geometric sequence. If sequence is not a geometric sequence, print that it is not and return False. If sequence is a geometric sequence, print the common ratio as well as n, the nth term, if the flag was specified. A list of numbers is a geometric sequence if there is a common ratio between each term and its preceding term. If any of the ratios do not match, it is a not a sequence. """ # Prevent a 0 division error. sequence[n] must always be greater than 0 if any((n == 0 for n in sequence)): print "Zero division error. Type 'man sq' for more info." return False i, j = 0, 1 # Establish a ratio to check against for all terms ratio = sequence[j] / sequence[i] while j < len(sequence): if sequence[j] / sequence[i] != ratio: print "Not a geometric sequence" return False i += 1; j += 1 else: # Convert ratio to integer if decimal is 0 ratio = atod(ratio) print "The sequence is a geometric sequence. Common ratio: %s" % (ratio) if n: print "Nthterm: %s" % (sequence[0] * (ratio**(n - 1))) def arithmetic_series(fterm, nterm, n): """Print and return the series of an arithmetic sequence. The series of an arithmetic sequence is the sum of every value in the sequence. In this function, a sequence is assumed. See /manuals/sr for more info. """ ssum = atod(n / 2 * (fterm + nterm)) print "Sum of the finite arithmetic series: %s" % ssum return ssum def geometric_series(fterm, nterm, ratio): """Print and return the series of an geometric sequence. The series of an geometric sequence is the sum of every value in the sequence. In this function, a sequence is assumed. See /manuals/sr for more info. """ # Find n, the number of elements in the series, round off decimal if needed n = atod(math.log10(nterm / fterm) / math.log10(ratio) + 1) # Use n to find the sum of the series ssum = atod((fterm * (1 - ratio**n)) / (1 - ratio)) print "Sum of the geometric series: %s" % ssum return ssum class Quadratic(object): def __init__(self, a, b, c): """Create a new instance of the quadratic object. Quadratic takes exactly three arguments: the a, b, and c values of a quadratic formula. This object contains many methods related to the quadratic equation and quadratic functions. """ self.a = a self.b = b self.c = c def FindVertex(self, out=True): """Given the a, b, and c values of the quadratic function, calculate and print the vertex. Return h and k, as this function is sometimes called by other functions. If the 'out' parameter is False, return the values else print the vertex. """ h = -self.b / (2 * self.a) # -b / 2a k = ((self.a * h * h) + (self.b * h) + self.c) # f(-b / 2a) if not out: return h, k print "Vertex: ({}{},{}{})".format('- '[h < 0], abs(h), ' -'[h < 0], abs(k)) def VertexForm(self): """Convert the standard form of a quadratic to vertex form ie y = a(x - h)^2 + k. """ vertex = self.FindVertex(False) h, k = vertex[0], vertex[1] print u"{}(x {} {})\u00b2 {} {}".format(check(self.a), '-+'[h < 0], abs(h), '+-'[k < 0], abs(k)) # Complete the square given the 'b' term of a quadratic equation. def CompleteSquare(self): print (self.b / 2) ** 2 def Discriminant(self, value=False): """Find the value of the discriminant and return or print its value. The discriminant is b^2 - 4ac, the value under the radical of the quadratic equation. This method can be used either as a return value or to print the discriminant and number of solutions to stdout, depending on the 'value' parameter. """ d = self.b * self.b - 4 * self.a * self.c if value is True: return d if d > 0: print "The discriminant is %s. There are 2 solutions." % d elif d == 0: print "The discriminant is %s. There is 1 solution." % d else: print "There are no real solutions." def FactorizeQuadratic(self): """Factorize the quadratic expression ax^2 + bx + x over the real numbers and print the factorization. If it is not factorable, raise an error. If the sol parameter is True, include solutions to the x values. ----- Examples ----- >>> factorize_quadratic(1, 4, 4) (x + 2)(x + 2) >>> factorize_quadratic(1, -4, 4) (x - 2)(x - 2) >>> factorize_quadratic(7, 19, -6) (7x - 2)(x + 3) """ # Make life easier a, b, c = self.a, self.b, self.c # Find common factor, if any f = abs(gcd(gcd(a, b), c)) a, b, c = a // f, b // f, c // f # Check if the discriminant is a perfect square. # If it is not, the equation is not factorable. discriminant = self.Discriminant(True) root = int(math.sqrt(abs(discriminant))) if root * root != discriminant: print "No real number factorization is possible" return False # The sorted function is strictly for visual purposes. It insures that # the factorization will be (x + 2)(x - 1) instead of (x - 1)(x + 2). r, s = sorted((Fraction(-b - root, 2 * a), Fraction(-b + root, 2 * a)), key=abs) def factor(t): if t == 0: return "x" n, d = t.numerator, t.denominator return "({}x {} {})".format(check(d), '-+'[n < 0], abs(n)) print "{}{}{}".format(check(f), factor(r), factor(s)) return True class Radical(object): def __init__(self, rad, root=2): self.rad = rad self.root = root def FindRoot(self): print self.rad ** (1 / self.root) if __name__ == '__main__': #check_geometric_sequence((4,12,36), False) geometric_series(3, 3072, 2)
038d6011227a6cfe626473dd89323a9e4d9bc555
Kamik423/advent-of-code-2020
/12.py
3,009
3.828125
4
#!/usr/bin/env python3 from math import cos, radians, sin from typing import List import aoc class Ship: """ ▲y N 90 │ W ● E 180 ● 0 └──▶x S 270 """ x: int y: int orientation: int waypoint_x: int waypoint_y: int commands: List[str] def __init__(self, commands: List[str]): self.x, self.y = (0, 0) self.waypoint_x, self.waypoint_y = (10, 1) self.orientation = 0 self.commands = commands def run(self) -> None: for command in self.commands: action = command[0] value = int(command[1:]) if action == "N": self.y += value elif action == "S": self.y -= value elif action == "E": self.x += value elif action == "W": self.x -= value elif action == "L": self.orientation += value elif action == "R": self.orientation -= value elif action == "F": self.x += int(cos(radians(self.orientation))) * value self.y += int(sin(radians(self.orientation))) * value else: assert False, f"Action '{action}' not known" while self.orientation >= 360: self.orientation -= 360 while self.orientation < 0: self.orientation += 360 def rotate_waypoint(self, angle: int) -> None: """Rotate waypoint counterclockwise for specified amount of degrees.""" theta = radians(angle) self.waypoint_x, self.waypoint_y = ( self.waypoint_x * int(cos(theta)) - self.waypoint_y * int(sin(theta)), self.waypoint_x * int(sin(theta)) + self.waypoint_y * int(cos(theta)), ) def run2(self) -> None: for command in self.commands: action = command[0] value = int(command[1:]) if action == "N": self.waypoint_y += value elif action == "S": self.waypoint_y -= value elif action == "E": self.waypoint_x += value elif action == "W": self.waypoint_x -= value elif action == "L": self.rotate_waypoint(value) elif action == "R": self.rotate_waypoint(-value) elif action == "F": for _ in range(value): self.x += self.waypoint_x self.y += self.waypoint_y else: assert False, f"Action '{action}' not known" @property def manhattan_distance(self) -> int: return abs(self.x) + abs(self.y) def main() -> None: ship = Ship(aoc.get_lines(12)) ship.run() print(ship.manhattan_distance) ship = Ship(aoc.get_lines(12)) ship.run2() print(ship.manhattan_distance) if __name__ == "__main__": main()
8e878e698cc603c45fc8f59fc3cdce95de5f271e
huangde/Project_Euler-and-Python-Challenge
/Project_Euler/P27.py
458
3.5625
4
import Primelist from P3 import IsPrime listb=Primelist.primes(1000) lista=range(-999,1000,2) def f1(a,b): return lambda n:n**2+a*n+b def Nprime(c): n=0 nprime=0 while c(n)>0: if IsPrime(c(n)): n+=1 nprime+=1 else: break return nprime res=[] for a in lista: for b in listb: c=f1(a,b) n=Nprime(c) # print n,a,b res.append((n,a,b)) print max(res)
e032b3741971024ab77674a3b95686fb87d94697
KIMSIYOUNG/Algorithm-study
/programmers-1/DivideArray.py
610
3.65625
4
''' 파이썬에서 문자열, 튜플, 리스트가 비어있는 경우 False를 반환한다. return문에서도 and | or 를 사용하면 boolean 유무를 판단하여 리턴한다. 둘을 합치면 return answer or -1 이 가능하다. - answer가 빈 리스트가 아니면 true이기에 그냥 리턴하고, 빈 리스트라면 false를 리턴하여 or 뒤의 구문이 실행된다. ''' def solution(arr, divisor): answer = sorted([v for v in arr if v % divisor == 0]) return answer or -1 print(solution([5, 9, 7, 10], 5)) print(solution([2, 36, 1, 3], 1)) print(solution([3, 2, 6], 10))
6731f1d1568d941135d74cdbcef070371cb6cc55
Born-S1nner/simpleCalc
/tablet.py
1,667
4.03125
4
from tkinter import * window = Tk() expression = "" def input_number(number, equation): global expression expression = expression + str(number) equation.set(expression) def clear_input_field(equation): global expression expression = "" equation.set("Enter the Expression") def evaluate(equation): global expression try: result = str(eval(expression)) equation.set(result) expression = "" except: expression = "" def mainCalc(): window.title("SimpleCalc") window.geometry("325x175") Label(window, text="Simple_Calculator").grid(row=0) equation = StringVar() input_field = Entry(window, textvariable=equation) input_field.place(height=100) input_field.grid(row=1, columnspan=4, ipadx=100, ipady=5) equation.set("Enter the Expression") _1 = Button(window, text="1", command=lambda: input_number(1, equation)) _1.grid(row=2, column=0) _2 = Button(window, text="2", command=lambda: input_number(2, equation)) _2.grid(row=3, column=0) _3 = Button(window, text="3", command=lambda: input_number(3, equation)) _3.grid(row=2, column=1) _4 = Button(window, text="4", command=lambda: input_number(4, equation)) _4.grid(row=3, column=1) add = Button(window, text="+", command=lambda: input_number('+', equation)) add.grid(row=4) equal = Button(window, text="=", command=lambda: evaluate(equation)) equal.grid(row=5, columnspan=6) clear = Button(window, text='Clear', command=lambda: clear_input_field(equation)) clear.grid(row=5, columnspan=3) window.mainloop() if __name__ == '__main__': mainCalc()
7f2b7ba2657636a731f522c10d6694510849a9bd
sontekliu/python-note
/python-02/python-04.py
827
4.0625
4
#!/usr/bin/python # -*- coding:utf-8 -*- # 递归函数,如果一个函数在函数内部调用了自身,那么这个函数就是递归函数 def fact(n): if 1 == n: return 1 return n * fact(n-1) print fact(10) print fact(100) # 栈溢出 print fact(1000) # 尾递归是指,在函数返回的时候,调用自身本身,并且return语句不能包含表达式。 # 这样,编译器或者解释器就可已把尾递归做优化,使递归本身无论调用多少次,都只占用一个栈帧,不会溢出 # 遗憾的是,大多数语言没有针对尾递归做优化,Python也没有做优化,即使换成尾递归的写法也会导致栈溢出 # 尾递归写法 def fact(n): return fact_iter(n, 1) def fact_iter(num, result): if num == 1: return result return fact_iter(num-1, num * result)
0126f30d5acbb541fe7f5c9b09deaac116a6d096
jethrodaniel/exercism
/python/acronym/acronym.py
159
3.6875
4
import re def abbreviate(words): words = re.compile(r'[^a-zA-Z\'?!]').sub(' ', ''.join(words)).split() return ''.join([x[0] for x in words]).upper()
c14b764a3ea115112b347021d4ef66f7fc43c19a
pzfrenchy/SortingMethods
/InsertionSort/InsertionSort/InsertionSort.py
508
3.90625
4
list = [3,2,5,8,4] for i in range(1, len(list)): currentValue = list[i] #copy current value to temp location while i > 0 and list[i-1] > currentValue: #check if index greater than 0 and preceeding value greater than current list[i] = list[i-1] #shift higher value right i -= 1 #decrement index location list[i] = currentValue #insert current value into correct location print(list)
3919e12eae9de47329e665a8f238bf8a5505bb4d
DavidNovo/ExplorationsWithPython
/ftpExperiments.py
797
3.640625
4
__author__ = 'davidnovogrodsky_wrk' from ftplib import FTP ftp = FTP('domainname.com') ftp.login(user='username', passwd='password') ftp.cwd('/specific domain or location/location of files/') # getting a file def grabFile: #name off file we want to grab fileName= 'fileName.txt' # opening a local file localfile = open(fileName, 'wb') # retrieve a file ftp.retrbinary('RETR ' + fileName, localfile.write, 1024) ftp.quit() localfile.close() #send a file to remote server def placeFile(): #define local file to send fileName= 'nameoflocalffile.txt' # use ftp commands to send file # open remote file ftp.storbinary('STOR '+fileName, open(fileName, 'rb')) # close ftp connection ftp.quit() # close local file
40107a49deb5b3f2ad8d4c1e79d4769189c924f5
Widdershin/CodeEval
/challenges/024-simplesorting.py
1,111
4.375
4
""" https://www.codeeval.com/browse/91/ Simple Sorting Challenge Description: Write a program which sorts numbers. Input Sample: Your program should accept as its first argument a path to a filename. Input example is the following 70.920 -38.797 14.354 99.323 90.374 7.581 -37.507 -3.263 40.079 27.999 65.213 -55.552 Output Sample: Print sorted numbers in the following way. -38.797 7.581 14.354 70.920 90.374 99.323 -55.552 -37.507 -3.263 27.999 40.079 65.213 -38.797 7.581 14.354 70.92 90.374 99.323 -55.552 -37.507 -3.263 27.999 40.079 65.213 """ ###### IO Boilerplate ###### import sys if len(sys.argv) < 2: input_file_name = "024-simplesorting-in.txt" else: input_file_name = sys.argv[1] with open(input_file_name) as input_file: input_lines = map(lambda x: x.strip(), filter(lambda x: x != '', input_file.readlines())) ###### /IO Boilerplate ###### def main(): for line in input_lines: numbers = map(float, line.split(' ')) print " ".join(map("{:.3f}".format, sorted(numbers))) if __name__ == '__main__': main()
82c732e4cb902a915572437ac165ae1c1d1230bf
ChrisLiu95/Leetcode
/easy/Balanced_Binary_Tree.py
1,169
4.125
4
""" Given a binary tree, determine if it is height-balanced. 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 1: Given the following tree [3,9,20,null,null,15,7]: 3 / \ 9 20 / \ 15 7 Return true. Example 2: Given the following tree [1,2,2,3,3,null,null,4,4]: 1 / \ 2 2 / \ 3 3 / \ 4 4 Return false. """ # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def isBalanced(self, root): """ :type root: TreeNode :rtype: bool """ # 比较每一个node的左右最大树深相差是否超过1 def balance(root): if not root: return [True, -1] left = balance(root.left) right = balance(root.right) isBalanced = left[0] and right[0] and abs(left[1] - right[1]) <= 1 return [isBalanced, max(left[1], right[1]) + 1] return balance(root)[0]
d09ac79c0c81eb6c6520483d9db5faaff60bd078
harishramuk/python-handson-exercises
/193. Important Methods and Functions for Dict keys,values,items1.py
306
3.9375
4
#KEYS & VALUES d = {100:'A',200:'B',300:'C'} print(d.keys()) for key in d.keys(): print(key) print(d.values()) for valu in d.values(): print(valu) #item method print(d.items()) for item in d.items(): print(item) for k,v in d.items(): print(k,'---------',v)
3de071389f50099ea8bb39632bb4bdb8caae030a
yuvika22/hackerrank-python
/basic/FindingThePercentage.py
496
3.609375
4
# Solution to https://www.hackerrank.com/challenges/finding-the-percentage/problem?h_r=next-challenge&h_v=zen if __name__ == '__main__': n = int(input()) student_marks = {} for _ in range(n): name, *line = input().split() scores = list(map(float, line)) student_marks[name] = scores query_name = input() # print(student_marks) n = student_marks[query_name] # print([n]) sum = 0 for marks in n: sum = sum + marks print("%1.2f" % (sum/len(n)))
fe48adf7a36ff5dc7dd0d6a30743c6214c6d2db5
EddieHandford/Speed-Pong
/pong.py
4,997
3.609375
4
# -*- coding: utf-8 -*- """ Created on Sun Feb 10 12:00:59 2019 @author: Eddie """ import turtle import winsound wn = turtle.Screen() wn.title("Pong by Eddie") wn.bgcolor("blue") wn.setup(width=800 , height=800) wn.tracer(0) #while True: # wn.update() # #creating a paddle #paddle a paddle_a = turtle.Turtle() paddle_a.speed(0) # max speed paddle_a.shape("square") paddle_a.color("white") paddle_a.shapesize(stretch_wid = 5, stretch_len=1) paddle_a.penup() paddle_a.goto(-350,0) #paddle b paddle_b = turtle.Turtle() paddle_b.speed(0) # max speed paddle_b.shape("square") paddle_b.color("white") paddle_b.shapesize(stretch_wid = 5, stretch_len=1) paddle_b.penup() paddle_b.goto(350,0) #ball ball = turtle.Turtle() ball.speed(0) # max speed ball.shape("square") ball.color("white") ball.penup() ball.goto(0,0) # Score score_a = 0 score_b = 0 ball.dx = (score_a+score_b) + 0.03 ball.dy = (score_a+score_b) + 0.03 # max move is by 2 pixels #pen pen = turtle.Turtle() pen.speed() pen.color("white") pen.penup() pen.hideturtle() pen.goto(0,260) pen.write("PlayerA: 0 Computer: 0" , align="center" , font=("Courier" , 24 , "normal")) #function for moving objects def paddle_a_up(): y = paddle_a.ycor() #assidle paddle y coor to a "y" y += 20 # goes up by 20 pixels when you press up paddle_a.sety(y) def paddle_a_down(): y = paddle_a.ycor() #assidle paddle y coor to a "y" y -= 20 # goes up by 20 pixels when you press up paddle_a.sety(y) def paddle_b_up(): y = paddle_b.ycor() #assidle paddle y coor to a "y" y += 20 # goes up by 20 pixels when you press up paddle_b.sety(y) def paddle_b_down(): y = paddle_b.ycor() #assidle paddle y coor to a "y" y -= 20 # goes up by 20 pixels when you press up paddle_b.sety(y) wn.listen() wn.onkeypress(paddle_a_up, "w") wn.onkeypress(paddle_a_down, "s") #if ball.ycor > paddle_b.ycor() : # paddle_b_up #if ball.ycor < paddle_b.ycor() : # paddle_b_down count_hits = 0 #this is the two player eddition , about to be removed #wn.onkeypress(paddle_b_up, "i") #wn.onkeypress(paddle_b_down, "k") while True: wn.update() # ball.dx = (score_a+score_b)*0.01 + 0.03 # ball.dy = (score_a+score_b)*0.01 + 0.03 # max move is by 2 pixels #move ball #ball.dx = ball.dx + (count_hits*0.05) # ball.dy = ball.dy + (count_hits*0.05) ball.setx(ball.xcor() + ball.dx) ball.sety(ball.ycor() + ball.dy) #border of game check if ball.ycor() >290: ball.sety(290) ball.dy *= -1 winsound.PlaySound("bounce.wav" , winsound.SND_ASYNC) if ball.ycor() <-290: ball.sety(-290) ball.dy *= -1 winsound.PlaySound("bounce.wav" , winsound.SND_ASYNC) if ball.xcor() >390: ball.goto(0,0) ball.dx += 0.01 ball.dy += 0.01 ball.dx *= -1 score_a += 1 pen.clear() pen.write("PlayerA: {} PlayerB: {}".format(score_a , score_b) , align="center" , font=("Courier" , 24 , "normal")) winsound.PlaySound("reload.wav" , winsound.SND_ASYNC) if ball.xcor() <-390: ball.goto(0,0) ball.dx *= -1 ball.dx += 0.01 ball.dy += 0.01 score_b += 1 pen.clear() pen.write("PlayerA: {} PlayerB: {}".format(score_a , score_b) , align="center" , font=("Courier" , 24 , "normal")) winsound.PlaySound("reload.wav" , winsound.SND_ASYNC) #paddle hitting the ball if ball.xcor() > 340 and ball.xcor() < 350 and (ball.ycor() < paddle_b.ycor() + 50 and ball.ycor() > paddle_b.ycor() - 50): ball.setx(340) winsound.PlaySound("bounce.wav" , winsound.SND_ASYNC) count_hits += 1 ball.dx = ball.dx + (0.05) ball.dy = ball.dy + (0.05) ball.dx *= -1 if ball.xcor() < -340 and ball.xcor() > -350 and (ball.ycor() < paddle_a.ycor() + 50 and ball.ycor() > paddle_a.ycor() - 50): ball.setx(-340) winsound.PlaySound("bounce.wav" , winsound.SND_ASYNC) count_hits += 1 ball.dx = ball.dx - (0.05) ball.dy = ball.dy - (0.05) ball.dx *= -1 if ball.ycor() > paddle_b.ycor() : y = paddle_b.ycor() #assidle paddle y coor to a "y" y += 20 # goes up by 20 pixels when you press up paddle_b.sety(y) if ball.ycor() < paddle_b.ycor() : y = paddle_b.ycor() #assidle paddle y coor to a "y" y -= 20 # goes up by 20 pixels when you press up paddle_b.sety(y)
22a64e103ec232d8d51d2360014391f04dd3febf
Ezward/ai-for-robotics
/python/kalman_filter/gaussian.py
3,492
3.5
4
import sys import math # # \frac{1}{\sqrt{2\pi\sigma^{2}}} \times e^{\frac{1}{2}\frac{(x-\mu)^{2}}{\sigma^{2}}} # def gaussian(mean, variance, x): """ Calculate the probability at x given a gaussian distribution. :param mean: mean of the gaussian distribution :param variance: variance of the gaussian distribution :param x: value at which to get probability :return: probability at x """ return (1.0 / math.sqrt(2.0 * math.pi * variance)) * math.exp(-0.5 * ((x - mean)**2 / variance)) # # measurement uses Bayes Rule/Product # def update(mean1, variance1, mean2, variance2): """ 'Measure' or 'Sense' Update a 1D gaussian state based on new measurement of the state. :param mean1: The mean of the prior gaussian; the most likely prior state :param variance1: The variance of the prior gaussian; the uncertainty in the prior state :param mean2: The mean of measurement; the most likely measured state :param variance2: The variance of measurement; the uncertainty in the measured state :return: (mean, variance) of updated gaussian state """ mean = 1.0 / (variance1 + variance2) * (variance2 * mean1 + variance1 * mean2) variance = 1.0 / (1.0 / variance1 + 1.0 / variance2) return (mean, variance) # # motion/predict uses total probability/convolution/addition # def predict(mean1, variance1, mean2, variance2): """ 'Move' Change a 1D gaussian state to a new state with some uncertainty in the change. :param mean1: The mean of the gaussian; the prior most likely state :param variance1: The variance of the gaussian; the uncertainty in the state. :param mean2: The mean of the change in state; the most like change. :param variance2: The variance of the change in the state; the uncertainty in the change :return: (mean, variance) of predicted gaussian state """ return (mean1 + mean2, variance1 + variance2) if __name__ == "__main__": if sys.argv[1] == "probability_at": if (len(sys.argv) != 5): print( 'Print the probability at x for the gaussian distribution defined by the mean and variance') print("Usage: python gaussian.py probability_at mean variance x") quit(1) print(gaussian(float(sys.argv[2]), float(sys.argv[3]), float(sys.argv[4]))) elif sys.argv[1] == "update": if len(sys.argv) != 6: print("combine two gaussian distributions and print the result") print("Usage: python gaussian.py update mean1 variance1 mean2 variance2") quit(1) result = update(float(sys.argv[2]), float(sys.argv[3]), float(sys.argv[4]), float(sys.argv[5])) print("mean = {}, variance = {}".format(str(result[0]), str(result[1]))) elif sys.argv[1] == "predict": if len(sys.argv) != 6: print("predict that gaussian distribution after a movement and print the result") print("Usage: python gaussian.py predict mean1 variance1 motion motion_variance") quit(1) prediction = predict(float(sys.argv[2]), float(sys.argv[3]), float(sys.argv[4]), float(sys.argv[5])) print("mean = {}, variance = {}".format(str(prediction[0]), str(prediction[1]))) else: print("Usage: python gaussian.py probability_at mean variance x") print("Usage: python gaussian.py update mean1 variance1 mean2 variance2") quit(1)
e241f56a767c82903d1da8976cf362dc5609a483
JohnMachado11/100-Projects-Python
/05.1_Avg_Height/avg_height_easier.py
448
4.25
4
# AVERAGE HEIGHT OF ALL STUDENTS # Example input = 67 82 51 31 21 student_heights = input("Input a list of student heights ").split() for n in range(0, len(student_heights)): student_heights[n] = int(student_heights[n]) # Method 1 - Easy total_height = sum(student_heights) number_of_students = len(student_heights) average_height = round(total_height / number_of_students) print(f"Students average height = {average_height}.")
11d076db3b191d1a1dd9514ae3473dc86a0ce05c
leaner2/python
/10.1.1读取整个文件.py
1,689
3.8125
4
with open('pi_digits.txt') as file_object: contents = file_object.read() print(contents) #10.1.2 文件路径 #绝对路径:with open('C:\users\other_files\text_files\filename.txt') as file_object: print('\n\n') #10.1.3 逐行读取 filename = 'pi_digits.txt' with open(filename) as file_object: for line in file_object: print(line) #去除空行用line.rstrip print('\n\n') #10.1.4 创建一个包含文件各行内容的列表 filename = 'pi_digits.txt' with open(filename) as file_object: lines = file_object.readlines() #raadlines() 把文件中的每一行读取后存储在列表中 for line in lines: print(line.rstrip()) print('\n\n') #10.1.5使用文件内容 filename = 'pi_digits.txt' with open(filename) as file_object: lines = file_object.readlines() includings = '' for line in lines: includings += line.rstrip() print(includings) print(len(includings)) #包含一百万位的大型文件 filename = 'rode.txt' with open(filename) as file_object: lines = file_object.readlines() including = '' for line in lines: including += line.rstrip() print(including[:600] + "...") print(len(including)) print('\n\n') #10.1.7 圆周率中包含你的生日吗 filename = 'rode.txt' with open(filename) as file_object: lines = file_object.readlines() including = '' for line in lines: including += line.rstrip() check_including = input("enter what do you wang to check: ") if check_including in including: print("there has what you want!") else: print("nothing you want")
f7572560f518e1ac5e678c79bbce205ff005f08d
singhwarrior/python
/python_samples/chap5/winner.py
2,670
4.0625
4
""" <Problem Statement> Read race timings of james,julie,mikey,sarah from corresponding input files. Print the top three performances of each. <Working Description> One line is read from all files which correspond to race-time values of each player. Each line is splitted by comma. Since comma separated values are not in proper format(like contains - or : in between), hence making the values in proper format using the function sanatize.So each value after split is sanatized and then after sanatizing the new list created is sorted. For each player, first three unique values are displayed from sorted list. Note: A good example of list comprehension has been used here. [sanatize(t) for t in james] => returns a list. it reduces quite a good amount of code. General format is as follows: output_list = [function(element) for element in input_list] """ def sanatize(time_string): splitter="" if "-" in time_string: splitter = "-" elif ":" in time_string: splitter = ":" else: return(time_string) (mins,secs)=time_string.split(splitter) return(mins+"."+secs) def top_three_items(time_list): unique_list=[] count=0 for time in time_list: if time not in unique_list: unique_list.append(time) count=count+1 if count == 3: break return unique_list james=[] julie=[] mikey=[] sarah=[] try: with open("james.txt") as james_file, open("julie.txt") as julie_file, open("mikey.txt") as mikey_file, open("sarah.txt") as sarah_file: james_time_taken = james_file.readline() julie_time_taken = julie_file.readline() mikey_time_taken = mikey_file.readline() sarah_time_taken = sarah_file.readline() james = james_time_taken.strip().split(",") julie = julie_time_taken.strip().split(",") mikey = mikey_time_taken.strip().split(",") sarah = sarah_time_taken.strip().split(",") james = sorted([sanatize(t) for t in james]) julie = sorted([sanatize(t) for t in julie]) mikey = sorted([sanatize(t) for t in mikey]) sarah = sorted([sanatize(t) for t in sarah]) top_three_performances_james=top_three_items(james) top_three_performances_julie=top_three_items(julie) top_three_performances_mikey=top_three_items(mikey) top_three_performances_sarah=top_three_items(sarah) print(james) print(julie) print(mikey) print(sarah) print("TOP THREE PERFOROMANCES JAMES :"+str(top_three_performances_james)) print("TOP THREE PERFOROMANCES JULIE :"+str(top_three_performances_julie)) print("TOP THREE PERFOROMANCES MIKEY :"+str(top_three_performances_mikey)) print("TOP THREE PERFOROMANCES SARAH :"+str(top_three_performances_sarah)) except IOError as err: print("File Error : "+str(err))
72a3c78ebc5aa2dda8b123a1f396e580a9aaa1d1
HussainAther/mathematics
/algebra/neuralnetworks/nesterov.py
2,109
3.71875
4
import numpy as np """ Nesterov's (Nesterov nesterov) method for proximal gradient descent. """ def grad(f, x, deltax): """ Compute the gradient numerically using our function f that takes in x as a variable. """ xval = f(x) # evaluate the function f at x. step = f(x + deltax) # step forward with deltax return (step - xval) / deltax # return the difference over the deltax value def nes(f, t, dim, alpha, xinit=None, eps=.05, num=False, deltax=.0005): """ Use the Nesterov method for proximal gradient descent. We improve convergence and can add a momentum term such that we relax the descent property. We update our function with a momentum value that accounts for the step size. f is our function that we evaluate. t is our learning rate. dim is the number of dimensions of x. xinit is our initialized x value. eps (epsilon) is our tolerance used to stop the algorithm. num (numerical gradient) sets whether to use the numerical gradient. deltax is the step size we use with the gradient. """ # initialize our x values to our dimensions. if xinit == None: x = np.zeros(dim) else: x = xinit # lambda is the estimate sequence used to estimate the phi function used to # minimize our function f. lprev = 0 # previous lambda value lcurr = 1 # current lambda value yprev = x # previous y value alpha = .025 # used in optimization # evaluate the gradient numerically g = grad(f, x, deltax) # until we reach our tolerance epsilon value from our gradient while np.linalg.norm(grad) >= epsilon: ycurr = x - alpha * gradient # current y value x = (1 - t) * ycurr + t * yprev # adjust our x value yprev = ycurr # move to the previous y value lmp = lcurr # temporarily save this lambda value lcurr = (1 + np.sqrt(1 + 4 * lprev**2)) / 2 # calculate current lambda value lprev = ltmp # move to the previous lambda value t = (y - lprev) / lcurr g = grad(f, x, deltax) # update our gradient return x # return
ecf2ad1669596a3c7467cfa7f463d7d9225d2cb8
marojas11/MC
/python/exercises/pyworkbook-10.py
507
4.03125
4
import numpy as np print "Exercise 10:Arithmetic" print "Create a program that reads two integers, a and b,from the user.Your program should compute and display" print "The sum of and b" a=float(raw_input("Please enter a=")) b=float(raw_input("Please enter b=")) print "La suma es: ", a+b print "La resta b-a es:", b-a print "El producto es:", a*b print "El cociente a/b es: ", a/b print "El residuo de a/b es: ", a%b print "El logaritmo en base 10 de a es:", np.log10(a) print "El exponencial a**b", a**b
4a07f78d93fe44d5baa928d7d8c2ee1c7c300e12
Zihan2Wang/Checkers
/turn.py
8,342
3.9375
4
''' This module contains one class, Turn, which represents the stages of the current turn. ''' from constants import NEW_TURN, VALID_PIECE_SELECTED, CHECK_MULTIPLE_JUMPS, \ MOVE_COMPLETE import random class Turn: ''' Class -- Turn Represents the stages of a player's turn. Attributes: self -- the current Turn object player -- the player whose turn it is, black or red step -- the stage of the turn e.g. new turn, capture required valid_moves -- a dictionary of all possible valid moves for this player capture_required -- a boolean indicating if a capture is required. This is True if a capture is possible. possible_targets -- populated after a Piece is selected, a list of all valid Moves for that Piece. final_move -- the Move that is actually made. Methods: __init__ -- constructor is_valid_turn -- checks if the selected Move meets the Turn requirements. is_turn_complete -- checks if the Turn is complete. complete_turn -- sets the step attribute to "complete". choose_ai_cell -- makes the AI's turn ''' def __init__(self, player, valid_moves): ''' Constructor -- Creates a new instance of Turn Parameter: self -- The current Turn object valid_moves -- A dictionary of all possible Moves for the current player. ''' self.player = player self.step = NEW_TURN self.valid_moves = valid_moves self.capture_required = self.is_capture_required() self.possible_targets = [] self.final_move = None def is_capture_required(self): ''' Method -- is_capture_required Checks if a capture must be made. Parameters: self -- The current Turn object Returns: True if the dictionary of valid_moves contains a capturing Move, False otherwise. ''' for piece in self.valid_moves: if self.valid_moves[piece][0].is_capture(): return True return False def playable_cell_selected(self, cell_clicked): ''' Method -- playable_cell_selected Checks if the selected cell is "playable". If the turn has just begun (no piece has been chosen), the cell must contain one of the current player's pieces. If a turn has begun (a piece has been chosen), the clicked cell must be a valid target for the chosen piece. TODO allow the user to change their mind and select a different piece to move Parameters: self -- The current Turn object cell_clicked - The cell clicked by the user Returns: True if the cell is playable, False otherwise. ''' if self.step == NEW_TURN: return cell_clicked in self.valid_moves elif not self.is_turn_complete(): return self.find_clicked_target(cell_clicked) is not None return False def find_clicked_target(self, cell_clicked): ''' Method -- find_clicked_target Helper method for completing a move. Checks if the cell that was clicked is a valid target for the selected piece. Parameters: self -- The current Turn object cell_clicked -- The cell that was clicked Return: The target Cell if found or None if the clicked cell is not a valid target. ''' for target in self.possible_targets: if cell_clicked == target.new_loc: return target return None def is_valid_turn(self, cell_clicked): ''' Method -- is_valid_turn Checks if the selected cell is "valid". To be valid, either no capture is required, or, if a capture IS required, the selected Piece can make a capture. Parameters: self -- The current Turn object cell_clicked -- The cell clicked Returns: True if cell will allow the player to make a Turn meeting the requirements. ''' if not self.playable_cell_selected(cell_clicked): return False if self.step == NEW_TURN: if self.allowed_start_piece(cell_clicked): self.finish_initial_selection(cell_clicked) return True target = self.find_clicked_target(cell_clicked) if target is not None and (target.is_capture() or not self.is_capture_required()): self.finish_piece_move(target) return True print("A capture is possible... piece MUST be captured!") return False def allowed_start_piece(self, cell_clicked): ''' Method -- allowed_start_piece Helper method called when the user selects a piece to move. Checks if the selected piece meets requirements. Parameters: self -- The current Turn object cell_clicked -- The cell clicked (or selected) Returns: True if the selected piece is allowed, False otherwise. ''' return not self.is_capture_required() or \ self.is_capture_required() and \ self.valid_moves[cell_clicked][0].is_capture() def finish_initial_selection(self, start_loc): ''' Method -- finish_initial_selection Helper method that updates Turn attributes when a valid piece is selected. Parameters: self -- the current Turn object start_loc -- The cell containing the selected piece ''' self.step += 1 self.possible_targets = self.valid_moves[start_loc] def finish_piece_move(self, move): ''' Method -- finish_piece_move Helper method that updates Turn attributes when a piece is moved. Parameters: self -- the current Turn object move -- The Move that is being made ''' self.step = CHECK_MULTIPLE_JUMPS if self.capture_required \ else MOVE_COMPLETE self.final_move = move def is_turn_complete(self): ''' Method -- is_turn_complete Checks if the Turn is complete. Parameters: self -- The current Turn object Returns: True if the Turn is complete, False otherwise. ''' return self.step == MOVE_COMPLETE def complete_turn(self): ''' Method -- complete_turn Sets the step attribute to complete the Turn Parameters: self -- The current Turn object ''' self.step = MOVE_COMPLETE def choose_ai_cell(self): ''' Method -- choose_ai_cell Chooses the cells for the AI move. If there are capturing moves available, chooses the first option. Otherwise, picks a move at random. Parameter: self -- The current Turn object ''' loc = None if self.step == NEW_TURN: if self.capture_required: for location in self.valid_moves: if self.valid_moves[location][0].is_capture(): loc = location break else: key_loc = random.randint(0, len(self.valid_moves) - 1) loc = list(self.valid_moves.keys())[key_loc] self.finish_initial_selection(loc) elif self.step == VALID_PIECE_SELECTED or self.step == CHECK_MULTIPLE_JUMPS: loc = self.possible_targets[0].new_loc self.finish_piece_move(self.possible_targets[0]) return loc
f7cf98e69d24d996f7e061598483a609fe5b348b
DOGANAY06/My-python-project-
/librarytobb4days.py
4,026
3.5
4
# -*- coding: utf-8 -*- """ Created on Tue Aug 27 13:25:25 2019 @author: Doğan AY """ import os dir(os) #%% import speech import time response = speech.input("Say something, please.") speech.say("You said " + response) def callback(phrase, listener): if phrase == "goodbye": listener.stoplistening() speech.say(phrase) listener = speech.listenforanything(callback) while listener.islistening(): time.sleep(.5) #%% import os os.name if os.name=="nt": print("Windows sizin isletim sisteminiz") else: print("Başka birşey") #%% liste=["a","b","c","d","e"] import random random.choice(liste) random.randint(1,5) #%% import random a=random.randint(1,7) sayac=3 for i in range (0,5): print(i,".") sayi=int(input("Sayı giriniz=")) if sayi > a: print("Sayıdan büyüksünüz=") sayac=sayac+1 elif sayi==a: print("Tebrikler =") sayac=sayac+1 break elif sayi<a: print("Sayı dan kücüksünüz =" ) sayac=sayac+1 else: print("Sayıyı bilemediniz=",a) #break komutundan sonraki else for elseyi ifade eder ve for la aynı hizada olmalı #%% a=random.randint(1,100) hak=3 while True: sayi=int(input("Sayıyı giriniz:")) if (sayi<a): print("Sayıyı giriniz...") hak=hak-1 elif sayi>a: print("Daha düsük bir sayi söyleyin") hak=hak-1 else: print("Tebrikler! Sayımız",a) break if (hak==0): print("Hakkınız bitti...") print("Sayımız:",a) break #%% import datetime gecerlizaman=datetime.datetime.now() #şuanki zamanı yazarız print(gecerlizaman) #%% print("Şuanki zaman",gecerlizaman) print("Year:",end="") print(gecerlizaman.year) print(gecerlizaman.month) print(gecerlizaman.hour) print(gecerlizaman.second) print("Minute:",end ="") print(gecerlizaman.minute) #%% zaman="2019-09-29" print("Zamanın kaldı=",zaman-gecerlizaman) #%% #fibonacci sayısı ödev def Topla(sayi1,sayi2): #fonksiyon tanımlamak için kullanılır print(sayi1+sayi2) Topla(3,5) sy1=int(input("Sayı girinz=")) #sayı girdisini alın sayıları toplatın sy2=int(input("Sayıyı giriniz=")) Topla(sy1,sy2) #%% x=int(input("Sınav notunuz:")) def sinavdegerlendirme(sinavnot): if sinavnot>100 or sinavnot<0: print("Hatalı girdin:") else: if sinavnot>50: print("Gectin") else: print("Sınavda kaldın") sinavdegerlendirme(x) #%% name1=input("İsminizi ve soyisminizi girinz:") name2=input("Soyisiminizi ve isminizi giriniz:") print("Alfabetik sıraya göre") if name1<name2: print(name1) print(name2) else: print(name2) print(name1) #%% 153 sayısının sayılarının rakamlarının karesini alan program sayi=153 birlerbasamagı=3 onlarbasamafı #%% birds=int(input("Kuş sayısı giriniz=")) def main(): texas() ankara() def texas(): birds=5000 print('Texas has',birds,'birds') def ankara(): #birds=11000 print('Ankara has got',birds,'birds') main() #%% def main(): first_name=input("İsminizi giriniz=") last_name=input("Soyadınızı giriniz=") print("Reezervasyon iŞlemi sahibi") reverse_name(first_name,last_name) def reverse_name(first,last): x=last y=first print(last,first) print(y,x) main() #%% def main(): value=int(input("Sayıyı giriniz=")) show_double(value) def __init__show_double(value): # buna başka bir değişkende girebiliriz fonksiyonlar için result =value * 2 print(result) main() #%% highscore=50 def main(): test1=int(input("1.Sınav notunu giriniz=")) test2=int(input("2.Sınavı giriiz=")) test3=int(input("3.SINAVI GİRİNİZ=")) average=(test1++test2+test3)/3 print("Ortalama=",average) def hesaplama(average): if average>=highscore: print("tEBRİKLER") main()
022fcaba4ab02fab876b5d6cb00a63bb81169f87
jennerwein/whoami
/app/helper.py
2,723
3.671875
4
import math ############################################################################## # Prettyprint duration of time def duration(time): def norm2(zahl): return(("00"+str(zahl))[-2:]) gesamtzeit=time dauer='' # Tage days = time // (24 * 3600) if days == 1: dauer=dauer+str(days)+' day ' if days > 1: dauer=dauer+str(days)+' days ' #Stunden time = time % (24 * 3600) hours = time // 3600 if hours == 1: dauer=dauer+str(hours)+' hour ' if hours > 1: dauer=dauer+str(hours)+' hours ' #Minuten time %= 3600 minutes = time // 60 if minutes >= 1: dauer=dauer+str(minutes)+' min ' # Sekunden time %= 60 seconds = time dauer=dauer+str(seconds)+' sec' ##### Testausdruck # print("d:h:m:s-> %d:%d:%d:%d" % (days, hours, minutes, seconds)) return dauer ############################################################################## # Prettyprint KB, MB, GB, or TB string def humanbytes(B): '''Return the given bytes as a human friendly KB, MB, GB, or TB string''' B = float(B) KB = float(1024) MB = float(KB ** 2) # 1,048,576 GB = float(KB ** 3) # 1,073,741,824 TB = float(KB ** 4) # 1,099,511,627,776 # if B < KB: return '{0} {1}'.format(B,'Bytes' if 0 == B > 1 else 'Byte') elif KB <= B < MB: return '{0:.3f} KB'.format(B/KB) elif MB <= B < GB: return '{0:.3f} MB'.format(B/MB) elif GB <= B < TB: return '{0:.3f} GB'.format(B/GB) elif TB <= B: return '{0:.3f} TB'.format(B/TB) ############################################################################## # Calculating the Perceived Brightness of a Color # https://www.nbdtech.com/Blog/archive/2008/04/27/Calculating-the-Perceived-Brightness-of-a-Color.aspx def rgb_brightness(color): R = int(color[1:3], 16) G = int(color[3:5], 16) B = int(color[5:7], 16) return math.sqrt(0.241*R*R + 0.691*G*G + 0.068*B*B ) # Bessere Formel in: # https://stackoverflow.com/questions/596216/formula-to-determine-brightness-of-rgb-color ############################################################################## ############################################################################## ############################################################################## if __name__ == '__main__': ##### Test humanbytes # tests = [1, 1024, 500000, 1048576, 50000000, 1073741824, 5000000000, 1099511627776, 5000000000000] # for t in tests: # print('{0} == {1}'.format(t,humanbytes(t))) ##### Test rgb-brghtness print(rgb_brightness("#121314")) ##### Test Prettyprint duration of time time = int(2*60*60+7) print(duration(time))
d428c57ec98d625ca335bec9369bf6567845c0c8
iofall/War
/war.py
7,029
4.15625
4
# A Simple War Game from random import shuffle # Two useful variables for creating Cards. SUITE = 'H D S C'.split() RANKS = '2 3 4 5 6 7 8 9 10 J Q K A'.split() class Deck: """ Deck Class for creating a deck of 52 cards """ def __init__(self): self.cards = [] for suite in SUITE: for rank in RANKS: card = rank + suite self.cards.append(card) def split(self): return self.cards[::2], self.cards[1::2] def shuffle(self): return shuffle(self.cards) class Hand: ''' Hand class is used to keep track of the current cards with a player ''' def __init__(self, cards): self.cards = cards def add(self, cards): """ Expects card as an iterable In some cases a single card is supplied as an argument to this function. This causes problems when using the insert method because it iterates through the string and ends up separating the card letters. """ if (type(cards) != list): cards = [cards] shuffle(cards) for card in cards: self.cards.insert(0, card) def remove(self): if (len(self) == 0): return "Loser" else: return self.cards.pop() def __len__(self): return len(self.cards) class Player: """ This is the Player class, which takes in a name and an instance of a Hand class object. The Player can then play cards and check if they still have cards. """ def __init__(self, name, hand): self.name = name self.hand = hand def __str__(self): return self.name def draw_card(self): """ Remove 1 card from hand """ return self.hand.remove() def draw_war_cards(self): """ Removes 3 or remaining cards in hand in case of war """ war_cards = [] if (len(self.hand) < 3): for _ in self.hand.cards: war_cards.append(self.hand.remove()) else: for _ in range(3): war_cards.append(self.hand.remove()) return war_cards def empty(self): if not len(self.hand) == 0: return True else: return False def rank(card): if len(card) == 2: return RANKS.index(card[0]) elif len(card) == 3: return RANKS.index(card[:2]) def main(): print("Welcome to War, let's begin...") # Instantiating a Deck d = Deck() d.shuffle() h1, h2 = d.split() user = Player("User", Hand(h1)) comp = Player("Computer", Hand(h2)) rounds = 0 while (user.empty() and comp.empty()): rounds += 1 current_cards = [] user_card = user.draw_card() comp_card = comp.draw_card() if "Loser" in user_card or "Loser" in comp_card: handle_loser(current_cards, user, comp, user_card, comp_card) else: current_cards.extend([user_card, comp_card]) if rank(user_card) > rank(comp_card): user.hand.add(current_cards) elif rank(user_card) < rank(comp_card): comp.hand.add(current_cards) else: war_routine(current_cards, user, comp) #war_single_routine(current_cards, user, comp) print("{}. User: {} Comp:{}, Total: {}".format(rounds, len(user.hand), len(comp.hand), len(comp.hand) + len(user.hand))) if rounds>100_000: print("Hand 1:", h1) print("Hand 2:", h2) break print() print("-"*20) if len(user.hand) > len(comp.hand): print("Winner is {}!".format(user)) elif len(user.hand) < len(comp.hand): print("Winner is {}!".format(comp)) else: print("Match draw") print("-"*20) def war_routine(current_cards, user, comp): # War: Adding 3 face down cards to the current cards # user_war_cards = user.draw_war_cards() comp_war_cards = comp.draw_war_cards() if "Loser" in user_war_cards or "Loser" in comp_war_cards: handle_loser(current_cards, user, comp, user_war_cards, comp_war_cards) else: current_cards.extend(user_war_cards) current_cards.extend(comp_war_cards) # One face up card for comparing ranks user_card = user.draw_card() comp_card = comp.draw_card() if "Loser" in user_card or "Loser" in comp_card: handle_loser(current_cards, user, comp, user_card, comp_card) else: current_cards.extend([user_card, comp_card]) if rank(user_card) > rank(comp_card): user.hand.add(current_cards) elif rank(user_card) < rank(comp_card): comp.hand.add(current_cards) else: war_routine(current_cards, user, comp) #war_single_routine(current_cards, user, comp) def war_single_routine(current_cards, user, comp): """ Handle in war clash, according to the second variation of the game """ # War-Clash: Adding 1 face down card to the current cards #### user_card = user.draw_card() comp_card = comp.draw_card() if "Loser" in user_card or "Loser" in comp_card: handle_loser(current_cards, user, comp, user_card, comp_card) else: current_cards.extend([user_card, comp_card]) # One face up card for comparing ranks user_card = user.draw_card() comp_card = comp.draw_card() if "Loser" in user_card or "Loser" in comp_card: handle_loser(current_cards, user, comp, user_card, comp_card) else: current_cards.extend([user_card, comp_card]) if rank(user_card) > rank(comp_card): user.hand.add(current_cards) elif rank(user_card) < rank(comp_card): comp.hand.add(current_cards) else: war_single_routine(current_cards, user, comp) def handle_loser(current_cards, user, comp, user_card, comp_card): # for strings if "Loser" == user_card: comp.hand.add(comp_card) comp.hand.add(current_cards) # for lists elif "Loser" in user_card: while "Loser" in user_card: user_card.remove("Loser") comp.hand.add(comp_card) comp.hand.add(user_card) # for strings elif "Loser" == comp_card: user.hand.add(user_card) user.hand.add(current_cards) # for lists elif "Loser" in comp_card: while "Loser" in comp_card: comp_card.remove("Loser") user.hand.add(comp_card) user.hand.add(user_card) if __name__ == "__main__": main()
ce3022538d7a4b1bba134194493ddb9dcbf63571
SlaoutiYannis/UDACITY-Hippocampal_Volume_Quantification
/out_section2/source_code/utils/volume_stats.py
2,670
4.09375
4
""" Contains various functions for computing statistics over 3D volumes """ import numpy as np def Dice3d(a, b): """ This will compute the Dice Similarity coefficient for two 3-dimensional volumes Volumes are expected to be of the same size. We are expecting binary masks - 0's are treated as background and anything else is counted as data Arguments: a {Numpy array} -- 3D array with first volume b {Numpy array} -- 3D array with second volume Returns: float """ if len(a.shape) != 3 or len(b.shape) != 3: raise Exception(f"Expecting 3 dimensional inputs, got {a.shape} and {b.shape}") if a.shape != b.shape: raise Exception(f"Expecting inputs of the same shape, got {a.shape} and {b.shape}") # TASK: Write implementation of Dice3D. If you completed exercises in the lessons # you should already have it. intersection = np.sum(a*b) volumes = np.sum(a) + np.sum(b) if volumes == 0: return -1 return 2.*float(intersection) / float(volumes) def Jaccard3d(a, b): """ This will compute the Jaccard Similarity coefficient for two 3-dimensional volumes Volumes are expected to be of the same size. We are expecting binary masks - 0's are treated as background and anything else is counted as data Arguments: a {Numpy array} -- 3D array with first volume b {Numpy array} -- 3D array with second volume Returns: float """ if len(a.shape) != 3 or len(b.shape) != 3: raise Exception(f"Expecting 3 dimensional inputs, got {a.shape} and {b.shape}") if a.shape != b.shape: raise Exception(f"Expecting inputs of the same shape, got {a.shape} and {b.shape}") # TASK: Write implementation of Jaccard similarity coefficient. Please do not use # the Dice3D function from above to do the computation ;) # ^ as in don't call the function ? intersection = np.sum(a*b) volumes = np.sum(a) + np.sum(b) union = volumes - intersection if union == 0: return -1 return float(intersection)/float(union) # Sensitivity and specificity # the lesser the sensitivity, the worse the under-segmentation def sensitivity(a,b): tp = np.sum(b[a==b]) fn = np.sum(b[a!=b]) if fn+tp == 0: return -1 return (tp)/(fn+tp) # the lesser the specificity, the worse the over-segmentation def specificity(a,b): # let's reverse the meaning of the values a, b = a*(-1)+1, b*(-1)+1 return sensitivity(a, b) # tn = np.sum(b[a==b]) # fp = np.sum(b[a!=b]) # if tn+fp == 0: # return -1 # return (tn)/(tn+fp)
b1f1e1cdf333359b1892158101c7952cb391bdd8
harmansehmbi/Project17
/practice17e.py
258
3.6875
4
import re # re -> Regular Expression # Regular Expression Symbols quote = "Search the Candle rather than Cursing the Darkness" result = re.match("Candle", quote) # Match from starting print(result) print(type(result))
677a27d08b98f30cdd05ed3dad09f614bc7f1d93
UWPCE-PythonCert-ClassRepos/Wi2018-Classroom
/solutions/Session03/slicing_lab.py
1,059
4.125
4
#!/usr/bin/env python3 """ One solution... """ def swap(seq): """with the first and last items exchanged""" return seq[-1:] + seq[1:-1] + seq[:1] assert swap('something') == 'gomethins' assert swap(tuple(range(10))) == (9, 1, 2, 3, 4, 5, 6, 7, 8, 0) def rem(seq): """With every other item removed""" return seq[::2] assert rem('a word') == 'awr' def rem4(seq): """With the first and last 4 items removed, and every other item in between""" return seq[4:-4:2] a_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11) print(rem4(a_tuple)) assert rem4(a_tuple) == (5, 7) def reverse(seq): """With the elements reversed (just with slicing)""" return seq[::-1] print(reverse('a string')) assert reverse([3, 6, 1, 8, 3, 7]) == [7, 3, 8, 1, 6, 3] def thirds(seq): """With the middle third, then last third, then the first third in the new order""" i = len(seq) // 3 return seq[i:-i] + seq[-i:] + seq[:i] print(thirds(tuple(range(12)))) assert thirds(tuple(range(12))) == (4, 5, 6, 7, 8, 9, 10, 11, 0, 1, 2, 3)
eee25bd963e53cee87a3b2cde57db530897b07d2
reshamj/DataStructures-Algorithms
/romannumbers.py
1,261
4.1875
4
#1. Verify if an roman number is valid #2. sort an array of roman numbers import re import collections #is it a valid Roman number def isRoman(inputRoman): thousand = r'M{0,3}' hundred = r'(C[MD]|D?C{0,3})' ten = r'(X[CL]|L?X{0,3})' digit = r'(I[VX]|V?I{0,3})' result = bool(re.match(thousand+ hundred+ten+digit+'$', inputRoman.upper())) return result def romanToint(roman_num): #print roman_num nums = {'M':1000, 'D':500, 'C':100, 'L':50, 'X':10, 'V':5, 'I':1} while(isRoman(roman_num)): sum = 0 for i in range(len(roman_num)): value = nums[roman_num[i]] if i+1 < len(roman_num) and nums[roman_num[i+1]] > value: sum -= value else: sum += value return sum #sort roman numbers in an array def sortRoman(inputArray): intValue = [] intdict = {} for roman in inputArray: integer = romanToint(roman) intdict[integer] = roman print intdict od = collections.OrderedDict(sorted(intdict.items())) print od #inputArray = ["MMMDCCCLXXXVIII","IV","VII","X","CCD"] inputArray = ["CDXXI", "X", "VIII", "XIII"] sortRoman(inputArray) #result = isRoman('vii') #print result
d184d0427bad72649228740361dc91ea625f1852
giovane1-8/aulas-AfroDev
/aula_9_continuação.py
816
4.15625
4
# I/O import os os.system("cls") import pandas as pd df = pd.read_excel("estudo_io_aula_9.xlsx") print(df.index) print(df) # df1 = df.dropna() remove a linha que tiver algum valor nulo em qualquer coluna df1 = df.fillna(0) # insere um valor para os campos nulos print(f"================= \n {df1}") #print("================\n",df["nome"]) mostra somente a coluna nome #print("================\n",df.loc[3]) acesso por linha #print("================\n",df.loc[3, "saldo bancario"]) acesso por linha e coluna print("================\n",df.sort_values(by="nome")) # ordena por coluna nesse caso por nome df["teste"] = "teste" # cria nova coluna del df["teste"] # deleta uma coluna print(df.loc[[0,3], ["nome","saldo bancario"]]) # retorna multiplas linhas e expecifica
272af9d5315a5e44621c3de72d7b008ab29d9df9
anahitahassan/The-Python-Bible
/4_Logic/ifStatements.py
694
4.125
4
# 32: if Statements # python immediately indents the next line. # if I wrote False instead of true, it wouldn't print. if True: print("it worked!") num1 = 100 num2 = 150 if num1 > num2: print("num1 is bigger than num2") else: print("num1 is less than num2") # what happens if num1 = num2? num3 = 400 num4 = 400 if num3 > num4: print("num3 is bigger than num4") else: print("num3 is less than num4") # notice how the second statement was printed? # HERE'S WHAT YOU ACTUALLY WANT TO DO: num5 = 500 num6 = 500 if num5 > num6: print("num5 is greater than num6") elif num6 > num5: print("num6 is greater than num5") else: print("both numbers are equal")
3f404ba3e1791d0d49730a5943fc868f8ac49a24
giulicom/coding-exercises
/maxAreaHist.py
431
3.640625
4
def maxArea(height): """ :type height: List[int] :rtype: int """ i = 0 j = len(height)-1 area = 0 while i < j: h = min(height[i], height[j]) currArea = h*(j-i) area = max(currArea, area) if height[i] > height[j]: j -= 1 else: i += 1 return area if __name__ == '__main__': hist = [1,8,6,2,5,4,8,3,7] print(maxArea(hist))
9add4c13c41e03652cefd80821169c236004d793
masumndc1/zim
/coding/python/header_masum.py
2,427
3.53125
4
#!/usr/bin/python3.4 import sys from urllib.request import urlopen from urllib.request import Request #res=Request('http://www.debian.org') """ ... here we will pass the url with formate of like # ./header_masum.py debian.org """ template='http://www.{}' urlreq=template.format(sys.argv[1]) #template.format(sys.argv[1]) res=Request(urlreq) #res=Request(template) res.add_header('Accept-Language', 'sv') print() print(res.header_items()) print('host name = ',res.host) print('url type = ',res.type) print() response=urlopen(res) # printing first fewlines and the page will be desplayed in swedish # language. #print(response.getheaders('Content-Type')) print(response.getheaders()[:10]) print(response.readlines()[:5]) #response=urlopen(res) #print(dir(response)) #print(response.header_items()) #print(s) """ there is another form of Request we can use. from the help of Request we got class Request(builtins.object) Methods defined here: __init__(self, url, data=None, headers={}, origin_req_host=None, unverifiable=False, method=None) ... here we can add the header into the Request like value pair formate separeted ... with the : like below. >>> res=Request('http://www.debian.org', headers={'Accept-language': 'sv'} ) ... here we have added the header information directly into the Request in ... header attribute with : between them. note here the formate of argument ... passing with the header value. >>> res.headers.items() dict_items([('Accept-language', 'sv')]) >>> >>> res.full_url 'http://www.debian.org' >>> """ """ output [('Accept-language', 'sv')] host name = www.debian.org url type = http [('Date', 'Fri, 02 Jun 2017 20:04:44 GMT'), ('Server', 'Apache'), ('Content-Location', 'index.sv.html'), ('Vary', 'negotiate,accept-language,Accept-Encoding'), ('TCN', 'choice'), ('X-Content-Type-Options', 'nosniff'), ('X-Frame-Options', 'sameorigin'), ('Referrer-Policy', 'no-referrer'), ('X-Xss-Protection', '1'), ('Last-Modified', 'Fri, 02 Jun 2017 16:38:54 GMT')] ... we have instruct the program to only show upto 10th item of the tuples and above ... command is showing something like that [b'<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">\n', b'<html lang="sv">\n', b'<head>\n', b' <meta http-equiv="Content-Type" content="text/html; charset=utf-8">\n', b' <title>Debian -- Det universella operativsystemet </title>\n'] """
3513114b3ba94e2481ac242c87d4c5488a55cffa
utk09/open-appacademy-io
/1_IntroToProgramming/1_Loops/4_sum_nums.py
340
3.953125
4
# Write a method sum_nums(max) that takes in a number max and returns the sum of all numbers from 1 up to and including max. def sum_nums(max_val): count = 0 for i in range(max_val+1): count = count + i return count print(sum_nums(4)) # prints 10 print(sum_nums(5)) # prints 15 print(sum_nums(100)) # prints 5050