blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
152821db50499e66c2e0db9b5ecdd0b69e3ae2df
SarahJaine/Python_Exercises
/HMC_Playtime/Lesson02_99bottles_v2.py
628
3.921875
4
beer_first=99 beer_second=beer_first-1 beer_store=beer_first def plural(x): if x==1: return "" else: return "s" while beer_second>-2: if beer_second>-1: print """{0} bottle{2} of beer on the wall, {0} bottle{2} of beer! Take one down, pass it around, {1} bottle{3} of beer on the wall!""".format(beer_first,beer_second,plural(beer_first),plural(beer_second)) else: print """{0} bottle{2} of beer on the wall, {0} bottle{2} of beer! Let's go to the store and buy some more, {1} bottle{3} of beer on the wall!""".format(beer_first,beer_store,plural(beer_first),plural(beer_store)) beer_first-=1 beer_second-=1
89aaf42d7885675b5e0e75d9ec12594bd8bd6fd1
nishitpatel01/Data-Science-Toolbox
/algorithm/BinarySearch/69_sqrtx.py
485
3.609375
4
class Solution(object): def mySqrt(self, x): """ :type x: int :rtype: int """ l, r = 0, x while l <= r: m = (l + r) // 2 if m ** 2 <= x: l = m + 1 ans = m else: r = m - 1 return ans def newton(self, x): r = x while r * r > x: r = (r + x / r) / 2 return r solver = Solution() print(solver.mySqrt(6))
2f9b57e6e96ab437cf1d23172d2e4e4f8baed739
Grazifelix/Python3-World-One
/ex008.py
319
3.890625
4
# Metro para centrimetro e milimetro # 18/02/21 # OK m = float(input("Insira um valor em metros:")) # float é numero de ponto flutuante, em outras palavras um numero real como casas decimais depois do ponto. cm = m*100 mm = m*1000 print("O valor {} em centimetros é {}, e em milímetros é {}.".format(m, cm, mm))
41fb6959e1a0fb5c4b5469ac87f8745db978d569
Hildayutami/tentara
/tugas3.py
5,338
3.703125
4
class dataOperasi: def __init__(self, operasi, sulit): self.operasi = operasi self.sulit = sulit def __str__(self): return ("operasi "+self.operasi+self.sulit) class dataTentara: def __init__(self, nama, umur, kekuatan): self.nama = nama self.umur = umur self.kekuatan = kekuatan self.level = 1 def __str__(self): nama = "Nama: "+self.nama umur = "HP: "+str(self.umur) kekuatan = "Power: "+str(self.kekuatan) return(nama,umur,kekuatan) def __repr__(self): data = self.nama,self.umur,self.kekuatan return str(data) def set_kekuatan(self, banyak): self.kekuatan += banyak def set_level(self, naik): self.level += naik def get_nama(self): return self.nama def get_umur(self): return self.umur def get_kekuatan(self): return self.kekuatan class Tentara: def __init__(self, n): self.d = {} self.operasi = [] for i in range(n): #snipper 3 print("jenis tentara dan jumlahnya") b = input().split() if b[0] not in self.d: self.d[b[0]]=[] for j in range(int(b[1])): print("masukkan data per tentara") c = input() # ===> agus;12;12 data_diri = c.split(";") self.d[b[0]].append(dataTentara(data_diri[0],data_diri[1],data_diri[2])) def new_tentara(self, jenis, list_data): data = list_data.split(";") if jenis in self.d: #kalau udah ada self.d[jenis].append(dataTentara(data[0],data[1],data[2])) else: self.d[jenis]=[] self.d[jenis].append(dataTentara(data[0],data[1],data[2])) print(data[0]+" bergabung") def new_operasi(self, nama_operasi, tingkat_sulit): if nama_operasi in self.operasi: #kalau udah ada self.operasi.append(dataOperasi(nama_operasi,tingkat_sulit)) else: self.operasi=[] self.operasi.append(dataOperasi(nama_operasi,tingkat_sulit)) print(nama_operasi+" dengan tingkat kesulitan "+tingkat_sulit+" berhasil dibuat") def join_operasi(self, jenis_tentara, nama, nama_operasi): if jenis_tentara in self.d: #for j in self.d.values(): #if nama not in self.d: # print("Tidak ada jenis tentara "+jenis_tentara+" bernama "+nama) if nama_operasi in self.operasi.keys(): self.operasi.append([jenis_tentara,nama]) print("berhasil tambahin") else: print("Tidak ada operasi bernama "+nama_operasi) else: print("Tidak ada jenis tentara "+jenis_tentara) def keluar_operasi(self, nama, nama_operasi): if nama_operasi in self.operasi: if nama in nama_operasi: for i in range(len(operasi)-1): for j in range(len(operasi[i])-1): if nama in operasi[i][j]: operasi[j].append([]) data = operasi[i][j] operasi[i].remove(data) else: print("Tidak ada tentara bernama "+nama+" pada tim operasi "+nama_operasi) else: print("Tidak ada operasi bernama "+nama_operasi) def pelatihan(self,jenis): if jenis in self.d: for key in self.d.keys(): if key == jenis: print(self.d[key].set_kekuatan(100)) else: print("Tidak ada "+jenis) def beraksi(self, nama_operasi): if nama_operasi in self.operasi: for i in self.operasi: if self.operasi[i][2] <= 0: print("Tidak ada personil pada tim operasi "+nama_operasi) else: else: print("Tidak ada operasi "+nama_operasi) print("nilai awal") t = Tentara(int(input())) while(True): #masukan perintah print("masukkan perintah baru") perintah = input().split() #NEW​ ​TENTARA​ ​Fighter​ ​Boy;25;125 if perintah[0] == 'new' and perintah[1] == 'tentara': t.new_tentara(perintah[2],perintah[3]) #NEW​ ​OPERASI​ ​Trikora​ ​2 (tingkat kesulitan) elif perintah[0] == 'new' and perintah[1] == 'operasi': t.new_operasi(perintah[2],perintah[3]) #MASUK​ ​Sniper​ ​Yumna​ ​Trikora elif perintah[0] == 'masuk': t.join_operasi(perintah[1],perintah[2],perintah[3]) #KELUAR​ ​Jarjit​ ​Trikora elif perintah[0] == 'keluar': t.keluar_operasi(perintah[1],perintah[2]) #pelatihan sniper elif perintah[0] == 'pelatihan': t.pelatihan(perintah[1]) #BERAKSI​ OPERASI​ <namaOperasi​> elif perintah[0] == 'beraksi': t.beraksi(perintah[2])
f28d28c592daad25aba51a0168ffa4e9152d4495
Nikunj-Gupta/Python
/palindrome.py
119
3.8125
4
n = input("Enter the number: ") a = list('n') b = a.reverse() if(b.join(a) == n): print True else: print False
f4fea9bc48959b2897a8e340c0319b51dc1b6adc
stuycs-softdev/submissions
/7/01-python/yu_rong/practice.py
1,100
3.75
4
def array123(nums): i = 2 while i < len(nums): if nums[i]==3 and nums[i-1]==2 and nums[i-2]==1: return True i+=1 return False def array_front9(nums): i = 0 while i<len(nums) and i < 4: if nums[i] == 9: return True i+=1 return False def array_count9(nums): i = 0 occur = 0 while i < len(nums): if nums[i]==9: occur = occur +1 i += 1 return occur def string_splosion(str): return string_splosion2(str, 1); def string_splosion2(str, int): if len(str) <= int: return str return str[0:int]+string_splosion2(str, int+1) #Codingbat python warmup 2 problems #Tried BubbleSort import random def bubblesort(iarr): notDone = True aNum = 0 while notDone: notDone = False i=0 while i+1<len(iarr): if iarr[i]>iarr[i+1]: aNum = iarr[i] iarr[i]=iarr[i+1] iarr[i+1] = aNum notDone = True i+=1 print(iarr) return iarr integer = 0 array1 = [] while integer < 5: array1.append(random.randint(0,99)) integer+=1 print(bubblesort(array1))
62a07f350ad0ccb8fa610d599bf89466fe6e2fd7
ViejoSantii/CNYT
/pruebas.py
5,685
3.609375
4
import unittest from calculadora import * class TestCases (unittest.TestCase): """--------------------Pruebas numeros complejos--------------------""" def test_adicion (self): result = adicion ((2, 5), (3, 3)) self.assertEqual (result, (5, 8)) def test_producto (self): result = producto ((2, 5), (3, 3)) self.assertEqual (result, (-9, 21)) def test_sustraccion (self): result = sustraccion ((2, 5), (3, 3)) self.assertEqual (result, (-1, 2)) def test_division (self): result = division ((2, 5), (3, 3)) self.assertEqual (result, (1.1666666666666667, 0.5)) def test_modulo (self): result = modulo ((2, 5)) self.assertEqual (result, (5.385164807134504)) def test_conjugado (self): result = conjugado ((2, 5)) self.assertEqual (result, ((2, -5))) def test_cart_a_pol (self): result = cart_a_pol ((2, 5)) self.assertEqual (result, (5.385164807134504, 1.1902899496825317)) def test_pol_a_cart (self): result = pol_a_cart ((2, 5)) self.assertEqual (result, (0.5673243709264525, -1.917848549326277)) def test_inversa (self): result = inversa ((2, 5)) self.assertEqual (result, ((-2, -5))) """--------------------Pruebas vectores--------------------""" def test_adicion_vect (self): result = adicion_vect (([(3,2),(0,0),(5,-6)]), ([(1,0),(4,2),(0,1)])) self.assertEqual (result, ([(4, 2), (4, 2), (5, -5)])) def test_producto_vect (self): result = producto_vect (((3,2)), ([(1,0),(4,2),(0,1)])) self.assertEqual (result, ([(3, 2), (8, 14), (-2, 3)])) def test_sustracc_vect (self): result = sustracc_vect (([(3,2),(0,0),(5,-6)]), ([(1,0),(4,2),(0,1)])) self.assertEqual (result, ([(2, 2), (-4, -2), (5, -7)])) def test_inversa_vect (self): result = inversa_vect (([(3,2),(0,0),(5,-6)])) self.assertEqual (result, ([(-3, -2), (0, 0), (-5, 6)])) def test_conjugado_vect (self): result = conjugado_vect (([(3,2),(0,0),(5,-6)])) self.assertEqual (result, ([(3, -2), (0, 0), (5, 6)])) def test_norma_vect (self): result = norma_vect (([(3,2),(0,0),(5,-6)])) self.assertEqual (result, (11.415800951370644)) def test_vectores_iguales (self): result = vectores_iguales (([(3,2),(0,0),(5,-6)]), ([(1,0),(4,2),(0,1)])) self.assertEqual (result, (False)) def test_producto_interno_vect (self): result = producto_interno_vect (([(3,2),(0,0),(5,-6)]), ([(1,0),(4,2),(0,1)])) self.assertEqual (result, ((-3, 3))) def test_distancia_vecto (self): result = distancia_vecto (([(3,2),(0,0),(5,-6)]), ([(1,0),(4,2),(0,1)])) self.assertEqual (result, (102.0)) def test_product_tensor (self): result = product_tensor (([(3,2),(0,0),(5,-6)]), ([(1,0),(4,2),(0,1)])) self.assertEqual (result, ([[(3, 2), (8, 14), (-2, 3)], [(0, 0), (0, 0), (0, 0)], [(5, -6), (32, -14), (6, 5)]])) """--------------------Pruebas matrices--------------------""" def test_adicion_matrices (self): result = adicion_matrices (([[(3,2),(0,0),(5,-6)],[(1,0),(4,2),(0,1)],[(4,-1),(0,0),(4,0)]]), ([[(5,0),(2,-1),(6,-4)],[(0,0),(4,5),(2,0)],[(7,-4),(2,7),(0,0)]])) self.assertEqual (result, [[(8, 2), (2, -1), (11, -10)], [(1, 0), (8, 7), (2, 1)], [(11, -5), (2, 7), (4, 0)]]) def test_sustraccion_matrices (self): result = sustraccion_matrices (([[(3,2),(0,0),(5,-6)],[(1,0),(4,2),(0,1)],[(4,-1),(0,0),(4,0)]]), ([[(5,0),(2,-1),(6,-4)],[(0,0),(4,5),(2,0)],[(7,-4),(2,7),(0,0)]])) self.assertEqual (result, [[(-2, 2), (-2, 1), (-1, -2)], [(1, 0), (0, -3), (-2, 1)], [(-3, 3), (-2, -7), (4, 0)]]) def test_producto_matrices (self): result = producto_matrices (([[(3,2),(0,0),(5,-6)],[(1,0),(4,2),(0,1)],[(4,-1),(0,0),(4,0)]]), ([[(5,0),(2,-1),(6,-4)],[(0,0),(4,5),(2,0)],[(7,-4),(2,7),(0,0)]])) self.assertEqual (result, [[(37, -13), (12, 3), (31, 9)], [(10, 0), (6, 28), (-6, 32)], [(50, -44), (3, 4), (4, -60)]]) def test_traspuesta_matrices (self): result = traspuesta_matrices (([[(3,2),(0,0),(5,-6)],[(1,0),(4,2),(0,1)],[(4,-1),(0,0),(4,0)]])) self.assertEqual (result, [[(3, 2), (1, 0), (4, -1)], [(0, 0), (4, 2), (0, 0)], [(5, -6), (0, 1), (4, 0)]]) def test_conjugado_matrices (self): result = conjugado_matrices (([[(3,2),(0,0),(5,-6)],[(1,0),(4,2),(0,1)],[(4,-1),(0,0),(4,0)]])) self.assertEqual (result, [[(3, -2), (0, 0), (5, 6)], [(1, 0), (4, -2), (0, -1)], [(4, 1), (0, 0), (4, 0)]]) def test_adjunta_matrices (self): result = adjunta_matrices (([[(3,2),(0,0),(5,-6)],[(1,0),(4,2),(0,1)],[(4,-1),(0,0),(4,0)]])) self.assertEqual (result, [[(3, -2), (1, 0), (4, 1)], [(0, 0), (4, -2), (0, 0)], [(5, 6), (0, -1), (4, 0)]]) def test_inversa_matrices (self): result = inversa_matrices (([[(3,2),(0,0),(5,-6)],[(1,0),(4,2),(0,1)],[(4,-1),(0,0),(4,0)]])) self.assertEqual (result, [[(3, -2), (0, 0), (5, 6)], [(1, 0), (4, -2), (0, -1)], [(4, 1), (0, 0), (4, 0)]]) def test_traza_matrices (self): result = traza_matrices (([[(3,2),(0,0),(5,-6)],[(1,0),(4,2),(0,1)],[(4,-1),(0,0),(4,0)]])) self.assertEqual (result, (11, 4)) if __name__ == '__main__': unittest.main()
8047fb5202fbe8cddbb8eb7a90f38e4ee7306b49
sl2631/rwet
/hw3/hw3.py
1,169
3.78125
4
#!/usr/bin/env python from __future__ import print_function import nltk import nltk.tokenize import random import sys from pprint import pprint text_path = 'kipling.txt' text = open(text_path).read() # both flat and nested will hold the entire poem lines = [] # accumulate each line for para in text.split('\n\n'): lines.extend([l for l in para.split('\n') if l]) # get rid of empty lines def print_poem(label, lines): print('\n', label, ':', sep='') for l in lines: print(l) print_poem('all', lines) # list comprehension: # iterate over lines, returning the line up to but not including the last character if the last character is in the punctuation set lines_strip_end_punct = [l[:-1] if l[-1] in ",.:;!" else l for l in lines] def gen_poem(n): # randomly pick n sentences from the poem sample = random.sample(lines_strip_end_punct, n) lines_with_punct = [] for i, l in enumerate(sample): j = i + 1 if j == n: # last line p = '!' elif j % 4 == 0: # divisible by 4 p = ';' else: p = ',' lines_with_punct.append(l + p) print_poem(n, lines_with_punct) n = len(lines) while n > 0: gen_poem(n) n /= 2
d1c20d7c78db56559c2f6f9664ddd4c2d68f81af
PablOCVi/Mastery
/Mastery18.py
463
3.921875
4
print("Si el numero ingresado es par y mayor a 10, lo mltiplicare por 4") x=int(input("Ingresa un numero par: ")) while (x%2!=0)or(x<10): if x%2!=0: print("El numero"+" "+str(x)+" "+"es par") if x<10: print("El numero"+" "+str(x)+" "+"es menor a 10") x=int(input("Ingresa un numero par mayor a 10: ")) print("El numero "+str(x)+" es par") print("El numero"+" "+str(x)+" "+"es mayor a 10") print("Al numero "+str(x)+" Lo multiplicare por 4 "+"= "+str(x*4))
bca634c94179e812c79840248875061b50a140d0
waddlefluf/advent-of-code-2020
/02/day2.py
814
3.5625
4
lines = open("input.txt", "r").readlines() def part1(passwords): valid = 0 for line in passwords: password = line.split(" ")[-1] letter = line.split(":", 1)[0].split(" ")[1] min = int(line.split(" ")[0].split("-")[0]) max = int(line.split(" ")[0].split("-")[1]) if min <= password.count(letter) <= max: valid += 1 return valid def part2(passwords): valid = 0 for line in passwords: password = line.split(" ")[-1] letter = line.split(":", 1)[0].split(" ")[1] num1 = int(line.split(" ")[0].split("-")[0]) num2 = int(line.split(" ")[0].split("-")[1]) if (password[num1-1] == letter) ^ (password[num2-1] == letter): valid += 1 return valid print(part1(lines)) print(part2(lines))
45564c401bfca8273afaf98e33a8c3db72f3b8b1
Afanasieva-m/infa_2019_afanasieva
/picture_16_2.py
5,307
3.8125
4
import math from graph import * def ellipse(x0, y0, a, b): #возвращает массив точек для построения эллипса lst = [] fii = 0.01 c = (a*a-b*b)**(1/2) exc = c/a point(x0+a, y0) while fii <= 360: ro = (a - exc*c)/(1+exc*math.cos(fii)) x = math.floor(x0 + c + ro*math.cos(fii)) y = math.floor(y0 + (b*(1-((x-x0)/a)**2)**(1/2))*(math.sin(fii)/math.fabs(math.sin(fii)))) temp = (x, y) lst.append(temp) fii = fii + 0.02 return lst def car (x0, y0): lst = ellipse(x0, y0+35, 20, 5) #выхлопная труба penColor(0, 0, 0) brushColor(0, 0, 0) polygon(lst) brushColor(0, 204, 255) rectangle(x0, y0, x0+210, y0+40) rectangle(x0+30, y0, x0+150, y0-27) brushColor(213, 246, 255) rectangle(x0+45, y0-5, x0+80, y0-22) #окна rectangle(x0+100, y0-5, x0+135, y0-22) brushColor(0, 0, 0) lst1 = ellipse(x0+30, y0+40, 20, 15) #колеса lst2 = ellipse(x0+170, y0+40, 20, 15) polygon(lst1) polygon(lst2) def car2 (x0, y0): lst = ellipse(x0, y0+35, 20, 5) #выхлопная труба penColor(0, 0, 0) brushColor(0, 0, 0) polygon(lst) brushColor(0, 204, 255) rectangle(x0, y0, x0-210, y0+40) rectangle(x0-30, y0, x0-150, y0-27) brushColor(213, 246, 255) rectangle(x0-45, y0-5, x0-80, y0-22) #окна rectangle(x0-100, y0-5, x0-135, y0-22) brushColor(0, 0, 0) lst1 = ellipse(x0-30, y0+40, 20, 15) #колеса lst2 = ellipse(x0-170, y0+40, 20, 15) polygon(lst1) polygon(lst2) def car3 (x0, y0): lst = ellipse(x0, y0+11, 6, 1.5) #выхлопная труба penColor(0, 0, 0) brushColor(0, 0, 0) polygon(lst) brushColor(0, 204, 255) rectangle(x0, y0, x0-65, y0+13) rectangle(x0-10, y0, x0-45, y0-9) brushColor(213, 246, 255) rectangle(x0-14, y0-1.5, x0-25, y0-7) #окна rectangle(x0-31, y0-1.5, x0-42, y0-7) brushColor(0, 0, 0) lst1 = ellipse(x0-10, y0+13, 6, 5) #колеса lst2 = ellipse(x0-56, y0+13, 6, 5) polygon(lst1) polygon(lst2) def buildings2(x0, y0): penSize(0) brushColor(147, 167, 172) rectangle(x0, y0, x0+70, y0+245) brushColor(147, 172, 167) rectangle(x0+91, y0+14, x0+161, y0+250) brushColor(183, 200, 196) rectangle(x0+49, y0+49, x0+126, y0+294) brushColor(219, 227, 226) rectangle(x0+245, y0, x0+322, y0+247) brushColor(111, 145, 138) rectangle(x0+224, y0+63, x0+294, y0+301) def buildings1(x0, y0): penSize(0) brushColor(147, 167, 172) rectangle(x0, y0, x0-70, y0+245) brushColor(147, 172, 167) rectangle(x0-91, y0+14, x0-161, y0+250) brushColor(183, 200, 196) rectangle(x0-49, y0+49, x0-126, y0+294) brushColor(219, 227, 226) rectangle(x0-245, y0, x0-322, y0+247) brushColor(111, 145, 138) rectangle(x0-224, y0+63, x0-294, y0+301) def background0(x0,y0): penSize(0) brushColor(37,37,37) rectangle(x0+400,y0,x0+500,y0+100) brushColor(79,79,79) rectangle(x0+420,y0,x0+480,y0+100) brushColor(25,25,25) rectangle(x0+420,y0,x0+480,y0+30) brushColor(37,37,37) rectangle(x0+300,y0,x0+398,y0+100) brushColor(9,9,9) rectangle(x0+300,y0+50,x0+320,y0+100) rectangle(x0+330,y0,x0+380,y0+100) brushColor(105,105,105) rectangle(x0+50,y0,x0+300,y0+100) brushColor(30,30,30) rectangle(x0+200,y0+10,x0+300,y0+100) brushColor(125,125,125) rectangle(x0+255,y0,x0+300,y0+100) brushColor(13,13,13) rectangle(x0+250,y0+50,x0+280,y0+100) brushColor(126,126,126) rectangle(x0,y0,x0+50,y0+100) brushColor(40,40,40) rectangle(x0,y0+50,x0+50,y0+100) brushColor(63,63,63) rectangle(x0+50,y0+50,x0+90,y0+100) def background(x0, y0): penSize(0) brushColor(83, 108, 103) rectangle(0, y0, x0, 1000) def background1(x0, y0): penColor(255,255,255) penSize(2) brushColor(183, 196, 200) rectangle(180, 90, x0, y0) def background2(x0, y0): penColor(255,255,255) penSize(2) brushColor(183, 196, 200) rectangle(0, 100, x0, y0+20) def big_cloud(x0, y0): lst = ellipse(x0, y0, 220, 50) penSize(0) penColor(168, 186, 186) brushColor(168, 186, 186) polygon(lst) def big_cloud1(x0, y0): lst = ellipse(x0, y0, 150, 33) penSize(0) penColor(168, 186, 186) brushColor(168, 186, 186) polygon(lst) def clouds(): big_cloud(110, 80) big_cloud(325, 200) big_cloud(80, 290) penColor(156, 180, 178) for x in range (155, 330): #там где облака полупрозрачны for y in range (30, 85): if (((x-375)/220)**2+((y-35)/50)**2 <= 1) and (((x-110)/220)**2 + ((y-80)/50)**2 <= 1): point(x, y) def clouds1(): big_cloud1(450, 150) background0(0, 0) background(800, 350) background1(800, 350) clouds1() buildings1(535, 103) background2(288, 352) buildings2(-60, 122) penSize(0) car (40, 460) car2(460,530) car3(460, 430) car3(360, 410) car3(255, 420) car3(90, 410)
d491f1431caf3eb5973dce9f0c874662fa67541a
AirVan21/Python
/Stepik/Basics/ending.py
294
3.765625
4
#! /usr/bin/env python3 body = 'программист' number = int(input()) if 10 < (number % 100) < 20: print(number, body + 'ов') elif number % 10 == 1: print(number, body) elif (number % 10) in set([2, 3, 4]): print(number, body + 'а') else: print(number, body + 'ов')
97e87e9eb726b2a2fb1915e76710b8ad6a4ebe08
nehageorge/Clueless-Recreated
/Display/slideshow.py
3,598
3.765625
4
''' Adapted from vegaseat's Tkinter slideshow (published 03dec2013) ''' from itertools import cycle from PIL import Image, ImageTk #import PIL.Image #from PIL import ImageTk try: # Python2 import Tkinter as tk except ImportError: # Python3 import tkinter as tk #from tkinter import * class App(tk.Tk): '''Tk window/label adjusts to size of image''' def __init__(self, image_files, x, y, delay): # the root will be self tk.Tk.__init__(self) # set x, y position only self.geometry('+{}+{}'.format(x, y)) self.delay = delay # allows repeat cycling through the pictures # store as (img_object, img_name) tuple self.pictures = cycle((tk.PhotoImage(file=image), Image.open(image).resize((100,100))) for image in image_files) self.picture_display = tk.Label(self) self.picture_display.pack() def show_slides(self): '''cycle through the images and show them''' # next works with Python26 or higher img_object, img_name = next(self.pictures) #self.resize((1000,100), Image.ANTIALIAS) self.picture_display.config(image=img_object) # shows the image filename, but could be expanded # to show an associated description of the image self.title(img_name) self.after(self.delay, self.show_slides) def run(self): self.mainloop() # set milliseconds time between slides delay = 2500 # get a series of gif images you have in the working folder # or use full path, or set directory to where the images are #for i in range (9): image_files = ['/home/pi/OutfitRaspberryPi/imgsOut/pants11.png' ,'/home/pi/OutfitRaspberryPi/imgsOut/pants13.png' ,'/home/pi/OutfitRaspberryPi/imgsOut/pants16.png' ,'/home/pi/OutfitRaspberryPi/imgsOut/pants18.png' ,'/home/pi/OutfitRaspberryPi/imgsOut/pants19.png' ,'/home/pi/OutfitRaspberryPi/imgsOut/pants21.png' ,'/home/pi/OutfitRaspberryPi/imgsOut/pants30.png' ,'/home/pi/OutfitRaspberryPi/imgsOut/pants1.png', '/home/pi/OutfitRaspberryPi/imgsOut/pants23.png'] #images = ['/home/pi/OutfitRaspberryPi/imgsOut/pants11.png' ,'/home/pi/OutfitRaspberryPi/imgsOut/pants13.png' ,'/home/pi/OutfitRaspberryPi/imgsOut/pants16.png' ,'/home/pi/OutfitRaspberryPi/imgsOut/pants18.png' ,'/home/pi/OutfitRaspberryPi/imgsOut/pants19.png' ,'/home/pi/OutfitRaspberryPi/imgsOut/pants21.png' ,'/home/pi/OutfitRaspberryPi/imgsOut/pants30.png' ,'/home/pi/OutfitRaspberryPi/imgsOut/pants1.png','/home/pi/OutfitRaspberryPi/imgsOut/pants23.png'] """ image_files = [None] * 9 for i in range (9): img = Image.open(images[i]) image_files[i] = img.resize((500,500), Image.ANTIALIAS) #(height, width) for i in range (9): image_files[i] = ImageTk.PhotoImage(Image.open(images[i]).resize((1000,1000), Image.ANTIALIAS)) """ #what to do what to do maybe put the photo image stuff up there ^ down there? #image_files = [Image.open(images[0]).resize((1000,100), Image.ANTIALIAS), Image.open(images[1]).resize((1000,100), Image.ANTIALIAS), Image.open(images[2]).resize((1000,100), Image.ANTIALIAS), Image.open(images[3]).resize((1000,100), Image.ANTIALIAS), Image.open(images[4]).resize((1000,100), Image.ANTIALIAS), Image.open(images[5]).resize((1000,100), Image.ANTIALIAS), Image.open(images[6]).resize((1000,100), Image.ANTIALIAS), Image.open(images[7]).resize((1000,100), Image.ANTIALIAS), Image.open(images[8]).resize((1000,100), Image.ANTIALIAS)] # upper left corner coordinates of app window #root = tk() x = 100 y = 50 app = App(image_files, x, y, delay) app.show_slides() app.run()
ac7bd89ba9b2a77895980e46880710d0b5f3744a
bencastan/udemy-Python_Bible
/pig_latin.py
880
4.1875
4
# Ask user for sentence original = input("Enter a sentence to convert to Pig Latin:").strip().lower() # Split sentence into words words = original.split() # Loop through words and convert to pig latin new_words = [] vowels = "aeiou" for word in words: # If it starts with a vowel, just add yay if word[0] in vowels: word = word + "yay" new_words.append(word) else: # Otherwise move the first consonant cluster to the end and add ay vowel_pos = 0 for letter in word: if letter not in vowels: vowel_pos = vowel_pos + 1 else: break cons = word[:vowel_pos] the_rest = word[vowel_pos:] new_word = the_rest + cons + "ay" new_words.append(new_word) # Stick words back into sentence output = " ".join(new_words) # Output the sentence print(output)
aaf77cdd1892df2529257e8c2e7029267b9d08d4
littlea1/IS211_Assignment9
/football_stats.py
4,404
3.734375
4
from bs4 import BeautifulSoup import urllib2 __author__ = 'Patrick Abejar' '''This function will find the column number of a given header title with the left most column being represented as 0 incremeted by 1 in the rightward dir- ection. It does this by searching for the given header title for all the string contents of the <th></th> tags in the soup. Once it has found the app- licable <th></th> tags, it will determine what order the <th></th> tag is in the row by taking a look at its parent and iterating through all the children to determine what order from the left most column contains the header. ''' def find_column(input_soup, header): # Since a labeled column is being searched for, <th> is appropriate since # it contains this information. table = input_soup.find_all('th') date_column = None header_row = None # Searches through all the table header <th> tags' string entries to find # where the input header is found in the BeautifulSoup object. for entry in table: if entry.string is not None and \ entry.string.lower() == header.lower(): # When the input header is found, a parent view is obtained in # order to search for the <td> cell's position from the first # <td> cell (or a.k.a. first parent's child) for i in range(0, len(entry.parent.contents)): if entry.parent.contents[i] == entry: date_column = i # First list item returned is the column position of the header # Second list item returned is access to the row of the header return date_column '''This script takes a response from the CBSSports.com website and parses through data in order to find the top 20 players' names, positions, teams, and their touchdown score. This will be displayed to users' screen. ''' def main(): # Take a request from the cbssports.com website in order to receive the # number of touchdowns as HTML data in a response req = urllib2.Request("http://www.cbssports.com/nfl/stats/playersort/nfl" "/year-2015-season-regular-category-touchdowns/") res = urllib2.urlopen(req) html_doc = res.read() soup = BeautifulSoup(html_doc, 'html5lib') # This list named table contains all the instances of the <a></a> tags in # the webpage being parsed. <a></a> tags were chosen as players' names # have a link back to their webpage, which is established by <a></a> tags table = soup.find_all('a') # Finds the column where player, pos, team, and td data are located name_column = find_column(soup, "player") position_column = find_column(soup, "pos") team_column = find_column(soup, "team") td_column = find_column(soup, "td") print "This script prints out the top 20 players of the NFL by the" \ " number of touchdowns they have received according\nto the " \ "cbssports.com website.\n(URL: http://www.cbssports.com/nfl/" \ "stats/playersort/nfl/year-2015-season-regular-category-touc" \ "hdowns/)\n" counter = 1 # Finds the players through the subsequent if statement and prints the # data to screen. for entry in table: # Rows with "/nfl/players/playerpage/" in their link are associated # with a player from the list of links in table. if entry['href'][:24] == "/nfl/players/playerpage/": # This has the entire row between the <tr> tags for all infor- # mation on the player player_record = entry.parent.parent # Player information is retrieved based on the information found # by using find_column on the player_record. player_name = player_record.contents[name_column].string player_position = player_record.contents[position_column].string player_team = player_record.contents[team_column].string player_touchdowns = player_record.contents[td_column].string print "Name: %s\n Position: %s\n Team: %s\n Touchdowns: %s\n" % \ (player_name, player_position, player_team, player_touchdowns) counter += 1 # Only the top 20 players for touchdowns scored sorted by the website # will be displayed if counter > 20: break if __name__ == "__main__": main()
b59611c0286f8142a97e424202ef5f3290745d1c
prathamkaveriappa/PythonAssignments
/gettingstarted.py
108
3.71875
4
start=1 end=10 while(start<=end): print(start) start+=1 for i in range(20,10,-1): print(i)
8d9752224aae2030f96912235bf83a691ed881cb
JoachimFavre/RegexRightToLeft
/main.py
7,483
4.4375
4
# -*- coding: utf-8 -*- r""" Inverses a regex expression in order to have it working for a reversed string. Use deep_reverse(regex) to reverse a regular expression and find_last(regex, string) to have an example of a use for reversed expressions. Do not hesitate to use r-strings (with a r before the ": such as r".\?") so that \ is a character in itself and is not used for escaping characters (else you would have to write "\\\\" instead of r"\\" to have a regex of \\ which matches \ ). Created on Sun Aug 29 22:01:21 2021 @author: Joachim Favre """ import re REVERSE_GROUP_OPERATOR = {"": "", # default case "?:": "?:", # non-capturing group "?=": "?<=", # positive lookafter "?<=": "?=", # positive lookbehind "?!": "?<!", # negative lookafter "?<!": "?!"} # negative lookbehind class ParseException(Exception): """ An exception that is triggered when there is a problem while parsing the given regex. """ def __init__(self, message): super().__init__("Error while parsing the regular expression. Error: " + message) def is_unit(char): """ Verifies whether the character given is a "unit" (meaning it is a regex command (by opposition to an operator)). """ assert len(char) == 1 return char.isalpha() or char.isnumeric() or char in ['.', ' ', '-'] def extract_operator(regex): """ Extracts a potential multiplication operator (meaning '*', '+', '?' or {...}) from the very beginning of a regular expression. Returns {operator}, {rest of the regular expression} """ operator = "" rest = regex if regex != "": if regex[0] in ["*", "+", "?"]: operator = regex[0] rest = regex[1:] if regex[0] == "{": end_point = get_closing_bracket_index(regex, "{", "}") + 1 operator = regex[:end_point] rest = regex[end_point:] if rest != "": if rest[0] in ["?", "+"]: # lazy or greedy possessive operator += rest[0] rest = rest[1:] return operator, rest def get_closing_bracket_index(regex, opening, closing): """ Returns the index of the corresponding ending bracket. This function needs to have the first character being an opening bracket. """ assert regex[0] == opening bracket_level = 0 for index, char in enumerate(regex): if char == opening: bracket_level += 1 elif char == closing: bracket_level -= 1 if bracket_level == 0: return index raise ParseException("No closing bracket '" + closing + "' found.") def split(regex): """ Splits a regular expression to a head, an operator and the rest. The head is one "atom" (meaning a unit, an escaped character, an interval, or a group). See the function extract_operator(regex) for further information on the operators. """ if regex == "": return "", "", "" end_point = None # excluded if is_unit(regex[0]): end_point = 1 elif regex[0] == "\\": end_point = 2 elif regex[0] == "[": end_point = get_closing_bracket_index(regex, "[", "]") + 1 elif regex[0] == "(": end_point = get_closing_bracket_index(regex, "(", ")") + 1 else: raise ParseException("Unexpected token in '" + regex + "'. If it is " "one character long, you can add it in the " "is_unit(char) function.") operator, rest = extract_operator(regex[end_point:]) return regex[:end_point], operator, rest def split_group(group): """ Converts a list of objects splitted by "|" into a list. The complication comes from the fact that we do not want to use other group's "|" to split this one. Meaning (a|(b|c)|e) should be splitted into ['a', '(b|c)', 'e']. Warning, this function supposes that there is no parenthesis around the given group (it must be under the form "a|(b|c)|e"). """ # suppose no parenthesis around group parenthesis_level = 0 last_split_index = 0 result = [] for index, char in enumerate(group): if char == "(": parenthesis_level += 1 elif char == ")": parenthesis_level -= 1 elif char == "|" and parenthesis_level == 0: result.append(group[last_split_index:index]) last_split_index = index + 1 result.append(group[last_split_index:]) return result def extract_group(group): """ Takes a group (which must begin with a '(' and end with a ')') and splits it into an operator (meaning anonym group, positive/negative lookahead, positive/negative lookbehind) and a list of the contained atoms (the atoms splitted by '|'); see split_group(group) for further information. """ assert group[0] == "(" and group[-1] == ")" operator_end = 1 if group[1] == "?": if len(group) >= 3 and group[1:3] in ["?:", "?=", "?!"]: operator_end = 3 if len(group) >= 4 and group[1:4] in ["?<=", "?<!"]: operator_end = 4 return group[1:operator_end], split_group(group[operator_end:-1]) def reverse(atom): """ Takes an atom and reverses it. The complications come from the fact that we need to reverse every signle element of a group. """ if len(atom) == 1: return atom if atom[0] == "\\" and len(atom) == 2: return atom if atom[0] == "[" and atom[-1] == "]": return atom if atom[0] == "(" and atom[-1] == ")": group_operator, terms = extract_group(atom) result = "(" + REVERSE_GROUP_OPERATOR[group_operator] for index, term in enumerate(terms): if index != 0: result += "|" result += deep_reverse(term) return result + ")" raise ParseException("'" + atom + "' is not an atom, this should not " "happen.") def deep_reverse(regex): """ Reverses completely a regex expression. This is the function you need to call as a user. The "head-operator-rest" takes its inspiration from the following video: https://www.youtube.com/watch?v=fgp0tKWYQWY """ if regex == "": return "" start = "" end = "" if regex[0] == "^": end = "$" regex = regex[1:] if regex[-1] == "$": start = "^" regex = regex[:-1] head, operator, rest = split(regex) return start + deep_reverse(rest) + reverse(head) + operator + end def find_last(regex, string): """ Finds the last (and biggest) occurence of the regular expression in the string. This is an example of how to use reversed_regex. If you need to use it into your code, you can just compute once reversed_regex using this program and only use this function in your code. """ reversed_regex = deep_reverse(regex) reversed_string = string[::-1] match = re.search(reversed_regex, reversed_string) print(reversed_string) reversed_result = match.group(0) result = reversed_result[::-1] return result
9d7a993407d296c0400727a0220bdae124841415
SaiSudhaV/coding_platforms
/permutation_sequence.py
467
3.59375
4
from math import factorial as fact class Solution: # @param A : integer # @param B : integer # @return a strings def getPermutation(self, A, B): tem, res = [i for i in range(1, A + 1)], "" while tem: n = len(tem) i = B // fact(n - 1) if (B % fact(n - 1) == 0): i -= 1 res += str(tem[i]) B -= fact(n - 1) * i tem.remove(tem[i]) return(res)
d8c99557a1844dbefe2c447b081f58470da92f3f
MidAutumn10100101/leetcode_everyday
/6-27-剑指12-矩阵中的路径/exist.py
1,208
3.5625
4
#将矩阵视为图,则找矩阵中的路径就是深度搜索。先将第一个字符所在位置全存储起来,后依次从第一个字符处深度搜索 class Solution: def exist(self, board, word: str) -> bool: def dfs(i, j, k): if not 0<=i<len(board) or not 0<=j<len(board[0]) or board[i][j]!=word[k]: return False if k == len(word)-1: return True tmp = board[i][j] board[i][j] = '/' res = dfs(i + 1, j, k + 1) or dfs(i - 1, j, k + 1) or dfs(i, j + 1, k + 1) or dfs(i, j - 1, k + 1) board[i][j] = tmp return res for i in range(len(board)): for j in range(len(board[0])): if dfs(i, j, 0): return True return False obj = Solution() print(obj.exist([["a","b","c","e"], ["s","f","c","s"], ["a","d","e","e"]], "abfb")) # 作者:jyd # 链接:https://leetcode-cn.com/problems/ju-zhen-zhong-de-lu-jing-lcof/solution/mian-shi-ti-12-ju-zhen-zhong-de-lu-jing-shen-du-yo/ # 来源:力扣(LeetCode) # 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
45dd16d1d3df5d7a0f001a3ef95ccf97d27f0f5d
seanlobo/fb-msg-mining
/functions/customdate.py
8,445
3.609375
4
from math import ceil from datetime import date, timedelta import re class CustomDate(): MONTHS_TO_INDEXES = {'January': 1, 'February': 2, 'March': 3, 'April': 4, 'May': 5, 'June': 6, 'July': 7, 'August': 8, 'September': 9, 'October': 10, 'November': 11, 'December': 12,} MONTH_INDEXES_TO_MONTHS = {1: 'January', 2: 'February', 3: 'March', 4: 'April', 5: 'May', 6: 'June', 7: 'July', 8: 'August', 9: 'September', 10: 'October', 11: 'November', 12: 'December'} WEEK_INDEXES_TO_DAY_OF_WEEK = {0: "Monday", 1: "Tuesday", 2: "Wednesday", 3: "Thursday", 4: "Friday", 5: "Saturday", 6: "Sunday"} def __init__(self, date_str): """Constructor for CustomDate object. has following fields: String full_date : the full date of this object, e.g. Wednesday, April 13, 2016 at 11:54pm PDT String week_day : the day of the week e.g. Monday String time : the time e.g. 11:54pm String time_zone : the time zone e.g. PDT datetime.date date : a date object representation of the year, month and day e.g. datetime.date(2016, 4, 13) """ if type(date_str) is type(self): date_str = date_str.full_date self.full_date = date_str temp = date_str.split(',') self.week_day = temp[0] month, day_of_month = temp[1].split() year, _, self.time, self.time_zone = date_str.split(',')[2].split() self.date = date(int(year), int(CustomDate.MONTHS_TO_INDEXES[month]), int(day_of_month)) @classmethod def from_date(cls, date_obj: date): """Alternative constructor using a datetime.date object Creates a CustomDate object with a default time of 12:00am PDT """ year = None if len(str(date_obj.year)) == 2: if date_obj.year <= 17: year = date_obj.year + 2000 else: year = date_obj.year + 1900 else: year = date_obj.year date_string = "{0}, {1} {2}, {3} at 12:00am PDT".format( CustomDate.WEEK_INDEXES_TO_DAY_OF_WEEK[date_obj.weekday()], CustomDate.MONTH_INDEXES_TO_MONTHS[date_obj.month], date_obj.day, year) return cls(date_string) @classmethod def from_date_string(cls, date_string: str): """Alternative constructor using a date string in the form '{month}/{day}/{year}'""" date_lst = [int(ele) for ele in date_string.split('/')] return CustomDate.from_date(date(date_lst[2], date_lst[0], date_lst[1])) def to_string(self) -> str: return "{0}/{1}/{2}".format(self.date.month, self.date.day, self.date.year) def day(self) -> int: return self.date.day def month(self) -> int: return self.date.month def weekday(self) -> int: return self.date.weekday() def year(self) -> int: return self.date.year def minutes(self) -> int: minutes = self.time[:-2] minutes = (int((minutes[:minutes.find(':')])) % 12) \ * 60 + int(minutes[minutes.find(':') + 1:]) if 'pm' in self.time: minutes += 12 * 60 return minutes def distance_from(self, other) -> int: """Returns the number of minutes ahead of other self is. If self is an earlier time result will be negative""" assert isinstance(other, CustomDate), "You must pass a valid CustomDate object" return (self.minutes() - other.minutes()) + (self - other) * 24 * 60 @staticmethod def minutes_to_time(minutes: int) -> str: """Opposite of .minutes() function, turns an int minutes into a time between 12:00am and 11:59pm""" assert minutes >= 0, "You can't have negative minutes" assert minutes <= 24 * 60, "You passed more than 1 day of minutes" hours = ceil(minutes // 60) if hours == 0: hours = 12 elif hours > 12: hours -= 12 mins = str(minutes % 60) if len(mins) == 1: mins = '0' + mins return "{0}:{1}{2}".format(hours, mins, 'pm' if minutes >= 12 * 60 else 'am') def plus_x_days(self, days): assert isinstance(days, int), "days must be an integer" return CustomDate.from_date(self + days) @staticmethod def bsearch_index(lst, date, low=0, high=None, key=lambda x: x) -> int: if high is None: high = len(lst) - 1 mid = (low + high) // 2 if isinstance(date, str): date = CustomDate.from_date_string(date) while key(lst[mid]) != date and low < mid < high: if key(lst[mid]) > date: high = mid - 1 mid = (low + high) // 2 else: low = mid + 1 mid = (low + high) // 2 distance = lambda x: abs(key(lst[x]).distance_from(date)) # Distance the current mid is from date if key(lst[mid]).distance_from(date) > 0: # If the midpoint is after the date # While the previous element is closer to the date we want while 0 <= distance(mid - 1) <= distance(mid): mid -= 1 mid -= 1 else: # Midpoint is before the date # while the next element is closer to the date while distance(mid + 1) <= distance(mid) and key(lst[mid + 1]).distance_from(date) <= 0: mid += 1 mid += 1 return mid @staticmethod def assert_date_string(date_string: str): assert isinstance(date_string, str), "The date-string needs to be a string" r = re.compile('\d{1,2}/\d{1,2}/\d{1,4}') assert r.fullmatch(date_string) is not None, ("\"{0}\" is not a valid date, it must be in the format " .format(date_string) + "{month}/{day}/{year}") r = re.compile('\d{1,2}/\d{1,2}/\d{3}') assert r.fullmatch( date_string) is None, "the {year} part of a date must be either 2 or 4 numbers (e.g. 2016 or 16)" date_list = [int(i) for i in date_string.split('/')] try: date(date_list[2], date_list[0], date_list[1]) return except ValueError as e: s = str(e) raise AssertionError(s) @staticmethod def assert_dates(*args): for date_string in args: if date_string is not None: CustomDate.assert_date_string(date_string) def __add__(self, other): if type(other) is not int: return NotImplemented return self.date + timedelta(days=other) def __sub__(self, other): if type(other) is not type(self): return NotImplemented return (self.date - other.date).days def __str__(self): return self.full_date def __repr__(self): return "CustomDate({0})".format(repr(self.full_date)) def __eq__(self, other): if not isinstance(other, CustomDate): return False return self.date == other.date and self.minutes() == other.minutes() def __hash__(self): return hash(self.full_date) def __lt__(self, other): if type(other) is not type(self): return NotImplemented if self.date < other.date: return True elif self.date == other.date: if self.minutes() < other.minutes(): return True return False def __le__(self, other): if type(other) is not type(self): return NotImplemented if self.date < other.date: return True elif self.date == other.date: if self.minutes() <= other.minutes(): return True return False def __gt__(self, other): if type(other) is not type(self): return NotImplemented if self.date > other.date: return True elif self.date == other.date: if self.minutes() > other.minutes(): return True return False def __ge__(self, other): if type(other) is not type(self): return NotImplemented if self.date > other.date: return True elif self.date == other.date: if self.minutes() >= other.minutes(): return True return False
1ec3e0ddd918dda4328ffb281993459adeda9bc8
sunzid02/fun-with-python
/basic/index.py
648
3.671875
4
# print('hi') # x = 2 # print(x) # x = x + 2 # print(x) # Using conditional statement # x = 2 # if x < 5: # print('smaller') # else: # print('bigger') # # While loop # # i = 10 # # while( i > 0): # # print(i) # # i = i-1 # # print('Boom') # # array # a = [ 10, 20 ] # i = 0 # while( i < len(a) ): # print(a[i]) # i = i + 1 # print('Boom') # take input # nam = input('zia'); # print('welcome Mr.','asdasd', nam); # europe usa lift problem # inp = input('europe floor: ') # print('Europe floor', inp) # usf = int(inp) + 1 # print('USA floor', usf) # print("123" + "abc") Spam = 2 x = int(98.6) print(x)
28096afdfb80b6f722b1c6caf74d72884b9d6f99
beccacauthorn/cs-module-project-hash-tables
/applications/word_count/word_count.py
695
3.96875
4
def word_count(x): wordFreq = {} lower = x.lower() bad_chars = ['"', ":", ";", ",", ".", "-", "+", "=", "/", "\\", "|", "[", ']', '{', '}', '(', ')', '*', '^', '&'] for i in bad_chars: lower = lower.replace(i, '') list_words = lower.split() for word in list_words: if word not in wordFreq: wordFreq[word] = 1 else: wordFreq[word] += 1 return wordFreq if __name__ == "__main__": print(word_count("")) print(word_count("Hello")) print(word_count('Hello, my cat. And my cat doesn\'t say "hello" back.')) print(word_count('This is a test of the emergency broadcast network. This is only a test.'))
2539bab3a48cdcad79af31f0bb1a90f9deb84966
Shtvaliev/ICT-HSE-Project
/programm-of-data-analysis-master/Project/Work/Scripts/bar_flights.py
3,906
3.546875
4
# данный скрипт выводит зависимость # количества рейсов в каждом городе от дня или месяца вылета import csv import matplotlib.pyplot as plt from main import FLIGHTS from data_import import graphs def plotting(file, title, width, height, sizee): fig, ax = plt.subplots(1, 1) x = file.keys() y = file.values() ax.bar(x, y) ax.tick_params(axis='x', labelrotation=90) fig.set_figwidth(width) # ширина fig.set_figheight(height) # высота plt.title(title, size=sizee) s = graphs + 'bar_flights.png' plt.savefig(s) plt.clf() def coppy_of_str(inputt, start, stopp): outputt = '' for i in range(start, stopp): outputt += inputt[i] # print('output=',outputt) return int(outputt) def date_inc(i): # print(i,'before') # print(i % 100) i += 1 if i % 100 > 31: i = i - 1 - 30 + 100 if i % 10000 > 1231: i = i - 1 - 1200 + 10000 # print(i,'after\n') return i def import_first(database, dictionary): count = 1 for i in range(0, database.shape[0]): if count > 0: s = database["дата"][i] s = s.replace("/", "") num = int(coppy_of_str(s, 4, 8) * 10000 + coppy_of_str(s, 2, 4) + coppy_of_str(s, 0, 2) * 100) if num in dictionary.keys(): dictionary[num] += 1 else: dictionary[num] = 1 count += 1 else: count += 1 del dictionary[''] return dictionary def compressor_of_first(dictionary): min_date = min(dictionary.keys()) max_date = max(dictionary.keys()) i = min_date while i < max_date: j = i + 1 while j <= max_date + 1: if i in dictionary.keys() and j in dictionary.keys(): if int(i / 100) == int(j / 100): dictionary[i] += dictionary[j] del dictionary[j] j -= 1 j = date_inc(j) if i in dictionary.keys(): dictionary[int(i / 100)] = dictionary[i] del dictionary[i] i = date_inc(i) return dictionary def trans_to_str(dictionary, answer): keys = [] for line in dictionary.keys(): keys.append(line) for line in keys: if answer == 'Да' or answer == 'Yes' or answer == '1' or answer == 'yes': s = line s = str(s % 100) + '.' + str(int(s / 100) % 100) + '.' + str(int(s / 10000)) else: s = str(line) s = s[4:] + '.' + s[:4] dictionary[s] = dictionary[line] del dictionary[line] return dictionary def flights(): flights_of_date = { '': '' } # print('Строить график по дням? (Yes/No)') # answer = input() # if answer == 'Да' or answer == 'Yes' or answer == '1' or answer == 'yes': # print('Хорошо, будем строить по дням, но он будет очень большой!\n (Это займёт какое-то время)') # else: # print('Ладно, тогда строим по месяцам') flights_of_date = import_first(FLIGHTS, flights_of_date) answer = 0 if not (answer == 'Да' or answer == 'Yes' or answer == '1' or answer == 'yes'): flights_of_date = compressor_of_first(flights_of_date) flights_of_date = trans_to_str(flights_of_date, answer) # print(flights_of_date.keys()) # print(len(flights_of_date.keys())) if answer == 'Да' or answer == 'Yes' or answer == '1' or answer == 'yes': plotting(flights_of_date, 'Количество рейсов в каждом дне', 160, 15, 50) else: plotting(flights_of_date, 'Количество рейсов в каждом месяце', 50, 10, 50) flights()
6665f7fa1a6339ac0a722f27272fef6befa13c4a
VGasparini/ICPC
/2017.1 Local/C.py
389
3.875
4
for i in range(int(input())): conjunto = list(map(int,input().split())) print("Conjunto: {} {} {}".format(conjunto[0],conjunto[1],conjunto[2])) for j in range(conjunto[2]): if (conjunto[0] > conjunto[1]): conjunto[0] = int(conjunto[0]/2) else: conjunto[1] = int(conjunto[1]/2) del conjunto[2] conjunto.sort(reverse=True) print(conjunto[0],conjunto[1]) print()
a8e770c0dc5dffb095697d3fb5173b217b1eda2e
PirieD704/pygame_first
/hero.py
1,583
3.921875
4
import pygame#duh class Hero(object): def __init__(self, screen): self.screen = screen # give the hero the ability to control the screen # Load the hero image, get it's rect self.image = pygame.image.load('ball.gif') self.rect = self.image.get_rect() #pygame makes give us get_rect on any object so we can get some dimensions and locations self.screen_rect = screen.get_rect() # assing a var so the hero class knows how big and where the screen is self.rect.centerx = self.screen_rect.centerx #this will put the middle of the hero at the middle of the screen self.rect.centery = self.screen_rect.centery # this will put our hero "bottom" at the bottom of the screen #not self.rect.centery because we want the bottom on the bottom, not the center self.moving_right = False #Set up movement booleans self.moving_left = False self.moving_up = False self.moving_down = False #Add updat to the hero class to keep all the hero updates in the hero class def update(self): if self.moving_right and self.rect.right < self.screen_rect.right: self.rect.centerx += 10 #Move the hero to the right! elif self.moving_left and self.rect.left > self.screen_rect.left: self.rect.centerx -= 10 #Move the hero to the left! if self.moving_up and self.rect.top > self.screen_rect.top: self.rect.centery -= 10 #Move the hero up! elif self.moving_down and self.rect.bottom < self.screen_rect.bottom: self.rect.centery += 10 #Move the hero down! def draw_me(self): self.screen.blit(self.image, self.rect) #Draw the Surface... (the image, the where)
197014528de4c35e7a550bef53592db68a1e567a
amanlalwani007/important-python-scripts
/counting sort.py
618
3.890625
4
#counting sort is based upon hashing and in this element are not compare with each other def countingsort(arr): max1=0 for i in arr: if i>max1: max1=i b=[0 for i in range(max1+1)] for i in arr: b[i]=b[i]+1 for i in range(1,len(b)): b[i]=b[i]+b[i-1] c=["" for i in range(len(arr))] for j in range(len(arr)-1,-1,-1): c[b[arr[j]]-1]=arr[j] b[arr[j]]=b[arr[j]]-1 print('the sorted array is ') for i in c: print(i,end=' ') if __name__=='__main__': arr=[3,44,2,2,56,6,88,2,4,6,7,32,5,21] countingsort(arr)
6869d350507603e55f4f2a3963a4ce81514473bb
AlexandruCabac/Rezolvarea-pr.-IF-FOR-WHILE
/Prob2.py
93
3.53125
4
import math n=int(input()) s=0 for i in range(1,n+1): s=math.factorial(i)+s print(s)
d3db22252d78bc2c56878abe4b3488577c7333a3
thinkphp/seeds.py
/monte_carlo_pi.py
370
3.90625
4
''' Monte Carlo simulation to approximate PI. ''' import math import random def PI(repeats = 10**5): count = 0 for _ in range( repeats ): x, y = random.random(), random.random() if((x**2 + y**2) <= 1): count+=1 return float (4 * count) / repeats print 'def PI: ', PI() print 'math.pi: ', math.pi
709d1e0379ebea730c22d604a31320ab5e580829
milkacaduke/Interview
/search/binarysearch.py
484
3.984375
4
def binarySearch(array, left, right, x): while right >= left: mid = left + (right - left) // 2; if array[mid] == x: # found it return mid elif x < array[mid]: # <- right = mid - 1 elif x > array[mid]: left = mid + 1 return False # main array = [4,35,2,6,3,66,45,8,1,34,78,43,23,22] array.sort() print(array) print(" ", end="") for i in range(len(array)): print("{}, ".format(i), end="") x = 5 result = binarySearch(array, 0, len(array)-1, x) print(result)
999dc52647c588857b3046a6b0009568ec1ee5a7
KatsuPatrick/advent2019
/day20/Part1.py
4,988
3.59375
4
import math; import re; import random; def adjacentTraversablePoints(point): global traversableSet; returnVar = [] if (point[0] + 1, point[1]) in traversableSet: returnVar.append((point[0] + 1, point[1])); if (point[0] - 1, point[1]) in traversableSet: returnVar.append((point[0] - 1, point[1])); if (point[0], point[1] + 1) in traversableSet: returnVar.append((point[0], point[1] + 1)); if (point[0], point[1] - 1) in traversableSet: returnVar.append((point[0], point[1] - 1)); return returnVar; def adjacentTraversablePointFromTwo(point1, point2): global traversableSet; if (point1[0] + 1, point1[1]) in traversableSet: return (point1[0] + 1, point1[1]); elif (point1[0] - 1, point1[1]) in traversableSet: return (point1[0] - 1, point1[1]); elif (point1[0], point1[1] + 1) in traversableSet: return (point1[0], point1[1] + 1); elif (point1[0], point1[1] - 1) in traversableSet: return (point1[0], point1[1] - 1); elif (point2[0] + 1, point2[1]) in traversableSet: return (point2[0] + 1, point2[1]); elif (point2[0] - 1, point2[1]) in traversableSet: return (point2[0] - 1, point2[1]); elif (point2[0], point2[1] + 1) in traversableSet: return (point2[0], point2[1] + 1); elif (point2[0], point2[1] + 1) in traversableSet: return (point2[0], point2[1] + 1); else: return None; inputStream = open("./input", "r"); #inputStream = open("./testInput", "r"); seperatedInput = inputStream.readlines(); traversableSet = set(); letterDict = {}; for j in range(len(seperatedInput)): for i in range(len(seperatedInput[j])): var = seperatedInput[j][i]; if var != " " and var != "#" and var != "\n": if var == ".": traversableSet.add((i, j)); else: letterDict[(i, j)] = var; portalsDict = {}; for i in letterDict: # each pair read only once by only checking down and right skip = False; j = None; if (i[0] + 1, i[1]) in letterDict: j = (i[0] + 1, i[1]); elif (i[0], i[1] + 1) in letterDict: j = (i[0], i[1] + 1); else: skip = True; if not skip: portalPoint = adjacentTraversablePointFromTwo(i, j); portalID = str(letterDict[i] + letterDict[j]); if portalID not in portalsDict: portalsDict[portalID] = []; portalsDict[portalID].append(portalPoint); if len(portalsDict[portalID]) > 2: print("o no", portalID, portalsDict[portalID]); input(); linkedMaze = {} for i in portalsDict: if len(portalsDict[i]) == 2: for j in portalsDict[i]: if j not in linkedMaze: linkedMaze[j] = set(); linkedMaze[portalsDict[i][0]].add(portalsDict[i][1]); linkedMaze[portalsDict[i][1]].add(portalsDict[i][0]); for i in traversableSet: if i not in linkedMaze: linkedMaze[i] = set(); connectedPoints = adjacentTraversablePoints(i); for j in connectedPoints: linkedMaze[i].add(j); startPoint = portalsDict["AA"][0]; endPoint = portalsDict["ZZ"][0]; currentPoint = startPoint; currentPath = []; pathsTaken = {}; currentLowestTraversal = math.inf; completedTraversal = False; count = 0 while not completedTraversal: movedForwards = False; #print(currentPath, currentLowestTraversal, linkedMaze[currentPoint], pathsTaken, movedForwards) if len(currentPath) < currentLowestTraversal: branchesAvailable = linkedMaze[currentPoint].copy(); if len(currentPath) > 0: if currentPath[-1] in branchesAvailable: branchesAvailable.remove(currentPath[-1]); if currentPoint not in pathsTaken: pathsTaken[currentPoint] = set(); for i in pathsTaken[currentPoint]: if i in branchesAvailable: branchesAvailable.remove(i); toPop = set(); for i in branchesAvailable: if i in currentPath: toPop.add(i); for i in toPop: branchesAvailable.remove(i); if len(branchesAvailable) > 0: newPoint = random.choice(tuple(branchesAvailable)); pathsTaken[currentPoint].add(newPoint); currentPath.append(currentPoint); currentPoint = newPoint; movedForwards = True; if currentPoint == endPoint: count += 1 if len(currentPath) < currentLowestTraversal: currentLowestTraversal = len(currentPath); currentPoint = currentPath[-1]; currentPath.pop(); if not movedForwards: if currentPoint in pathsTaken: pathsTaken.pop(currentPoint); if len(currentPath) > 0: currentPoint = currentPath[-1]; currentPath.pop(); else: completedTraversal = True; print(currentLowestTraversal);
cebe84bd2f08c4c1e807d9f60f69df1e6e76c949
Wedyarit/SchoolBot
/utils/Dates.py
423
3.5625
4
import datetime def weekday(day): return {0:"Понедельник", 1:"Вторник", 2:"Среда", 3:"Четверг", 4:"Пятница", 5:"Суббота", 6:"Воскресенье"}.get(day, "Invalid month") def today(): return datetime.date.today() def tomorrow(): return datetime.date.today() + datetime.timedelta(days=1) def after_tomorrow(): return datetime.date.today() + datetime.timedelta(days=2)
95608818d523c940376117b0a7bb6096edd0cecc
michellexyeo/DailyProgrammer
/Dynamic/coin_change.py
560
3.59375
4
# Hackerrank coin change problem: https://www.hackerrank.com/challenges/coin-change # Enter your code here. Read input from STDIN. Print output to STDOUT # using this: http://www.ideserve.co.in/learn/coin-change-problem-number-of-ways-to-make-change n, m = map(int, raw_input().strip().split()) coins = map(int, raw_input().strip().split()) # base case: n = 0 sol = [0]*(n+1) sol[0] = 1 for i in xrange(1, m+1): # for each coin for j in xrange(1, n+1): # range of change if j >= coins[i-1]: sol[j] += sol[j-coins[i-1]] print sol[-1]
f59ead3a084224a33a6e8bb427fc4d5179c9f0ce
eren-memet/Python-Starter-
/type-conversion.py
636
4.0625
4
""" x = input ('1.sayı ') y = input ('2.sayı ') print(type(x)) print(type(y)) toplam = int(x) + int (y) print(toplam) """ x = 5 #int y = 2.5 #float name = 'Çınar' #str isOnline = True #bool # print(type (x)) # print(type (y)) # print(type (name)) # print(type (isOnline)) # Type Conversion # float to int # y = int(y) # print(y) # print(type(y)) # result = str (x) + str(y) # print(result) # print(type(result)) #bool to int isOnline = False isOnline = int(isOnline) print(isOnline) print(type(isOnline))
ee864436866bba25781063c4f9294fba9999748b
chyt123/cosmos
/coding_everyday/lc500+/lc820/ShortEncodingofWords.py
581
3.640625
4
from typing import List class Solution: def minimumLengthEncoding(self, words: List[str]) -> int: new_words = sorted([i[::-1] for i in words], reverse=True) l = len(new_words) s = '#' + new_words[0] for i in range(1, l): if not new_words[i-1].startswith(new_words[i]): s += '#' + new_words[i] return len(s) if __name__ == "__main__": sol = Solution() words = ["time", "ime", "me", "e", "abc"] words = ["me", "time"] words = ["time", "me", "bell"] print(sol.minimumLengthEncoding(words))
3c639bf5bd4c671a7174b9c60abac8c2ff82d241
luisemaldonadoa/ejemplos
/listbox.py
507
3.640625
4
from Tkinter import * def agregar(): lista1.insert(END,"ENTRADA") #lista1.insert(END,) def remover(): lista1.delete(0,END) ventana=Tk() ventana.title("listbox") ventana.geometry("700x400+10+10") lista1=Listbox(ventana) lista1.insert(1,"Python") lista1.insert(2,"PHp") lista1.insert(3,"java") lista1.insert(4,"c++") lista1.place(x=10,y=20) btnAdd=Button(ventana,text="Agregar",command=agregar).place(x=140,y=20) btnRemove=Button(ventana,text="Delete",command=remover).place(x=200,y=20) ventana.mainloop()
e1248bf30ed6e8915d3ed802566b36a1b5364063
curatorcorpus/FirstProgramming
/Python/input files.py
370
3.75
4
# count how many a there are in a txt document def count_a(document, strng): reading = document.read() count = 0 for char in reading: if char == strng: count += 1 return count import os os.chdir('C:\Users\Jung Woo Park\Desktop') document = open("document.txt") strng = "a" print count_a(document, strng) document.close()
ec7106faff2677d421fe8b417fc54fc3171cd5ec
aclissold/CodeEval
/problem004/solution.py
764
4.03125
4
#!/usr/bin/env python3 """Problem 4: Sum of Primes Challenge Description: Write a program to determine the sum of the first 1000 prime numbers. Input sample: None Output sample: Your program should print the sum on stdout.i.e. 3682913 """ def main(): """Prints the sum of the first 1000 prime numbers.""" prime_sum = 2 # A running summation primes = 1 # A count of how many primes were found num = 3 # The current integer to check for primeness while primes < 1000: for i in range(2, num): if num % i == 0: # If prime break else: # If no divisors found prime_sum += num primes += 1 num += 1 print(prime_sum) if __name__ == '__main__': main()
69bdba133a00266ace3d21661cfc462f0751a003
jig4l1nd0/PythonFirsts
/ex36.py
2,712
4.0625
4
# - - coding: utf- 8 - - #### Key words in python #### ### None def improper_return_function(a): if a % 2 == 0: return True x = improper_return_function(3) print x ### and, or, not print True and False print True or False print not False ### as import math as myAlias print myAlias.cos(myAlias.pi) ### assert (se usa para debugging, muestra error si la condición es falsa) a = 4 assert a < 5, "El numero es muy grande" #assert condition, mesage #otra forma if not a < 5: raise AssertionError("El numero es muy grande") ### break, continue for i in range(1,11): if i == 5: #se salta el 5 y sale del bucle break print(i) for i in range(1,11): if i == 5: #se salta el 5 pero continue #no sale de del bucle print(i) ### del (borra referencia a un objeto) a = b = 5 del a #print a #error, a no esta definida a = ["l","s","t","u"] del a[1] print a #["x","z"] ### except, raise, try (with errors that suggests something # went wrong while executing our program. ) #IOError, ValueError, ZeroDivisionError, ImportError, NameError, TypeError def reciprocal(num): try: r = 1/num except: print('Exception caught') return return r print reciprocal(10) print reciprocal(0) #Here, the function reciprocal() returns the reciprocal of the input number. #When we enter 10, we get the normal output of 0.1. But when we input 0, a ZeroDivisionError is raised automatically. #This is caught by our try…except block and we return None. We could have also raised the ZeroDivisionError explicitly by checking the input and handled it elsewhere as follows: def reciprocal(num): if num == 0: raise ZeroDivisionError('cannot divide') r = 1/num return r print reciprocal(10) print reciprocal(1) ### finally #Using finally ensures that the block of code inside it gets executed even if there is an unhandled exception. For example: #try: # Try-block #except exception1: # Exception1-block #except exception2: # Exception2-block #else: # Else-block #finally: # Finally-block ### global #global is used to declare that a variable inside #the function is global (outside the function). globvar = 10 def read1(): print globvar def write1(): global globvar globvar = 5 def write2(): globvar = 15 read1() write1() read1() write2() read1() ### lambda (crea funciones de una sola linea ) f = lambda x: x*2 for z in range (1,6): print f(z) ### pass #Nothing happens when it is executed. It is used as a placeholder def function(args): pass class example: pass
2137fc037c3e02b35b039548f27740b1893fe79f
HelenDeunerFerreira/exercicios_para_praticar
/1.py
1,750
3.84375
4
# Crie uma função que recebe uma lista de números e # a. retorne o maior elemento # b. retorne a soma dos elementos # c. retorne o número de ocorrências do primeiro elemento da lista # d. retorne a média dos elementos # e. retorne a soma dos elementos com valor negativo def listaNumeros(): n1 = int(input('Primeiro número: ')) n2 = int(input('Segundo número: ')) n3 = int(input('Terceiro número: ')) n4 = int(input('Quarto número: ')) n5 = int(input('Quinto número: ')) listaDeNumeros = [n1, n2, n3, n4, n5] listaSem = [n2, n3, n4, n5] soma = n1 + n2 + n3 + n4 + n5 resposta = input('Escolha o que deseja fazer com a lista: ') if resposta == 'a': maiorNumero = 0 for i in listaDeNumeros: if i > maiorNumero: maiorNumero = i print(f'O maior número dessa lista é {maiorNumero}') elif resposta == 'b': print(f'A soma dos números da sua lista é {soma}') elif resposta == 'c': ocorrencias = 1 for i in listaSem: if i == n1: ocorrencias += 1 print( f'O número de vezes em que o primeiro elemento da sua lista aparece: {ocorrencias}') elif resposta == 'd': media = soma/5 print(f'A média aritmética dos elemnetos listados é {media}') elif resposta == 'e': somaNegativos = 0 for i in listaDeNumeros: listaNegativos = [] if i < 0: listaNegativos.append(i) for i in listaNegativos: somaNegativos += i print(f'A soma dos elementos negativos é {somaNegativos}') else: print('Essa opção não é válida!') listaNumeros()
f7e595d619ca3e0482c01f4f14e8fe63cc3fe5f4
ikekou/python-exercise-100-book
/78.py
124
3.5
4
d = {'b':222,'a':111,'d':444,'c':333} key_to_get_min_value = min(d.keys(), key= lambda k: d[k]) print(key_to_get_min_value)
93e1df28b83f8e84eb9908981796c26e5b7473c5
kepich/Swarm
/Bug.py
4,924
3.625
4
from math import sqrt import pygame import random from Display import Display class Bug(pygame.sprite.Sprite): SIZE = 5 MOVEMENT_SPEED = 2 HEAR_RANGE = 50 FOOD_TARGET = 1 QUEEN_TARGET = -1 def __init__(self, x, y, speed_offset): pygame.sprite.Sprite.__init__(self) # self.myfont = pygame.font.SysFont("monospace", 6) self.speed_offset = speed_offset # Drawing self.image = pygame.Surface([self.SIZE, self.SIZE]) self.image.fill((0, 0, 0)) self.image.set_colorkey((0, 0, 0)) pygame.draw.circle(self.image, (0, 255, 0), (self.SIZE // 2, self.SIZE // 2), self.SIZE // 2) self.mask = pygame.mask.from_surface(self.image) self.rect = self.image.get_rect() self.rect.x = x self.rect.y = y # Position self.x_pos = x # Float values of position self.y_pos = y self.move_vector = [] self.set_movement([random.randint(-2000, 2000), random.randint(-2000, 2000)]) # Counters self.target_food = 300 self.target_queen = 300 self.target = self.FOOD_TARGET def set_movement(self, vector): vector_len = sqrt(vector[0] * vector[0] + vector[1] * vector[1]) if vector_len > 10: self.move_vector = [(self.MOVEMENT_SPEED + self.speed_offset) * vector[0] / vector_len, (self.MOVEMENT_SPEED + self.speed_offset) * vector[1] / vector_len] def update(self, *action, **kwargs) -> None: if action[0] == "move": self.move_action(action) elif action[0] == "hear": self.hear_action() def move_action(self, action): if self.x_pos + self.move_vector[0] > Display.WINDOW_WIDTH - self.SIZE or self.x_pos + self.move_vector[0] < 0 \ or self.y_pos + self.move_vector[1] > Display.WINDOW_HEIGHT - self.SIZE or self.y_pos + self.move_vector[1] < 0: self.set_movement([random.randint(-2000, 2000), random.randint(-2000, 2000)]) else: self.move(action[1], action[2], action[3]) def hear_action(self): hearable_bugs = list(filter(lambda sprite: sqrt( (self.x_pos - sprite.x_pos) ** 2 + ( self.y_pos - sprite.y_pos) ** 2) < self.HEAR_RANGE and sprite != self, self.groups()[0].sprites())) if len(hearable_bugs) > 0: best_bug_food = min(hearable_bugs, key=lambda bug: bug.target_food) best_bug_queen = min(hearable_bugs, key=lambda bug: bug.target_queen) if self.target_food > (best_bug_food.target_food + self.HEAR_RANGE): self.target_food = best_bug_food.target_food + self.HEAR_RANGE if self.target == self.FOOD_TARGET: self.set_movement([best_bug_food.x_pos - self.x_pos, best_bug_food.y_pos - self.y_pos]) if self.target_queen > (best_bug_queen.target_queen + self.HEAR_RANGE): self.target_queen = best_bug_queen.target_queen + self.HEAR_RANGE if self.target == self.QUEEN_TARGET: self.set_movement([best_bug_queen.x_pos - self.x_pos, best_bug_queen.y_pos - self.y_pos]) def move(self, food, queens, stone): collisions_food = pygame.sprite.spritecollide(self, food, False, pygame.sprite.collide_mask) collisions_queens = pygame.sprite.spritecollide(self, queens, False, pygame.sprite.collide_mask) if len(collisions_food) > 0: self.target_food = 0 if self.target == self.FOOD_TARGET: # target - food self.turn_around() else: self.set_movement([random.randint(-2000, 2000), random.randint(-2000, 2000)]) elif len(collisions_queens) > 0: self.target_queen = 0 if self.target == self.QUEEN_TARGET: # target - food self.turn_around() else: self.set_movement([random.randint(-2000, 2000), random.randint(-2000, 2000)]) self.x_pos += self.move_vector[0] self.y_pos += self.move_vector[1] self.rect.x = self.x_pos self.rect.y = self.y_pos self.inc_counters(stone) def inc_counters(self, stone): self.target_food += 1 self.target_queen += 1 if len(pygame.sprite.spritecollide(self, stone, False, pygame.sprite.collide_mask)) > 0: self.target_food += 20 self.target_queen += 20 def turn_around(self): self.target *= -1 self.move_vector[0] = -self.move_vector[0] self.move_vector[1] = -self.move_vector[1] if self.target == self.FOOD_TARGET: pygame.draw.circle(self.image, (0, 255, 0), (self.SIZE // 2, self.SIZE // 2), self.SIZE // 2) else: pygame.draw.circle(self.image, (255, 0, 0), (self.SIZE // 2, self.SIZE // 2), self.SIZE // 2)
bef8b3230ae6aaa8ccd7d558a902ac91c6457ab8
clivejan/python_basic
/data_type/birthdays.py
414
4.21875
4
birthdays = {'Clive': 'Aug 12', 'Carrie': 'Jul 13', 'Tzuyu': 'Jun 14'} while True: name = input('Enter a name (blank to exit): ') if name == '': break if name in birthdays: print(f"{birthdays[name]} is the birthday of {name}.") else: print(f'I do not have birthday information for {name}.') bday = input(f'What is {name}\'s birthday: ') birthdays[name] = bday print('Birthday database updated.')
a60d1a4dcab1116cbf67c7017e5b3d2864027260
burkharz9279/cti110
/M2HW2_Tip Tax and Total_Burkhardt.py
335
4.03125
4
#CTI 110 #M2HW2 - Tip, Tax, and Total #Zachary Burkhardt #9/10/17 print("Input your meal cost to find your tip, tax, and total") meal_cost = float(input("Meal cost: ")) tip = meal_cost * 0.18 print("Tip is", tip) tax = meal_cost * 0.07 print("Tax is", tax) total_cost = meal_cost + tip + tax print("Your total cost is", total_cost)
6353c1cfff07ad2ab843f12752c25019ab615aa9
muhtarkasimov/PythonBot
/MyTime.py
2,697
3.984375
4
import time from _datetime import datetime import time class Time: def __init__(self): self.current_time = datetime.now() # format dd.mm.yyyy hh:mm:ss self.current_time_string = datetime.strftime(datetime.now(), "%d.%m.%Y %H:%M:%S") self.current_date = self.current_time_string[:10] self.current_year = self.current_time_string[6:10] self.current_month = self.current_time_string[3:5] self.current_day = self.current_time_string[0:2] self.current_hour = self.current_time_string[11:13] self.current_minute = self.current_time_string[14:16] self.current_second = self.current_time_string[17:] # -------------------------------------------------- # Time # format dd.mm.yyyy hh:mm:ss # current_time_string = time_string = datetime.strftime(datetime.now(), "%d.%m.%Y %H:%M:%S") # print(current_time_string) # -------------------------------------------------- # current_date = current_time_string[:10] # current_year = current_time_string[6:10] # current_month = current_time_string[3:5] # current_day = current_time_string[0:2] def print_time(self): self.update_time() print('date: ' + self.current_date) print('year: ' + self.current_year) print('month: ' + self.current_month) print('day: ' + self.current_day) print('hour: ' + self.current_hour) print('minute: ' + self.current_minute) print('second: ' + self.current_second) def get_time(self): self.update_time() return [self.current_year, self.current_month, self.current_day, self.current_hour, self.current_minute] def update_time(self): # format dd.mm.yyyy hh:mm:ss #--------0123456789012345678 self.current_time = datetime.now() self.current_date = self.current_time_string[:10] self.current_year = self.current_time_string[6:10] self.current_month = self.current_time_string[3:5] self.current_day = self.current_time_string[0:2] self.current_hour = self.current_time_string[11:13] self.current_minute = self.current_time_string[14:16] # self.current_second = self.current_time_string[17:19] # print(self.current_time_string) # print(self.current_second) # def update_time_per_hour(self): # current_time = datetime.now() # # # format dd.mm.yyyy hh:mm:ss # current_time_string = time_string = datetime.strftime(datetime.now(), "%d.%m.%Y %H:%M:%S") # my_time = Time() # my_time.update_time() # # while(True): # my_time.update_time # my_time.print_time() # time.sleep(30)
e75b4e0671e49037b728cef644c1e0383e0946de
rahuldesai02/LeetCode-Solutions
/py/118.PascalTriangle.py
553
3.71875
4
''' Question Given an integer numRows, return the first numRows of Pascal's triangle. Input: numRows = 5 Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]] ''' class Solution: def generate(self, numRows: int) -> List[List[int]]: ll = [[]] tmp = [] for i in range(numRows): tmp = [] for j in range(i+1): res = math.factorial(i)/(math.factorial(j) * math.factorial(i-j)) tmp.append(int(res)) ll.append(tmp) ll.pop(0) return ll
3776283dbb9b380eb7b4b1b4b124bac8839a4b20
ricardo64/Over-100-Exercises-Python-and-Algorithms
/src/further_examples/trees_graphs/binary_tree.py
15,992
4.125
4
#!/usr/bin/python3 # mari von steinkirch 2013 # http://astro.sunysb.edu/steinkirch ''' Implementation of a binary tree and its properties. For example, the following bt: 1 ---> level 0 2 3 ---> level 1 4 5 ---> level 2 6 7 ---> level 3 8 9 ---> level 4 has the following properties: - SIZE OR NUMBER OF NODES: n = 9 - NUMBER OF BRANCHES OR INTERNAL NODES: b = n-1 = 8 - VALUE OF ROOT = 1 - MAX_DEPTH OR HEIGHT: h = 4 - IS BALANCED? NO - IS BST? NO - INORDER DFT: 8, 6, 9, 4, 7, 2, 5, 1, 3 - POSTORDER DFT: 8, 9, 6, 7, 4, 5, 2, 3, 1 - PREORDER DFT: 1, 2, 4, 6, 8, 9, 7, 5, 3 - BFT: 1, 2, 3, 4, 5, 6, 7, 8, 9 ''' from collections import deque class NodeBT(object): def __init__(self, item=None, level=0): ''' Construtor for a Node in the Tree ''' self.item = item self.level = level self.left = None self.right = None self.traversal = [] #self.parent = None # not used here but can be necessary for some problems ''' METHODS TO MODIFY NODES ''' def _addNextNode(self, value, level_here=1): ''' Aux for self.addNode(value)''' self.traversal = [] new_node = NodeBT(value, level_here) if not self.item: self.item = new_node elif not self.left: self.left = new_node elif not self.right: self.right = new_node else: self.left = self.left._addNextNode(value, level_here+1) return self ''' METHODS TO PRINT/SHOW NODES' ATTRIBUTES ''' def __repr__(self): ''' Private method for this class'string representation''' return '{}'.format(self.item) def _getDFTpreOrder(self, node): ''' Traversal Pre-Order, O(n)''' if node: if node.item: self.traversal.append(node.item) self._getDFTpreOrder(node.left) self._getDFTpreOrder(node.right) return self def _printDFTpreOrder(self, noderoot): ''' Fill the pre-order traversal array ''' self.traversal = [] self._getDFTpreOrder(noderoot) return self.traversal def _getDFTinOrder(self, node): ''' Traversal in-Order, O(n)''' if node: self._getDFTinOrder(node.left) if node.item: self.traversal.append(node.item) self._getDFTinOrder(node.right) return self def _printDFTinOrder(self, noderoot): ''' Fill the in-order traversal array ''' self.traversal = [] self._getDFTinOrder(noderoot) return self.traversal def _getDFTpostOrder(self, node): ''' Traversal post-Order, O(n)''' if node: self._getDFTpostOrder(node.left) self._getDFTpostOrder(node.right) if node.item: self.traversal.append(node.item) return self def _getBFT(self, node): ''' Traversal bft, O(n)''' if node: queue = deque() queue.append(node) while len(queue) > 0: current = queue.popleft() if current.item: self.traversal.append(current) if current.left: queue.append(current.left) if current.right: queue.append(current.right) return self def _printBFT(self, noderoot): ''' Fill the in-order traversal array ''' self.traversal = [] self._getBFT(noderoot) return self.traversal def _printDFTpostOrder(self, noderoot): ''' Fill the post-order traversal array ''' self.traversal = [] self._getDFTpostOrder(noderoot) return self.traversal def _searchForNode(self, value): ''' Traverse the tree looking for the node''' if self.item == value: return self else: found = None if self.left: found = self.left._searchForNode(value) if self.right: found = found or self.right._searchForNode(value) return found def _findNode(self, value): ''' Find whether a node is in the tree. if the traversal was calculated, it is just a membership checking, which is O(1), otherwise it is necessary to traverse the binary tree, so best case is O(1) and worst is O(n). ''' if self.traversal: return value in self.traversal else: return self._searchForNode(value) def _isLeaf(self): ''' Return True if the node is a leaf ''' return not self.right and not self.left def _getMaxHeight(self): ''' Get the max height at the node, O(n)''' levelr, levell = 0, 0 if self.right: levelr = self.right._getMaxHeight() + 1 if self.left: levell = self.left._getMaxHeight() + 1 return max(levelr, levell) def _getMinHeight(self, level=0): ''' Get the min height at the node, O(n)''' levelr, levell = -1, -1 if self.right: levelr = self.right._getMinHeight(level +1) if self.left: levell = self.left._getMinHeight(level +1) return min(levelr, levell) + 1 def _isBalanced(self): ''' Find whether the tree is balanced, by calculating heights first, O(n2) ''' if self._getMaxHeight() - self._getMinHeight() < 2: return False else: if self._isLeaf(): return True elif self.left and self.right: return self.left._isBalanced() and self.right._isBalanced() elif not self.left and self.right: return self.right._isBalanced() elif not self.right and self.left: return self.right._isBalanced() def _isBalancedImproved(self): ''' Find whehter the tree is balanced in each node, O(n) ''' return 'To Be written' ''' There are two solutions to check whether a bt is a bst: (1) Do an inorder, check if the inorder is sorted. However inorder can't handle the difference between duplicate values on the left or on the right (if it is in the right, the tree is not bst). ''' def _isBST(self): ''' Find whether the tree is a BST, inorder ''' if self.item: if self._isLeaf(): return True elif self.left: if self.left.item < self.item: return self.left._isBST() else: return False elif self.right: if self.right.item > self.item: return self.right._isBST() else: return False else: raise Exception('Tree is empty') def _getAncestorBST(self, n1, n2): ''' Return the ancestor of two nodes if it is a bst. we are supposing the values in the tree are unique.''' if n1 == self.item or n2 == self.item : return self.item elif self.item < n1 and self.item < n2: self.right.getAncestorBST(n1, n2) elif self.item > n1 and self.item > n2: self.left.getAncestorBST(n1, n2) else: return self.item class BinaryTree(object): ''' >>> bt = BinaryTree() >>> for i in range(1, 10): bt.addNode(i) >>> bt.hasNode(7) True >>> bt.hasNode(12) False >>> bt.printTree() [1, 2, 4, 6, 8, 9, 7, 5, 3] >>> bt.printTree('pre') [1, 2, 4, 6, 8, 9, 7, 5, 3] >>> bt.printTree('bft') [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> bt.printTree('post') [8, 9, 6, 7, 4, 5, 2, 3, 1] >>> bt.printTree('in') [8, 6, 9, 4, 7, 2, 5, 1, 3] >>> bt.hasNode(9) True >>> bt.hasNode(11) False >>> bt.isLeaf(8) True >>> bt.getNodeLevel(1) 0 >>> bt.getNodeLevel(8) 4 >>> bt.getSizeTree() 9 >>> bt.isRoot(10) False >>> bt.isRoot(1) True >>> bt.getHeight() 4 >>> bt.isBST(1) False >>> bt.isBalanced() False >>> bt.isBalanced(2) False >>> bt.getAncestor(8, 5) 2 >>> bt.getAncestor(8, 5, 'pre-post') 2 >>> bt.getAncestor(8, 5, 'post-in') 2 ''' def __init__(self): ''' Construtor for the Binary Tree, which is a container of Nodes''' self.root = None ''' METHODS TO MODIFY THE TREE ''' def addNode(self, value): ''' Add new node to the tree, by the left first, O(n) ''' if not self.root: self.root = NodeBT(value) else: self.root._addNextNode(value) ''' METHODS TO PRINT/SHOW TREES' ATTRIBUTES ''' def __repr__(self): ''' Private method for this class'string representation''' return '{}'.format(self.item) def printTree(self, order = 'pre'): ''' Print Tree in the chosen order ''' if self.root: if order == 'pre': return self.root._printDFTpreOrder(self.root) elif order == 'in': return self.root._printDFTinOrder(self.root) elif order == 'post': return self.root._printDFTpostOrder(self.root) elif order == 'bft': return self.root._printBFT(self.root) else: raise Exception('Tree is empty') def hasNode(self, value): ''' Verify whether the node is in the Tree ''' return bool(self.root._findNode(value)) def isLeaf(self, value): ''' Return True if the node is a Leaf ''' node = self.root._searchForNode(value) return node._isLeaf() def getNodeLevel(self, item): ''' Return the level of the node, best O(1), worst O(n) ''' node = self.root._searchForNode(item) if node: return node.level else: raise Exception('Node not found') def getSizeTree(self): ''' Return how many nodes in the tree, O(n) ''' return len(self.root._printDFTpreOrder(self.root)) def isRoot(self, value): '''Return the root of the tree ''' return self.root.item == value def getHeight(self): ''' Returns the height/depth of the tree, best/worst O(n) ''' return self.root._getMaxHeight() def isBalanced(self, method=1): ''' Return True if the tree is balanced''' if method == 1: ''' O(n2)''' return self.root._isBalanced() else: ''' O(n)''' return self.root._isBalancedImproved() ''' The followin methods are for searching the lowest common ancestor in a BT. Since a simple BT does not have ordering, it can be O(n). If we have a link for the ancestors, the steps are: (1) search both trees in order to find the nodes separately (2) list all ancestors (3) find first that mach obs: if we do this too many times we can do a pre and use the methods here''' def isBST(self, method=1): ''' Return True if the tree is BST''' if method == 1: inorder = self.root._printDFTinOrder(self.root) return inorder == sorted(inorder) elif method == 2: return self.root._isBST() def _getAncestorPreIn(self, preorder, inorder, value1, value2): ''' Return the ancestor of two nodes with pre and in''' root = preorder[0] preorder = preorder[1:] i = 0 item = inorder[0] value1left, value2left = False, False while item != root and i < len(inorder): if item == value1: value1left = True elif item == value2: value2left = True i += 1 item = inorder[i] if (value1left and not value2left) or (value2left and not value1left): return root else: return self._getAncestorPreIn(preorder, inorder[:i] + inorder[i+1:], value1, value2) def _getAncestorPrePost(self, preorder, postorder, value1, value2): ''' Return the ancestor of two nodes with pre and post''' root = preorder[0] preorder = preorder[1:] postorder = postorder[:-1] value1right, value2right = False, False i = len(postorder)-1 itempre = preorder[0] itempos = postorder[i] while itempre != itempos and i > 0: if itempos == value1: value1right = True elif itempos == value2: value2right = True i -= 1 itempos = postorder[i] if (value1right and not value2right) or (value2right and not value1right): return root else: return self._getAncestorPrePost(preorder, postorder[:i] + postorder[i+1:], value1, value2) def _getAncestorInPost(self, inorder, postorder, value1, value2): ''' Return the ancestor of two nodes with in and post''' root = postorder[-1] postorder = postorder[:-1] value1left, value2left = False, False i = 0 item = inorder[i] while item != root and i < len(inorder): if item == value1: value1left = True elif item == value2: value2left = True i += 1 item = inorder[i] if (value1left and not value2left) or (value2left and not value1left): return root else: return self._getAncestorInPost(postorder, inorder[:i] + inorder[i+1:], value1, value2) def _getAncestorBST2(self, preorder, value1, value2): ''' Return the ancestor of two nodes if it is a bst, using traversal''' while preorder: current = preorder[0] if current < value1: try: preorder = preorder[2:] except: return current elif current > value2: try: preorder = preorder[1:] except: return current elif value1 <= current <= value2: return current return None def getAncestor(self, value1, value2, method='pre-in'): ''' Return the commom ancestor for two nodes''' if method == 'pre-in': ''' Using pre and inorder, best/worst O(n)''' preorder = self.root._printDFTpreOrder(self.root) inorder = self.root._printDFTinOrder(self.root) return self._getAncestorPreIn(preorder, inorder, value1, value2) if method == 'pre-post': ''' Using pre and postorder, best/worst O(n)''' preorder = self.root._printDFTpreOrder(self.root) postorder = self.root._printDFTpostOrder(self.root) return self._getAncestorPrePost(preorder, postorder, value1, value2) if method == 'post-in': ''' Using in and postorder, best/worst O(n)''' inorder = self.root._printDFTinOrder(self.root) postorder = self.root._printDFTpostOrder(self.root) return self._getAncestorInPost(inorder, postorder, value1, value2) if method == 'bst': if self.isBST(): return self.root._getAncestorBST(value1, value2) #preorder = self.root._printDFTpreOrder(self.root) #return self._getAncestorBST2(preorder, value1, value2) else: return Exception('The tree is not a BST') if __name__ == '__main__': import doctest doctest.testmod()
cb57484eeef35b091ff32342b4600c992f390e96
tillderoquefeuil-42-ai/bootcamp-ml
/day01/ex05/fit.py
1,782
3.765625
4
import numpy as np def fit_(x, y, theta, alpha, max_iter): """ Description: Fits the model to the training dataset contained in x and y. Args: x: has to be a numpy.ndarray, a vector of dimension m * 1: (number of training examples, 1). y: has to be a numpy.ndarray, a vector of dimension m * 1: (number of training examples, 1). theta: has to be a numpy.ndarray, a vector of dimension 2 * 1. alpha: has to be a float, the learning rate max_iter: has to be an int, the number of iterations done during the gradient descent Returns: new_theta: numpy.ndarray, a vector of dimension 2 * 1. None if there is a matching dimension problem. """ if x.shape[0] * y.shape[0] * theta.shape[0] == 0: return None if x.shape[0] != y.shape[0] or theta.shape[0] != 2: return None x = add_intercept(x.transpose()[0]) y = y.transpose()[0] t = theta[:] for i in range(0, max_iter): oldt = t[:] t = gradient(x, y, t, alpha) if oldt[0] == t[0] and oldt[1] == t[1]: return t return t def gradient(x, y, theta, alpha): if x.shape[0] * y.shape[0] * theta.shape[0] == 0: return None if x.shape[0] != y.shape[0] or theta.shape[0] != 2: return None result = [ forumla(x, y, theta, alpha, 0), forumla(x, y, theta, alpha, 1) ] return np.array(result) def forumla(x, y, theta, alpha, j): length = x.shape[0] value = theta[j] - alpha * (1/length) * sum(((x.dot(theta) - y) * x[:,j:][:,0])) return value def add_intercept(x): if x.shape[0] == 0: return None if 1 == len(x.shape): x = x.reshape(x.shape[0], 1) return np.insert(x, 0, 1, axis=1)
db56c96d54eb9271ef43798a367fb3de51661cb2
Petuxpetuxov/GeekBrains
/Homework(Algorithms)/task_3.py
621
4.1875
4
""" По введенным пользователем координатам двух точек вывести уравнение прямой вида y = kx + b, проходящей через эти точки. """ print("Введите координаты 1 точки (x1; x2) :") x1 = float(input("x1 = ")) y1 = float(input("y1 = ")) print("Введите координаты 2 точки (x2, y2) :") x2 = float(input("x2 = ")) y2 = float(input("y2 = ")) k = (y1 - y2) / (x1 - x2) b = y2 - k * x2 print(f'Уравнение прямой проходящей через эти точки :\ny = {k}x + {b}')
8bd5ad3343910560aef1e0a9ca30fb5e23aa79a7
foolOnTheHill/ml
/scripts/part2/mlp_data_proccessing.py
3,586
3.625
4
import random random.seed(58) def normalize(X, Y, num_classes=0): """ Pre-processes the data that will be used to train the network creating bit lists for the classes. """ for i in range(len(X)): c = [0 for k in range(num_classes)] c[Y[i][0]] = 1 Y[i] = c return (X, Y) def getClass(class_bits): """ Returns the class that corresponds to the bit list. """ for c in range(len(class_bits)): if class_bits[c] == 1: return c def readData(filename): """ Reads a dataset from `filename` and returns it as a matrix. """ f = open(filename, 'r') lines = f.readlines() # Pre-proccesses the data by removing the semicolons mp = lambda l : l.split(',') data = map(mp, lines) getX = lambda l : l[:len(l)-1] X = map(getX, data) getY = lambda l : l[-1][:-1] # Gets the last element (the class parameter) Y = map(getY, data) return (X, Y) def proccessData(filename): """ Maps the input data to the model defined at the documentation and divides it into the experiments sets (train, validation and test). """ # Dataset info: # # Total: 958 data points # 2 classes (positive, negative) # # - positive: 626 # - negative: 332 # # Experiments division: # # - positive: # => Train: 313 # => Val: 157 # => Test: 155 # # - negative: # => Train: 166 # => Val: 83 # => Test: 83 (X, Y) = readData(filename) mp = lambda x : 1 if x == 'x' else 0 if x == 'o' else -1 proccessX = lambda l : map(mp, l) X = map(proccessX, X) proccessY = lambda y : [1] if y == 'positive' else [0] Y = map(proccessY, Y) (X, Y) = normalize(X, Y, num_classes=2) # processes Y to classes bit list C = [[], []] for i in range(len(Y)): if Y[i] == [1, 0]: C[0].append(i) else: C[1].append(i) random.shuffle(C[0]) random.shuffle(C[1]) negative = {'train':C[0][:166], 'validation':C[0][166:249], 'test':C[0][249:]} positive = {'train':C[1][:313], 'validation':C[1][313:470], 'test':C[1][470:]} trainData = negative['train']+positive['train'] validationData = negative['validation']+positive['validation'] testData = negative['test']+positive['test'] random.shuffle(trainData) random.shuffle(validationData) random.shuffle(testData) dataset = {'train':([],[]), 'validation':([],[]), 'test':([],[])} trainFile = open('train.txt', 'w') validationFile = open('validation.txt', 'w') testFile = open('test.txt', 'w') mp = lambda x : str(x) jn = lambda l : ' '.join(map(mp, l)) for i in range(len(trainData)): pos = trainData[i] dataset['train'][0].append(X[pos]) dataset['train'][1].append(Y[pos]) trainFile.write( jn(X[pos]+Y[pos]) ) trainFile.write('\n') for i in range(len(validationData)): pos = validationData[i] dataset['validation'][0].append(X[pos]) dataset['validation'][1].append(Y[pos]) validationFile.write( jn(X[pos]+Y[pos]) ) validationFile.write('\n') for i in range(len(testData)): pos = testData[i] dataset['test'][0].append(X[pos]) dataset['test'][1].append(Y[pos]) testFile.write( jn(X[pos]+Y[pos]) ) testFile.write('\n') trainFile.close() validationFile.close() testFile.close() return dataset def loadData(): """ Reads and pre-processes the dataset. """ return proccessData('tic-tac-toe.data.txt')
3461a2f5fffa58b8afd2a43a1093da34f62319d7
SWEETCANDY1008/algorithm_python
/ch02/quicksort.py
548
3.71875
4
S = [9, 8, 7, 6, 5, 4, 3, 2, 1] def quicksort(low, high): if high > low: pivotpoint = partition(low, high) quicksort(low, pivotpoint) quicksort(pivotpoint+1, high) def partition(low, high): pivotitem = S[low] j = low for i in range(low+1, high): if S[i] < pivotitem: j = j + 1 temp = S[i] S[i] = S[j] S[j] = temp pivotpoint = j temp = S[low] S[low] = S[pivotpoint] S[pivotpoint] = temp return pivotpoint quicksort(0, 9) print(S)
52d0e619f91554a302e2d59da6ce4073018c6ae3
insidescoop/sandbox-repo
/carter/sand.py
364
4.3125
4
print ('ben is a ugly boy') print ('ben is not loved') x=23*12356789 print (x) # This is an example of a string data type x="5*5*5*5*5*5*5*5*58" print (x) # Get a value from user and display it name=input("Name of company: ") print (name) #example of conditional statement z=25 if z>1: print ("buy") elif z==25: print ("hold") else: print ("sell")
18bb0bcc5b310ec85e8aed6a75ac5a89775d52bc
kresged/pytut
/03/lesson_03_loops.py
6,325
4.65625
5
# # Lesson 03: Loops # # I'm going to define a little helper function that will allow me to pause/resume the # program while I'm doing the presentation. Don't worry about this for now. If you # are running this program in "non-presentation" mode, then set PRESENTATION_MODE to False. PRESENTATION_MODE = True def pause_program(): print() if PRESENTATION_MODE: input("*** Program paused. Press Enter key to resume...") print("*" * 80) print() # In python, there are really only 2 types of loops. We covered one of them in Lesson 02, # namely the "while" loop. While the condition evaluates to True, keep doing whatever is # inside the while loop. Once the condition becomes False, the while loop ends and we move # on to the next statement in our program. A little refresher on the while loop and lists... # Remember lists are enclosed with square brackets numbers = [10, 2, 5, 1, 7, 6, 8, 3, 9, 4] # Number to find in the list find_number = 6 # position will keep track of where we are while traversing the list. In programming, # we usually call this an index (e.g. the number 10 is at index 0, 2 is at index 1) position = 0 # How many numbers do we have in out list? The len function will tell us this. numbers_length = len(numbers) print(f"Looking for number {find_number} in numbers list {numbers} with length {numbers_length} using while ...") while position < numbers_length: if numbers[position] == find_number: print(f" Found number {find_number} at position {position} so breaking out of while loop") break else: print(f" Number {numbers[position]} at position {position} is not what we're looking for") position = position + 1 pause_program() # Now let's introduce the for loop by attempting to do the same thing that we did with the while loop. position = 0 print(f"Looking for number {find_number} in numbers list {numbers} with length {numbers_length} using for ...") # In this for loop, item will be set to each value in the numbers list. You can say that we're # "walking the numbers list" one item at a time. for item in numbers: if item == find_number: print(f" Found number {find_number} at position {position} so breaking out of for loop") break else: print(f" Number {item} at position {position} is not what we're looking for") position = position + 1 pause_program() # Now I'll let you in on a little "secret." In the above for loop code, we were keeping track of the position # (index) so that we could display the position the number was found at. Python can do that for us with the # enumerate function, which will return both the position (index) *and* the item at that position. print(f"Looking for number {find_number} in numbers list {numbers} with length {numbers_length} using enumerate ...") for position, item in enumerate(numbers): if item == find_number: print(f" Found number {find_number} at position {position} so breaking out of for loop") break else: print(f" Number {item} at position {position} is not what we're looking for") pause_program() # We'll change the code above just a little bit to try to "loop over" a series of numbers that we'll try to find. # In the above code, notice that we did not handle the case where the number is not found. There are a few ways # to do this, but I'm going to show you a way that works with the "break" statement. We did not cover it last week, # but there is actually an "else" statement that can be used with the while statement. It is *only* run if the while # loop did not exit as a result of a break statement being run. Since we're using break when we find the number, we # can use the else statement to print out a message when we don't find the number. find_numbers = [6, 20] for find_number in find_numbers: position = 0 print(f"Looking for number {find_number} in numbers list {numbers} with length {numbers_length} using while ...") while position < numbers_length: if numbers[position] == find_number: print(f" Found number {find_number} at position {position} so breaking out of while loop") break else: print(f" Number {numbers[position]} at position {position} is not what we're looking for") position = position + 1 else: print(f" Did not find number {find_number} in numbers list {numbers}") pause_program() # Similarly, the for loop has the same else logic, just like while. Let's use enumerate again as well. for find_number in find_numbers: print(f"Looking for number {find_number} in numbers list {numbers} with length {numbers_length} using for ...") for position, item in enumerate(numbers): if item == find_number: print(f" Found number {find_number} at position {position} so breaking out of for loop") break else: print(f" Number {item} at position {position} is not what we're looking for") else: print(f" Did not find number {find_number} in numbers list {numbers}") pause_program() # What if we didn't care about the position (index)? Much shorter code... for find_number in find_numbers: print(f"Looking for number {find_number} in numbers list {numbers} with length {numbers_length} using in test ...") if find_number in numbers: print(f" Found number {find_number}") else: print(f" Did not find number {find_number}") pause_program() # In python, the for loop syntax really resembles the following: # for item in iterable: # statement(s) # [else: # statement(s)] # # The brackets surrounding the else statement mean that the else statement is optional. You'll # see this sort of thing a lot in the programming world, so I just thought I'd mention it. # # What is an iterable? An iterable is any python object that is capable of returning its members one at a time, # permitting it to be iterated (walked) over in a for loop. So far, we've covered 2 iterables -- lists and, drum roll # please, strings! What?!? A string is iterable? Let's check it out. for item in "hello": print(f"{item}") pause_program() # As you can see, we get back the characters of a string, one at a time. As time goes on, we'll run # across more and more iterables.
82aa359e55b2bd1983c263e2c38cc0a1419717ca
ptiwari/Housing-Price-Prediction
/housingregression.py
796
3.625
4
from sklearn.linear_model import LinearRegression import numpy as np import pandas as pd values = list(map(int,input().strip().split(' '))) labels = np.zeros(shape=(values[1])) x_train = np.zeros(shape=(values[1],values[0])) #print(values[1]); #print(range(0,values[1])) for i in range(0,values[1]): #print(i) v = list(map(float,input().strip().split(' '))) #print(v) x_train[i,:] = v[0:len(v)-1] labels[i] = v[len(v)-1]; # Create linear regression regr = LinearRegression() # Fit the linear regression model = regr.fit(x_train, labels) #print(feature) n = int(input()); x_test = np.zeros(shape=(n,values[0])) for i in range(0,n): v = list(map(float,input().strip().split(' '))) x_test[i,:] = v[0:len(v)] y_predict = regr.predict(x_test) for i in y_predict: print(i)
2241f6f280cd21c13983b96ee3da0b8feaef1873
STW59/biophys3
/Homework3/Hw3_3[5]_STW59.py
559
3.515625
4
""" Kirill and Stephen worked together on the coding part. Kirill: math parts Stephen: recursive algorithms """ import numpy as np def ave_r(r, kt): return np.exp(-r / kt) def main(): for kt in range(1, 11, 1): if kt in [1, 2, 5, 10]: top_sum = 0 bottom_sum = 0 for r in np.arange(0.01, 10.01, 0.01): top_sum += r * ave_r(r, kt) bottom_sum += ave_r(r, kt) r_avg = top_sum / bottom_sum print('At kt = {}, r_avg = {}.'.format(kt, r_avg)) main()
21d8b2b25adb4241d0771122a0d8b45b6241d09c
rishinkaku/Software-University---Software-Engineering
/Python Fundamentals/Final_Exam_Prep/01. Movie Profit.py
235
3.796875
4
movie = input() days = int(input()) tickets = int(input()) price = float(input()) total = days * tickets * price cinema_profit = float(input())*total/100 print(f"The profit from the movie {movie} is {total - cinema_profit:.2f} lv.")
dab5fe10b45e2cf297bf201c74e46e4282765623
Friction6/TITAN
/v0 2.5/cards.py
1,399
3.625
4
import random class Card: def __init__(self, rank_id, suit_id): self.rank_id = rank_id self.suit_id = suit_id if self.suit_id == 1: self.suit = "Spades" elif self.suit_id == 2: self.suit = "Hearts" elif self.suit_id == 3: self.suit = "Clubs" elif self.suit_id == 4: self.suit = "Diamonds" else: self.suit = "SuitError" if self.rank_id == 1: self.rank = "Ace" elif self.rank_id == 11: self.rank = "Jack" elif self.rank_id == 12: self.rank = "Queen" elif self.rank_id == 13: self.rank = "King" elif self.rank_id == 14: self.rank = "Ace" elif self.rank_id <= 10 and self.rank_id >= 2: self.rank = str(self.rank_id) else: self.rank = "RankError" def __str__(self): return "{} of {}".format(self.rank, self.suit) class Deck: def __init__(self): self.cards = [] for a in range(1,5): for b in range(2,15): self.cards.append(Card(b, a)) def shuffle(self): random.shuffle(self.cards) def draw(self, num = 1): result = [] for i in range(num): result.append(self.cards.pop()) return result
06a6ba6d5cd6c19e2b4cbec7b4f83432ea5e995a
iteong/comp9021-principles-of-programming
/quizzes/quiz_7/extended_linked_list solution.py
1,413
3.640625
4
# Written by Eric Martin for COMP9021 from linked_list import * class ExtendedLinkedList(LinkedList): def __init__(self, L = None): super().__init__(L) def rearrange(self): node = self.head length = 1 index_of_smallest_value = 0 smallest_value = node.value while node.next_node: node = node.next_node if node.value < smallest_value: smallest_value = node.value index_of_smallest_value = length length += 1 # We link the last node to the first one and create a loop. node.next_node = self.head index_of_to_be_second_node = (index_of_smallest_value - 1) % length node = self.head while index_of_to_be_second_node: node = node.next_node index_of_to_be_second_node -= 1 previous_node = node current_node = self.head = previous_node.next_node nb_of_iterations = (length - 1) // 2 while nb_of_iterations: next_previous_node = current_node.next_node current_node.next_node = previous_node current_node = next_previous_node.next_node previous_node.next_node = current_node previous_node = next_previous_node nb_of_iterations -= 1 current_node.next_node = previous_node previous_node.next_node = None
de532285cd38db59111bd31e8ab0149dc4394249
msanchezzg/AdventOfCode
/AdventOfCode2020/day12/ships.py
4,370
3.828125
4
#!/usr/bin/python3 import math from directions import Direction, Instruction class Waypoint(): def __init__(self, horizontal=0, vertical=0): self.hor_axis = horizontal self.vert_axis = vertical def move(self, instruction): """ Move the waypoint in a given direction. """ movements = { Direction.NORTH: lambda n: self.__move_vertically(n), Direction.SOUTH: lambda n: self.__move_vertically(-n), Direction.EAST: lambda n: self.__move_horizontally(n), Direction.WEST: lambda n: self.__move_horizontally(-n), Direction.RIGHT: lambda n: self.__rotate(-n), Direction.LEFT: lambda n: self.__rotate(+n), } movements.get(instruction.direction, lambda n: None)(instruction.n) def __move_horizontally(self, n): self.hor_axis += n def __move_vertically(self, n): self.vert_axis += n def __rotate(self, angle, radians=False): """ Rotate the waypoint counterclockwise. To rotate clockwise, use a negative angle. """ if not radians: angle = math.radians(angle) qx = math.cos(angle) * (self.hor_axis) - math.sin(angle) * (self.vert_axis) qy = math.sin(angle) * (self.hor_axis) + math.cos(angle) * (self.vert_axis) self.hor_axis = round(qx) self.vert_axis = round(qy) def __repr__(self): hor_direction = Direction.EAST if self.hor_axis >= 0 else Direction.WEST vert_direction = Direction.NORTH if self.vert_axis >= 0 else Direction.SOUTH return f'[{abs(self.vert_axis)} {vert_direction.value}, {abs(self.hor_axis)} {hor_direction.value}]' class Ship(): degrees = [ [(0, 89), Direction.NORTH], [(90, 179), Direction.EAST], [(180, 269), Direction.SOUTH], [(270, 359), Direction.WEST] ] def __init__(self, horizontal=0, vertical=0, degrees=90): self.degrees = degrees self.hor_axis = horizontal self.vert_axis = vertical def move(self, instruction): movements = { Direction.NORTH: lambda n: self.__move_vertically(n), Direction.SOUTH: lambda n: self.__move_vertically(-n), Direction.EAST: lambda n: self.__move_horizontally(n), Direction.WEST: lambda n: self.__move_horizontally(-n), Direction.RIGHT: lambda n: self.__rotate(n), Direction.LEFT: lambda n: self.__rotate(-n), Direction.FORWARD: lambda n: self.__advance(n) } movements.get(instruction.direction, lambda n: None)(instruction.n) def __move_horizontally(self, n): self.hor_axis += n def __move_vertically(self, n): self.vert_axis += n def __rotate(self, degrees): self.degrees = (self.degrees + degrees) % 360 if self.degrees < 0: self.degrees = 360 - self.degrees def __advance(self, n): pointing_direction = self.get_pointing_direction() self.move(Instruction(pointing_direction, n, from_enum=True)) def get_pointing_direction(self): for deg, direction in Ship.degrees: if self.degrees >= deg[0] and self.degrees <= deg[1]: return direction def __repr__(self): hor_direction = Direction.EAST if self.hor_axis >= 0 else Direction.WEST vert_direction = Direction.NORTH if self.vert_axis >= 0 else Direction.SOUTH return f'[{abs(self.vert_axis)} {vert_direction.value}, {abs(self.hor_axis)} {hor_direction.value}, {self.degrees}º]' class MovingShip(): def __init__(self, horizontal=0, vertical=0): self.hor_axis = horizontal self.vert_axis = vertical self.waypoint = Waypoint(10, 1) def move(self, instruction): if instruction.direction != Direction.FORWARD: self.waypoint.move(instruction) else: self.hor_axis += instruction.n * self.waypoint.hor_axis self.vert_axis += instruction.n * self.waypoint.vert_axis def __repr__(self): hor_direction = Direction.EAST if self.hor_axis >= 0 else Direction.WEST vert_direction = Direction.NORTH if self.vert_axis >= 0 else Direction.SOUTH return f'[{abs(self.vert_axis)} {vert_direction.value}, {abs(self.hor_axis)} {hor_direction.value}]'
96f697e2dc6ec8a84537bd0ffa8d4e8bc9d02acc
jinmanz/twitter
/mexico earthquake/rt_counter_per_day.py
1,595
3.65625
4
# -*- coding: utf-8 -*- import csv from os import listdir import re def read_file(filename): "Read the contents of FILENAME and return as a string." infile = open(filename) # windows users should use codecs.open after importing codecs contents = infile.read() infile.close() return contents def list_textfiles(directory): "Return a list of filenames ending in '.txt' in DIRECTORY." textfiles = [] for filename in listdir(directory): if filename.endswith(".csv"): textfiles.append(directory + "/" + filename) return textfiles filenames = list_textfiles("csv") # 遍历csv文件,读取每个csv文件中的text列,并把所得的list 变成 string tweet_text=[] for filename in filenames: with open(filename,'rb') as csvfile: reader = csv.reader(csvfile) #tweet_text.append( [row[3] for row in reader]) tweet_text.append(' '.join(map(str,[row[3] for row in reader]))) #str用来当文件名变量,再循环中保存每天的转发量 str = '1' #对每天的text分析,统计转发量 for text_per_day in tweet_text: rts = re.findall(r'@[\w]+',text_per_day) #a list of all the matches rts_set = set(rts) count_list = [] for item in rts_set: count_list.append((item,rts.count(item))) count_list_sorted = sorted(count_list,cmp=lambda x,y:cmp(x[1],y[1]),reverse=True) headers = ['Account','Frequency'] with open(str+'.csv','wb') as f: writer = csv.writer(f) writer.writerow(headers) writer.writerows(count_list_sorted) str += '1'
58cc92256c8187f24e3d8ee8857df49333b8136f
bhuwanadhikari/ajingar-plays
/2d-array-hourglass.py
956
3.78125
4
# Complete the hourglassSum function below. def hourglassSum(arr): largestSum = 0 sums = [] for x in range(4): for y in range(4): # loop in the hourglass: sum = 0 for i in range(x, x + 3): for j in range(y, y + 3): if i == x + 1 and (j == y + 2 or j == y): print(arr[i][j]) continue sum = sum + arr[i][j] sums.append(sum) # print(sum) print('---------') largestSum = largestSum or sum largestSum = sum if sum > largestSum else largestSum return largestSum print( hourglassSum( [ [-9, -9, -9, 1, 1, 1], [0, -9, 0, 4, 3, 2], [-9, -9, -9, 1, 2, 3], [0, 0, 8, 6, 6, 0], [0, 0, 0, -2, 0, 0], [0, 0, 1, 2, 4, 0], ] ) )
5e9615fbedbc7c35297ad29735c3bd3fb964ddbd
jinrunheng/base-of-python
/python-basic-grammer/python-basic/02-python-variables-and-string/string_find_replace.py
345
3.96875
4
# print("nice to meet you".find("ee")) # print("nice to meet you".find("ee",0,7)) str = "nice to meet you,I need your help" print(str.find("ee")) # 返回第一个找到的位置 print(str.find("ee",11,len(str) - 1)) is_exist = "ee" in str print(is_exist) str1 = "hello world" print(str1.replace("world","kim")) print(str1.replace("o","O",2))
5ad081f27c5e4e59394b29df1c85639059ffcb78
dralee/LearningRepository
/PySpace/time/time5.py
723
3.796875
4
#!/usr/bin/python3 # 文件名:time5.py """ Python 程序能用很多方式处理日期和时间,转换日期格式是一个常见的功能。 Python 提供了一个 time 和 calendar 模块可以用于格式化日期和时间。 时间间隔是以秒为单位的浮点小数。 每个时间戳都以自从1970年1月1日午夜(历元)经过了多长时间来表示。 Python 的 time 模块下有很多函数可以转换常见日期格式。如函数time.time()用于获取当前时间戳, 如下实例: """ ''' Calendar模块有很广泛的方法用来处理年历和月历,例如打印某月的月历: ''' import calendar cal = calendar.month(2017,6) print("以下输出2017年6月日历:") print(cal)
7d68e06b3951e8b20ca075737dc5024975dfe93f
Haasha/RandomForest
/weakLearner.py
10,236
3.5625
4
#---------------Instructions------------------# # You will be writing a super class named WeakLearner # and then will be implmenting its sub classes # RandomWeakLearner and LinearWeakLearner. Remember # all the overridded functions in Python are by default # virtual functions and every child classes inherits all the # properties and attributes of parent class. # Your task is to override the train and evaluate functions # of superclass WeakLearner in each of its base classes. # For this purpose you might have to write the auxiliary functions as well. #--------------------------------------------------# # Now, go and look for the missing code sections and fill them. #-------------------------------------------# import numpy as np import scipy.stats as stats from numpy import inf import random class WeakLearner: # A simple weaklearner you used in Decision Trees... """ A Super class to implement different forms of weak learners... """ def __init__(self): self.F_Index,self.Split=-1,-1 def TotalEntropy(self,Y): UniqueLabels,Count=np.unique(Y,return_counts=True) TotalCount=np.sum(Count) TotalEntropy=0 for i in range(len(UniqueLabels)): TotalEntropy+=(-Count[i]/TotalCount)*np.log2(Count[i]/TotalCount) return TotalEntropy def calculateEntropy(self, Y, mship): TotalLabelsLesser,TotalLabelsGreater=Y[mship],Y[mship==0] UniqueLabelsGreater,CountGreater=np.unique(TotalLabelsGreater,return_counts=True) UniqueLabelsLesser,CountLesser=np.unique(TotalLabelsLesser,return_counts=True) TotalGreaterCount,TotalLesserCount=np.sum(CountGreater),np.sum(CountLesser) TotalCount=TotalGreaterCount+TotalLesserCount result_1=0 result_2=0 for k in range(len(UniqueLabelsGreater)): if CountGreater[k]!=0 and TotalGreaterCount!=0: result_1+= ((-CountGreater[k]/TotalGreaterCount)*np.log2(CountGreater[k]/TotalGreaterCount)) for k in range(len(UniqueLabelsLesser)): if CountLesser[k]!=0 and TotalLesserCount!=0: result_2+= ((-CountLesser[k]/TotalLesserCount)*np.log2(CountLesser[k]/TotalLesserCount)) return result_1*(TotalGreaterCount/TotalCount) + result_2*(TotalLesserCount/TotalCount) def evaluate_numerical_attribute(self,feat, Y): TotalEntropy=self.TotalEntropy(Y) UniqueLabels,Count=np.unique(Y,return_counts=True) Index=0 TargetedEntropy=float('Inf') for i in range(len(feat)): Point=feat[i] mship=feat<=Point Temp=self.calculateEntropy(Y,mship) if Temp<TargetedEntropy: TargetedEntropy=Temp Index=i score=TotalEntropy-TargetedEntropy split=feat[Index] RightChildInd=feat>split LeftChildInd=feat<=split return split, score,LeftChildInd,RightChildInd def train(self, X, Y): nexamples,nfeatures=X.shape split,score,LeftChildInd,RightChildInd=0,-float('inf'),0,0 FeatureIndex=-1 for i in range(nfeatures): split_temp,score_temp,LeftChildInd_temp,RightChildInd_temp=self.evaluate_numerical_attribute(X[:,i],Y) if i!=0: if score_temp>score: score=score_temp split=split_temp LeftChildInd=LeftChildInd_temp RightChildInd=RightChildInd_temp FeatureIndex=i else: score=score_temp split=split_temp LeftChildInd=LeftChildInd_temp RightChildInd=RightChildInd_temp FeatureIndex=i self.F_Index=FeatureIndex self.Split=split return split,score,LeftChildInd,RightChildInd def evaluate(self,X): if X[self.F_Index]<=self.Split: return True return False class RandomWeakLearner(WeakLearner): # Axis Aligned weak learner.... def __init__(self, nsplits=+np.inf, nrandfeat=None): WeakLearner.__init__(self) # calling base class constructor... self.nsplits=nsplits self.nrandfeat=nrandfeat self.fidx=-1 self.split=-1 #pass def train(self, X, Y): #print "Inside the train of Random" nexamples,nfeatures=X.shape #print "Train has X of length ", X.shape if(not self.nrandfeat): self.nrandfeat=int(np.round(np.sqrt(nfeatures))) #-----------------------TODO-----------------------# #--------Write Your Code Here ---------------------# Index=-1 split,score,LeftChildInd,RightChildInd=0,-float('inf'),0,0 Features=np.random.randint(0,nfeatures,self.nrandfeat) for i in range(len(Features)): split_temp,score_temp,LeftChildInd_temp,RightChildInd_temp=self.findBestRandomSplit(X[:,Features[i]],Y) if score_temp>score: score=score_temp split=split_temp LeftChildInd=LeftChildInd_temp RightChildInd=RightChildInd_temp Index=Features[i] self.F_Index=Index self.Split=split return split,score,LeftChildInd,RightChildInd #---------End of Your Code-------------------------# def findBestRandomSplit(self,feat,Y): frange=np.max(feat)-np.min(feat) #-----------------------TODO-----------------------# #--------Write Your Code Here ---------------------# TotalEntropy=self.TotalEntropy(Y) splitvalue,TargetEntropy,Index=0,float('inf'),-1 for i in range(self.nsplits): RandomIndex=random.randrange(len(feat)) mship=feat<=feat[RandomIndex] score_temp=self.calculateEntropy(Y,mship) if score_temp<=TargetEntropy: TargetEntropy=score_temp splitvalue=feat[RandomIndex] Index=RandomIndex #---------End of Your Code-------------------------# score=TotalEntropy-TargetEntropy LeftChildInd=feat<=feat[Index] RightChildInd=feat>feat[Index] return splitvalue, score, LeftChildInd, RightChildInd def evaluate(self, X): #-----------------------TODO-----------------------# #--------Write Your Code Here ---------------------# #print X.shape, self.fidx, "xshape" if X[self.F_Index]<=self.Split: return True return False #---------End of Your Code-------------------------# # build a classifier ax+by+c=0 class LinearWeakLearner(RandomWeakLearner): # A 2-dimensional linear weak learner.... def __init__(self, nsplits=10): self.a=0 self.b=0 self.c=0 self.F1=0 self.F2=0 RandomWeakLearner.__init__(self,nsplits) #pass def train(self,X, Y): nexamples,nfeatures=X.shape #-----------------------TODO-----------------------# #--------Write Your Code Here ---------------------# MinScore,Index=float('Inf'),-1 self.F1,self.F2=random.sample(range(0, nfeatures), 2) Left=[] Right=[] for i in range(self.nsplits): Temp_a,Temp_b,Temp_c=np.random.uniform(-4,4,3) Results=[] for j in range(len(X)): if (Temp_a*X[j,self.F1]+Temp_b*X[j,self.F2]+Temp_c)<=0: Results.append(1) else: Results.append(0) if np.sum(Results)>0 and np.sum(Results)<len(X): Score=super().calculateEntropy(Y,list(Results)) if MinScore>=Score: MinScore=Score self.a=Temp_a self.b=Temp_b self.c=Temp_c Index=i Left=Results Right=Results for i in range(len(Right)): if Right[i]==1: Right[i]=0 else: Right[i]=1 return 0, MinScore, Left, Right def evaluate(self,X): if self.a*X[self.F1]+self.b*X[self.F2]+self.c<=0: return True return False #build a classifier a*x^2+b*y^2+c*x*y+ d*x+e*y+f class ConicWeakLearner(RandomWeakLearner): # A 2-dimensional linear weak learner.... def __init__(self, nsplits=10): self.a=0 self.b=0 self.c=0 self.d=0 self.e=0 self.f=0 self.F1=0 self.F2=0 RandomWeakLearner.__init__(self,nsplits) pass def train(self,X, Y): nexamples,nfeatures=X.shape MinScore,Index=float('Inf'),-1 self.F1,self.F2=random.sample(range(0, nfeatures), 2) Left=[] Right=[] for i in range(self.nsplits): Temp_a,Temp_b,Temp_c,Temp_d,Temp_e,Temp_f=np.random.uniform(-4,4,6) Results=[] for j in range(len(X)): if (Temp_a*(X[j,self.F1]**2)+Temp_b*(X[j,self.F2]**2)+Temp_c*X[j,self.F1]*X[j,self.F2] + Temp_d*X[j,self.F1]+ Temp_e*X[j,self.F2] +Temp_f<=0)<=0: Results.append(1) else: Results.append(0) if np.sum(Results)>0 and np.sum(Results)<len(X): Score=super().calculateEntropy(Y,list(Results)) if MinScore>=Score: MinScore=Score self.a=Temp_a self.b=Temp_b self.c=Temp_c self.d=Temp_d self.e=Temp_e self.f=Temp_f Index=i Left=Results for i in range(len(Left)): if Left[i]==1: Right.append(0) else: Right.append(1) return 0, MinScore, Left, Right def evaluate(self,X): if self.a*(X[self.F1]**2)+self.b*(X[self.F2]**2)+self.c*X[self.F1]*X[self.F2] + self.d*X[self.F1]+ self.e*X[self.F2] +self.f<=0: return True return False
91892203497861c90b842a53b5861777e5f30d3a
MarcPartensky/Pygame-Geometry
/pygame_geometry/manager.py
21,018
3.921875
4
from .context import Context from pygame.locals import * import pygame class SimpleManager: """Manage a program using the context by many having functions that can be overloaded to make simple and fast programs. This process allow the user to think directly about what the program does, instead of focusing on how to display things. The way it works is by making the main class of the program inheriting from this one.""" def __init__(self, name="SimpleManager", **kwargs): """Create a context manager with the optional name.""" self.context = Context(name=name, **kwargs) self.pause = False def __call__(self): """Call the main loop.""" while self.context.open: self.events() if not self.pause: self.update() self.show() def events(self): """Deal with all the events.""" for event in pygame.event.get(): if event.type == pygame.QUIT: self.context.open = False if event.type == KEYDOWN: if event.key == K_ESCAPE: self.context.open = False if event.key == K_SPACE: self.pause = not (self.pause) if event.key == K_f: self.context.switch() # Set or reverse fullscreen if event.type == MOUSEBUTTONDOWN: if event.button == 4: self.context.draw.plane.zoom([1.1, 1.1]) if event.button == 5: self.context.draw.plane.zoom([0.9, 0.9]) def update(self): """Update the context manager.""" def show(self): """Show the context manager.""" self.context.refresh() self.context.control() self.context.flip() class oldManager: # This manager is deprecated """Manage a program using the context by many having functions that can be overloaded to make simple and fast programs. This process allow the user to think directly about what the program does, instead of focusing on how to display things. The way it works is by making the main class of the program inheriting from this one.""" def __init__(self, context): """Create a context manager.""" self.context = context def __call__(self): """Call the main loop.""" self.main() def main(self): """Execute the main loop.""" self.loop() def loop(self): """Main loop.""" while self.context.open: self.perform() def perform(self): """Execute the content of the main loop.""" self.detect() self.update() self.show() def debug(self): self.context.console(str(ContextManager.__dict__['react'].__dict__)) def update(self): """Update the context manager.""" pass def show(self): """Show the context manager.""" self.context.refresh() self.context.control() self.debug() self.context.flip() def detect(self): """Deal with all the events.""" for event in pygame.event.get(): self.react(event) def react(self, event): """React to a given event.""" self.reactToQuit(event) if event.type == KEYDOWN: self.reactToKeyboard(event) return def reactToQuit(self, event): """Close the context if the quit button is pressed.""" if event.type == pygame.QUIT: self.context.open = False def reactToKeyboard(self): """React to the keyboards buttons being pressed.""" self.reactToEscape() def reactToEscape(self): """React to the button escape.""" if event.key == K_ESCAPE: self.context.open = False class Manager: def __init__(self, name="Manager", dt=10e-3, **kwargs): """Create a manager using a context, this methods it to be overloaded.""" self.context = Context(name=name, **kwargs) self.count = self.context.count self.pause = False self.dt = dt # Typing stuff self.typing = False self.alphabet = "abcdefghijklmnopqrstuvwxyz" self.caps_numbers = ")!@#$%^&*(" self.numbers = "0123456789" self.typing = False self.shiftlock = False self.capslock = False self.altlock = False def __str__(self): """Return the string representation of the manager.""" return type(self).__name__ + "(\n{}\n)".format( "\n".join(map(lambda x: ":".join(map(str, x)), self.__dict__.items()))) def __call__(self): """Call the main loop, this method is to be overloaded.""" self.main() def main(self): """Main loop of the simple manager.""" self.setup() # Name choices inspired from processing while self.context.open: self.loop() def setup(self): """Code executed before the loop.""" pass def loop(self): """Code executed during the loop.""" self.eventsLoop() self.updateLoop() self.showLoop() def eventsLoop(self): """Deal with the events in the loop.""" for event in pygame.event.get(): self.react(event) def react(self, event): """React to the pygame events.""" if event.type == QUIT: self.switchQuit() elif event.type == KEYDOWN: self.reactKeyDown(event.key) elif event.type == KEYUP: self.reactKeyUp(event.key) elif event.type == MOUSEBUTTONDOWN: self.reactMouseButtonDown(event.button, event.pos) elif event.type == MOUSEBUTTONUP: self.reactMouseButtonUp(event.button, event.pos) elif event.type == MOUSEMOTION: self.reactMouseMotion(event.pos) def switchQuit(self): """React to a quit event.""" self.context.open = not (self.context.open) def reactKeyDown(self, key): """React to a keydown event.""" self.reactAlways(key) if self.typing: self.reactTyping(key) else: self.reactMain(key) def reactKeyUp(self, key): """React to a keyup event.""" pass def reactAlways(self, key): """React to a key whether or not the typing mode is on.""" # print(key) for debugging the keys if key == K_ESCAPE: self.switchQuit() if key == K_SLASH or key == K_BACKSLASH: if not self.typing: self.context.console("Typing activated.") self.typing = True if key == K_BACKQUOTE: self.switchTyping() def reactLock(self, key): """React to a locking key.""" if key == K_CAPSLOCK: self.capslock = not (self.capslock) elif key == K_LSHIFT or key == K_RSHIFT: self.shiftlock = True elif key == K_LALT or key == K_RALT: self.altlock = True def reactTyping(self, key): """React to a typing event.""" self.reactLock(key) if self.altlock: self.reactAltCase(key) elif self.capslock or self.shiftlock: self.reactUpperCase(key) else: self.reactLowerCase(key) if key == K_SPACE: self.write(" ") elif key == 8: self.delete() if key == K_LCTRL: self.context.console.nextArg() elif key == K_UP: self.context.console.back() elif key == K_DOWN: self.context.console.forward() elif key == K_RETURN: self.eval() self.context.console.nextLine() def eval(self): """Execute a line.""" content = self.context.console.line.content if content[0] == "/": for command in content[1:]: try: self.context.console(str(eval(command))) except: self.context.console("Invalid command.") if content[0] == "\\": for command in content[1:]: try: exec(command) self.context.console("Command " + command + " executed.") except Exception as e: self.context.console(str(e)) self.context.console.eval() def reactAltCase(self, key): """React when typing with alt key pressed.""" if key == K_e: self.write("`") # Stupid elif key == 167: self.write("´") def reactLowerCase(self, key): """React when typing in lower case.""" d = {K_COMMA: ",", K_PERIOD: ".", K_SEMICOLON: ";", K_LEFTBRACKET: "[", K_RIGHTBRACKET: "]", 39: "'", 45: "-", K_EQUALS: "="} if 48 <= key <= 57: self.write(self.numbers[key - 48]) elif 97 <= key <= 122: self.write(self.alphabet[key - 97]) elif key in d: self.write(d[key]) elif key == K_SLASH: if not self.context.console.line.empty: self.context.console.nextLine() self.write("/") self.context.console.nextArg() elif key == K_BACKSLASH: if not self.context.console.line.empty: self.context.console.nextLine() self.write("\\") self.context.console.nextArg() def reactUpperCase(self, key): """React to a key when typing in uppercase.""" d = {59: ":''", 44: "<", 46: ">", 47: "?", 45: "_", 39: "\"", 61: "+"} if 48 <= key <= 57: self.write(self.caps_numbers[key - 48]) elif 97 <= key <= 122: self.write(self.alphabet[key - 97].upper()) elif key in d: self.write(d[key]) def write(self, c): """Write some content.""" self.context.console.lines[-1].content[-1] += c self.context.console.lines[-1].refresh() self.shiftlock = False self.altlock = False def delete(self, n=1): """Delete some content.""" self.context.console.lines[-1].content[-1] = self.context.console.lines[-1].content[-1][:-n] self.context.console.lines[-1].refresh() def reactMain(self, key): """React as usual when not typing.""" if key == K_f: self.switchFullscreen() if key == K_1: self.switchCapture() if key == K_2: self.switchCaptureWriting() if key == K_3: self.switchScreenWriting() if key == K_LALT: self.switchPause() def switchTyping(self): """Switch the typing mode.""" self.typing = not (self.typing) if self.typing: self.context.console("Typing activated.") self.context.console.nextLine() else: self.context.console("Typing deactivated.") def switchScreenWriting(self): """Switch the screen writing mode.""" if self.context.camera.screen_writing: self.context.camera.screen_writer.release() self.context.camera.switchScreenWriting() if self.context.camera.screen_writing: self.context.console('The screen is being written.') else: self.context.console('The screen video has been released') self.context.console('and is not being written anymore.') def switchCaptureWriting(self): """Switch the capture writing mode.""" if self.context.camera.capture_writing: self.context.camera.capture_writer.release() self.context.camera.switchCaptureWriting() if self.context.camera.capture_writing: self.context.console('The capture is being written.') else: self.context.console('The capture video has been released') self.context.console('and is not being written anymore.') def switchPause(self): """React to a pause event.""" self.pause = not self.pause if self.pause: self.context.console('The system is paused.') else: self.context.console('The system is unpaused.') def switchCapture(self): """React to a capture event.""" self.context.camera.switchCapture() if self.context.camera.capturing: self.context.console('The camera capture is turned on.') else: self.context.console('The camera capture is turned off.') def switchFullscreen(self): """React to a fullscreen event.""" self.context.switch() if self.context.fullscreen: self.context.console("The fullscreen mode is set.") else: self.context.console("The fullscreen mode is unset.") def reactMouseButtonDown(self, button, position): """React to a mouse button down event.""" if button == 4: self.context.draw.plane.zoom([1.1, 1.1]) if button == 5: self.context.draw.plane.zoom([0.9, 0.9]) def reactMouseButtonUp(self, button, position): """React to a mouse button up event.""" pass def reactMouseMotion(self, position): """React to a mouse motion event.""" pass def updateLoop(self): """Update the manager while in the loop.""" if not self.pause: self.update() self.count() self.context.camera.write() # Write on the camera writers if they are on def update(self): """Update the components of the manager of the loop. This method is to be overloaded.""" pass def showLoop(self): """Show the graphical components and deal with the context in the loop.""" if not self.typing: # Ugly fix for easier pratical use self.context.control() self.context.clear() self.context.show() self.show() self.showCamera() self.context.console.show() self.context.flip() def show(self): """Show the graphical components on the context. This method is to be overloaded.""" pass def showCamera(self): """Show the camera if active.""" if self.context.camera.capturing: self.context.camera.show() def counter(): doc = "The Counter property." def fget(self): """Bind the counter of the manager to the one of the context.""" return self.context.counter def fset(self, counter): """Set the counter of the context.""" self.context.counter = counter return locals() counter = property(**counter()) class BodyManager(Manager): """Manage the bodies that are given when initalizing the object.""" @classmethod def createRandomBodies(cls, t, n=5, **kwargs): """Create random bodies using their class t. The bodies of the class t must have a random method.""" bodies = [t.random() for i in range(n)] return cls(bodies, **kwargs) def __init__(self, *bodies, following=False, **kwargs): """Create a body manager using its bodies and optional arguments for the context.""" super().__init__(**kwargs) self.bodies = bodies self.following = following def update(self): """Update the bodies.""" self.updateFollowers() self.updateBodies() def updateFollowers(self): """Update the bodies that are followers.""" # This is not implemented correctly for now.""" p = self.context.point() if self.following: for body in self.bodies: body.follow(p) def updateBodies(self): """Update the bodies individually.""" for body in self.bodies: body.update(self.dt) def show(self): """Show the bodies.""" self.showBodies() def showBodies(self): """Show all the bodies individually.""" for body in self.bodies: body.show(self.context) class EntityManager(Manager): """Create a manager that deals with entities.""" def __init__(self, *entities, dt=0.1, friction=0.1, **kwargs): """Create an entity manager using the list of entities and optional arguments for the manager.""" super().__init__(**kwargs) self.entities = list(entities) self.dt = dt self.friction = friction def update(self): """Update all entities.""" for entity in self.entities: entity.update(self.dt) def show(self): """Show all entities.""" for entity in self.entities: entity.show(self.context) def reactKeyDown(self, key): """Make all entities react to the keydown event.""" super().reactKeyDown(key) for entity in self.entities: entity.reactKeyDown(key) def reactMouseMotion(self, position): """Make all entities react to the mouse motion.""" position = self.context.getFromScreen(tuple(position)) for entity in self.entities: entity.reactMouseMotion(position) def reactMouseButtonDown(self, button, position): """Make all entities react to the mouse button down event.""" position = self.context.getFromScreen(tuple(position)) for entity in self.entities: entity.reactMouseButtonDown(button, position) def spread(self, n=10): """Spread randomly the bodies.""" for entity in self.entities: entity.motion *= n def setFriction(self, friction): """Set the friction of all entities to the given friction.""" for entity in self.entities: entity.setFriction(friction) class BlindManager(Manager): """Ugly way to make a manager without camera.""" def __init__(self, camera=False, **kwargs): super().__init__(camera=camera, **kwargs) class AbstractManager(Manager): """Manager that deals with abstract objects.""" def __init__(self, *group, **kwargs): """Create a group of abstract (geometrical) objects.""" super().__init__(**kwargs) self.group = list(group) def show(self): """Show the objects of the group.""" for e in self.group: e.show(self.context) class GameManager(Manager): """Base class Manager for games.""" def __init__(self, game, controller=None, **kwargs): super().__init__(**kwargs) self.game = game self.controller = controller self.context.units = [10, 10] def update(self): if self.controller: player = self.getPlayer() if player and not self.game.won: self.context.position = player.position self.game.update() def showLoop(self): """Show the graphical components and deal with the context in the loop.""" if not self.typing: # Ugly fix for easier practical use # self.context.control() pass if self.game.won: self.context.control() self.context.clear() self.show() self.showCamera() self.context.console.show() self.context.flip() def show(self): self.game.show(self.context) def reactKeyDown(self, key): super().reactKeyDown(key) self.game.reactKeyDown(key) def reactMouseMotion(self, position): position = self.context.getFromScreen(position) self.game.reactMouseMotion(position) def reactMouseButtonDown(self, button, position): position = self.context.getFromScreen(position) self.game.reactMouseButtonDown(button, position) def getPlayer(self): return self.game.control(self.controller) class ActivityManager(Manager): """Activity manager inspired from android studio""" def __init__(self, activities, **kwargs): super().__init__(**kwargs) self.activities = activities self.index = 0 def show(self): self.activity.show(self.context) def update(self): self.activity.update(self.dt) def reactKeyUp(self, key): self.activity.onKeyUp(key) def reactKeyDown(self, key): self.activity.onKeyDown(key) def reactMouseButtonDown(self, button, position): position = self.context.getFromScreen(position) self.activity.onMouseButtonDown(button, position) def reactMouseMotion(self, position): position = self.context.getFromScreen(position) self.activity.onMouseMotion(position) def getActivity(self): return self.activities[self.index] def setActivity(self, activity): self.activities[self.index] = activity activity = property(getActivity, setActivity) if __name__ == "__main__": from .entity import Entity m = EntityManager.random(build=False) print(m) # cm()
5855be39b71849dc0e3b1ecde6a5220371731fcc
bergercookie/src_utils
/python/euler_problems/adderdict.py
268
4.15625
4
#!/usr/bin/env python def addDict(dict1 ,dict2): """ Computes the union of two dictionaries """ final_dict = {} for (i,j) in dict1.items(): final_dict[i] = j for (i,j) in dict2.items(): final_dict[i] = j return final_dict
552de5be2c373cd4aa9932fef8f25802cda9c0e4
gpeFC/sistParDist
/proyectoMPI/version2/respaldo_perceptron.py
8,918
3.546875
4
""" Modulo que contiene las clases necesarias para crear objetos de redes neuronales artificiales de tipo perceptron multicapa y ser entrenadas con un algoritmo de retropropagacion. """ from funciones import * class Neurona: """ Neurona artificial tipo perceptron. """ def __init__(self, total_args): """ total_args Numero total de valores de los pesos sinapticos de la neurona. Inicializa los datos miembro de la neurona. """ self.alpha = 0.0 self.salida = 0.0 self.bias = pseudoaleatorio(-1.0, 1.0) self.pesos = [] for i in range(total_args): self.pesos.append(pseudoaleatorio(-1.0, 1.0)) def calcular_salida(self, id_funcion, entrada): """ id_funcion Indice de la funcion de activacion asociada a la neurona. entrada Entrada presinaptica de la neurona. Calcula la salida postsinaptica de la neurona. """ if id_funcion == 1: self.salida = identidad_lineal(suma_ponderada(self.bias, entrada, self.pesos)) elif id_funcion == 2: self.salida = sigmoide_logistico(suma_ponderada(self.bias, entrada, self.pesos)) elif id_funcion == 3: self.salida = sigmoide_tangencial(suma_ponderada(self.bias, entrada, self.pesos)) elif id_funcion == 4: self.salida = sigmoide_hiperbolico(suma_ponderada(self.bias, entrada, self.pesos)) class CapaNeuronal: """ Capa de neuronas artificiales tipo perceptron. """ def __init__(self, total_neurs, total_args): """ total_neurs Numero total de neuronas de la capa. total_args Numero total de valores de los pesos sinapticos de cada neurona de la capa. Inicializa los datos miembro de la capa. """ self.delthas = [0.0] * total_neurs self.neuronas = [] for i in range(total_neurs): self.neuronas.append(Neurona(total_args)) def establecer_alphas(self, alphas): """ """ for i in range(len(alphas)): self.neuronas[i].establecer_alpha(alphas[i]) def actualizar_biases(self): """ Actualiza el bias de cada neurona de la capa. """ for i in range(len(self.neuronas)): self.neuronas[i].bias += (self.neuronas[i].alpha * self.delthas[i]) def actualizar_pesos(self, entrada): """ entrada Entrada presinaptica de cada neurona de la capa. Actualiza los pesos sinapticos de cada neurona de la capa. """ for i in range(len(self.neuronas)): for j in range(len(entrada)): self.neuronas[i].pesos[j] -= (self.neuronas[i].alpha * self.delthas[i] * entrada[j]) def calcular_delthas_salida(self, id_funciones, errores, entrada): """ id_funciones Vector de indices que indican la funcion de activacion asociada a la neurona. errores Vector de errores obtenidos en las neuronas de la capa de salida de la red. entrada Vector de valores presinapticos de entrada de la capa. Calcula los errores deltha cometidos por cada neurona de la capa de salida de la red. """ for i in range(len(errores)): if id_funciones[i] == 1: self.delthas[i] = errores[i] * derivada_lineal(suma_ponderada(self.neuronas[i].bias, entrada, self.neuronas[i].pesos)) elif id_funciones[i] == 2: self.delthas[i] = errores[i] * derivada_logistica(suma_ponderada(self.neuronas[i].bias, entrada, self.neuronas[i].pesos)) elif id_funciones[i] == 3: self.delthas[i] = errores[i] * derivada_tangencial(suma_ponderada(self.neuronas[i].bias, entrada, self.neuronas[i].pesos)) elif id_funciones[i] == 4: self.delthas[i] = errores[i] * derivada_hiperbolica(suma_ponderada(self.neuronas[i].bias, entrada, self.neuronas[i].pesos)) def calcular_delthas_ocultas(self, id_funciones, entrada, capa_sig): """ id_funciones Vector de indices que indican la funcion de activacion asociada a la neurona. entrada Vector de valores presinapticos de entrada de la capa. capa_sig Capa neuronal siguiente a la actual. Calcula los errores deltha cometidos por cada neurona de las capas ocultas de la red. """ for i in range(len(self.neuronas)): suma_deltha = 0.0 for j in range(len(capa_sig.neuronas)): pesos = capa_sig.neuronas[j].pesos suma_deltha += (capa_sig.delthas[j] * pesos[i]) if id_funciones[i] == 1: self.delthas[i] = derivada_lineal(suma_ponderada(self.neuronas[i].bias, entrada, self.neuronas[i].pesos)) * suma_deltha elif id_funciones[i] == 2: self.delthas[i] = derivada_logistica(suma_ponderada(self.neuronas[i].bias, entrada, self.neuronas[i].pesos)) * suma_deltha elif id_funciones[i] == 3: self.delthas[i] = derivada_tangencial(suma_ponderada(self.neuronas[i].bias, entrada, self.neuronas[i].pesos)) * suma_deltha elif id_funciones[i] == 4: self.delthas[i] = derivada_hiperbolica(suma_ponderada(self.neuronas[i].bias, entrada, self.neuronas[i].pesos)) * suma_deltha def calcular_salidas(self, id_funciones, entrada): """ id_funciones Vector de indices que indican la funcion de activacion asociada a la neurona. entrada Vector de valores presinapticos de entrada de la capa. Calcula las salidas postsinapticas de cada neurona de la capa. """ for i in range(len(id_funciones)): self.neuronas[i].calcular_salida(id_funciones[i], entrada) class RedNeuronal: """ Red neuronal artificial tipo perceptron multicapa. """ def __init__(self, total_args, nombre, config_alphas, config_funcns, indices_funcns): """ """ self.nombre_red = nombre self.configuracion_alphas = config_alphas self.configuracion_funciones = config_funcns self.indice_funcion_activacion = indices_funcns self.capas = [] for i in range(len(self.indice_funcion_activacion)): if i == 0: self.capas.append(CapaNeuronal(len(self.indice_funcion_activacion[i]), total_args)) else: self.capas.append(CapaNeuronal(len(self.indice_funcion_activacion[i]), len(self.indice_funcion_activacion[i-1]))) def establecer_valores_alphas(self, indice): """ """ if indice == 1: alpha = pseudoaleatorio(0.0, 1.0) for i in range(len(self.capas)): for j in range(len(self.capas[i].neuronas)): self.capas[i].neuronas[j].alpha = alpha elif indice == 2: for i in range(len(self.capas)): alpha = pseudoaleatorio(0.0, 1.0) for j in range(len(self.capas[i].neuronas)): self.capas[i].neuronas[j].alpha = alpha elif indice == 3: for i in range(len(self.capas)): for j in range(len(self.capas[i].neuronas)): self.capas[i].neuronas[j].alpha = pseudoaleatorio(0.0, 1.0) def aplicar_red_neuronal(self, entrada): """ """ salidas = [] for i in range(len(entrada)): self.realizar_propagacion(entrada[i]) neuronas_salida = self.capas[-1].neuronas salida = [] for j in range(len(neuronas_salida)): salida.append(neuronas_salida[j].salida) salidas.append(salida) return salidas def realizar_propagacion(self, entrada): """ """ for i in range(len(self.capas)): if i == 0: self.capas[i].calcular_salidas(self.indice_funcion_activacion[i], entrada) else: neuronas = self.capas[i-1].neuronas entrada = [] for j in range(len(neuronas)): entrada.append(neuronas[j].salida) self.capas[i].calcular_salidas(self.indice_funcion_activacion[i], entrada) def realizar_retropropagacion(self, salidas, entrada): """ """ for i in range(len(self.capas)): indice = len(self.capas) - (i+1) neuronas_actuales = self.capas[indice].neuronas if indice == len(self.capas) - 1: neuronas_previas = self.capas[indice - 1].neuronas errores = [] for j in range(len(neuronas_actuales)): errores.append(salidas[j] - neuronas_actuales[j].salida) entrada = [] for j in range(len(neuronas_previas)): entrada.append(neuronas_previas[j].salida) self.capas[indice].calcular_delthas_salida( self.indice_funcion_activacion[indice], errores, entrada) else: capa_siguiente = self.capas[indice + 1] if indice == 0: self.capas[indice].calcular_delthas_ocultas( self.indice_funcion_activacion[indice], entrada, capa_siguiente) else: neuronas_previas = self.capas[indice - 1].neuronas entrada = [] for j in range(len(neuronas_previas)): entrada.append(neuronas_previas[j].salida) self.capas[indice].calcular_delthas_ocultas( self.indice_funcion_activacion[indice], entrada, capa_siguiente) def actualizar_parametros_neuronales(self, entrada): """ """ for i in range(len(self.capas)): self.capas[i].actualizar_biases() if i == 0: self.capas[i].actualizar_pesos(entrada) else: neuronas = self.capas[i-1].neuronas entrada = [] for j in range(len(neuronas)): entrada.append(neuronas[j].salida) self.capas[i].actualizar_pesos(entrada)
e972c8650d55169fbce011e612015dd437ce7785
Celot1979/Proy_Person
/Adivina el nunero.py
849
4.125
4
import random intentosRealizados = 0 print("Hola! ¿ Cómo te llamas? ") miNombre= input() numero = random.randint(1,20) print(" Bueno " + miNombre + " estoy pensando un numero entre 1 y 20 ") print(" Escribe el número que piensas... ") while intentosRealizados < 6: print(" Intenta adivinar ") estimacion = input() estimacion = int(estimacion) intentosRealizados = intentosRealizados + 1 if estimacion < numero: print(" Tu estimacion es muy baja. ") elif estimacion > numero: print(" Tu estimacion es muy alta ") elif estimacion == numero: break if estimacion == numero: intentosRealizados = str(intentosRealizados) print(" Buen trabajo " + miNombre + " has adivinado mi numero en " + intentosRealizados + " intentos ") if estimacion != numero: numero = str(numero) print(" Pues no. El numero que estaba pensado era " + numero)
b6653ff6ac1c6dd5522fbbcc553db6d28ec0c00f
darsovit/AdventOfCode2017
/Day24/Day24.py
2,219
3.765625
4
#!python def read_input(): input=[] with open('input.txt') as file: for line in file: input.append(line.strip()) return input def read_sample(): input=[] input.append('0/2') input.append('2/2') input.append('2/3') input.append('3/4') input.append('3/5') input.append('0/1') input.append('10/1') input.append('9/10') return input def build_graph( graph, input ): for line in input: (left, right) = line.split('/') if left not in graph['node']: graph['node'][left] = {} if right not in graph['node']: graph['node'][right] = {} graph['node'][left][right] = ( line, int(left)+int(right) ) graph['node'][right][left] = ( line, int(left)+int(right) ) def find_strongest( graph, start_node, used_links, strength, length ): #print( "find_strongest, start_node:", start_node, ", used_links:", used_links, ", strength: ", strength ) strongest_link=strength for link_node in graph['node'][start_node]: (link,this_strength) = graph['node'][start_node][link_node] if link not in used_links: my_set=set() my_set.add( link ) this_strength=find_strongest( graph, link_node, used_links.union(my_set), strength+this_strength, length+1) if this_strength > strongest_link: strongest_link = this_strength if length+1 > graph['longest'][0]: graph['longest'] = ( length+1, this_strength ) elif length == graph['longest'][0] and this_strength > graph['longest'][1]: graph['longest'] = ( length+1, this_strength ) return strongest_link def find_strongest_bridge( graph ): start_node='0' used_links=set() return find_strongest( graph, start_node, used_links, 0, 0 ) def print_graph( graph ): for node in sorted(graph['node'].keys()): print( node, ":", graph['node'][node] ) lines = read_input() graph={} graph['node']={} graph['edge']={} graph['longest']=(0,0) build_graph( graph, lines ) print_graph( graph ) print( "strongest chain: ", find_strongest_bridge( graph ) ) print( "longest strongest: ", graph['longest'] )
9100da26f42152870c1b069209baa5ec8d166a6a
dws940819/DataStructures
/DS_Introduction/DS1_introduction.py
5,329
3.6875
4
# 注册牛客网,LettCode(必刷) # 如果a+b+c = 1000,并且a^2 + b^2 = c^2,求出所有a,b,c可能的组合 # 第一种算法,三层循环 # import time # start_time = time.time() # for a in range(0,1001): # for b in range(0,1001): # for c in range(0,1001): # if a+b+c == 1000 and a**2+b**2 == c**2: # print('a,b,c:%d,%d,%d'%(a,b,c)) # end_time = time.time() # print('运行时间为:%f'%(end_time - start_time)) ''' a,b,c:0,500,500 a,b,c:200,375,425 a,b,c:375,200,425 a,b,c:500,0,500 运行时间为:173.669719 ''' # 为了时间更短,使用第二种算法 # import time # start_time = time.time() # for a in range(0,1001): # for b in range(0,1001): # c = 1000 - a - b # if a**2 + b**2 == c**2: # print('a,b,c:%d,%d,%d'%(a,b,c)) # end_time = time.time() # print('执行的时间是:%f'%(end_time - start_time)) ''' a,b,c:0,500,500 a,b,c:200,375,425 a,b,c:375,200,425 a,b,c:500,0,500 执行的时间是:1.419609 ''' # 思考:都可以从哪些角度去优化程序 ''' 1.什么是算法: 算法是独立存在的一种解决问题的方法和思想 2.算法的五大特性: 输入:算法具有0个或者多个输入 输出:算法至少有1个或者多个输出 有穷性:算法正在有限的步骤之后,会自动结束而不会无限循环,并且每一个步骤可以再可接受的时间完成。 确定性:算法中的每一步都有确定的含义,不会出现二义性 可行性:算法的每一步都是可行的(每一步都能够执行有限的次数完成) 3.算法效率衡量 实现算法程序的执行时间可以反应出来算法的效率 单纯依靠运行时间来比较算法的优劣,不一定是客观准确的(程序的运行离不开计算机环境,所以和硬件,操作系统有关系) 4.最终算法用什么去衡量 时间复杂度 5.表示法:大O记法 假设计算机执行算法每个基本操作的时间是固定的一个时间单位,那么有多少个基本操作就代表会花费多少时间单位,虽然对于不同的机器环境而言,确切的时间单位是不同的,但是对于算法进行多少个基本操作在规模数据级上是相同的,因此,可以忽略机器环境的影响,而客观的反应算法的时间效率。 对于算法的时间效率,用“大O记法” O(n^3) 100n^2 10000n^2 O(n^2) 6.时间复杂度分类 最优时间复杂度:算法完成工作最少需要多少基本操作(过于理想化,没什么参考价值) 最坏时间复杂度:算法完成工作最多需要多少基本操作(提供了一种保障,表明算法在此程度的基本操作中,一定能完成工作) 平均时间复杂度:算法完成工作最多需要多少基本操作(对算法整体一个全面的评价我,但是这种衡量方式没有保证) 总结:我们关注算法的最坏情况!!! 7.时间复杂度的几条基本计算规则 基本操作,也就是只有常数项,认为其时间复杂度为O喔(1) 顺序结构,时间复杂度按加法进行计算 循环结构,时间复杂度按乘法进行计算 分支:取最大值 判断一个算法的效率时,只需要关注操作数量的最高次项,其他次要项和常数项可以忽略 没有特殊情况下,我们分析的都是最坏时间复杂度 8.练习 12 O喔(1) 2n + 3 O(n) 3n^2 + 2n + 1 O(n^2) 5logn + 20 O(logn) 2n + 5nlogn + 20 O(nlogn) 100000n^2 + 2*n^3 + 4 O(n^3) 2^n O(2^n) O(1) < O(logn) < O(n) <O(nlogn) < O(n^2) < O(n^3) < O(2^n) < O(n!) < O(n^n) 9. 练习:求前N个正整数的和 ''' # 作业:计算前1000个正整数的和(两种算法) # import time # start_time = time.time() # def sum_of_n(n): # the_sum = 0 # for i in range(1,n+1): # the_sum = the_sum + 1 # end_time = time.time() # return the_sum,end_time-start_time # for i in range(5): # print(sum_of_n(100000000)) # def sum_of_n_2(n): # return (n*(n+1))/2 # start = time.time() # print(sum_of_n2(100000000)) # end = time.time() # print(end - start) ''' 练习:编写函数求出列表中的最小值, 要求: 函数1:O(n^2) 两两比较 函数2:O(n) 设置一个临时变量,更优化的算法是把这个临时变量设置成列表中的第一个元素 ''' my_list = [1000,3,4,9,6,8,100] def get_min(my_list): for i in range(len(my_list)): for j in range(len(my_list)): # if my_list[i] > my_list[j]: break else: return my_list[i] print(get_min(my_list)) def get_min2(): min_num = my_list[0] for i in range(len(my_list)): if my_list[i] < min_num: min_num = my_list[i] return min_num print(get_min2(my_list))
32088286c46bc1711dbc9a232bbf6b650b80f4ff
jz33/LeetCodeSolutions
/Google Onsite 03 Minimum Modification on Matrix Route.py
2,228
3.875
4
from typing import List, Tuple from heapq import heappush, heappop ''' https://leetcode.com/discuss/interview-question/476340/Google-or-Onsite-or-Min-Modifications Given a matrix of direction with L, R, U, D, at any point you can move to the direction which is written over the cell [i, j]. We have to tell minimum number of modifications to reach from [0, 0] to [N - 1, M - 1] . Example :- R R D L L L U U R Answer is 1, we can modify cell [1, 2] from L To D. PS: I was not able to solve it during the interview, but in the end of the interview I got a nice idea to solve the problem but interviewer was not interested in listening as time was up and I was not 100% sure about that so I did not insist but later I found that was the correct solution. I want to see how other people solve this problem, I will reveal the answer later, with time complexity of O(N * M) ''' class Solution: def nextMove(self, i: int, j: int, direction: str) -> Tuple[int, int]: if direction == 'R': return i, j+1 if direction == 'D': return i+1, j if direction == 'L': return i, j-1 if direction == 'U': return i-1, j def minModification(self, mat: List[str]) -> int: rowCount = len(mat) colCount = len(mat[0]) maxVal = rowCount * colCount # Global visited check, {(i,j) : modification count} visited = [[maxVal] * colCount for _ in range(rowCount)] visited[0][0] = 0 heap = [(0,0,0)] # [(modification count, x, y)] while heap: mc, i, j = heappop(heap) oldDir = mat[i][j] for newDir in ['R', 'D', 'L', 'U']: x,y = self.nextMove(i,j,newDir) newMc = mc if oldDir == newDir else mc + 1 if 0 <= x < rowCount and 0 <= y < colCount and newMc < visited[x][y]: if x == rowCount - 1 and y == colCount - 1: return newMc visited[x][y] = newMc heappush(heap, (newMc, x, y)) return -1 sol = Solution() matrix = [ 'RRD', 'LLL', 'UUR', ] matrix = [ 'RRR', 'LLL', 'RRR', 'LLL', 'LLL', ] print(sol.minModification(matrix))
769ad966b6394e4184a6e2caa7b76adc96e326d3
AsterWang/leecode
/不分行从上往下打印二叉树.py
1,290
3.75
4
''' 从上往下打印出二叉树的每个结点,同一层的结点按照从左到右的顺序打印。 样例 输入如下图所示二叉树[8, 12, 2, null, null, 6, null, 4, null, null, null] 8 / \ 12 2 / 6 / 4 输出:[8, 12, 2, 6, 4] 算法: 1. 我们从root开始按照bfs(宽度优先) 顺序遍历整棵树,首先访问left child, 然后是right child 2. 然后在从左到右扩展第三层节点 3. 一次类推 时间复杂度 BFS时每个节点仅被遍历一次,所以时间复杂度是 O(n)O(n)。 ''' # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def printFromTopToBottom(self, root): """ :type root: TreeNode :rtype: List[int] """ if not root: return [] result = [root.val] tmp = [root] while len(tmp) != 0: top = tmp.pop(0) if top.left: tmp.append(top.left) result.append(top.left.val) if top.right: tmp.append(top.right) result.append(top.right.val) return result
194ffaff14302cc3758f8498eaf609b4261d2900
jookimmy/BravesDataAnalysis
/analyze/analyzelib.py
2,806
3.578125
4
import numpy as np import pandas as pd import matplotlib.pyplot as plt #using pandas to read excel file given data = pd.read_excel("batData/BattedBallData.xlsx") #making different functions to call def histogram(variable1): #converting recieved values into a python list list1 = data[variable1].values.tolist() #matplotlib library to convert data into histogram plt.hist(list1) plt.title("Frequency of " + variable1) plt.ylabel("Frequency") plt.xlabel(variable1) #saving the figure onto a static file storage plt.savefig('bravesWeb/static/graphs/plot.png') #clear current figure so that calling another function won't be affected plt.clf() def scatter(variable1, variable2): #converting recieved values into a python list list1 = data[variable1].values.tolist() list2 = data[variable2].values.tolist() #plotting x and y variables into scatter plot plt.scatter(list1,list2, s= 10, c = (0,0,0), alpha = 0.5) plt.ylabel(variable2) plt.xlabel(variable1) plt.title(variable1 + " vs " + variable2) #gridding the graph so that each data point is easier to understand plt.grid(True) #saving figure onto a statif file storage plt.savefig('bravesWeb/static/graphs/plot.png') #clear current figure plt.clf() def bar_chart(variable1, variable2): #creating variables to utilize for bar chart sacrifice_count = 0 sacrifice_sum = 0.0 single_count = 0 single_sum = 0.0 double_count = 0 double_sum = 0.0 triple_count = 0 triple_sum = 0.0 homeRun_count = 0 homeRun_sum = 0.0 out_count = 0 out_sum = 0.0 if variable1 != 'PLAY_OUTCOME': return None else: list1 = data[variable1].values.tolist() list2 = data[variable2].values.tolist() for i in range(len(list1)): if list1[i] == 'Single': single_sum += list2[i] single_count += 1 if list1[i] == 'Double': double_sum += list2[i] double_count += 1 if list1[i] == 'Triple': triple_sum += list2[i] triple_count += 1 if list1[i] == 'Out': out_sum += list2[i] out_count += 1 if list1[i] == 'HomeRun': homeRun_sum += list2[i] homeRun_count += 1 if list1[i] == 'Sacrifice': sacrifice_sum += list2[i] sacrifice_count += 1 x_axis = ['Single', 'Double', 'Triple', 'Home Run', 'Sacrifice', 'Out'] single_bar = single_sum/single_count double_bar = double_sum/double_count triple_bar = triple_sum/triple_count homeRun_bar = homeRun_sum/homeRun_count out_bar = out_sum/out_count sacrifice_bar = sacrifice_sum/sacrifice_count y_pos = np.arange(len(x_axis)) averages = [single_bar, double_bar, triple_bar, homeRun_bar, sacrifice_bar, out_bar] plt.bar(y_pos, averages, align = 'center', alpha = 0.5) plt.xticks(y_pos, x_axis) plt.ylabel(variable2) plt.title("Average " + variable2 + " per Play Outcome") plt.savefig('bravesWeb/static/graphs/plot.png') plt.clf()
65ef3623b0bd01fd07c62239414f9961c9243ce2
Aman-dev271/Pythonprograming
/7thfoor.py
422
4.25
4
# for loop list = ['amandeep','mandeep','singh'] for item in list: print(item) # list in list list1 = [['amandeep' ,4],["deep" ,5],["singh" ,6]] for item,number in list1: print("item is:" ,item +','+"number is:", number) # by the dictionary dict1 = dict(list1) print(type(dict1)) for key,number in dict1.items(): print(key , number) # if i want only key for item in dict1: print(item)
9582c251fee5df6c926327e539909710672410ac
nirvaychaudhary/Python-Assignmnet
/data types/question32.py
298
4.09375
4
# write a python script to generate and print dictionary that contains a number (between 1 and n) in the form(x, x*x). # Sample Dictionary (n=5) # Expected Output : {1: 2, 2: 4, 3: 9, 4: 16, 5:25} n = int(input("ENter any number: ")) d = dict() for x in range(1,n+1): d[x] = x * x print(d)
6e1da209e12a6f316e17119bae89e6a34e074274
Gscsd8527/python
/面试题/阿里-巴巴/算法/选择排序.py
722
3.6875
4
# 初始时在序列中找到最小(大)元素,放到序列的起始位置作为已排序序列; # 然后,再从剩余未排序元素中继续寻找最小(大)元素,放到已排序序列的末尾。 # 以此类推,直到所有元素均排序完毕。 lst = [7, 2, 3, 8, 11, 22, 5, 1] for i in range(len(lst)): for j in range(i+1, len(lst)): if lst[i] > lst[j]: lst[i], lst[j] = lst[j], lst[i] print(lst) # # [1, 7, 3, 8, 11, 22, 5, 2] # [1, 2, 7, 8, 11, 22, 5, 3] # [1, 2, 3, 8, 11, 22, 7, 5] # [1, 2, 3, 5, 11, 22, 8, 7] # [1, 2, 3, 5, 7, 22, 11, 8] # [1, 2, 3, 5, 7, 8, 22, 11] # [1, 2, 3, 5, 7, 8, 11, 22] # [1, 2, 3, 5, 7, 8, 11, 22]
3d038303b6569c4e3f9960965fac283ed8682941
betty29/code-1
/recipes/Python/499347_Automatic_explicit_file_close/recipe-499347.py
1,343
3.59375
4
def iopen(name, mode='rU', buffering = -1): ''' iopen(name, mode = 'rU', buffering = -1) -> file (that closes automatically) A version of open() that automatically closes the file explicitly when input is exhausted. Use this in place of calls to open() or file() that are not assigned to a name and so can't be closed explicitly. This ensures early close of files in Jython but is completely unnecessary in CPython. usage: from iopen import iopen print iopen('fname').read(), for l in iopen('fname'): print l, lines = [l for l in iopen('fname')] lines = iopen('fname').readlines() ''' class Iopen(file): def next(self): try: return super(Iopen, self).next() except StopIteration: self.close(); raise def read(self, size = -1): data = super(Iopen, self).read(size) if size < 0 or not len(data): self.close() return data def readline(self, size = -1): data = super(Iopen, self).readline(size) if size != 0 and not len(data): self.close() return data def readlines(self, size = -1): data = super(Iopen, self).readlines(size) if size < 0 or not len(data): self.close() return data return Iopen(name, mode, buffering)
25a5d0483244e05787436460ec912e263da46c41
GuillaumeLab/-fluffy-garbanzo
/addsalaries.py
3,785
3.5
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Mar 12 10:11:45 2019 @author: Celia """ import numpy as np import pandas as pd import re df = pd.read_csv('df_pymongo.csv') #on prends seulement les colonnes pertinents #df = df.loc[41:] #on reset l'index #df = df.reset_index() df.drop(['index'], axis=1, inplace=True) def cleansal(lis): """cleans list of dirty salaries replace empty list with nan and extracts salary IS USED IN FIND_SALARIES""" for i in range(len(lis)): if len(lis[i])==0: lis[i] = np.nan else: lis[i] = lis[i][0] return lis def find_salaries(dataframe, column): """trouve des salaires dans la colonne et dataframe entrees en parametres column doit etre un string renvoies une liste""" salaries = [] regex = r'((?:Rémunération|Gratification|Salaire|Salary)?\s?:?\s?[0-9]*(?:.|,)[0-9]*(?:.|,)[0-9]*€?\s(?:(?:to|-|à)?\s?[0-9]*(?:.|,)[0-9]*(?:.|,)[0-9]*€?\s)?\s?(?:\/|par|per)\s?(?:mois|an|year|month))' for i in range(len(df)): l = re.findall(regex,dataframe[column][i]) salaries.append(l) salaries = cleansal(salaries) #on nettoie avec la fonction cleansal return(salaries) def intify_etc(sals): """paramètres : liste de salaires en forme de string cette fonction convertie toutes les phrases en ints: remplace les salaires avec une moyenne si c'est une fourchette et avec une moyenne transformé en annuel s'il sagit d'une salaire par mois retourne une liste netoyée, prête à étre ajouté au dataframe :)) """ regex = '[0-9]*? ?[0-9]{3}' #for each line for i in range(len(sals)): #if it's not a nan if type(sals[i]) != float: #now we must separate per months from per year #and fourchettes from non fourchettes if 'par an' in sals[i]: #print('par an') if '-' in sals[i]: #print('fourchette') frm = re.findall(regex,sals[i])[0] to = re.findall(regex,sals[i])[1] frm, to = frm.replace(' ',''), to.replace(' ','')#getting rid of space frm, to = int(frm), int(to)#convert to int avg = (frm+to)/2 #calculate average sals[i] = avg else: #print('not fourchette') sal = re.findall(regex,sals[i])[0] sal=sal.replace(' ','')#get rid of space sals[i] = int(sal)#convert to int elif 'par mois' in sals[i]: #print('par mois') if '-' in sals[i]: #print('fourchette') frm = re.findall(regex,sals[i])[0] to = re.findall(regex,sals[i])[1] frm, to = frm.replace(' ',''), to.replace(' ','')#get rid of the space frm, to = int(frm), int(to)#converting to int avg = (frm+to)/2#calculate average par_an = avg*12#convert to yearly salary sals[i] = par_an else: #print('not fourchette') sal = re.findall(regex,sals[i])[0] sal = sal.replace(' ','')#get rid of space sals[i] = int(sal)*12#convert to yearly salary return sals #This is my main function that uses the other functions below. def add_salaries(dataframe): sals = intify_etc(find_salaries(dataframe, 'Title')) dataframe['Salary'] = sals return dataframe add_salaries(df) #number of salaries in the data nbsal = len(df) - df['Salary'].isna().sum() #percent of salaries percent = nbsal/len(df) *100
91c8016997d6b4c3dce7dd0ae0991fcf0a454a7e
Eldersev/LibExcel
/Forca.py
3,472
3.8125
4
import os class forca: def __init__(self, secret_word, tips): self.secret_word = secret_word.upper() self.secret_word_size = len (secret_word) self.secret_word_found = ('_'*len(self.secret_word)) self.tips = tips self.error_count = 0 self.try_quantity = len(self.secret_word) + 3 self.win = False def set_letter(self,pos,letter): x = 0 y = 0 aux = '' while (x < len(self.secret_word)): if x == pos[y]: aux = aux + letter.upper() if (y < len(pos)-1): y = y+1 else: aux = aux + self.secret_word_found[x].upper() x = x + 1 self.secret_word_found = aux if self.secret_word_found==self.secret_word: self.win = True def find_letter (self, letter): x = 0 pos =[] while (x < self.secret_word_size): #print( word_secret[x].lower()) if letter.upper() == self.secret_word[x]: pos.append(x) x = x+1 if len(pos) == 0: self.error_count = self.error_count + 1 else: self.set_letter(pos,letter) self.try_quantity= self.try_quantity -1 return pos def can_try (self): if self.try_quantity > 0 and self.error_count <2 and self.win == False: ret = True else: ret = False return ret def draw(self): os.system('cls') print ('') print ('') print ('') print (' -------------------------') print (' | |') print (' | |') if self.error_count > 2: print (' | Perdeu a cabeça') else: print (' | ( )') if self.error_count > 1: print (' | Perdeu os braços') else: print (' | /|\ ') print (' | | ') if self.error_count > 0: print (' | Perdeu as pernas') print (' | / \ ') print (' | ') print (' | ') print (' / \ ') print ('') print ('') if self.error_count > 2: print ('Você perdeu! Tente novamente') print ('') print ('') #try_count = len(secret_word) + 3 elif self.win == True: print ('Você Ganhou! Parabens') print ('') print ('') elif self.can_try() == False: print ('Você Perdeu! Você usou todas as tentativas ') print ('') print ('') else: print ('') print ('') print (' ' + self.secret_word_found) print ('') print ('') print ('A dica é: ', self.tips[0] ) if self.error_count > 0: print ('A segunda dica é: ', self.tips[1] ) print ('') print ('')
60c216e3867d11a2ddaaf974812344a33093e64d
acusp/dotfiles
/scripts/security/crypto/caesar.py
5,337
4.125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys # a的ANSI码是97, z的ANSI码是122。 # A的ANSI码是65, Z的ANSI码是90。 def caesar_encry(): cipher = "" plain = raw_input("Please input plain text: ") shift = raw_input("Please input key: ") plain_list = list(plain) try: shift=int(shift) except shiftError: print("Please input an integer.") sys.exit() plain_list_len = len(plain_list) times = 0 while times < plain_list_len: times=times+1 #ansi_raw即没有经过任何处理的原始ANSI。 ansi_raw=ord(plain_list[times-1]) if ansi_raw == 32: cipher += " " continue #ansi是经过移位加密的ANSI。 ansi=ansi_raw+int(shift) #word是用户输入的原始字符。 word=(plain_list[times-1]) #如果ansi_raw小于65或大于90,而且还不是小写字母,那么则说明它根本就不是字母。不加密,直接输出原始内容。 if (ansi_raw < 65 or ansi_raw > 90) and word.islower() == False : print "Plain text is not letter,", word #如果ansi_raw小于97或大于122,而且还不是大写字母,那么则说明它根本不是字母。不加密,直接输出原始内容。 elif (ansi_raw < 97 or ansi_raw > 122) and word.isupper() == False: print "Plain text is not letter,", word #否则,它就是字母。 else: #如果它是大写字母,而且ANSI码大于90,则说明向后出界。那么通过这个公式回到开头,直到不出界为止。 while word.isupper() == True and ansi > 90: ansi = -26 + ansi #如果它是大写字母,而且ANSI码小于65,则说明向前出界。那么通过这个公式回到结尾,直到不出界为止。 while word.isupper() == True and ansi < 65: ansi = 26 + ansi #如果它是小写字母,而且ANSI码大于122,则说明向后出界。那么通过这个公式回到开头,直到不出界为止。 while word.isupper() == False and ansi > 122: ansi = -26 + ansi #如果它是小写字母,而且ANSI码小于97,则说明向前出界。那么通过这个公式回到结尾,直到不出界为止。 while word.isupper() == False and ansi < 97: ansi = 26 + ansi #将处理过的ANSI转换为字符,来输出密文。 cipher += chr(ansi) print "Cipher text: ", cipher def caesar_decry(): plain = ["","","","","","","","","","","","","","","","","","","","","","","","","",""] cipher = raw_input("Please input cipher text: ") cipher_list = list(cipher) cipher_list_len = len(cipher_list) for shift in range(1, 26): times = 0 while times < cipher_list_len: times=times+1 #ansi_raw即没有经过任何处理的原始ANSI。 ansi_raw=ord(cipher_list[times-1]) if ansi_raw == 32: plain[shift] += " " continue #ansi是经过移位加密的ANSI。 ansi=ansi_raw+int(shift) #word是用户输入的原始字符。 word=(cipher_list[times-1]) #如果ansi_raw小于65或大于90,而且还不是小写字母,那么则说明它根本就不是字母。不加密,直接输出原始内容。 if (ansi_raw < 65 or ansi_raw > 90) and word.islower() == False : print "Cipher text is not letter,", word #如果ansi_raw小于97或大于122,而且还不是大写字母,那么则说明它根本不是字母。不加密,直接输出原始内容。 elif (ansi_raw < 97 or ansi_raw > 122) and word.isupper() == False: print "Cipher text is not letter,", word #否则,它就是字母。 else: #如果它是大写字母,而且ANSI码大于90,则说明向后出界。那么通过这个公式回到开头,直到不出界为止。 while word.isupper() == True and ansi > 90: ansi = -26 + ansi #如果它是大写字母,而且ANSI码小于65,则说明向前出界。那么通过这个公式回到结尾,直到不出界为止。 while word.isupper() == True and ansi < 65: ansi = 26 + ansi #如果它是小写字母,而且ANSI码大于122,则说明向后出界。那么通过这个公式回到开头,直到不出界为止。 while word.isupper() == False and ansi > 122: ansi = -26 + ansi #如果它是小写字母,而且ANSI码小于97,则说明向前出界。那么通过这个公式回到结尾,直到不出界为止。 while word.isupper() == False and ansi < 97: ansi = 26 + ansi #将处理过的ANSI转换为字符,来输出密文。 plain[shift] += chr(ansi) print shift, "-", "Plain text: ", plain[shift] if __name__ == "__main__": caesar_encry() #caesar_decry() input()
84ce37c62bd4a60502e9ba4cd10ea8ac85bfb16c
frankdoylezw/Learn-Python-The-Hard-Way
/ex12c.py
315
3.640625
4
from sys import argv AGE = raw_input("How old are you? ") HEIGHT = raw_input("How tall are you? ") WEIGHT = raw_input("How much do you weigh? ") print "So, you're %r old, %r tall and %r heavy." % ( AGE, HEIGHT, WEIGHT) SCRIPT, FIRST, SECOND = argv print "You also entered two variables: ", FIRST + " and", SECOND
642f8b12faaeb3dcff5b9cb7b9a95e3b0ba60d93
lixinchn/LeetCode
/src/0100_SameTree.py
1,833
3.796875
4
class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None @staticmethod def create(arr): head = None this = None left, right = False, False prev_nodes = [] for val in arr: node = TreeNode(val) if not head: head = node this = node continue if left and right: this = prev_nodes.pop(0) left = False right = False if not left: this.left = node left = True elif not right: this.right = node right = True if node and node.val: prev_nodes.append(node) return head class Solution(object): def isSameTree(self, p, q): """ :type p: TreeNode :type q: TreeNode :rtype: bool """ if not p and not q: return True elif p and q: if p.val != q.val: return False if p.left and q.left: if not self.isSameTree(p.left, q.left): return False elif p.left and not q.left or not p.left and q.left: return False if p.right and q.right: if not self.isSameTree(p.right, q.right): return False elif p.right and not q.right or not p.right and q.right: return False else: return False return True if __name__ == "__main__": solution = Solution() head1 = TreeNode.create([3, None, 2, None, 1]) head2 = TreeNode.create([3, None, 2, None, 1]) print solution.isSameTree(head1, head2)
868669d40230716eb8e164f4ca7a2ea096f5ea2b
ritikapatel1410/Python_Data_Structure
/List/create_copy_list.py
2,031
3.640625
4
''' @Author: Ritika Patidar @Date: 2021-02-26 18:35:10 @Last Modified by: Ritika Patidar @Last Modified time: 2021-02-26 18:35:38 @Title : create duplicate list of original list ''' import sys import os sys.path.insert(0, os.path.abspath('LogFile')) import loggerfile def duplicate_list(user_defind_list): """ Description: this function is define for create duplicate element of list Parameter: user_defind_list (list) : user defined list Return: clone_user_defind_list (list) : duplicate list """ clone_user_defind_list=list(user_defind_list) return clone_user_defind_list def main(): """ Description: this main function for create list from taking input from user and call duplicate_list function Parameter: None Return: None """ user_defind_list=[] while True: try: size_of_list=int(input("===================================================================\nenter size of list: ")) for element in range(size_of_list): while True: try: value=int(input("enter index {0} element: ".format(element))) user_defind_list.append(value) break except ValueError as error: loggerfile.Logger("error","{0} error occured".format(error)) except Exception as error: loggerfile.Logger("error","{0} error occured".format(error)) print("====================================================\noriginal list : {0} duplicate list : {1}".format(user_defind_list,duplicate_list(user_defind_list))) loggerfile.Logger("info","successfully create duplicate list") break except ValueError as error: loggerfile.Logger("error","{0} error occured".format(error)) except Exception as error: loggerfile.Logger("error","{0} error occured".format(error)) main()
1ecc9313213bc1d48925cf65d7cf322e3f5e0a12
VictorVrabie/PythonIntroduction
/NewFile.py
2,034
3.875
4
#1st exercise """def Median(numbers): ln = len(numbers) srt = sorted(numbers) return numpy.median(numpy.array(x)) print(Median([1,2,15,16])) #2nd exercise city = input("Where you are going ? ") d = int(input("How many days you are staying")) def Hotel_cost(d, city): if city == "Paris": return 180*d if city == "London": return 220 * d if city == "Brussels": return 240 * d if city == "New York": return 500 * d else: return 140 * d def car_cost(d): if d>=7: return (40*d)-50 else: return (40*d) def total_cost(d,city): return Hotel_cost(d,city)+car_cost(d) print(total_cost(d,city)) #3rd exercise Billy = { "name":"Billy", "homework": [90.0,97.0,75.0,92.0], "quizzes": [88.0,40.0,94.0], "test": [75.0,90.0], } Joyce = { "name":"Joyce", "homework": [100.0,92.0,98.0,100.0], "quizzes": [82.0,83.0,91.0], "test": [89.0,97.0], } Steven = { "name":"Steven", "homework": [0.0,87.0,75.0,22.0], "quizzes": [0.0,75.0,734.0], "test": [100.0,100.0], } students = [Billy,Joyce,Steven] for student in students: for key in student.keys(): print(student.keys()) def average(numbers): total = float(sum(numbers)) return total/len(numbers) def get_average(student): home1 = average(student['homework']) quiz1 = average(student['quizzes']) test1 = average(student['test']) return 0.1*home1+0.4*quiz1+0.5*test1 print(get_average(Steven))""" #4th exercise class Shape(object): def shrink(self,factor): return (self) def surface(self): return 0 class Circle(Shape): def __init__(self,color,radius): self.color = color self.radius = radius def shrink(self,factor): self.radius += factor class Square(Shape): def __init__(self,color,side): self.color = color self.side = side def surface(self,factor): surf = self.side * self.side return surf #5th exercise
ccbc908e0d0deb4e206892572b2c52ab83cc882d
Milan-Chicago/ds-guide
/binary_tree_pruning.py
1,675
3.953125
4
""" Binary Tree Pruning Given the root of a binary tree, return the same tree where every subtree (of the given tree) not containing a 1 has been removed. A subtree of a node node is node plus every node that is a descendant of node. Example 1: Input: root = [1,null,0,0,1] Output: [1,null,0,null,1] Explanation: Only the red nodes satisfy the property "every subtree not containing a 1". The diagram on the right represents the answer. Example 2: Input: root = [1,0,1,0,0,0,1] Output: [1,null,1,null,1] Example 3: Input: root = [1,1,0,1,1,0,1,0] Output: [1,1,0,1,1,null,1] """ # 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 pruneTree(self, root: TreeNode) -> TreeNode: # Return the pruned tree if it contains a 1 else null return root if self.contains_one(root) else None def contains_one(self, node: TreeNode) -> bool: if not node: return False # Check if any node in the left subtree contains a 1 left_contains_one = self.contains_one(node.left) # Check if any node in the right subtree contains a 1 right_contains_one = self.contains_one(node.right) # If not, prune the left subtree if not left_contains_one: node.left = None # If not, prune the right subtree if not right_contains_one: node.right = None # Return true if the current node or its left or right subtree contains a 1 return node.val or left_contains_one or right_contains_one
56869ad0190c29282d3001208ef4dd56a5a6b49c
CodeInDna/Algo_with_Python
/04_Random/51_Miscellaneous/coinChange.py
891
4.03125
4
# ---------------------- PROBLEM 2 (RANDOM) ----------------------------------# # Write a function called coinChange which accepts two parameters: an array of # denominations and a value. The function should return the number of ways you can # obtain the value from the given collection of denominations. You can think of # this as figuring out the number of ways to make change for a given value from a # supply of coins. # Sample input: [1, 5, 10, 25], 5 # Sample output: 2 # ----------------METHOD 01---------------------# # Using Divide and Conquer # COMPLEXITY = TIME: O(n^2 ), SPACE: O(1) def coinChange(denoms, num): ways = [0] * (num+1) ways[0] = 1 for denom in denoms: for amount in range(1, num + 1): if denom <= amount: ways[amount] += ways[amount - denom] return ways[num] # ----------------METHOD 01---------------------# print(coinChange([1, 5, 10, 25], 5))
1a372144dc2dadb31e3a26596186404bddc4b712
guard1000/Everyday-coding
/190115_위장.py
725
3.53125
4
def solution(clothes): answer = 1 n = len(clothes) alist=[] #각 의상 종류별 몇개의 옷이 있는지를 저장한 리스트 alist clothes =sorted(clothes, key=lambda x : x[1]) i = 0 while i < n: j = i while j < n and clothes[i][1] == clothes[j][1]: j += 1 alist.append(j-i) i = j #각 의상별 안입을 수 있는 경우까지 고려해 모두 곱함 for c in alist: answer *= (c+1) return answer-1 c1 = [['yellow_hat', 'headgear'], ['blue_sunglasses', 'eyewear'], ['green_turban', 'headgear']] c2 = [['crow_mask', 'face'], ['blue_sunglasses', 'face'], ['smoky_makeup', 'face']] print(solution(c1)) print(solution(c2))
0a408ab0043115d976f01e83340bd7e41872b0b3
claudiordgz/coding-challenges
/heapsort.py
1,337
3.609375
4
from heapq import heappop, heappush def heapify(arr): for root in range(len(arr) // 2 - 1, -1, -1): rootVal = arr[root] child = 2 * root + 1 while child < len(arr): if child + 1 < len(arr) and arr[child] > arr[child + 1]: child += 1 if rootVal <= arr[child]: break arr[child], arr[(child - 1) // 2] = arr[(child - 1) // 2], arr[child] child = child * 2 + 1 return arr def heapsort(iterable): h = [] for value in iterable: heappush(h, value) return [heappop(h) for i in range(len(h))] ''' TRIES ''' def insert_key(k, v , trie): #insert key into trie and put value in key's bucket pass def has_key(k, trie): pass def retrieve_val(k, trie): pass def start_with_prefix(prefix, trie): pass def make_trie(*words): _end = '_end' root = dict() for word in words: current_dict = root for char in word: current_dict = current_dict.setdefault(char, {}) current_dict[_end] = _end return root print(make_trie('foo', 'bar', 'baz', 'barz')) def in_trie(trie, word): current_dict = trie for char in word: if char in current_dict: current_dict = current_dict[char] else: return False
fc6f42ba074d2ef914cf2b55d9e9cd459e0c7a79
rafaelperazzo/programacao-web
/moodledata/vpl_data/59/usersdata/215/34948/submittedfiles/testes.py
237
4.15625
4
# -*- coding: utf-8 -*- a=float(input('digite a')) b=float(input('digite b')) if a<b: q=a*a print (a) elif b<a: q=b*b print (q) elif a>==0 and a>b: r=a**0.5 print(r) elif b>==0 b>a: r= b**0.5 print (r)
77385595847249d0d0629bea81a0bc1d1172b274
adilahiri/Udemy_Algorithm
/Python_Basic/String_Functions.py
3,581
4.53125
5
## Methods and functions we can use on String objects # Official documentation: https://docs.python.org/3/library # We ran the following functions on strings # len(), type(), id(), dir() # We ran the following string methods # capitalize(), upper(), lower(), strip(), find() # split(), join() # Test them out on the variable declaration below, two examples # provided greeting = "hello" print(len(greeting)) print(greeting.capitalize()) # We then looked at two ways of importing # first the whole module like below # import string # Then we just imported what we need from the module like below # from string import ascii_lowercase # I have some variables defined below, go ahead and try # the various functions and methods on them, I've started # below by using the len function on the welcome_message # variable greeting = "hello" user = "jon snow" welcome_message = "hello jon snow, and welcome to the Algorithms course" print(len(welcome_message)) # Question 1: Given the string below, use the find method to determine # what index the word "universe" starts in? (and print it) my_string = "There's a lot going on in the universe don't you think?" ## Write your code below, 1 line ## print(my_string.find('u')) ## End question 1 # Question 2: Create a variable my_slice. Using a step size of 2, assign # it to a slice of my_string from the beginning to the end (the whole string) # including white spaces. Print how many characters are in this new string? (my_slice) ## Write your code below, 2 lines ## my_slice=my_string[::2] print(len(my_slice)) ## End question 2 # Question 3: Given the two string below, use string concatenation to # create and print one string (one followed by the other) seperated by a # comma and a space ", " bright_idea = "If we used yesterday's stock price instead" result = "it would result in a 2% increase in the value of our assets" ## Write your code below, 1 line ## print(bright_idea+", "+result) ## End question 3 # Question 4: You can test whether one string is equal to another by using the # equality test operator '=='. For example if you wanted to test whether "Harry" # was equal to "Harry", you would use the following code "Harry" == "Harry". # Python would evaluate that expression to True (capital T). If you tested if # "Harry" == "harry" instead, Python would evaluate that to False (capital F) # since "harry" in the second case is not capitalized. Given the string # word_to_test below, write and print an equality test in one line to check if # the string would be equal to a string if the order of its characters were # reversed. Hint: You can use the slice reverse trick. word_to_test = "level" ## Write your code below, 1 line ## print(word_to_test == word_to_test[::-1]) ## End question 4 # Question 5: You can use the len function to get the total characters or # 'length' of a string. For example len("hello") will give you 5. If you divide # this length by 2 using the floor division operator '//', you can get the index # at half of your string. You can then use slice notation to capture half of # your string since you know the length//2. With this knowledge, print out the # second half of the string below in one line. Output should be "I am the second # half". my_daily_thought = "I am the first half I am the second half" ## Write your code below, 1 line ## print(my_daily_thought[len(my_daily_thought)//2:]) ## End question 5 # Question 6: Import the hexdigits constant from the string module and print # them out. ## Write your code below, 2 lines ## import string print(string.hexdigits) ## End queston 6
0f8ddcaa26bcdf914b2bce9c0f61b193206f2466
devmacrile/notebook
/bioinformatics/rosalind/simple_transcription.py
560
4.28125
4
# -*- coding: utf-8 -*- """ Given a DNA string tt corresponding to a coding strand, its transcribed RNA string u is formed by replacing all occurrences of 'T' in t with 'U' in u. Given: A DNA string t having length at most 1000 nt. Return: The transcribed RNA string of t. """ from franklin import clock def load_data(): with open('data/rosalind_rna.txt') as f: dna_string = ''.join(f.read().splitlines()) return dna_string @clock def main(): dna = load_data() return dna.replace('T', 'U') if __name__ == '__main__': main()
f8806552f3eb3ea5514a3546e5180f2adaf38978
huseyin4334/Python-Education
/Numpy/indekslemeParcalama.py
841
3.671875
4
import numpy as np #numpy vektörleride indislerle çalışılırken pythondaki listeler gibi çalışırlar. sayilar = np.array([12,45,6,8,34,6,5,3,56,3,44,55,66,77,8]) print(sayilar[0]) print(sayilar[6]) #Hata!! print(sayilar[19]) print(sayilar[0:3]) print(sayilar[::2]) print(sayilar[::-1]) sayilar2 = sayilar.reshape(3,5) print("Çalışılan dizi : ") print(sayilar2) print("\n") print("\nİndis 1 : ") print(sayilar2[1]) print("\n1.indisin 1.indisi : ") print(sayilar2[1][1]) #veya print(sayilar2[1,1]) print("\ndizinin indislerinin 1.indisi : ") print(sayilar2[:,1]) print("\ndizinin indislerinin 0.indisten 2.indise kadar olan elemanları : ") print(sayilar2[:,0:2]) print(sayilar2[-1,:]) print(sayilar2[:,-1]) #Yukarıda kullanılan virgülün solu satırı, sağı sütunu temsil eder. İki noktada tüm anlamına gelir.
0ab4a32a56a017085b72245893d09f8fa9beaa4e
qimanchen/Algorithm_Python
/python_interview_program/python数据类型_字典.py
731
3.765625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ python面试问题 数据类型-字典 36- """ """ 36. 字典操作中del和pop有什么区别 del可以根据索引来删除元素,没有返回值 pop可以根据索引弹出一个值,然后接收它的返回值 """ """ 37. 按字典内的年龄排序 d1 = [ {'name': 'alice', 'age':38}, {'name': 'bob', 'age':18}, {'name': 'Carl', 'age':28} ] sorted(d1, key=lambda x: x['age']) """ """ 38. 请合并下面两个字典 a={"A":1,"B":2},b={"C":3,"D":4} a.update(b) 或者 {**a, **b} -- 解包的方式 """ """ 39. 如何使用生成式的方式生成一个字典,写一段功能代码 d = {'a':'1', 'b':'2'} print({v:k for k, v in d.items()}) """
6f8e819c6bfe8be8b2a0a8d38e0813565c547875
BrianMath-zz/ExerciciosPython
/Exercicios - Mundo2/Ex. 043.py
450
3.640625
4
# Ex. 043 massa = float(input("Digite sua massa (kg): ")) alt = float(input("Digite sua altura (m): ")) imc = massa/(alt**2) print(f"\nSeu IMC é de {imc:.1f}") if imc < 18.5: print("Você está ABAIXO DO PESO! Cuidado!") elif imc < 25: print("Você está com o PESO IDEAL. Parabéns") elif imc < 30: print("Você está SOBREPESO!") elif imc < 40: print("Você está com OBESIDADE!") else: print("Você está com OBESIDADE MÓRBIDA! Cuidado!")
51d22a8fc8c55486972ac2cefc6d90d2261fad20
rupali23-singh/list_question
/level_1ex_.py
116
3.734375
4
i=0 empty=[] while i<10: user=int(input("enter the number")) empty.append(user) i=i+1 print(empty)
3c6424b24f9fbf178360b5f0eb5322b0002174dd
swynnejr/bank_account
/bank_account.py
1,211
3.875
4
class BankAccount: def __init__(self, int_rate, balance): self.int_rate = int_rate self.balance = balance # self.name = User def deposit(self, amount): self.balance += amount return self def withdrawl(self, amount): if self.balance < amount: print("We took $5 that you don't even have.") self.balance -= (amount + 5) return self else: self.balance -= amount return self def display_account_info(self): print(f'Your balance is: {self.balance}') def yield_interest(self): self.balance += self.int_rate * self.balance return self # class User: # def __init__(self, name, email): # self.name = name # self.email = email # self.balance = 0 account1 = BankAccount(.02, 100) account2 = BankAccount(.02, 100) account3 = BankAccount(.02, 100) account1.deposit(350).deposit(475).deposit(225).withdrawl(14).yield_interest().display_account_info() account2.withdrawl(400).display_account_info() account3.deposit(125).deposit(900).withdrawl(19).withdrawl(42).withdrawl(7).withdrawl(19).yield_interest().display_account_info()
ee00b90fb4ff5512a78a14d359a0f4f72bb69982
g95g95/Examination
/Electoral_Montecarlo.py
2,695
3.71875
4
# -*- coding: utf-8 -*- """ Created on Wed Oct 30 17:12:33 2019 @author: Giulio """ import numpy as np import random as rd import string Results2018={'Movimento 5 stelle':0.327,'Centrosinistra':0.22,'Centrodestra':0.37,'LeU':0.03} #ResultsHyp1 ={'Movimento 5 stelle':0.18,'Centrosinistra':0.20,'Lega':0.35,'Centrodestra':0.15} #ResultsHyp2 ={'Centrosinistra':0.38,'Centrodestra':0.52} Seats2018 ={'Movimento 5 stelle':221,'Centrosinistra':109,'Centrodestra':260,'LeU':22} #excluding abroad seats def max_key(d):#this method returns the key with the highest value of a dictionary max_key = '' max_value = 0 for key in list(d.keys()): if d[key]>max_value: max_key = key max_value = d[key] elif d[key] == max_value: max_key = rd.choice([key,max_key]) return max_key def Fill_Seats(N,Results,weight_maj,weight_prop): """This method runs the Montecarlo's algorythm for each collegium. It can be performed using different weights according to the electoral law we are considering""" seats = {key:int(Results[key]*N*weight_prop)+int(Results[key]*(1-sum(list(Results.values())))) for key in list(Results.keys())} for i in range (int(N*weight_maj)): Resultscopy = Results.copy() Resultscopy = {key:Results[key]*np.random.rand() for key in Results.keys()}#this is the core of the program seats[max_key(Resultscopy)]+=1 return seats def Complete_Simulation(N,Results,weight_maj,weight_prop): seats = {key:0 for key in list(Results)} """This function provides a valid estimation for the assigned number of seats by averaging over 10000 simulation. This result will be used for confrontation with real data""" for i in range(10000): for key in list(Results): seats[key]+=Fill_Seats(N,Results,weight_maj,weight_prop)[key] average_seats = {key:int(seats[key]/10000.) for key in list(Results.keys()) } return average_seats def winning_min_seats(Party,min_seats,Results): wins = 0 """This method returns how many times a certain party can obtain more than a specified number of seats""" for i in range(10000): current_situation = Fill_Seats(0.61,0.37,Results) if (current_situation[Party]>min_seats): wins +=1 print(Party,"got",current_situation[Party],"seats") return wins def Possible_Results(N,Results,weight_maj,weight_prop,Iterations): """This function returns a dicionary having the parties has keys and each value is a list of all the results obtained all over an N iteration of Fill_Seats()""" possible_results = {key:[Fill_Seats(N,Results,weight_maj,weight_prop)[key]for i in range(Iterations)]for key in list(Results)} return possible_results
c5181d56e6dd93d380311f473c62990f767a8879
awan1/double_space_tracker
/double_space_tracker.py
2,526
3.71875
4
""" This is a background application that will alert a user when they input two spaces (instead of one) after a sentence-ending punctuation mark. It exhibits interesting functionality: - Monitoring keyboard inputs on OSX - Displaying OSX alerts Algorithm: if a space is seen after a sentence-ending punctuation mark and a space, output an alert. That's it. Could do more subtle checking of context (e.g. don't want to alert when writing code) but I can't think of any contexts where a double space is actually desired. Author: adrianwan2@gmail.com """ import os from pynput.keyboard import Key, KeyCode, Listener # The universal key to stop the tracking with. # Must be one of the values of keyboard.Key STOP_KEY = 'f8' def notify_double_space(): """ Utility function to notify if a double space was pressed after a period. """ os.system( """ osascript -e 'display notification "Double space!" with title "KeyTracker"' """ ) class LengthTwoQueue(object): """ A queue that holds two objects. - first is the most recently inserted item - second is the second-most-recently inserted item """ def __init__(self): self.first = None self.second = None def add(self, item): self.second = self.first self.first = item class ListenerWithCache(Listener): """ An extension of the Listener class that comes with a cache. """ _sentence_end_punctuation_keys = [ KeyCode.from_char(c) for c in ['.', '!', '?', ')'] ] def __init__(self): self.cache = LengthTwoQueue() # Run the superclass __init__, passing in *instance methods*. # This gives the methods appropriate access to the cache. super(ListenerWithCache, self).__init__( on_press=self.on_press, on_release=self.on_release) def on_press(self, key): if (key == Key.space and self.cache.first == Key.space and self.cache.second in self._sentence_end_punctuation_keys): notify_double_space() self.cache.add(key) def on_release(self, key): if key == getattr(Key, STOP_KEY): return False if __name__ == '__main__': print("Starting to watch for double-spacing. Press {} outside " "of terminal windows to exit." "".format(STOP_KEY)) with ListenerWithCache() as listener: try: listener.join() finally: print("Double-space tracker stopped.")
ab1f83666b24f3ce63ddf52092b00a471ff69052
benediktwerner/AdventOfCode
/2016/day09/sol.py
1,042
3.671875
4
#!/usr/bin/env python3 from os import path def decompressed_length(line, start=0, end=None, recurse=True): count = 0 i = start if end is None: end = len(line) while i < end: if line[i] == "(": marker = "" while True: i += 1 if line[i] == ")": break marker += line[i] i += 1 length, repeat = map(int, marker.split("x")) if recurse: total_length = decompressed_length(line, i, i + length) else: total_length = length count += total_length * repeat i += length else: count += 1 i += 1 return count def main(): with open(path.join(path.dirname(__file__), "input.txt")) as f: line = f.readline().strip() print("Part 1:", decompressed_length(line, recurse=False)) print("Part 2:", decompressed_length(line)) if __name__ == "__main__": main()
c5f27d819d48e4f68234854d1c2a891dd0ae703a
Abdul-Rehman1/Python-Assignment1
/guessNumber.py
816
3.671875
4
# -*- coding: utf-8 -*- """ Created on Sat Jul 20 12:30:33 2019 @author: Abdul Rehman """ import random lst=("first","second","third","fourth","fifth") print("Guess Number from [1 to 10]\n You have to guess the number with in 5 trials") numToGuess = random.randint(1, 10) count=0 guessedNum = int(input("Enter a number to guess "+lst[count]+" trail:")) while(numToGuess!=guessedNum and count<4): count+=1 print("Inputed number was not matched with the number to be guessed") guessedNum = int(input("Enter a different number to guess "+lst[count]+" trail:")) if count<4: if numToGuess==guessedNum: print(f"You win, you guessed the number in your {lst[count]} trial"); else: print("Sorry You have completed you 5 tries and can not guess the number");
092ddceda7961bc746b1ebdfbb4ec0d7a0a60cd6
kyeeh/holbertonschool-machine_learning
/math/0x00-linear_algebra/13-cats_got_your_tongue.py
274
3.75
4
#!/usr/bin/env python3 """ Module with function to Concatenate two matrices """ import numpy as np def np_cat(mat1, mat2, axis=0): """ Concatenates two matrices along a specific axis Returns the new matrix """ return np.concatenate((mat1, mat2), axis)