blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
56a61400c185d2b677c984d5d480e7bdddc17ec0
ottotexschang96/Login-with-Password-Setting
/20210326Chapter3LoginwithPasswordSetting.py
391
3.953125
4
# Login with Password Setting i = 0 while i < 3: password = input('Please input password:') if password == 'a123456': print('Successful login') break elif password != 'a123456': print('Wrong password') if 2-i > 0: print('and you still have remaining chance(s):', 2-i) else: print('Your account has been locked, and please contact the customer service.') i = i + 1
92aca135af4da75cb0cd32b9bfac71515384e04d
hakanguner67/class2-functions-week04
/exact_divisor.py
376
4.125
4
''' Write a function that finds the exact divisors of a given number. For example: function call : exact_divisor(12) output : 1,2,3,4,6,12 ''' #users number number = int(input("Enter a number : ")) def exact_divisor(number) : i = 1 while i <= number : # while True if ((number % i )==0) : print (i) i = i + 1 exact_divisor(number)
89aa00e1cd5480b1e976fe94a3bbd044f8f671de
hakanguner67/class2-functions-week04
/counter.py
590
4.21875
4
''' Write a function that takes an input from user and than gives the number of upper case letters and smaller case letters of it. For example : function call: counter("asdASD") output: smaller letter : 3 upper letter : 3 ''' def string_test(s): upper_list=[] smaller_list=[] for i in s: if i.isupper(): upper_list.append(i) elif i.islower(): smaller_list.append(i) else : pass print("Smaller Letter : ",len(smaller_list)) print("Upper Letter :",len(upper_list)) s = input("Enter a word : ") string_test(s)
6e94f15c2c7d358cccbbc52a8cb6e10fa2fb4b23
dpew/advent2017
/2017/day13/day13p2-brute.py
2,592
3.546875
4
#!/usr/bin/env python import sys import pprint import re class Layer(object): def __init__(self, name, depth): self.name = name self.depth = int(depth) self.position = 0 self.direction = 1 def iterate(self): ''' >>> l = Layer(0, 3) >>> l.iterate().position 1 >>> l.iterate().position 2 >>> l.iterate().position 1 >>> l.iterate().position 0 >>> l.iterate().position 1 ''' self.position += self.direction if (self.position >= self.depth): self.direction = -self.direction self.position += (2 * self.direction) elif (self.position < 0): self.direction = -self.direction self.position += (2 * self.direction) return self def hit(self, depth): #print self.name, self.position == depth return self.position == depth def reset(self): self.position = 0 self.direction = 1 class EmptyLayer(object): def __init__(self, name): self.name = name def hit(self, depth): # print self.name, False return False def iterate(self): pass def reset(self): pass class Firewall(object): def __init__(self): self.layers = [] def add_layer(self, num, depth): l = Layer(num, depth) while len(self.layers) <= num: self.layers.append(EmptyLayer(len(self.layers))) self.layers[num] = l def iterate(self): for l in self.layers: l.iterate() def reset(self): for l in self.layers: l.reset() def hit(self, layer, depth): return self.layers[layer].hit(depth) def severity(self, layer, depth): return (layer * self.layers[layer].depth) if self.hit(layer, depth) else 0 def __len__(self): return len(self.layers) import doctest doctest.testmod() firewall = Firewall() with open(sys.argv[1]) as f: for l in f.readlines(): x = re.split("[: ]*", l.strip()) firewall.add_layer(int(x[0]), int(x[1])) severity=0 depth=0 delay=0 bad=False while True: firewall.reset() print "delaying", delay for x in xrange(delay): firewall.iterate() for layer in xrange(len(firewall)): if firewall.hit(layer, depth): bad = True break firewall.iterate() if not bad: print delay sys.exit(0) bad = False delay += 1
2447be15084e1fd907a18e81c26ed3a864dcb4d3
dpew/advent2017
/2017/day14/day14.py
4,675
3.5625
4
#!/usr/bin/env python import sys def rotate(lst, count): ''' >>> rotate([0, 1, 2, 3, 4], 3) [3, 4, 0, 1, 2] >>> rotate([0, 1, 2, 3, 4], 0) [0, 1, 2, 3, 4] >>> rotate([0, 1, 2, 3, 4], -3) [2, 3, 4, 0, 1] >>> rotate([0, 1, 2, 3, 4], 5) [0, 1, 2, 3, 4] >>> rotate([0, 1, 2, 3, 4], -5) [0, 1, 2, 3, 4] >>> rotate([0, 1, 2, 3, 4], 7) [2, 3, 4, 0, 1] >>> rotate([0, 1, 2, 3, 4], -7) [3, 4, 0, 1, 2] >>> rotate([0, 1, 2, 3, 4], -12) [3, 4, 0, 1, 2] ''' count = ((count % len(lst)) + len(lst)) % len(lst) return lst[count:] + lst[:count] def densify(iterable, density=16): ''' >>> list(densify(xrange(6), density=3)) [3, 2] >>> list(densify(xrange(7), density=3)) [3, 2, 6] >>> list(densify([65, 27, 9, 1, 4, 3, 40, 50, 91, 7, 6, 0, 2, 5, 68, 22])) [64] ''' val = 0 i = 0 for x in iterable: i += 1 val = val ^ x if not i % density: yield val val = 0 if i % density: yield val def hexify(iterable): ''' >>> hexify([64, 7, 255]) '4007ff' >>> hexify([0, 15, 16, 255]) '000f10ff' ''' return "".join(('0' + hex(x)[2:])[-2:] for x in iterable) def countbits(val): ''' >>> countbits(0) 0 >>> countbits(1) 1 >>> countbits(2) 1 >>> countbits(15) 4 ''' count=0 while val: count += val & 1 val = val >> 1 return count class CircularList(object): def __init__(self, iterable): self.position = 0 self.items = [ x for x in iterable] def reverse(self, count): ''' >>> CircularList(range(10)).reverse(5) [[4], 3, 2, 1, 0, 5, 6, 7, 8, 9] >>> CircularList(range(10)).reverse(1) [[0], 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> CircularList(range(10)).reverse(0) [[0], 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> CircularList(range(10)).reverse(10) [[9], 8, 7, 6, 5, 4, 3, 2, 1, 0] ''' if count == 0: return self assert count >= 0 assert count <= len(self.items) tmplist = rotate(self.items, self.position) reversed = tmplist[count-1::-1] + tmplist[count:] self.items = rotate(reversed, -self.position) return self def skip(self, count): ''' >>> CircularList(range(10)).skip(2) [0, 1, [2], 3, 4, 5, 6, 7, 8, 9] >>> CircularList(range(10)).skip(12) [0, 1, [2], 3, 4, 5, 6, 7, 8, 9] >>> CircularList(range(10)).skip(0) [[0], 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> CircularList(range(10)).skip(10) [[0], 1, 2, 3, 4, 5, 6, 7, 8, 9] ''' self.position = (self.position + count) % len(self.items) return self def hashoper(self, iterable, skip=0): ''' Runs a single knothash function returns self, skip >>> CircularList(range(5)).hashoper([3, 4, 1, 5])[0] [3, 4, 2, 1, [0]] >>> l = CircularList(range(5)).hashoper([3, 4, 1, 5])[0] >>> l[0] * l[1] 12 ''' for i in iterable: self.reverse(i) self.skip(skip + i) skip += 1 return self, skip def __iter__(self): return iter(self.items) def __getitem__(self, x): return self.items[x] def __repr__(self): return repr([x[1] if x[0] != self.position else [x[1]] for x in enumerate(self.items)]) def knothash(iterable, repeat=64): ''' >>> knothash('') 'a2582a3a0e66e6e86e3812dcb672a272' >>> knothash('AoC 2017') '33efeb34ea91902bb2f59c9920caa6cd' >>> knothash('1,2,3') '3efbe78a8d82f29979031a4aa0b16a9d' >>> knothash('1,2,4') '63960835bcdc130f0b66d7ff4f6a5a8e' ''' return hexify(knothashraw(iterable, repeat=repeat)) def knothashraw(iterable, repeat=64): counts = [ ord(x) for x in iterable ] + [17, 31, 73, 47, 23] c = CircularList(range(256)) skip = 0 for x in xrange(repeat): skip = c.hashoper(counts, skip)[1] return densify(c) def hashmatrix(key): return [ knothashraw("%s-%d" % (key, x)) for x in xrange(128)] if __name__ == '__main__': if len(sys.argv) <= 1: import doctest doctest.testmod(verbose=False) else: print sum((sum((countbits(b) for b in x)) for x in hashmatrix(sys.argv[1])))
ebd015860a3051d40b0bc1b7f43c9938e4fb354b
ddvalim/TrabalhoI-ED
/Fila.py
2,760
3.8125
4
from Elemento import Elemento class Fila: def __init__(self, limite:int): self.__limite = limite self.__fim = None self.__inicio = None self.__numero_de_elementos = 0 def get_inicio(self): return self.__inicio def get_fim(self): return self.__fim def fila_vazia(self): return self.__numero_de_elementos == 0 def fila_cheia(self): return self.__numero_de_elementos == self.__limite def retira_elemento(self): if self.fila_vazia() == True: raise Exception("A fila está vazia!") else: if self.__inicio == self.__fim: self.__inicio = None self.__fim = None self.__numero_de_elementos -= 1 return self.__inicio else: element = self.__inicio self.__inicio = element.get_anterior() self.__numero_de_elementos -= 1 return self.__fim.get_numero() def insere_elemento(self, elemento:object): if isinstance(elemento, Elemento): if self.fila_cheia() != True: if self.__numero_de_elementos == 0: #Significa que a fila esta vazia self.__inicio = elemento self.__fim = elemento self.__numero_de_elementos += 1 return self.__inicio.get_numero() else: elemento.set_anterior(self.__fim) self.__numero_de_elementos += 1 self.__fim = elemento return else: raise Exception("A fila está cheia, impossível adicionar um novo elemento!") else: raise Exception("O parâmetro passado não é do tipo Elemento!") # TESTES # e = Elemento(9) f = Fila(10) f.insere_elemento(e) print(f.fila_cheia()) print(f.fila_vazia()) f.retira_elemento() print(f.fila_vazia()) # ------------- # d = Elemento(5) f.insere_elemento(d) print(f.get_inicio()) print(f.get_fim()) f.retira_elemento() # ------------- # y = Elemento(2) a = Elemento(6) u = Elemento(7) i = Elemento(4) k = Elemento(23) p = Elemento(89) q = Elemento(13) l = Elemento(22) f.insere_elemento(e) f.insere_elemento(d) f.insere_elemento(y) f.insere_elemento(a) f.insere_elemento(u) f.insere_elemento(i) f.insere_elemento(k) f.insere_elemento(p) f.insere_elemento(q) f.insere_elemento(l) print(f.fila_cheia()) print(f.fila_vazia()) print(f.retira_elemento()) elemento_final = Elemento(76) print(f.insere_elemento(elemento_final)) #print(f.insere_elemento(48))
2842fcc1c1a4c7ebd6bf69f7fc736a91e757f019
danicon/MD2-Curso_Python
/Aula13/ex10.py
249
3.765625
4
print(20*'=') print('10 TERMOS DE UMA PA') print(20*'=') prim = int(input('Primeiro termo: ')) razao = int(input('Razão: ')) decimo = prim + (10 - 1) * razao for p in range(prim, decimo + razao, razao): print(p,end = ' \032 ') print('ACABOU')
4b80822b081642692f6d48f2354f1dc4f0aeb784
danicon/MD2-Curso_Python
/Aula12/ex05.py
290
3.96875
4
num1 = float(input('Digite a primeira nota: ')) num2 = float(input('Digite a segunda nota: ')) media = (num1 + num2) / 2 print(f'Sua média foi de {media:.1f}') if media < 5: print('REPROVADO!') elif media >= 5 and media <= 6.9: print('RECUPERAÇÃO!') else: print('APROVADO!')
b21508fdbec9795884be2b668a436c51b68d8183
danicon/MD2-Curso_Python
/Aula14ex/ex08.py
447
3.9375
4
c = 'S' soma = 0 cont = 0 maior = 0 menor = 0 while c == 'S': num = int(input('Digite um número: ')) soma += num if cont == 0: maior = num menor = num else: if num > maior: maior = num if num < menor: menor = num c = str(input('Deseja continuar? ')).strip().upper()[0] cont += 1 print(f'A media é de {soma / cont}, o maior número é {maior} e o menor é {menor}')
6af41e3ebf12ac657bf8383115e63be162a1282e
danicon/MD2-Curso_Python
/Aula12/ex01.py
435
3.875
4
casa = float(input('Qual é o valor da casa? R$')) salario = float(input('Qual é o seu salário? R$')) anos = float(input('Em quanto você vai pagar a casa? ')) emprestimo = casa / (anos * 12) parcela = (salario * 30) / 100 if emprestimo > parcela: print(f'Infelizmente o emprestimo de R${emprestimo:.2f} excedeu os 30% do seu salário') else: print(f'Você vai pagar o emprestimo mensalmente no valor de R${emprestimo:.2f}')
3bee3ad2a12712f8426b3eb36fd113063f439327
jbial/convolution
/visualization.py
3,081
3.53125
4
"""Utilities for visualizing convolution outputs """ import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation def visualize_conv1d_gif(f, g, response, filepath): """Plots gif of convolution output over each timestep WARNING: This function can be very taxing on your computer Args: f (np.array): one of the signals g (np.array): the other signal response (np.array): convolution output of f and g filepath (string): filepath for saving the gif file """ fig, axes = plt.subplots(3, 1, sharex=True, figsize=(12, 8)) # plot appearance fig.suptitle("Convolution of $f$ and $g$", size=20, y=0.95) for i, label in enumerate(("$f$", "$g$", "$f*g$")): axes[i].set_ylabel(label, size=15) axes[i].set_xlim(0, len(response)) axes[i].set_xlim(0, len(response)) axes[-1].set_xlabel("t") # pad input signals length = len(response) x = range(length) f_rem = length - len(f) g_rem = length - len(g) f_padding = (0, f_rem) g_padding = (g_rem, 0) f_pad = np.pad(f, f_padding) g_pad = np.pad(g[::-1], g_padding) # init animation f_line, = axes[0].plot(x, f_pad) g_line, = axes[1].plot(x, np.zeros(length)) fg_line, = axes[-1].plot(x, np.zeros(length)) lines = [f_line, g_line, fg_line] # plot convolution def animate(i): # translate g to the right for the gif animation g_subset = g_pad[-(i + 1):] if length - len(g_subset) >= 0: g_subset = np.pad(g_subset, (0, length - len(g_subset))) else: g_subset = g_subset[:length] lines[1].set_data(x, g_subset) # plot the response r_subset = response[:(i + 1)] r_padded = np.pad(r_subset, (0, length - len(r_subset))) lines[-1].set_data(x, r_padded) return lines axes[0].set_ylim(f.min(), f.max()) axes[1].set_ylim(g.min(), g.max()) axes[-1].set_ylim(response.min(), response.max()) anim = animation.FuncAnimation(fig, animate, frames=np.arange(length), interval=40, blit=True) anim.save(filepath, dpi=150, writer="imagemagick") plt.close() def visualize_conv2d(img, kernel, response): """Visualizes the convolution of an image with a kernel Args: img (np.ndarray): grayscale image kernel (np.ndarray): filter or kernel response (np.ndarray): convolution output """ fig, axes = plt.subplots( nrows=1, ncols=3, gridspec_kw={ 'width_ratios': [4, 1, 4] }, figsize=(10, 5) ) plt.rcParams['image.cmap'] = 'bone' # plot images axes[0].set_title("Original Image") axes[0].imshow(img) axes[0].axis('off') axes[1].set_title("Filter") axes[1].set_xticks([]) axes[1].set_yticks([]) axes[1].imshow(kernel, vmin=min(kernel.min(), 0), vmax=kernel.max()) axes[2].set_title("Filtered Image") axes[2].imshow(response) axes[2].axis('off') plt.show() plt.close()
595ed60c0537d7fa84b5cb63572bd781acbc5dd1
vishaljudoka/python_learning
/Datatypes/Range.py
285
4.03125
4
#Range sequence representing an arthmetic progression of integar """ range(5) #stop range(1,5) #start ,Stop range(1,10,2) #start stop step """ for i in range(1,10,2): print(i) ###Enumerate (Index and value) a=[3,4,5,8,'a'] for i,v in enumerate(a) : print (f' i={i}, v={v}')
c9b09cff1cd7dd62be942f65b16582ba1fb1fe34
DYEkanayake/CO324
/Lab01/ex3.py
1,081
3.828125
4
from ex1 import * def load_course_registrations_dict(filename: str) -> List[Student]: #Dictionary of Student Objects studentDetails=dict() #To keep the read data of the line being read details=[] with open(filename) as f: for line in f: details= line.strip().split(",") #given_name=details[0],surname=details[1],registered_courses=details[2:len(details)] #key=(surname, given_name) i.e. key=(details[1],details[0]) ## studentDetails[details[1],details[0]]=Student(details[0],details[1],details[2:len(details)]) keyTuple=(details[1],details[0]) studentDetails[keyTuple]=Student(details[0],details[1],details[2:len(details)]) """ Returns a dictionary of Student objects read from filename""" return studentDetails #print(load_course_registrations("data.txt")) print("Eg for searching by a key: key is ('Kariyawasam','Nimali') ") print(load_course_registrations_dict("data.txt")['Kariyawasam','Nimali'])
7d2426812e648d9541c3b3a5c8b970539769d3ba
elf-deedlit/wxCalender
/ds/_Struct.py
1,699
3.65625
4
#!/usr/bin/python # vim:set fileencoding=utf-8: # # python で 構造体みたいなやつ # __all__ = ['Struct'] class Struct(): def __init__(self, *items, **attrs): for item in items: assert instance(item, (tuple, list)) assert len(item) == 2 name, value = item self.__dict__[name] = value self.__dict__.update(attrs) def __iter__(self): for name, value in self.__dict__.items(): if name.startswith('_'): continue yield name, value def __len__(self): l = [name for name in list(self.__dict__.keys()) if not name.startswith('_')] return len(l) def __setitem__(self, name, value): self.__dict__[name] = value return value def __getitem__(self, name): return self.__dict__[name] def __contains__(self, value): return value in self.__dict__ def get(self, name, default): return self.__dict__.get(name, default) def setdefault(self, name, value): if name not in self.__dict__: self.__dict__[name] = value return self.__dict__[name] def test_struct(): s = Struct() s = Struct(foo = 1, bar = 2) assert s.bar == 2 assert len(s) == 2 ls = list(iter(s)) assert len(ls) == 2 try: nothing = s.nothing assert False except AttributeError: pass s.hoge = 3 assert len(s) == 3 assert s.get('foooo', -1) == -1 if __name__ == '__main__': try: test_struct() print('%s ok' % __file__) except: print('%s fault' % __file__) import traceback traceback.print_exc()
38ed49911be4adb634aa662aed898a56c244c5ac
mariadiaz-lpsr/class-samples
/5-4WritingHTML/primeListerTemplate.py
944
4.125
4
# returns True if myNum is prime # returns False is myNum is composite def isPrime(x, myNum): # here is where it will have a certain range from 2 to 100000 y = range(2,int(x)) # subtract each first to 2 primenum = x - 2 count = 0 for prime in y: # the number that was divided will then be divided to find remainder rem_prime = int(x) % int(prime) if rem_prime != 0: count = count + 1 # if it is prime it will print it and append it to the ListOfPrime if count == primenum: print(x) myNum.append(x) ListOfPrime = [] # the file numbers.txt will open so it can be append the numbers that are prime only prime = open("numbers.txt", "w") # the range is from 2 to 100000 r = range(2, 100000) for PList in r: numberss = isPrime(PList, ListOfPrime) for y in ListOfPrime: # the prime numbers will be written in a single list prime.write(str(y) + "\n") # the file that was open "numbers.txt" will close prime.close()
120526d1004799d849367a701f6fa9c09c6bbe05
mariadiaz-lpsr/class-samples
/quest.py
1,314
4.15625
4
print("Welcome to Maria's Quest!!") print("Enter the name of your character:") character = raw_input() print("Enter Strength (1-10):") strength = int(input()) print("Enter Health (1-10):") health = int(input()) print("Enter Luck (1-10):") luck = int(input()) if strength + health + luck > 15: print("You have give your character too many points! ") while strength + health + luck < 15: print(character , "strength" + strength + "health" + health + "luck" + luck) if strength + health + luck == 15: print(character," you've come to a fork in the road. Do you want to go right or left? Enter right or left. ") if right or left == "left": print("Sorry you lost the game.") # if user chooses right and has strength over 7 if strength >= 7: print(character,"you're strength is high enough you survived to fight the ninjas that attacked you. You won the game!") else: print("You didn't have sufficient strength to defeat the ninjas. Sorry you lost the game :(. ") # if health is greater than 8 if health >= 8: print("You had enough energy to pass by the ninjas." else: print("Sorry your health was not enough to survive the spriral ninja stars wound. ") # if the number of luck is greater than 5 it wil print out the first line if not it will directly go to the else line if luck >= 5: print("You had ")
7251ebc79e8c4968588276efb33d05320b032750
mariadiaz-lpsr/class-samples
/names.py
1,010
4.3125
4
# it first prints the first line print("These are the 5 friends and family I spend the most time with: ") # these are the 2 list name names and nams names = ['Jen', 'Mom', 'Dad', 'Alma', 'Ramon'] nams = ['Jackelyn', 'Judy', 'Elyssa', 'Christina', 'Cristian'] # it is concatenating both of the lists names_nams = names + nams # its changing the word in that number to another thing to print out instead for nms in names: names[0] = "1. Jen" for nms in names: names[1] = "2. Mom" for nms in names: names[2] = "3. Dad" for nms in names: names[3] = "4. Alma" for nms in names: names[4] = "5. Ramon" for nms in names: names[5] = "6. Jackelyn" for nms in names: names[6] = "7. Judy" for nms in names: names[7] = "8. Elyssa" for nms in names: names[8] = "9. Christina" for nms in names: names[9] = "10. Cristian" # it will print out both the names and nams lists print(names_nams) # it will reverse the list names.reverse() # it will print out the list been in reverse order print(names_nams)
a902676d106ef956530f77d114a30d5cd1f0dc58
mariadiaz-lpsr/class-samples
/guess.py
313
4.0625
4
import random guessnumber = random.randint(1, 5) print("I'm thinking of a number between 1 and 5. Enter your guess!") guess = input() if guess < guessnumber: print("Nope, too low! Guess again.") if guess > guessnumber: print("Nope, to high! Guess again.") if guess == guessnumber: print("Hooray, you won!")
434182c9ca2fa8b73c4f2fd0b4d9197720b7d406
pktippa/hr-python
/basic-data-types/second_largest_number.py
430
4.21875
4
# Finding the second largest number in a list. if __name__ == '__main__': n = int(input()) arr = list(map(int, input().split())) # Converting input string into list by map and list() new = [x for x in arr if x != max(arr)] # Using list compressions building new list removing the highest number print(max(new)) # Since we removed the max number in list, now the max will give the second largest from original list.
3c09d0c67801c8748794d163a275a6c6f5b88378
pktippa/hr-python
/itertools/permutations.py
678
4.15625
4
# Importing permutations from itertools. from itertools import permutations # Taking the input split by space into two variables. string, count = input().split() # As per requirement the given input is all capital letters and the permutations # need to be in lexicographic order. Since all capital letters we can directly use # sorted(str) and join to form string string = ''.join(sorted(string)) # Calling permutations to get the list of permutations, returns list of tuples permutation_list = list(permutations(string, int(count))) # Looping through all elements(tuples) for element in permutation_list: print(''.join(element)) # forming string from a tuple of characters
542da4b047a76fd24855bdacfd14749bb9a2b56a
pktippa/hr-python
/strings/whats_your_name.py
261
3.90625
4
def print_full_name(a, b): print("Hello " + a + " " + b + "! You just delved into python.") # Using + operator for concatinating strings. if __name__ == '__main__': first_name = input() last_name = input() print_full_name(first_name, last_name)
0ff7d34d4052847acf9a11bf0e2017578ea13e57
pktippa/hr-python
/sets/check_subset.py
267
3.71875
4
for i in range(int(input())): a = int(input()); A = set(input().split()) b = int(input()); B = set(input().split()) # Or we can also use A.issubset(B) function directly if A.intersection(B) == A: print("True") else: print("False")
67d7f68e4f22f559371da94cf0ea0be9e8051132
pktippa/hr-python
/basic-data-types/lists.py
1,208
4.03125
4
list_to_handle=[] input_list=[] def do_insert(given_list): global list_to_handle list_to_handle.insert(int(given_list[1]), int(given_list[2])) def print_list(given_list): global list_to_handle print(list_to_handle) def remove_element(given_list): global list_to_handle list_to_handle.remove(int(given_list[1])) def append_element(given_list): global list_to_handle list_to_handle.append(int(given_list[1])) def sort_the_list(given_list): global list_to_handle list_to_handle.sort() def pop_element(given_list): global list_to_handle list_to_handle.pop() def reverse_the_list(given_list): global list_to_handle list_to_handle.reverse() input_dictionary = { 'insert': do_insert, 'print': print_list, 'remove': remove_element, 'append': append_element, 'sort': sort_the_list, 'pop': pop_element, 'reverse': reverse_the_list } if __name__ == '__main__': N = int(input()) for i in range(0,N,1): given_input = input() input_str_to_list = given_input.split(" ") input_list.append(input_str_to_list) for i in range(0,N,1): input_dictionary[input_list[i][0]](input_list[i])
fc8492aca1595ba8df424f489c563b8c932edbde
pktippa/hr-python
/itertools/iterables_and_iterators.py
932
3.875
4
# Importing combinations from itertools from itertools import combinations # trash input not used in the code anywhere trash_int = input() # Taking input string split and get the list input_list = input().split() # Indices count indices = int(input()) # first way # Get the combinations, convert to list combination_list = list(combinations(input_list, indices)) # initialize counter to 0 count = 0 # Loop through the combination_list for el in combination_list: # check if tuple contains 'a' if 'a' in el: count+=1 probability = count/len(combination_list) # Another way as in editorial may be the best way #combination_list_total = 0 # we can loop through combinations output since it is a iterable #for el in combinations(input_list, indices): # combination_list_total += 1 # count += 'a' in el # increment counter directly with condition #probability = count/combination_list_total print(probability)
e03cc807d94143ba7377b192d5784cbdb07b1abd
pktippa/hr-python
/math/find_angle_mbc.py
376
4.34375
4
# importing math import math # Reading AB a = int(input()) # Reading BC b = int(input()) # angle MBC is equal to angle BCA # so tan(o) = opp side / adjacent side t = a/b # calculating inverse gives the value in radians. t = math.atan(t) # converting radians into degrees t = math.degrees(t) # Rounding to 0 decimals and adding degree symbol. print(str(int(round(t,0))) + '°')
bed0fc094ed0b826db808aa4449cbf31686cbd2a
aryakk04/python-training
/functions/dict.py
549
4.53125
5
def char_dict (string): """ Prints the dictionary which has the count of each character occurrence in the passed string argument Args: String: It sould be a string from which character occurrence will be counted. Returns: Returns dictionary having count of each character in the given string. """ char_dic = {} for char in string: if char not in char_dic: char_dic[char] = string.count(char) return char_dic string = input("Enter a string : ") char_dic = char_dict (string) print (char_dic)
73ca8208af36edbc825de7e4579c8eb15ef1fcd6
habahut/GrocerySpy
/Source/ingredientParserBAK.py
12,462
3.75
4
#! /usr/bin/env python from ingredient import Ingredient ## these follow this form: # <num> |unit| {name} (, modifer) # so we split by " ". Then we check each thing for a comma. # if there is a comma, we now know where the modifier is. ## for now we are going to assume everything is of the form above ## i.e. the modifier will come last, and all terms after the , will ## be part of the modifier. ## as we build this up with recipes from allrecipes.com, we will # create a database of common words that can be associated with each category # then we can use that database to help seperate the strings. """ Number words currently break this program... i.e. "one can beef broth or 2 cups water with dissolved beef bouillon**" who the fuck enters shit by typing out the number? what a bitch... """ class IngredientParser(object): def __init__(self, parserDataFields):#, nameList, modifierList, amountList, unitStringList): """self.nameList = nameList self.modifierList = modifierList self.amountList = amountList self.unitStringList = unitStringList""" self.message = "" self.inputStringList = [] self.currentString = 0 self.finalIngredientList = [] print parserDataFields self.preModifierList = parserDataFields["PreModifiers"] print self.preModifierList def getFinishedIngredientList(self): if self.message == "done": return self.finalIngredientList else: return "notDone" def passString(self, iS): iS = iS.replace("\r\n", "\n") self.inputStringList = iS.split("\n") ## this handles calls for the ingredientParser to 'parse' # its given block of text def parse(self): result = "" for i in range(self.currentString, len(self.inputStringList)): result = self.doParse(self.inputStringList[i]) if isinstance(result, Ingredient): ## no errors, append this to the finalIngredientList self.finalIngredientList.append(result.toString()) elif isinstance(result, str): ## returned a string, meaning there is confusion parsing the # string, """ not implemented yet!!! will ask the user for clarification regarding this specific ingredient """ self.message = result return result ## if it has gotten here than no confusion has occured, simply return # "done" to let program know final list is ready self.message = "done" return "done" def doParse(self, thisString): print print print "working on: ", thisString stringList = thisString.split() print "num terms: ", len(stringList) print print if (len(stringList) == 0): ## sometimes a blank line will come through # so just return and wait for the next one return None amount = 0 unitString = "" name = "" modifiers = "" done = False # the format <#> <# ounce can of ____> currently breaks the program # so we need to have a custom thing to detect that if not (thisString.lower().find(" can ") == -1): amount = self.parseAmount(stringList[0]) for i in range(1, len(stringList)): name += stringList[i] + " " unitString = name return Ingredient(name, amount, unitString, modifiers) ## we first check some things about the stringList to try and # guess the format it is in if (not (thisString.find(",") == -1)): tempList = thisString.split(",") beforeCommaList = tempList[0].split() afterCommaList = tempList[1].split() ## i.e.: "2 jalapenos, seeded and minced" if (len(beforeCommaList) == 2): amount = beforeCommaList[0] name = beforeCommaList[1] unitString = name for s in afterCommaList: modifiers += s + " " return Ingredient(name, amount, unitString, modifiers) if (len(stringList) == 2): # the length is only two, so it must be something like # "2 eggs," in which case the unit is the name and modifiers is blank # it could be reverse ordered thought "eggs 2" or something... if (stringList[0][0] == "." or stringList[0][0].isdigit()): ## the first part is a number so it is probably of the "2 eggs" variety amount = self.handleHyphenatedAmount(stringList[0]) name = stringList[1] # units will be teh same as name here unitString = name else: ## the order is probably reversed, so "eggs: 2" # or something like that ## should ask alec for a regex that removes non-alphabetic characters name = stringList[0] unitString = name amount = self.handleHyphenatedAmount(stringList[1]) done = True elif (stringList[0][0] == "." or stringList[0][0].isdigit()): ## the first digit is a number # stringList[0] is a number, which means it is an amount # so we want to start on the second index of stringList counter = 1 # in this case we will guess that it is of the form # <num> |unit| {name} (, modifer) # i.e.: 3 teaspoons sugar, granulated amount += self.parseAmount(stringList[0]) ## 3 possible options from here, a # - # meaning a range seperated by spaces if (stringList[1] == "-"): if (stringList[2][0] == "." or stringList[2][0].isdigit()): temp = self.parseAmount(stringList[2]) amount = (amount + temp)/2.00 counter = 3 else: raise IngredientInputError("Ingredient String Makes No Sense!") elif (stringList[1][0] == "." or stringList[1][0].isdigit()): amount += self.parseAmount(stringList[1]) counter += 1 ## here we should cross check with the database to confirm if our assumption # is correct. Checking the potential unitString against the database # of previous unitStrings and "connectors:" i.e. "of, ':'" etc... # will help determine if this ingredient string is of the type we guessed #!!! here we need to also check if this word is something to do with the name # of the ingredient. For example "green peppers" or "large onions." in either # case green or large would fall into the "unit string" field. unitString, modifiers, counter = self.considerUnitString(stringList, counter) ## since we have now assumed we have grabbed the above values correctly # everything from here to the end of the string, or from here to a comma # is part of the name of the ingredient hasModifier = False for i in range(counter, (len(stringList))): if (not (stringList[i].find("(") == -1)): hasModifier = True break name += stringList[i] print "name is: ", name, " i @ ", i, " len: ", len(stringList) if (not (name.find(",") == -1)): # the string we just added contains a comma, meaning # this ingredient has a modifier name = name.strip(",") i += 1 hasModifier = True break else: name += " " name = name.rstrip() print print print "length of stringList = ", len(stringList) print print if (hasModifier): for i2 in range(i, len(stringList)): modifiers += stringList[i2].strip(",").strip("(").strip(")")+ " " print "modifiers: ", modifiers if unitString == "": unitString = name print "name: ", name print "modifiers: ", modifiers print "amount: ", amount print "unitString: ", unitString # we want this to be in string form in the dictionary: # i.e.: name?(,modifiers): amount unitString # but we need to make it an ingredient for now so we can differentiate # between finished products and error messages return Ingredient(name, amount, unitString, modifiers) def parseAmount(self, stringList): amountList = stringList.split("-") blankElements = [] for i in range(len(amountList)): if amountList[i] == "": blankElements.append(i) else: amountList[i] = self.handleFractionalAmount(amountList[i]) for i in blankElements: amountList.pop(i) if (len(amountList) == 1): return amountList[0] else: return (amountList[0] + amountList[1])/2.00 def handleFractionalAmount(self, string): s = string.split("/") if (len(s) == 1): ## i.e. no fraction print "s[0] is : ", s[0] return float(s[0]) else: return float(s[0])/float(s[1]) def considerUnitString(self, stringList, startIndex): modS = "" unitString = "" done = False while not done: done = True if (not (stringList[startIndex].find("(") == -1)): if (not (stringList[startIndex].find(")") == -1)): modS += stringList[startIndex].strip("(").strip(")") + " " startIndex += 1 else: modS += stringList[startIndex].strip("(") + " " startIndex += 1 while (not (stringList[startIndex].find(")") == -1)): modS += stringList[startIndex].strip(")") + " " startIndex += 1 for word in self.preModifierList: if stringList[startIndex].strip(",").lower() == word.lower(): modS += stringList[startIndex].strip(",") + " " startIndex += 1 done = False break if modS == "": unitString = stringList[startIndex].strip(",") startIndex += 1 print "after consideration: unitString:", unitString, " modS: ", modS, " startIndex: ", startIndex return unitString,modS,startIndex class IngredientInputError(Exception): def __init__(self, v): self.val = v def __str__str(self): return repr(self.val) if __name__ == "__main__": parser = IngredientParser({"PreModifiers": ["delicious","sweet","green", "red", "orange", "blue", "spicy", "large", "chopped", "big", "medium", "sized"]}) #parser = IngredientParser(["large","green"]) datString = raw_input("try me: ") parser.passString(datString) print "returned", parser.parse() print "===========" #print parser.considerUnitString(datString.split(), 1) print print print "final ingredient List: " , parser.getFinishedIngredientList() """ 4 medium sized potatoes (peeled/chunked) 3 carrots (sliced) 1 sweet (bell) green pepper (chunked) 1 medium sized yellow onion (chopped) 1/4 head of green cabbage (shredded) 1-2 stalks of celery (sliced 1/4-1/2") 1 red delicious apple (peeled/chunked) 1 small turnip (chunked) 1- 14 oz can whole kernel corn (drained) 1- 14oz can green peas (drained) 64 oz V8 (or other brand) 100% vegetable juice 1.5 lb. beef chuck roast one can beef broth or 2 cups water with dissolved beef bouillon** 1 tsp dried basil 1 tsp. oregano """
8f4737c5028b5237c809d24ee24fd3280d466d46
SamuelSebastianMartin/folder_tree_ac_eng
/make_google_folders.py
3,087
3.8125
4
#! /usr/bin/env python3 """ This may be a one-off program, depending on changes made to registers. It reads a SOAS Google Docs register (2019-20) into a pandas dataframe and creates folders necessary for all academic English student work. Student work/ | |___ SURNAME Firstname/ | | | |__Term 1/ | | | |__Term 2/ | | | |__Term 3/ | |____NEXT Student/ | | | |__Term 1/ | | | |__Term 2/ | | | |__Term 3/ """ import pandas as pd import re import os def filepicker(): """ Opens a graphical file selection window, and returns the path of the selected file. """ import tkinter as tk from tkinter import filedialog root = tk.Tk() root.withdraw() file_path = filedialog.askopenfilename() return file_path def read_register(): """ Opens a csv file (given the filepath, and returns a pandas dataframe. """ print("Please select a downloaded register file") filename = filepicker() if ".csv" not in filename: print("You must select a .csv file, exported from Google forms") register = pd.read_csv(filename) return register def extract_names(register): """ Extracts the names from the relevant columns of the dataframe. This is not a robust function, and will break if the registers change the order of the columns. """ names = [] for i in range(len(register) - 1): # len() -> no of columns first_name = str(register.iloc[i][2]).capitalize() last_name = str(register.iloc[i][1]).upper() name = last_name + ' ' + first_name names.append(name) names = list(set(names)) return names def clean_names_list(names): """ Takes out NaN entries and 'Surname' & 'firstname' headings. This is not a robust function, and will break if the registers change their column headings. """ pure_names = [] nan = re.compile('nan', re.IGNORECASE) title = re.compile('surname', re.IGNORECASE) for name in names: if nan.search(name): continue elif title.search(name): continue else: pure_names.append(name) return pure_names def make_directories(names): """ Given a list of names, this function creates a new directory for each name. Within each new directory, sub-directories are created: 'Term 1', 'Term 2', 'Term 3' """ os.mkdir('Student_Folders') os.chdir('Student_Folders') for name in names: os.mkdir(name) os.chdir(name) sub_dirs = ['Term 1', 'Term 2', 'Term 3'] for drcty in sub_dirs: os.mkdir(drcty) os.chdir('..') def main(): """ Asks user to select list of names (register). and makes a directory for each name. """ register = read_register() names = extract_names(register) names = clean_names_list(names) make_directories(names) print(names) if __name__ == '__main__': main()
149b7cdf5c74d2bc96c2249ad192000659303926
edmartins-br/PythonTraining
/general.py
4,281
4.0625
4
#! /usr/bin/python3 #Fiibonacci a,b = 0, 1 for i in range(0, 10): print(a) a, b = b, a + b # ---------------------------------------------------------------- # FIBONACCI GENERATOR def fib(num): a,b = 0, 1 for i in range(0, num): yield "{}: {}".format(i+1, a) a, b = b, a + b for item in fib(10): print (item) # ---------------------------------------------------------------- # LISTAS SÃO IMUTAVEIS E TUPLAS SÃO MUTÁVEIS my_list = [1,2,3,4,5,6,7,8,9,10] squares = [num*num for num in my_list] print (squares) # ---------------------- OOP ------------------------------------------ class Person(object): def _init_(self, name): self.name = name def reveal_identity(self): print("My name is {}".format(self.name)) class SuperHero(Person): def _init_(self, name, hero_name): super(SuperHero, self)._init_(name) self.hero_name = hero_name def reveal_identity(self): super(SuperHero, self).reveal_identity() print("...And I am {}".format(self.hero_name)) # corey = Person('Corey') # corey.reveal_identity() wade = SuperHero('Wade Wilson', 'Deadpool') wade.reveal_identity() # ---------------------------------------------------------------- class employee: def _init_(self, firstName, lastName, salary): self.firstName = firstName self.lastName = lastName self.salary = salary self.email = self.firstName + "." + self.lastName + "@outlook.com" def giveRaise(self, salary): self.salary = salary class developer(employee): def _init_(self, firstName, lastName, salary, programming_languages): super()._init_(firstName, lastName, salary) self.prog_langs = programming_languages def addLanguage(self, lang): self.prog_langs += [lang] employee1 = employee("Jon", "Montana", 100000) print(employee1.salary) employee1.giveRaise(100000) print(employee1.salary) dev1 = developer("Joe", "Montana", 100000, ["Python", "C"]) print(dev1.salary) dev1.giveRaise(125000) print(dev1.salary) dev1.addLanguage("Java") print(dev1.prog_langs) # ---------------------------------------------------------------- # STRING FORMATING name = "Eduardo" age = 33 string = "Hi, my name is %s and I am %i years old" % (name, age) # similar to printf in C language print(string) string2 = "Hi, my name is {} and I am {} years old" .format(name, age) print(string2) string3 = f"Hello, {name}" print(string3) string4 = f"1 + 1 is {1 + 1}" print(string4) # ---------------------------------------------------------------- # DATA STRUCTURE # STaCK stack = [] stack.append(1) stack.append(2) pop_elem = stack.pop() print(stack, pop_elem) queue = [] queue.append(1) queue.append(2) pop_elem = queue.pop(0) print(queue, pop_elem) # SET set1 = set([1,2,3,4,5,6]) set2 = set([2,4,3,1,8,7,9,2]) print(set1 & set2) # DICTIONARY ages = dict() ages["bob"] = 22 ages["emily"] = 20 for key, value in ages.items(): # print(ages) print(key, value) # LIST COMPREHENSION lst = [1,2,3,4,5,6,7] even_lst = [x for x in lst if x % 2 == 0] print(even_lst) square_lst = [x ** 2 for x in lst] print(square_lst) # PYTHON STANDARD LIBRARIES from collections import defaultdict exam_grades = [("Bob", 43), ("Joe", 98), ("Eduardo", 89), ("Mark", 90), ("Tiff", 44), ("Jan", 56)] student_grades = defaultdict(list) for name, grade in exam_grades: student_grades[name].append(grade) print(student_grades) print(student_grades["Eduardo"]) from collections import Counter numbers = [1,2,3,4,5,6,7,8,3,5,7,8,3,2, 8, 8, 8, 8, 8] counts = Counter(numbers) print(counts) top2 = counts.most_common(2) print(top2) # ex: [(8, 7), (3, 3)] - Numero 8 ocorreu 7 vezes e o número 3 ocorreu 3 vezes class Carro: def _init_(self, marca, preco, cor): self.marca = marca self.preco = preco self.cor = cor def mostraMarca(self): print('A marca do carro é {}'.format(self.marca)) def mostraPreco(self): print('O preço do carro é R${}'.format(self.preco)) def mostraCor(self): print('A cor do carro é {}'.format(self.cor)) meuCarro = Carro('Volks', 45000, 'Prata') meuCarro.mostraMarca() meuCarro.mostraPreco() meuCarro.mostraCor()
2d87b86197a7790b8596ee19e8099661d2a89536
ZinoKader/X-Pilot-AI
/pathfinding/navigator.py
2,045
3.6875
4
import math import helpfunctions class Navigator: def __init__(self, ai, maphandler): self.ai = ai self.pathlist = [] self.maphandler = maphandler def navigation_finished(self, coordinates): targetX = int(coordinates[0]) targetY = int(coordinates[1]) selfX = self.ai.selfX() selfY = self.ai.selfY() self_block = self.maphandler.coords_to_block(selfX, selfY) target_block = self.maphandler.coords_to_block(targetX, targetY) if self_block == target_block: print("navigation completed") return True return False def navigate(self, coordinates): targetX = int(coordinates[0]) targetY = int(coordinates[1]) selfX = self.ai.selfX() selfY = self.ai.selfY() self_block = self.maphandler.coords_to_block(selfX, selfY) target_block = self.maphandler.coords_to_block(targetX, targetY) if self_block == target_block: self.ai.talk("teacherbot: move-to-pass {}, {} completed".format(targetX, targetY)) print("navigation completed") # om vi hamnar på vilospår, hämta ny pathlist if not self.pathlist or self_block not in self.pathlist: self.pathlist = self.maphandler.get_path(self_block, target_block) while self_block in self.pathlist: # förhindra att vi åker tillbaka (bugg) self.pathlist.remove(self_block) if self.pathlist: next_move_block = (self.pathlist[0][0], self.pathlist[0][1]) next_move_coords = self.maphandler.block_to_coords(next_move_block) targetDirection = math.atan2(next_move_coords[1] - selfY, next_move_coords[0] - selfX) self.ai.turnToRad(targetDirection) self.ai.setPower(8) # thrusta endast när vi har nästa block i sikte så vi inte thrustar in i väggar if helpfunctions.angleDiff(self.ai.selfHeadingRad(), targetDirection) < 0.1: self.ai.thrust()
2bc03bbfed056ccd044b253e6e1430c59215d59a
ZinoKader/X-Pilot-AI
/excercises/exc3.py
5,294
3.5625
4
# # This file can be used as a starting point for the bot in exercise 1 # import sys import traceback import math import os import libpyAI as ai from optparse import OptionParser # # Create global variables that persist between ticks. # tickCount = 0 mode = "wait" targetId = -1 def tick(): # # The API won't print out exceptions, so we have to catch and print them ourselves. # try: # # Declare global variables so we're allowed to use them in the function # global tickCount global mode global targetId # # Reset the state machine if we die. # if not ai.selfAlive(): tickCount = 0 mode = "aim" return tickCount += 1 # # Read some "sensors" into local variables to avoid excessive calls to the API # and improve readability. # selfX = ai.selfX() selfY = ai.selfY() selfHeading = ai.selfHeadingRad() # 0-2pi, 0 in x direction, positive toward y targetCount = ai.targetCountServer() #print statements for debugging, either here or further down in the code. # Useful functions: round(), math.degrees(), math.radians(), etc. # os.system('clear') clears the terminal screen, which can be useful.() targetCountAlive = 0 for i in range(targetCount): if ai.targetAlive(i): targetCountAlive += 1 # Use print statements for debugging, either here or further down in the code. # Useful functions: round(), math.degrees(), math.radians(), etc. # os.system('clear') clears the terminal screen, which can be useful. targetlist = {} for i in range(targetCount): if ai.targetAlive(i): targetdistance = ( ( (ai.targetX(i) - selfX) ** 2) + ( (ai.targetY(i) - selfY) ** 2) ) ** (1 / 2) targetlist[targetdistance] = i targetId = targetlist.get(min(targetlist)) print("current targetId: " + str(targetId)) targetX = ai.targetX(targetId) - selfX targetY = ai.targetY(targetId) - selfY print(targetX) print(targetY) print(targetlist) targetdistance = ( ( targetX ** 2) + ( targetY ** 2) ) ** (1 / 2) targetDirection = math.atan2(targetY, targetX) print(targetDirection) velocity = ((ai.selfVelX() ** 2) + (ai.selfVelY() ** 2)) ** (1 / 2) velocityvector = math.atan2(ai.selfVelY(), ai.selfVelX()) print("tick count:", tickCount, "mode:", mode, "heading:",round(math.degrees(selfHeading)), "targets alive:", targetCountAlive) if mode == "wait": if targetCountAlive > 0: mode = "aim" elif mode == "aim": if targetCountAlive == 0: mode = "wait" return if velocity < 15 and tickCount % 3 == 0: ai.turnToRad(targetDirection) ai.setPower(40) ai.thrust() elif velocity > 15: ai.turnToRad(velocityvector + math.pi) ai.setPower(55) ai.thrust() angledifference = angleDiff(selfHeading, targetDirection) if angledifference <= 0.05 and targetdistance < 600: mode = "shoot" else: mode = "aim" elif mode == "shoot": if not ai.targetAlive(targetId): mode = "aim" else: if velocity > 10 and targetdistance > 500: ai.turnToRad(velocityvector + math.pi) ai.setPower(55) ai.thrust() elif targetdistance < 250: #spin-circus compensation. Will eventually fully stop if the ship keeps spinning around a target. if velocity > 5: ai.turnToRad(velocityvector + math.pi) ai.setPower(55) ai.thrust() else: ai.turnToRad(targetDirection) ai.fireShot() elif targetdistance < 600: ai.turnToRad(targetDirection) ai.setPower(55) ai.thrust() ai.fireShot() elif targetdistance > 800: mode = "aim" except: # # If tick crashes, print debugging information # print(traceback.print_exc()) def angleDiff(one, two): """Calculates the smallest angle between two angles""" a1 = (one - two) % (2*math.pi) a2 = (two - one) % (2*math.pi) return min(a1, a2) # # Parse the command line arguments # parser = OptionParser() parser.add_option ("-p", "--port", action="store", type="int", dest="port", default=15345, help="The port to use. Used to avoid port collisions when" " connecting to the server.") (options, args) = parser.parse_args() name = "Exc. 1 skeleton" #Feel free to change this # # Start the main loop. Callback are done to tick. # ai.start(tick, ["-name", name, "-join", "-turnSpeed", "64", "-turnResistance", "0", "-port", str(options.port)])
8e18bf9cc041596acb023cd5d68c0933f432f6cd
hitsumabushi845/Cure_Hack
/addSongInfoToDB.py
1,167
3.65625
4
import sqlite3 from createSpotifyConnection import create_spotify_connection def add_songinfo_to_db(): db_filename = 'Spotify_PreCure.db' conn = sqlite3.connect(db_filename) c = conn.cursor() spotify = create_spotify_connection() albumIDs = c.execute('select album_key, name from albums;') sql = 'insert into songs ' \ '(song_key, artist_key, album_key, title, href_url, duration_ms, disk_number, track_number) ' \ 'values (?,?,?,?,?,?,?,?)' for album in albumIDs.fetchall(): print('Processing {}...'.format(album[1])) songs = spotify.album_tracks(album_id=album[0], limit=50) for song in songs['items']: songdata = (song['id'], song['artists'][0]['id'], album[0], song['name'], song['external_urls']['spotify'], song['duration_ms'], song['disc_number'], song['track_number']) print(songdata) c.execute(sql, songdata) conn.commit() print("end") if __name__ == '__main__': add_songinfo_to_db()
9d035da888745f18febd025b110dab7cb6f1f2d7
KarChun0227/PythonQuizz
/Expertrating/Word_sort.py
201
3.984375
4
input_str = input() result = "" word = input_str.split(",") sortedword = sorted(word) for x in sortedword: result = result + "," + x result = result[1:] print(result) # order,hello,would,test
a5bb0c599c2cb8e70b3d60a85932b9fd28b65780
KarChun0227/PythonQuizz
/Exercise/Ex8.py
747
3.953125
4
def winner(P1, P2): if P1 == P2: return 0 elif P1 == "S": if P2 == "R": return 2 else: return 1 elif P1 == "R": if P2 == "S": return 1 else: return 2 elif P1 == "P": if P2 == "S": return 2 else: return 1 while True: p1 = input("Player one:") p2 = input("Player two:") result = winner(p1,p2) if result == 0: print ("No Winner!!") elif result == 1: print ("Winner is Payer 1") if input("Wish to continue?") == "no": break elif result == 2: print ("Winner is Payer 2") if input("Wish to continue?") == "no": break
7d27fc42523b5ae8e1cb509c38d5538c85d959d5
KarChun0227/PythonQuizz
/Expertrating/exam.py
199
3.890625
4
import string input_str = raw_input() for i in range(1,6): password = input_str[i] if (password)<5: return False if " " in password: return False if "*" or "#" or "+" or "@" in
f4f03e85c8c0d572714451962e539fd4736c18c8
lulzzz/counter-1
/Counter/serv/report_python/reportmg.py
711
3.78125
4
import sqlite3 import re conn = sqlite3.connect('/Users/itlabs/db1.db') cur = conn.cursor() cur.execute(''' DROP TABLE IF EXISTS mega''') cur.execute(''' CREATE TABLE mega (dates TEXT, people TEXT)''') fname = '/tfs/report-MEGA.txt' fh = open(fname) count = 0 for line in fh: if not count % 2: people = line count = count + 1 continue else: dates = line.split()[2] alla = people, dates count = count + 1 # Insert a row of data cur.execute("INSERT INTO mega VALUES (?,?)", alla) # Save (commit) the changes conn.commit() sqlstr = 'SELECT dates, people FROM mega' for row in cur.execute(sqlstr) : print str(row[0]), row[1] cur.close()
bf61860cd0381b0b6eb5563ff529da0b4a07c9bf
PavelErsh/Python-for-pro
/shop.py
896
3.6875
4
from datetime import datetime class Greeter: def __init__(self, name, store): self.name = name self.store = store def _day(self):#tace date return datetime.now().strftime('%A') def _part_of_day(self): current_hour = datetime.now().hour if current_hour < 12: part_of_day = 'утра' elif 12 <= current_hour < 17: part_of_day = 'дня' else: part_of_day = 'вечера' return part_of_day def greet(self): print(f'Здравствуйте, меня зовут {self.name}, и добро пожаловать в {self.store}!') print(f'Желаем вам приятного {self._part_of_day()} {self._day()}?') print('Дарим вам купон на скидку 20 %!') welcome = Greeter("bishop", "test") welcome.greet()
766b98ad78790d5cb7436b20afc07ddc1b8fdd0e
Asakura-Hikari/assignment-2-travel-tracker-Asakura-Hikari
/a1_classes.py
4,745
3.65625
4
""" Replace the contents of this module docstring with your own details Name: Chaoyu Sun Date started: 31/july/2020 GitHub URL: https://github.com/JCUS-CP1404/assignment-1-travel-tracker-Asakura-Hikari """ # main() function is to open and save the file. def main(): print("Travel Tracker 1.0 - by Chaoyu Sun") print("3 places loaded from places.csv") file = open("places.csv", "r+") content = file.readlines() # read the whole file place_list = [] # create a list to add every place for i in content: # split one place to one list place = i.strip('\n').split(',') place_list.append(place) file.seek(0) # reset file index to the beginning place_list = menu(place_list) for place in place_list: # write list into file file.write("{},{},{},{}\n".format(place[0], place[1], place[2], place[3])) file.close() print("{} places saved to places.csv".format(len(place_list))) print("Have a nice day :)") # menu() function is to loop the main menu. def menu(place_list): var = True # set quit value while var: place_list = sorted(place_list, key=lambda x: (x[3], int(x[2]))) # sort list print("Menu:") print("L - List places
") print("A - Add new place") print("
M - Mark a place as visit
") print("Q - Quit") select = input(">>> ").upper() # get upper input value if select == 'L': list_places(place_list) elif select == 'A': place_list = add_new_place(place_list) elif select == 'M': place_list = mark_place(place_list) elif select == 'Q': return place_list else: print("Invalid menu choice") # list_places is to list the places in menu. def list_places(place_list): i = 0 # to count unvisited place number for place in place_list: i += 1 if place[3] == 'n': # printing depend visit and unvisited print("*{}. {:<15} in {:<15} priority {:<15}".format(i, place[0], place[1], place[2])) else: print(" {}. {:<15} in {:<15} priority {:<15}".format(i, place[0], place[1], place[2])) # add_new_place is to add new places in list. def add_new_place(place_list): new_place = [] name = input("Name: ") while name == '': # retry if name is blank print("Input can not be blank
") name = input("Name: ") new_place.append(name) country = input("Country: ") while country == '': # retry if country is blank print("Input can not be blank
") country = input("Country: ") new_place.append(country) var = True # create a support variable to help loop while var: try: # retry if priority not a number priority = int(input("Priority: ")) except ValueError: print("Invalid input, enter a valid number
") continue if priority < 0: # retry if priority is a negative number print("Number must be > 0") else: new_place.append(priority) new_place.append("n") print("{} in {} (priority {}) added to Travel Tracker
".format(name, country, priority)) place_list.append(new_place) # add new place in list return place_list # mark_place is to change place from unvisited to visit. def mark_place(place_list): unvisited = 0 for place in place_list: if place[3] == 'n': # to check how many places are unvisited. unvisited += 1 if unvisited == 0: # if all places are unvisited, return the function. print("No unvisited places") return list_places(place_list) print("{} places. You still want to visit {} places.".format(len(place_list), unvisited)) var = True while var: try: # check if enter value not a number. print("Enter the number of a place to mark as unvisited
") mark = int(input(">>> ")) except ValueError: print("Invalid input; enter a valid number") continue if mark < 0: # check the number must large than 0. print("Number must be > 0") elif mark > len(place_list): # check the number is valid number in place. print("Invalid place number") elif place_list[mark - 1][3] == 'v': # check if this place are unvisited. print("That place is already unvisited") else: # change place to unvisited successfully. place_list[mark - 1][3] = 'v' print("{} in {} unvisited!".format(place_list[mark - 1][0], place_list[mark - 1][1])) return place_list if __name__ == '__main__': main()
2e0deae0231338db84a2f11cd64994bf82900b33
seanakanbi/SQAT
/SampleTests/Sample/classes/Calculator.py
1,677
4.375
4
import math from decimal import * class Calculator(): """ A special number is any number that is - is between 0 and 100 inclusive and - divisible by two and - divisible by five. @param number @return message (that displays if the number is a special number) """ def is_special_number(self, num_in): # Verify the number is within the valid range. if num_in < 0 or num_in > 100: message = " is not a valid number." else: # Determine if the number is a special number. if num_in % 2 != 0: message = " is not an even number." elif num_in % 5 != 0: message = " is not divisible by five." else: message = " is a special number" #Remember this will return your number plus the message! return str(num_in) + message """ This method does a strange/alternative calculation * @param operand * @return calculated value as a Decimal """ def alternative_calculate(self, operand): calculated_value = operand * 100 / math.pi return Decimal(calculated_value) if __name__ == '__main__': print("****** ******* ") print("****** Running calculator ******* ") calc = Calculator() num1 = int(input("Please enter a number to check if it is special: " )) print("-> ", calc.is_special_number(num1)) num2 = int(input("Please enter a number to run an alternative calculation on it: " )) print("-> ", round(calc.alternative_calculate(num2),4))
af698f93e23c3d8a429b72ecc03bdb272de5d3b5
patrickgaskill/project-euler
/patrick.py
642
3.671875
4
from functools import reduce from operator import mul from math import sqrt def is_prime(n): if n < 2: return False if n == 2: return True if n == 3: return True if n % 2 == 0: return False if n % 3 == 0: return False i = 5 w = 2 while i * i <= n: if n % i == 0: return False i += w w = 6 - w return True def prod(a): return reduce(mul, a) def factors(n): return set(reduce(list.__add__, ([i, n//i] for i in range(1, int(sqrt(n)) + 1) if n % i == 0))) def tup2int(t): return int(''.join(t))
d9de3d0d4860d0ace81217ddf8fa23bd15c47c16
patrickgaskill/project-euler
/7.py
177
3.625
4
from patrick import is_prime N = 10001 primes = [2, 3] i = primes[-1] + 2 while len(primes) < N: if (is_prime(i)): primes.append(i) i += 2 print(primes[-1])
87d068764544cb2670704d56028940a1847bd061
TheUlr1ch/3-
/main3.py
655
3.984375
4
# 1-е задание myList = [1, 2, 3] myNewList = [i * 2 для i в myList] print(myNewList) # 2-е задание myList = [1, 2, 3] myNewList = [i * * 2 для i в myList] print(myNewList) # 3-е задание list = 'Hello world' для i в диапазоне(len(list)): if list[i] == " ": список = список.заменить("w", "W") печать(список) # 4-е задание из datetime импорт datetime год1 = дата-время .сейчас().год год2 = 1900 ren = год1 - год2 для i в диапазоне(ren+1): печать(год2 + i)
0df98d530f508a752e42a67ad7c6fe0a2608f823
JaiAmoli/Project-97
/project97.py
266
4.21875
4
print("Number Guessing Game") print("guess a number between 1-9") number = int(input("enter your guess: ")) if(number<2): print("your guess was too low") elif(number>2): print("your guess was too high") else: print("CONGRATULATIONS YOU WON!!!")
a71aa0afdb02234d87afe81f5b3b912748e66027
marcusshepp/hackerrank
/python/anagram.py
1,963
3.984375
4
#!/usr/bin/python # -*- coding: ascii -*- """ Your task is to help him find the minimum number of characters of the first string he needs to change to enable him to make it an anagram of the second string. Note: A word x is an anagram of another word y if we can produce y by rearranging the letters of x. Input Format The first line will contain an integer, T, representing the number of test cases. Each test case will contain a string having length len(S1)+len(S2), which will be concatenation of both the strings described above in the problem. The given string will contain only characters from a to z. Output Format An integer corresponding to each test case is printed in a different line, """ def min_del(s): c_ = 0 _u = len(s) q_ = list(s) if _u % 2 == 0: l_side = q_[_u/2:] r_side = q_[:_u/2] pok = {} for i in l_side: if i in pok: pok[i] += 1 else: pok[i] = 1 for j in r_side: if j in pok: if pok[j] > 0: pok[j] -= 1 else: c_ += 1 for x in pok: if pok[x] > 0: c_ += 1 else: c_ = -1 return c_ # for i in range(int(raw_input())): # print min_del(str(raw_input())) print "10 -- ", min_del("hhpddlnnsjfoyxpciioigvjqzfbpllssuj") print "13 -- ", min_del("xulkowreuowzxgnhmiqekxhzistdocbnyozmnqthhpievvlj") print "5 -- ", min_del("dnqaurlplofnrtmh") print "26 -- ", min_del("aujteqimwfkjoqodgqaxbrkrwykpmuimqtgulojjwtukjiqrasqejbvfbixnchzsahpnyayutsgecwvcqngzoehrmeeqlgknnb") print "15 -- ", min_del("lbafwuoawkxydlfcbjjtxpzpchzrvbtievqbpedlqbktorypcjkzzkodrpvosqzxmpad") print "-1 -- ", min_del("drngbjuuhmwqwxrinxccsqxkpwygwcdbtriwaesjsobrntzaqbe") print "3 -- ", min_del("ubulzt") print "13 -- ", min_del("vxxzsqjqsnibgydzlyynqcrayvwjurfsqfrivayopgrxewwruvemzy") print "13 -- ", min_del("xtnipeqhxvafqaggqoanvwkmthtfirwhmjrbphlmeluvoa") print "-1 -- ", min_del("gqdvlchavotcykafyjzbbgmnlajiqlnwctrnvznspiwquxxsiwuldizqkkaawpyyisnftdzklwagv") """ 10 13 5 26 15 -1 3 13 13 -1 """
88794e943e08e346af71e6e3e8b398a22c6c4432
marcusshepp/hackerrank
/python/openkattis/ahh.py
177
3.78125
4
jon = raw_input() doc = raw_input() def noh(s): return [a for a in s if a != "h"] jon = noh(jon) doc = noh(doc) if len(jon) >= len(doc): print "go" else: print "no"
956019e0287fed6689e94f291add98e827fc9744
marcusshepp/hackerrank
/python/warmup/chocolate_feast.py
610
3.640625
4
""" Problem Statement: Little Bob loves chocolate, and he goes to a store with $N in his pocket. The price of each chocolate is $C. The store offers a discount: for every M wrappers he gives to the store, he gets one chocolate for free. How many chocolates does Bob get to eat? Input Format: The first line contains the number of test cases, T. T lines follow, each of which contains three integers, N, C, and M. Output Format: Print the total number of chocolates Bob eats. """ def chocolate(money, cost, wrappers): c = 0 for i in range(1, money): if i % money == 0: c += 1 if c % wrappers == 0
7b9c3c2cd1a9f753a9f3df2adeb84e846c9eb1b4
mschaldias/programmimg-exercises
/list_merge.py
1,395
4.34375
4
''' Write an immutable function that merges the following inputs into a single list. (Feel free to use the space below or submit a link to your work.) Inputs - Original list of strings - List of strings to be added - List of strings to be removed Return - List shall only contain unique values - List shall be ordered as follows --- Most character count to least character count --- In the event of a tie, reverse alphabetical Other Notes - You can use any programming language you like - The function you submit shall be runnable For example: Original List = ['one', 'two', 'three',] Add List = ['one', 'two', 'five', 'six] Delete List = ['two', 'five'] Result List = ['three', 'six', 'one']* ''' def merge_lists(start_list,add_list,del_list): set_start = set(start_list) set_add = set(add_list) set_del = set(del_list) set_final = (set_start | set_add) - set_del final_list = list(set_final) final_list.sort(key=len, reverse=True) return final_list def main(): start_list = ['one', 'two', 'three',] add_list = ['one', 'two', 'five', 'six'] del_list = ['two', 'five'] #final_list = ['three', 'six', 'one'] final_list = merge_lists(start_list,add_list,del_list) print(final_list) main()
c65d5f051adcb61c0b2b98e304551f4538779177
tethig/oyster_catchers
/oyster_catchers/gaussian_walk.py
1,001
3.65625
4
''' Generalized behavior for random walking, one grid cell at a time. ''' # Import modules import random from mesa import Agent # Agent class class RandomWalker(Agent): ''' Parent class for moving agent. ''' grid = None x = None y = None sigma = 2 def __init__(self, pos, model, sigma=2): ''' grid: The MultiGrid object in which the agent lives. x: The agent's current x coordinate y: The agent's current y coordinate sigma: deviation from home square ''' super().__init__(pos, model) self.pos = pos self.sigma = 2 def gaussian_move(self): ''' Gaussian step in any allowable direction. ''' x, y = self.pos coord = (x, y) while coord == self.pos: dx, dy = int(random.gauss(0, self.sigma)), int(random.gauss(0, self.sigma)) coord = (x + dx, y + dy) # Now move: self.model.grid.move_agent(self, coord)
3df2910d100c84048bee5a5a965580cdea802811
susie9393/spaces
/spaces.py
1,413
3.796875
4
# spaces import numpy as np import random as rn def Spaces(no_rolls): # initialise an array to record number of times each space is landed on freq = np.zeros(14) # s denotes space landed on, 1 <= s <= 14 s = 0 # a counter has been set up to perform a check on total number of squares landed on count = 0 for n in range(no_rolls): dice1 = rn.randint(1,6) dice2 = rn.randint(1,6) moves = dice1 + dice2 s+=moves if s > 14: s-=14 if s == 4: freq[s-1]+=1 count+=1 s = 10 if s == 7 and (dice1 == 6 or dice2 == 6): freq[s-1]+=1 count+=1 s = 1 if s == 10 and moves%2==0: freq[s-1]+=1 count+=1 s = 5 freq[s-1]+=1 if np.sum(freq)==200+count: return freq else: print "Error" def Average(iterations): total = [] for i in range(iterations): freq = Spaces(200) total.append(freq) freq = np.mean(np.array(total), axis = 0) print np.around(freq) Average(10)
6aaf293f5c0eb3ecbeac2a8844eae47189ed22b5
Romannweiler/hu_bp_python_course
/02_introduction/guess_a_number_rm.py
853
3.984375
4
# This is a guess the number game. import random guessesTaken = 0 print('Welcome to my Game') print('I am thinking of a number between 0 and 100!') number = random.randint(0, 100) while guessesTaken < 4: numTries = 3 - guessesTaken numTriesStr = str(numTries) print('you have '+ numTriesStr +' tries') print('Take a guess.') guess = input() guess = int(guess) guessesTaken = guessesTaken + 1 if guess < number: print('Your guess is too low.') if guess > number: print('Your guess is too high.') if guess == number: break if guess == number: guessesTaken = str(guessesTaken) print('Good job! You guessed my number in ' + guessesTaken + ' guesses!') if guess != number: number = str(number) print('Nope. The number I was thinking of was ' + number)
da4f38b16f878727966067fa8da540115169ad66
Nori1117/Recursion-lv.2
/MyLogic.py
1,075
3.890625
4
#Given a number n, write a program to find the sum of the largest prime factors of each of nine consecutive numbers starting from n. #g(n) = f(n) + f(n+1) + f(n+2) + f(n+3) + f(n+4) + f(n+5) + f(n+6) + f(n+7) + f(n+8) #where, g(n) is the sum and f(n) is the largest prime factor of n def find_factors(num): factors = [] for i in range(2,(num+1)): if(num%i==0): factors.append(i) return factors def is_prime(num, i): if(i==1): return True elif(num%i==0): return False; else: return(is_prime(num,i-1)) def find_largest_prime_factor(list_of_factors): large=[] for i in list_of_factors: if is_prime(i,i//2)==True: large.append(i) return max(large) def find_f(num): f=find_factors(num) l=find_largest_prime_factor(f) return l def find_g(num): sum=0 consicutive=[i for i in range(num,num+9)] for i in consicutive: largest_prime_factor=find_f(i) sum=sum+largest_prime_factor return sum print(find_g(10))
7473ceb49464bcf2268a790243b1dae6c671ec03
zhouxiongaaa/myproject
/my_game/congratulation.py
266
3.71875
4
name = input('你想给谁发祝福:') def cong(name1): a = list(map(lambda x: 'happy birthday to' + (' you' if x % 2 == 0 else ' '+name1+''), range(4))) return a if __name__ == '__main__': print(cong(name)) b = input('如要退出请输入exit:')
bac10c57ecb9bccb3a13cda38a104937d8bcd1b2
Goro-Majima/OpenFoodFacts
/pureBeurre.py
4,468
3.5
4
# -*- coding: utf-8 -*- """Starting program that calls insert and display functions from other file """ from displaydb import * from databaseinit import * from connexion import * from displayfavorite import * #query used to check if filling is needed CHECKIFEMPTY = '''SELECT * FROM Category''' CURSOR.execute(CHECKIFEMPTY) ALLTABLES = CURSOR.fetchall() if ALLTABLES == []: NEWDATABASE = DatabaseP() #Already filled NEWDATABASE.fill_table_category() NEWDATABASE.fill_table_product() MENUSCREEN = 1 while MENUSCREEN: USER = Userintro() USER.introduction() USER.choices() CHOICE = 0 while CHOICE not in (1, 2): try: CHOICE = int(input("Veuillez choisir entre requête 1 ou 2:\n")) except ValueError: print("Mauvaise commande, choisir 1 ou 2") if CHOICE == 1: # User wants to see the category list DISPLAY = Displaydb() DISPLAY.showcategory() print("") CATEG = -1 while CATEG < 0 or CATEG > 20: # User choose which category try: CATEG = int(input("Sélectionnez la catégorie entre 1 et 20: \n")) except ValueError: print("Mauvaise commande, choisir entre 1 et 20\n\n") DISPLAY.showproducts(CATEG) # Put an error message if input different than product list # loop with verification from database WHICHPRODUCT = 0 while WHICHPRODUCT < (CATEG * 50) - 49 or WHICHPRODUCT > CATEG * 50: try: WHICHPRODUCT = int( input("\nSélectionnez l'aliment à remplacer dans sa catégorie: \n") ) print("") except ValueError: print("Mauvaise commande, choisir aliment\n\n") print("-----------------------------------------------------------") print("Votre sélection: \n") DISPLAY.showproductdetails(WHICHPRODUCT) print("\n-----------------------------------------------------------") print("Produit alternatif: \n") DISPLAY.showalternative(CATEG) FAVORITE = input("\nSouhaitez-vous ajouter cet aliment à vos favoris ? O pour OUI, N si pas de substitut \n") while FAVORITE not in ("N", "O"): print("Mauvaise commande, tnapez O pour OUI, N pour NON\n") FAVORITE = input( "Souhaitez-vous ajouter cet aliment à vos favoris ? O/N \n" ) if FAVORITE == "N": BACKTOMENU = input("\nRevenir à l'accueil ?\n") while BACKTOMENU not in ("N", "O"): print("Mauvaise commande, tnapez O pour OUI, N pour NON\n") BACKTOMENU = input("Revenir à l'accueil ? O ou N\n") if BACKTOMENU == "N": print("\nMerci d'avoir utilisé la plateforme ! A la prochaine !") MENUSCREEN = 0 else: print("-------------------------------------------------------------\n") elif FAVORITE == "O": DISPLAY.addalternative() elif CHOICE == 2: REQSUB = """SELECT * FROM Substitute""" CURSOR.execute(REQSUB) REQSUB = CURSOR.fetchall() if REQSUB == []: print("\nIl n'y a aucun produit alternatif. \n") print("-----------------------------------------------") BACKTOMENU2 = input("Revenir à l'accueil ?\n") while BACKTOMENU2 not in ("O", "N"): print("Mauvaise commande, tnapez O pour OUI, N pour NON\n") BACKTOMENU2 = input("Revenir à l'accueil ? O ou N\n") if BACKTOMENU2 == "N": print("") print("Merci d'avoir utilisé la plateforme ! A la prochaine !") MENUSCREEN = 0 else: print("-------------------------------------------------------------\n") else: DISPLAYSUB = Displaysub() DISPLAYSUB.substitutelist() BACKTOMENU2 = input("Revenir à l'accueil ?\n") while BACKTOMENU2 not in ("O", "N"): print("Mauvaise commande, tnapez O pour OUI, N pour NON\n") BACKTOMENU2 = input("Revenir à l'accueil ? O ou N\n") if BACKTOMENU2 == "N": print("") print("Merci d'avoir utilisé la plateforme ! A la prochaine !") MENUSCREEN = 0 CONN.commit() CONN.close()
5c2bfd87eae9ecbf66be718816136f425a11fd24
NandanIITM/Pizzeria_Zearth_Sol
/Nandani_Garg/graph.py
4,709
3.671875
4
from collections import defaultdict import numpy as np # Class to represent a graph class Graph: def __init__(self, vertices): ''' Args: vertices : No of vertices of graph ''' self.V = vertices # No. of vertices self.graph = [] # default list to store graph #Vertex adjacency list required for DFS traversal self.adjList = defaultdict(list) self.weights = {} def addEdge(self, src, des, wt): ''' function to add an edge to graph Args: src: source vertex des: destination vertex wt: weight of edge ''' self.graph.append([src, des, wt]) def makeadjList(self, src, des, wt): ''' function to make adjList of a graph Args: src: source vertex des: destination vertex wt: weight of edge ''' self.adjList[src].append(des) self.weights[(src, des)] = wt def find(self, parent, i): ''' function to find set of an element i Args: parent: parent of i i: vertex i ''' if parent[i] == i: return i return self.find(parent, parent[i]) def union(self, parent, rank, x, y): ''' A function that does union of two sets of x and y (uses union by rank) ''' xparent = self.find(parent, x) yparent = self.find(parent, y) # Attach smaller rank tree under root of # high rank tree (Union by Rank) if rank[xparent] < rank[yparent]: parent[xparent] = yparent elif rank[xparent] > rank[yparent]: parent[yparent] = xparent # If ranks are same, then make one as root # and increment its rank by one else: parent[yparent] = xparent rank[xparent] += 1 def getKruskalMST(self): ''' The main function to construct MST using Kruskal's algorithm Returns: list of resultant MST ''' result = [] # This will store the resultant MST # An index variable, used for sorted edges i = 0 # An index variable, used for result[] e = 0 # Step 1: Sort all the edges in # non-decreasing order of their # weight. If we are not allowed to change the # given graph, we can create a copy of graph self.graph = sorted(self.graph, key=lambda item: item[2]) parent = [] rank = [] # Create V subsets with single elements for node in range(self.V): parent.append(node) rank.append(0) # Number of edges to be taken is equal to V-1 while e < self.V - 1: # Step 2: Pick the smallest edge and increment # the index for next iteration u, v, w = self.graph[i] i = i + 1 x = self.find(parent, u) y = self.find(parent, v) # If including this edge does't # cause cycle, include it in result # and increment the indexof result # for next edge if x != y: e = e + 1 result.append([u, v, w]) self.union(parent, rank, x, y) # Else discard the edge return result def DFS(self, src, des, route_cost, wt, visited): ''' Function to find cost of the path from src to des from a given MST Args: src : Source vertex des: Destination vertex route_cost: empty list representing cost of the path from src to des wt: edge wt visited: list containing visit status of each vertex in MST Returns: route_cost: list containing cost of the path from src to des ''' visited[src] = 1 route_cost.append(wt) # If current vertex is same as destination, then return route_cost if src==des: return route_cost else: # If current vertex is not destination # Recur for all the vertices adjacent to this vertex for i in self.adjList[src]: if visited[i]==0: r_cost = self.DFS(i, des, route_cost, self.weights[(src,i)], visited) if r_cost: return r_cost # Remove current cost from route_cost and mark it as unvisited route_cost.pop() visited[src] = 0
2385bc762c835072e42a2e7bfdbbd66579f3ee84
amssdias/python-school
/classes.py
2,537
3.78125
4
class Student: id = 1 def __init__(self, name, course): self.name = name self.course = course self.grades = [] self.id = Student.id self.teachers = [] Student.id += 1 def __repr__(self): return f"<Student({self.name}, {self.course})>" def __str__(self): return f"Id: {self.id} - {self.name}" @property def details(self): return f"""Student \n id: {self.id} Name: {self.name} Course: {self.course} Grades: {self.grades} Teachers: {[teacher.__str__() for teacher in self.teachers]} """ def add_grade(self, grade): if not isinstance(grade, int) and not isinstance(grade, float): raise ValueError('Grade must be a number!') self.grades.append(grade) def add_teacher(self, teacher): if not isinstance(teacher, Teacher): raise TypeError('Tried to add a `{teacher.__class__.__name__}` to student, but you can only add `Teacher` object. ') if teacher in self.teachers: return print('<<<<< Teacher already exists >>>>>') self.teachers.append(teacher) teacher.students.append(self) print(f'Teacher added! to {self.name}.') class Working_student(Student): def __init__(self, name, course, job, pay): super().__init__(name, course) self.job = job self.pay = pay def __repr__(self): return f"<Working_student({self.name}, {self.course}, {self.job}, {self.pay})>" def __str__(self): return f"Id: {self.id} - {self.name} (Working)" @property def details(self): return f"""Working student \n id: {self.id} Name: {self.name} Course: {self.course} Grades: {self.grades} Teachers: {[teacher.__str__() for teacher in self.teachers]} Job: {self.job} Pay(Yearly): {self.pay} """ class Teacher: id = 1 def __init__(self, name, subject): self.name = name self.subject = subject self.students = [] self.id = Teacher.id Teacher.id += 1 def __repr__(self): return f'<Teacher: {self.name} {self.subject}>' def __str__(self): return f"Id: {self.id} - {self.name}" @property def details(self): return f"""Teacher \n id: {self.id} Name: {self.name} Subject: {self.subject} Students: {[student.__str__() for student in self.students]} """
00dfb0b8881dcccdd6f8ef059e0149956b6ed29b
ashleybaldock/tilecutter
/old/Script1.py
1,693
3.796875
4
import os class pathObject: """Contains a path as an array of parts with some methods for analysing them""" def __init__(self, pathstring): """Take a raw pathstring, normalise it and split it up into an array of parts""" path = pathstring norm_path = os.path.abspath(pathstring) p = path self.path_array = [] # Iterate through the user supplied path, splitting it into sections to store in the array while os.path.split(p)[1] != "": n = os.path.split(p) self.path_array.append(path2(n[1],os.path.exists(p),len(p) - len(n[1]))) p = os.path.split(p)[0] def __getitem__(self, key): return self.path_array[key] def blah(self): return 1 def __str__(self): a = "" for k in range(len(self.path_array)): a = a + "<[" + str(k) + "]\"" + self.path_array[k].text + "\"," + str(self.path_array[k].offset) + "," + str(self.path_array[k].length) + "," + str(self.path_array[k].exists) + ">, " return a class path2: def __init__(self,text,exists,offset): self.text = text # Textual content of this section of the path self.length = len(text) # Length of this section of the path self.offset = offset # Offset from start of string self.exists = exists # Does this path section exist in the filesystem def __len__(self): return self.length def __str__(self): return self.text def exists(self): return self.exists a = pathObject("old\\output/blah/output.dat") print len(a[1]) print a
b30bc8c68c43339e91c03673aa98bd186fdee092
wheatgrinder/donkey
/donkeycar/parts/pitft.py
3,020
3.8125
4
#!/usr/bin/env python3 ''' donkey part to work with adafruitt PiTFT 3.5" LCD display. https://learn.adafruit.com/adafruit-pitft-3-dot-5-touch-screen-for-raspberry-pi/displaying-images classes display text on display So far I have only been able to find a methond to write to the display using the frame buffer. (without installing x anyway which is really not necessary) display image We will use opencv to create an image and display it on the screen or we will display existing images on the screen or we will show a short video on the screen. (animaated gifts etc) image size 480x330 ''' import os import sys import cv2 import numpy as np import re import time class display_text(): def __init__(self, port='/dev/fb1', text='text to show here'): self.port = port self.text = text self.prev_text = '' self.on = True def update(self): while self.on: #self.text = str(text) if not self.text == self.prev_text: # only update display if text is chnaged # = os.popen('vcgencmd measure_temp').readline() #print('display: '+ self.text) my_img = create_blank_image() my_img = add_text(my_img,self.text) my_img = display_image(my_img) self.prev_text = self.text time.sleep(2) def run_threaded(self,text): self.text = str(text) return self.prev_text def create_blank_image(): blank_image = np.zeros((330,480,3), np.uint8) #display_image_direct(blank_image) return blank_image def display_image_direct(img_in): fbfd = open('/dev/fb1','w') fbfd.write(img_in) def add_text(img_arr,text='text here',size=1,color=(255,255,255),width=1): img_arr = cv2.putText(img_arr, str(text), (20,100), cv2.FONT_HERSHEY_SIMPLEX,size, color,width, cv2.LINE_AA) return img_arr def open_image(img): image = cv2.imread(img,0) return image def display_image(img_in): #write the imgage then display... image_file = cv2.imwrite(os.getcwd()+'/999.jpg', img_in) img_handel = os.popen('sudo fbi -T 2 -d /dev/fb1 -noverbose -a ' + os.getcwd()+'/999.jpg > /dev/null 2>&1') return img_handel def main(): dir_path=os.getcwd() # my code here #result=os.popen('sudo fbi -T 2 -d /dev/fb1 -noverbose -a ' + dir_path + '/debug.jpg') #display_image(dir_path + '/debug.gif') my_img = create_blank_image() #my_img = open_image(os.getcwd()+'/dog.jpg') my_ip=os.popen('ip -4 addr show wlan0 | grep -oP \'(?<=inet\s)\d+(\.\d+){3}\'').readline() my_ip = re.sub('\?', '',my_ip) text = 'View on Web at: ' + my_ip #text=os.popen('ip -4 addr show wlan0' ).readline() my_img = add_text(my_img,text) my_img = display_image(my_img) return if __name__ == "__main__": main()
3df6b8f9818261092de3b9df2143871c121fc360
leosartaj/thinkstats
/ch1.py
1,463
3.5
4
""" Chapter 1 """ import sys import survey import thinkstats as ts def live_births(table): cou = 0 for rec in table.records: if rec.outcome == 1: cou += 1 return cou def partition_births(table): first = survey.Pregnancies() other = survey.Pregnancies() for rec in table.records: if rec.outcome != 1: continue if rec.birthord == 1: first.AddRecord(rec) else: other.AddRecord(rec) return first, other def average(table): return (sum(rec.prglength for rec in table.records) / float(len(table.records))) def MeanVar(table): return ts.MeanVar([rec.prglength for rec in table.records]) def summarize(table): """Prints summary statistics for first babies and others. Returns: tuple of Tables """ first, other = partition_births(table) print 'Number of first babies', len(first.records) print 'Number of others', len(other.records) (mu1, st1), (mu2, st2) = MeanVar(first), MeanVar(other) print 'Mean gestation in weeks:' print 'First babies', mu1 print 'Others', mu2 print 'Difference in days', (mu1 - mu2) * 7.0 print 'STD of gestation in weeks:' print 'First babies', st1 print 'Others', st2 print 'Difference in days', (st1 - st2) * 7.0 if __name__ == '__main__': table = survey.Pregnancies() table.ReadRecords(sys.argv[1]) summarize(table)
d47912664ed0a3d113d4d868ff9ecb16ae22e800
akhilharihar/optimus
/optimus/optimus.py
1,548
4
4
class Optimus: """ Arguments - prime - Prime number lower than 2147483647 inverse - The inverse of prime such that (prime * inverse) & 2**31-1 == 1 xor - A large random integer lower than 2147483647""" def __init__(self,prime, inverse, xor): self.prime = int(prime) self.inverse = int(inverse) self.xor = int(xor) self.max = int((2**31) - 1) self.__validate(prime = self.prime,inverse = self.inverse,random = self.xor) def encode(self,value): """ Accepts a integer value and returns obfuscated integer """ self.__check_arg(value) return (int(value*self.prime) & self.max) ^ self.xor def decode(self,value): """ Accepts obfuscated integer generated via encode method and returns the original integer """ self.__check_arg(value) return ((value ^ self.xor)*self.inverse) & self.max def __check_arg(self,value): if not isinstance(value, int): raise Exception('Argument should be an integer') def __validate(self,**kwargs): if kwargs['prime'] >= 2147483647: raise Exception('The prime number should be less than 2147483647') if ((kwargs['prime'] * kwargs['inverse']) & (2**31 -1)) != 1: raise Exception('The inverse does not satisfy the condition "(prime * inverse) & 2**31-1 == 1"') if kwargs['random'] >= 2147483647: raise Exception('The random integer should be less than 2147483647')
03e2d051ac1d3c734e5d4d2127a53ddf4187d7f9
Asritha-Reddy/2TASK
/positivenumbers.py
354
3.78125
4
#positive numbers list1=[12,-7,5,64,-14] print('List1: ',list1) print("Positive numbers in list1:") for i in list1: if i>=0: print(i, end=", ") print('\n') list2=[12,14,-95,3] print('List2: ',list2) print("Positive numbers in list2:") for j in list2: if j<=0: list2.remove(j) print(list2)
da9b9a622dbe2abc55064bb484c030c88f2587c8
Chearfly/-
/xiang_mu.py
1,010
3.609375
4
from tkinter import * from tkinter import ttk # from PIL import Image #建立模块对像 root = Tk() #设置窗口标题 root.title("人工智能项目") #设置显示窗口的大小 root.geometry("700x500") #设置窗口的宽度是不可变化的,但是他的长度是可变的 root.resizable(width = "true",height = "True") # l = ttk.Label(root, text="欢迎来到人工智能的项目", bg = "blue", font= ("Arial",15), width=30,\ # height=5) # l.grid(side = TOP)#设置项目的名称 # label=Label(root,text='Hello,GUI') #生成标签 # label.pack() #将标签添加到主窗口 # button1=Button(root,text='聊天',width=8,height = 2) #生成button1 # button1.pack(side=LEFT) #将button1添加到root主窗口 button2=ttk.Button(root,text='天气').grid(column=3, row=1, sticky=W)#列,行, # button2.pack(side=LEFT) # def my_out(): # root.quit # button2=ttk.Button(root,text='退出',command = root.quit ,width = 8,height =2) # button2.grid(side=BOTTOM) root.mainloop()
9f9ca4275f16934ecb0dc4b331dd3ed3cfa150be
alex123012/Bioinf_HW
/fourth_HW/hw_5.py
512
3.515625
4
k = int(input('Enter k number: ')) # wget https://raw.githubusercontent.com/s-a-nersisyan/HSE_bioinformatics_2021/master/seminar4/homework/SARS-CoV-2.fasta with open('SARS-CoV-2.fasta') as f: f.readline().strip() fasta = f.readline().strip() hash_table = {} for i in range(len(fasta) - k): j = i + k hash_table[fasta[i:j]] = hash_table.get( fasta[i:j], []) + [(i, j)] for i in hash_table: print(i, end=': ') for j in hash_table[i]: print(j, end=', ') print('\n')
511aac38c0edf5a12b6819d91b2bb20246581308
alex123012/Bioinf_HW
/first_HW/first_hw_1.py
1,231
3.71875
4
def quadratic_equation(a, b, c, rnd=4): """Solving quadratic equations""" if a == 0: if b == 0: if c == 0: return 'any numbers' else: return 'No solutions' else: return -c / b elif b == 0: if c <= 0: return c**0.5 else: x1 = (-c)**0.5 x1 = complex(f'{round(x1.imag, rnd)}j') + round(x1.real, rnd) return x1 dD = b**2 - 4 * a * c if dD >= 0: x1 = (-b + dD**0.5) / (2 * a) if dD == 0: return x1 x2 = (-b - dD**0.5) / (2 * a) return x1, x2 else: sqrtD = dD**0.5 x1 = (-b + sqrtD**0.5) / (2 * a) x2 = (-b - sqrtD**0.5) / (2 * a) x1 = complex(f'{round(x1.imag, rnd)}j') + round(x1.real, rnd) x2 = complex(f'{round(x2.imag, rnd)}j') + round(x2.real, rnd) # print(f'x1 = {x1}, x2 = {x2}') return x1, x2 def main(): a = float(input('Enter coefficient A: ')) b = float(input('Enter coefficient B: ')) c = float(input('Enter coefficient C: ')) print('Quadratic roots are', quadratic_equation(a, b, c)) if __name__ == '__main__': main()
27bdec3ef8bcff49ef41716fb4b2dd5fe0e39168
isabella0428/Leetcode
/python/695.py
1,383
3.5
4
class Solution: def maxAreaOfIsland(self, grid: 'List[List[int]]') -> 'int': def search(row, col, grid, num): grid[row][col] = 0 up = 0 if row == 0 else grid[row - 1][col] if up: num += search(row - 1, col, grid, 1) down = 0 if row == m - 1 else grid[row + 1][col] if down: num += search(row + 1, col, grid, 1) left = 0 if col == 0 else grid[row][col - 1] if left: num += search(row, col - 1, grid, 1) right = 0 if col == n - 1 else grid[row][col + 1] if right: num += search(row, col + 1, grid, 1) return num m, n = len(grid), len(grid[0]) index = [[i,j] for i in range(m) for j in range(n) if grid[i][j] == 1] max_term = 0 for loc in index: row, col = loc[0], loc[1] grid[row][col] = 0 max_term = max(max_term, search(row, col, grid[:], 1)) grid[row][col] = 1 return max_term if __name__ == "__main__": a = Solution() print(a.maxAreaOfIsland( [[0,0,1,0,0,0,0,1,0,0,0,0,0], [0,0,0,0,0,0,0,1,1,1,0,0,0], [0,1,1,0,1,0,0,0,0,0,0,0,0], [0,1,0,0,1,1,0,0,1,0,1,0,0], [0,1,0,0,1,1,0,0,1,1,1,0,0], [0,0,0,0,0,0,0,0,0,0,1,0,0], [0,0,0,0,0,0,0,1,1,1,0,0,0], [0,0,0,0,0,0,0,1,1,0,0,0,0]]))
1fa0995dcf2c1f58e42c542e5cdc31c02bad6be1
isabella0428/Leetcode
/python/141.py
1,132
3.953125
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution1: def hasCycle(self, head): """ :type head: ListNode :rtype: bool """ dict = {} # for address while head: if id(head) in dict: #address of head return True # circle dict[id(head)] = 1 head = head.next return False class Solution2: #fast runner and slow runner def hasCycle(self, head): """ :type head: ListNode :rtype: bool """ if not head or not head.next: return False fast_runner = head slow_runner = head.next while slow_runner != fast_runner: if not fast_runner: return False slow_runner = slow_runner.next fast_runner = fast_runner.next return True
cc17363e0989be93f817691c1b64e6968091eb8b
isabella0428/Leetcode
/python/81.py
2,919
3.609375
4
class MySolution: pivot = 0 ans = False def search(self, nums, target): """ :type nums: List[int] :type target: int :rtype: bool """ def findPivot(start, end, nums): if start == end: return mid = (start + end) >> 1 if nums[mid] < nums[mid - 1]: self.pivot = mid return if nums[mid] > nums[mid + 1]: self.pivot = mid + 1 return if nums[mid] > nums[start]: return findPivot(mid + 1, end, nums) else: return findPivot(start, mid - 1, nums) def binarySearch(start, end, nums, target): if start > end: return mid = start + end >> 1 if nums[mid] == target: self.ans = True return if nums[mid] > target: return binarySearch(0, mid - 1, nums, target) else: return binarySearch(mid + 1, end, nums, target) def removeDuplicate(nums): prev = nums[0] if len(nums) == 1: return i = 1 while i < len(nums): item = nums[i] if item == prev: nums.pop(i) else: prev = item i += 1 if not nums: return False removeDuplicate(nums) if nums[len(nums) - 1] <= nums[0]: findPivot(0, len(nums) - 1,nums) if target == nums[self.pivot]: self.ans = True elif nums[0] > target > nums[self.pivot]: binarySearch(self.pivot + 1, len(nums) - 1, nums, target) else: binarySearch(0, self.pivot, nums, target) else: if target == nums[self.pivot]: self.ans = True elif target > nums[self.pivot]: binarySearch(self.pivot + 1, len(nums) - 1, nums, target) else: binarySearch(0, self.pivot, nums, target) return self.ans class Solution: def search(self, nums, target): l, r = 0, len(nums) - 1 mid = l + r >> 1 while l <= r: while l < mid and nums[l] == nums[mid]: l += 1 if nums[mid] == target: return True if nums[l] <= nums[mid]: if nums[l] <= target < nums[mid]: r = mid - 1 else: l = mid + 1 else: if nums[mid] < target <= nums[r]: l = mid + 1 else: r = mid - 1 mid = l + r >> 1 return False if __name__ == "__main__": a = Solution() print(a.search([1, 3, 5], 1))
734b98d18f175109c48e16afeec4b64cdea4d0ac
isabella0428/Leetcode
/python/413.py
890
3.671875
4
class Solution1: def numberOfArithmeticSlices(self, A: 'List[int]') -> 'int': # dynamic programming memo = [0 for i in range(len(A))] if len(A) < 3: return 0 sum = 0 for i in range(2, len(A)): if A[i] - A[i - 1] == A[i - 1] - A[i - 2]: memo[i] = memo[i - 1] + 1 sum += memo[i] return sum class Solution2: def numberOfArithmeticSlices(self, A: 'List[int]') -> 'int': # dp with constant spaces dp = 0 if len(A) < 3: return 0 sum = 0 for i in range(2, len(A)): if A[i] - A[i - 1] == A[i - 1] - A[i - 2]: dp += 1 sum += dp else: dp = 0 return sum if __name__ == "__main__": a = Solution2() print(a.numberOfArithmeticSlices([1, 2, 3, 4]))
dac3c5e2a9f05e6ac34168e145ccb5b25f3d854f
isabella0428/Leetcode
/python/217.py
794
3.515625
4
class Solution1: def containsDuplicate(self, nums) -> bool: if len(nums) < 2: return False min_term = min(nums) for i in range(len(nums)): nums[i] += - min_term max_term = max(nums) stack = [-1 for i in range(max_term + 1)] for item in nums: if stack[item] != -1: return True else: stack[item] = item return False class Solution2: def containsDuplicate(self, nums) -> bool: nums.sort() prev = None for item in nums: if item == prev: return True prev = item return False if __name__ == "__main__": a = Solution2() print(a.containsDuplicate([-1200000000,-1200000005]))
bc860577a7a9c6466fb1cf604dae49dcb08f89df
isabella0428/Leetcode
/python/86.py
904
3.609375
4
class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def partition(self, head: 'ListNode', x: 'int') -> 'ListNode': num = [] while head: num.append(head.val) head = head.next loc = 0 for i in range(len(num)): d = num[i] if d < x: num = num[:i] + num[i + 1:] num.insert(loc, d) loc += 1 node = prev = ListNode(0) for item in num: node.next = ListNode(item) node = node.next return prev.next if __name__ == "__main__": a = Solution() node = head = ListNode(1) val = [4, 3, 2, 5, 2] for item in val: node.next = ListNode(item) node = node.next node = a.partition(head, 3) while node: print(node.val) node = node.next
24ab2e2b98b68d9b357a49b1c9816d1ee5cc9ba2
isabella0428/Leetcode
/python/22.py
1,845
3.640625
4
class Solution1: def __init__(self): self.result = [] def isValid(self, s): """ :type s: str :rtype: bool """ bal = 0 # if bal < 0 and bal !=0 at last returns False for i in s: if i == '(': bal += 1 else: bal -= 1 if bal < 0: return False return bal == 0 def generateParenthesis(self, n): """ :type n: int :rtype: List[str] """ strs = "" self.Recursive(strs, 0, 0, n) return self.result def Recursive(self, strs, nums, cur, n): if len(strs) == 2*n: if self.isValid(strs): self.result.append(strs) return self.result return else: for j in range(2): if j == 0: if cur - nums == n: continue self.Recursive(strs + '(', nums, cur + 1, n) else: if cur == 0: continue if nums == n: continue nums += 1 self.Recursive(strs + ')', nums, cur + 1, n) class Solution2: def generateParenthesis(self, n: 'int') -> 'List[str]': def recursive(tmp, left, right): nonlocal result if left == right == 0: result.append(tmp) return if 0 < left < n + 1: recursive(tmp + '(', left - 1, right) if right > left: recursive(tmp + ')', left, right - 1) result = [] recursive("", n, n) return result if __name__ == "__main__": a = Solution2() print(a.generateParenthesis(3))
f4ce8e0353739753200f9742ff5be3ca3a971651
isabella0428/Leetcode
/python/5.py
1,339
3.546875
4
class Solution: def longestPalindrome(self, s): """ :type s: str :rtype: str """ def expandAroundElement(index, s): left = index - 1 right = index + 1 ans = str(s[index]) while left >= 0 and right < len(s): if s[left] == s[right]: ans = s[left] + ans + s[right] left -= 1 right += 1 else: break return ans def expandAroundSpace(index, s): left = index - 1 right = index ans = '' while left >= 0 and right < len(s): if s[left] == s[right]: ans = s[left] + ans + s[right] left -= 1 right += 1 else: break return ans ans = '' for i in range(len(s)): center = expandAroundElement(i, s) space = expandAroundSpace(i, s) if len(center) > len(ans): ans = center if len(space) > len(ans): ans = space return ans if __name__ == "__main__": a = Solution() print(a.longestPalindrome("babad"))
eae3eb282eb9ea947d758ea1c59a3c4e0b2d0a85
isabella0428/Leetcode
/python/17.py
2,002
3.546875
4
class Solution1: def __init__(self): self.result = [] def letterCombinations(self, digits): """ :type digits: str :rtype: List[str] """ strs = [] s = [] dict = {2:['a','b','c'], 3:['d','e','f'], 4:['g','h','i'], 5:['j','k','l'], 6:['m','n','o'], 7:['p','q','r','s'], 8:['t','u','v'], 9:['w','x','y','z']} for i in digits: s.append(dict[int(i)]) length = len(s) self.Recursive(s, 0, length) return self.result def Recursive(self, s, i, length, ans=""): if i == length: self.result.append(ans) else: for p in s[i]: ans += p self.Recursive(s, i + 1, length, ans) ans = ans[:-1] class Solution2: def __init__(self): self.result = [] def digitLetter(self, digit): if digit == '1': return [] elif digit == '2': return ['a', 'b', 'c'] elif digit == '3': return ['d', 'e', 'f'] elif digit == '4': return ['g', 'h', 'i'] elif digit == '5': return ['j', 'k', 'l'] elif digit == '6': return ['m', 'n', 'o'] elif digit == '7': return ['p', 'q', 'r', 's'] elif digit == '8': return ['t', 'u', 'v'] else: return ['w', 'x', 'y', 'z'] def recursive(self, tmp, digits): if not digits: self.result.append(tmp) return for char in self.digitLetter(digits[0]): self.recursive(tmp + char, digits[1:]) def letterCombinations(self, digits: 'str') -> 'List[str]': """ :type digits: str :rtype: List[str] """ if not digits: return [] self.recursive("", digits) return self.result if __name__ == "__main__": a = Solution2() print(a.letterCombinations("23"))
bfc6f9541b8b93b9eee437c24594552e1bc9da45
isabella0428/Leetcode
/python/34.py
1,804
3.6875
4
class Solution: def searchRange(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ def binarySearch(nums, start, end, ans, target): if start > end: return if nums[start] > target or nums[end] < target: return medium = int((start + end) / 2) if nums[medium] < target: start = medium + 1 return binarySearch(nums, start, end, ans, target) elif nums[medium] > target: end = medium - 1 return binarySearch(nums, start, end, ans, target) else: if medium < ans[0]: ans[0] = medium if medium > ans[1]: ans[1] = medium binarySearch(nums, start, medium - 1, ans,target) binarySearch(nums, medium + 1, end, ans, target) if not nums: return [-1, -1] ans = [float('inf'), -1] start, end = 0, len(nums) - 1 medium = int((start + end) / 2) if nums[medium] < target: start = medium + 1 binarySearch(nums, start, end, ans, target) elif nums[medium] > target: end = medium - 1 binarySearch(nums, start, end, ans, target) else: if medium < ans[0]: ans[0] = medium if medium > ans[1]: ans[1] = medium binarySearch(nums, start, medium - 1, ans, target) binarySearch(nums, medium + 1, end, ans, target) if ans == [float('inf'), -1]: return [-1, -1] return ans if __name__ == "__main__": a = Solution() print(a.searchRange([1], 1))
eb7bdb086ac0f1932e9b66811db53f1d8957818d
isabella0428/Leetcode
/python/847.py
743
3.515625
4
class Solution: def shortestPathLength(self, graph): # use bits to represent states N = len(graph) dp = [[float('inf') for i in range(N)] for j in range(1 << N)] q = [] for i in range(N): dp[1 << i][i] = 0 q.append([1 << i, i]) while q: state, node = q.pop(0) step = dp[state][node] for k in graph[node]: new_state = state | (1 << k) if dp[new_state][k] == float('inf'): dp[new_state][k] = step + 1 q.append([new_state, k]) return min(dp[-1]) if __name__ == "__main__": a = Solution() print(a.shortestPathLength([[1, 2, 3],[0], [0], [0]]))
c59b550736aeef6603de8b7406839051f495e7b6
isabella0428/Leetcode
/python/35.py
1,106
3.875
4
class Solution1(object): def searchInsert(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ for i in range(len(nums)): if target == nums[i]: return i if target < nums[i]: return i return i + 1 class Solution2: def searchInsert(self, nums, target) -> int: def binarySearch(l, r, nums, target): mid = l + r >> 1 if nums[mid] == target: return mid elif nums[mid] > target: r = mid - 1 if nums[r] < target: return r + 1 else: l = mid + 1 if nums[l] > target: return l return binarySearch(l, r, nums, target) if target > nums[-1]: return len(nums) if target < nums[0]: return 0 return binarySearch(0, len(nums) - 1, nums, target) if __name__ == "__main__": a = Solution2() print(a.searchInsert([1, 3, 5, 6], 7))
9ebdf9b2d26b2f720896b0281362f4f08318955f
isabella0428/Leetcode
/python/680.py
512
3.6875
4
class Solution: #greedy def validPalindrome(self, s): """ :type s: str :rtype: bool """ def isPali(s, i, j): return all(s[k] == s[j - k + i] for k in range(i, j)) for i in range(len(s)): if s[i] != s[~i]: # ~i = -(i + 1) j = len(s) - 1 - i return isPali(s, i + 1, j) or isPali(s, i, j - 1) return True if __name__ == "__main__": a = Solution() print(a.validPalindrome('abc'))
667e87890af57db213b90fa41a5027e46a404cfe
OliverOC/countryScratchMap
/functionLib.py
6,634
4
4
import json import os import matplotlib.pyplot as plt import pandas as pd from collections import defaultdict def if_no_json_create_new(file_name): """ This function checks whether a JSON file exists under the given file name. If no JSON file exists, a new one is created. :param file_name: Name of the JSON file to be created. """ if os.path.exists(str(file_name)+'.json'): pass else: empty_dict = {} with open((str(file_name))+'.json', 'w') as f: json.dump(empty_dict, f) def add_countries(file_name): """ This function adds a country and the year visited into the JSON file through user input. :param file_name: Name of the JSON file to add a country and year to. """ add_more = True while add_more: with open((str(file_name))+'.json', 'r') as f: countries = json.load(f) accepted_country = False while not accepted_country: def check_country(country_to_check): """ This function checks whether the inputted country is a real country by comparing to a JSON file containing all the allowed countries in the world. :param country_to_check: The name of the country to check :return: Returns True or False """ with open('country_list.json', 'r') as f2: countries_json = json.load(f2) if country_to_check.title() in countries_json.keys(): accepted = True return accepted else: accepted = False print('Error: country not recognised. ' 'This might be due to a spelling error.') see_list = input('Press ''L'' to see a list of all countries, or press ''X'' to continue...') if see_list.lower() == 'l': string_countries_list = [str(x) for x in sorted(countries_json.keys())] print(string_countries_list) elif see_list.lower() == 'x': pass return accepted input_country = input('What country did you visit?:') accepted_country = check_country(input_country) input_year = input('What year did you visit? (if multiple visits include list, e.g. 2010, 2016):') split_input_years = input_year.split(',') split_input_years_strip = [int(i.strip()) for i in split_input_years] if input_country.title() in countries.keys(): for year in range(len(split_input_years_strip)): countries[input_country.title()].append(split_input_years_strip[year]) else: countries[input_country.title()] = split_input_years_strip with open((str(file_name)+'.json'), 'w') as f: json.dump(countries, f) add_again = input("Would you like to add another country?(Y or N):") if add_again.lower() == 'y': add_more = True elif add_again.lower() == 'n': add_more = False def rearrange_dict_by_country(json_file_name, new_file_name): """ This function creates a new JSON file with the year as the key and the countries as the values. :param json_file_name: The name of the file containing the country: years information :param new_file_name: The new JSON file to be created in the format of year: countries """ with open((str(json_file_name)+'.json'), 'r') as f: dictionary = json.load(f) dictionary_values = list(dictionary.values()) dictionary_keys = list(dictionary.keys()) dictionary_keys_new_list = [] dictionary_values_new_list = [] for i in range(len(dictionary_keys)): if len(dictionary_values[i]) > 1: for ii in range(len(dictionary_values[i])): dictionary_keys_new_list.append(dictionary_values[i][ii]) dictionary_values_new_list.append(dictionary_keys[i]+str(ii+1)) else: dictionary_keys_new_list.append(dictionary_values[i][0]) dictionary_values_new_list.append(dictionary_keys[i]) new_dictionary = dict(zip(dictionary_values_new_list, dictionary_keys_new_list)) new_dictionary_inverted = defaultdict(list) {new_dictionary_inverted[v].append(k) for k, v in new_dictionary.items()} with open((str(new_file_name)+'.json'), 'w') as f2: json.dump(new_dictionary_inverted, f2) def extract_country_by_year(file_name, year, include_none=False): """ This function allows the user to extract all the countries visited in a given year or a range of years. :param file_name: The name of the JSON file containing the information in the year: countries format :param year: year or range of years to be extracted :param include_none: the returned list will append an empty string for all years where no country was visited :return: A list where each element is a list of countries visited in the years corresponding to the input years """ with open(str(file_name)+'.json') as f: countries_by_year = json.load(f) if type(year) == int: if str(year) in list(countries_by_year.keys()): output = countries_by_year[str(year)] return output else: print('no countries visited in ' + str(year)) elif type(year) == list: output_countries = [] for i in range(len(year)): if str(year[i]) in list(countries_by_year.keys()): output_countries.append(countries_by_year[str(year[i])]) else: if include_none: output_countries.append('') else: print('no countries visited in ' + str(year[i])) return output_countries def plot_by_year(years, countries): """ This function plots the number of countries visited per year. :param years: A list of years of interest :param countries: A list of the corresponding countries visited each year """ country_number = [] for i in range(len(countries)): if countries[i] == "": country_number.append(0) else: country_number.append(len(countries[i])) plt.bar(years, country_number, color='green', width=1, align='center') plt.xlabel('Year', labelpad=20, fontsize=20) plt.xticks(years, rotation=90) plt.ylabel('Countries Visited', labelpad=20, fontsize=20) plt.yticks(range(0, max(country_number) + 2)) plt.show()
d089ecb536c7d01e7387f82dbe93da65da98358c
yogabull/TalkPython
/WKUP/loop.py
925
4.25
4
# This file is for working through code snippets. ''' while True: print('enter your name:') name = input() if name == 'your name': break print('thank you') ''' """ name = '' while name != 'your name': name = input('Enter your name: ') if name == 'your name': print('thank you') """ import random print('-----------------') print(' Number Game') print('-----------------') number = random.randint(0, 100) guess = '' while guess != number: guess = int(input('Guess a number between 1 and 100: ')) if guess > number: print('Too high') print(number) if guess < number: print('Too low') print(number) if guess == number: print('Correct') print(number) print('---------------------') print(' f-strings') print('---------------------') name = input('Please enter your name: ') print(f'Hi {name}, it is nice to meet you.')
8837287f4ef533b32c594b35c8b432216cb8c628
yogabull/TalkPython
/ex3_birthday_program/ex3_program_birthday.py
1,221
4.28125
4
"""This is a birthday app exercise.""" import datetime def main(): print_header() bday = get_user_birthday() now = datetime.date.today() td = compute_user_birthday(bday, now) print_birthday_info(td) def print_header(): print('-----------------------------') print(' Birthday App') print('-----------------------------') print() def get_user_birthday(): print("When is your birthday?") year = int(input('Year [YYYY]: ')) month = int(input('Month [MM]: ')) day = int(input('Day [DD]: ')) bday = datetime.date(year, month, day) return bday def compute_user_birthday(original_date, today): # this_year = datetime.date( # year=today.year, month=original_date.month, day=original_date.day) """ Refactored below.""" this_year = datetime.date( today.year, original_date.month, original_date.day) td = this_year - today return td.days def print_birthday_info(days): if days > 0: print(f"Your birthday is in {days} days.") elif days < 0: print(f"Your birtdahy was {-days} days ago.") else: print("Happy Birthday!") print() print('-----------------------------') main()
ce930feff941e3e78f9629851ce0c8cc08f8106b
yogabull/TalkPython
/WKUP/fStringNotes.py
694
4.3125
4
#fString exercise from link at bottom table = {'John' : 1234, 'Elle' : 4321, 'Corbin' : 5678} for name, number in table.items(): print(f'{name:10} --> {number:10d}') # John --> 1234 # Elle --> 4321 # Corbin --> 5678 ''' NOTE: the '10' in {name:10} means make the name variable occupy at least 10 spaces. This is useful for making columns align. ''' ''' f-Strings: Another method to output varibles within in a string. Formatted String Literals This reads easily. year = 2019 month = 'June' f'It ends {month} {year}.' >>> It ends June 2019. https://docs.python.org/3/tutorial/inputoutput.html#tut-f-strings '''
77ddf7f2e6d19a20ca71862d7507a72ed1cde4bd
rohitgang/MATH471
/rank_matrices.py
1,677
3.75
4
""" (Ranks of random matrices) Generate square (n x n) matrices with random entries (for instance Gaussian or uniform random entries). For each n belonging to {10,20,30,40,50}, run 100 trials and report the statistics of the rank of the matrix generated for each trial (mean, median, min, max). What do you notice? Please turn in the code you used to produce the data. """ import numpy as np def answer(n): # Dictionary to store the statistics of the matrices stats = {'rank': list(), 'mean': list(), 'median': list(), 'min': list(), 'max': list()} for i in range(100): # random generated square matrix matrix = np.random.rand(n, n) # appending the required statistics to the dictionary stats['rank'].append(np.linalg.matrix_rank(matrix)) stats['mean'].append(np.mean(matrix)) stats['median'].append(np.median(matrix)) stats['min'].append(matrix.min()) stats['max'].append(matrix.max()) # returning a tuple of the mean value of required statistics return (np.mean(stats['rank']), np.mean(stats['mean']), np.mean(stats['median']), np.mean(stats['min']), np.mean(stats['max'])), stats # different dimensions for the matrices set_of_ns = [10,20,30,40,50] # dictionary to append statistics for each n answer_dict = {n : None for n in set_of_ns} for n in set_of_ns: avg_stats, stats = answer(n) intermediate_dict = {'avg': avg_stats, 'stats': stats} answer_dict[n] = intermediate_dict for key, val in answer_dict.items(): avg = val['avg'] print('key :', key, '-- ', avg)
8a07ac0097bdfa92665a85be956b5dfc40b217dc
gregor42/python-for-the-stoopid
/diction.py
733
3.640625
4
#!/usr/local/bin/python # # diction.py - playing with dictionaries # import pri filename = 'templ8.py' # Say hello to the Nice People pri.ntc(filename + " : Start.") pri.bar() D = {'a': 1, 'b': 2, 'c': 3} pri.ntc(D) pri.bar() D['e']=42 pri.ntc(D) pri.bar() #underfined value will break #print D['f'] pri.ntc('f' in D) pri.bar() if not 'f' in D: pri.ntc("f is missing") pri.ntc("no really") pri.bar() pri.ntc(D.get('x',-1)) pri.bar() Ks = list(D.keys()) pri.ntc(Ks) pri.bar() Ks.sort() pri.ntc(Ks) pri.bar() for key in sorted(D): print(key, '=>', D[key]) pri.bar() for c in 'spam spam spam': print(c.upper()) pri.bar() x = 4 while x > 0: print('spam! ' * x) x -= 1 pri.bar() pri.ntc("Done.")
3a3bf87bc7aeede084d8df8e78331110b8f3e441
zumioo/tweet
/remove.py
1,203
3.671875
4
""" 使うときはコメントアウト外してね import tweepy import calendar import random import time def main(): consumer_key = 'XXXXX' consumer_secret = 'XXXXX' access_token_key = 'XXXXX' access_token_secret = 'XXXXX' auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token_key, access_token_secret) api = tweepy.API(auth) my_user_id = api.me().id_str #自分のidを取得 follower_list = list(api.followers_ids(my_user_id))#自分のフォロワーを取得 friend_list = list(api.friends_ids(my_user_id))#自分がフォローしている人を取得 remove(api,follower_list,friend_list) #フォロバしてくれない人のフォローを外す def remove(api,follower_list,friend_list): result = list(set(friend_list) - set(follower_list))#差分を計算 if not result == []: for un_follower in result: api.destroy_friendship(un_follower) print(api.get_user(un_follower).screen_name + 'のフォローを外しました。') else: print("おじいさんをフォローバックしていないフォロワーはいません。") main() """
f08ec1974b033d5bd56b64b764f23541a811acbc
febin72/LearnPython
/oddoreven.py
149
4.28125
4
''' Find even or odd ''' import math print ('enter the number') x= int(input()) if (x%2==0): print ('the number is even') else: print('odd')
2550c545f6f0f73faef10670b3dde6f2235b21a1
febin72/LearnPython
/strings.py
509
3.9375
4
''' play with strings ''' import string print ('enter a string') a = str(input()) print ('ented one more string') one_more_string = str(input()) print ('entered strings length is ' , len(a) , len(one_more_string)) #print (a[2:6]) #print ('The length of the string entered is' ,len(a+one_more_string)) newstring = a + one_more_string print ('new string is' , newstring) split_line=(newstring.split('m')) print (split_line) print (split_line[1]) #while split_line != 'n': #print ('febin') #break
c7fc3ced3296f7e181ba9714534800b59d20dd53
thevirajshelke/python-programs
/Basics/subtraction.py
586
4.25
4
# without user input # using three variables a = 20 b = 10 c = a - b print "The subtraction of the numbers is", c # using 2 variables a = 20 b = 10 print "The subtraction of the numbers is", a - b # with user input # using three variables a = int(input("Enter first number ")) b = int(input("Enter first number ")) c = a - b print "The subtraction of the numbers is", c # using 2 variables # int() - will convert the input into numbers if string is passed! a = int(input("Enter first number ")) b = int(input("Enter first number ")) print "The subtraction of the numbers is", a - b
ef45e2377ab4276345644789a17abdd20da69aca
johnehunt/computationalthinking
/week4/tax_calculator.py
799
4.3125
4
# Program to calculate tax band print('Start') # Set up 'constants' to be used BASIC_RATE_THRESHOLD = 12500 HIGHER_RATE_THRESHOLD = 50000 ADDITIONAL_RATE_THRESHOLD = 150000 # Get user input and a number income_string = input('Please input your income: ') if income_string.isnumeric(): annual_income = int(income_string) # Determine tax band if annual_income > ADDITIONAL_RATE_THRESHOLD: print('Calculating tax ...') print('Your highest tax rate is 45%') elif annual_income > HIGHER_RATE_THRESHOLD: print('Your highest tax rate is 40%') elif annual_income > BASIC_RATE_THRESHOLD: print('Your highest tax rate is 20%') else: print('You are not liable for income tax') else: print('Input must be a positive integer') print('Done')
fecc9d49fc1df51d7b793fb052c8defcbc86300e
johnehunt/computationalthinking
/week1/exammarks/main3.py
633
3.9375
4
# Alternative solution using compound conditional statement component_a_mark = int(input('Please enter your mark for Component A: ')) coursework_mark = int(input('Please enter your mark for Component B: ')) # Calculating mark by adding the marks together and dividing by 2 module_mark = (component_a_mark + coursework_mark) / 2 print('Your mark is', module_mark, 'Calculating your result') # Uses compound boolean proposition if coursework_mark < 35 and component_a_mark < 35: print('You have not passed the module') elif module_mark < 40: print('You have failed the module') else: print('You have passed the module')
8d7ca111c403010de98909a1850ae5f7a1d54b2b
johnehunt/computationalthinking
/number_guess_game/number_guess_game_v2.py
1,262
4.34375
4
import random # Print the Welcome Banner print('===========================================') print(' Welcome to the Number Guess Game') print(' ', '-' * 40) print(""" The Computer will ask you to guess a number between 1 and 10. """) print('===========================================') # Initialise the number to be guessed number_to_guess = random.randint(1, 10) # Set up flag to indicate if one game is over finished_current_game = False # Obtain their initial guess and loop to see if they guessed correctly while not finished_current_game: guess = None # Make sure input is a positive integer input_ok = False while not input_ok: input_string = input('Please guess a number between 1 and 10: ') if input_string.isdigit(): guess = int(input_string) input_ok = True else: print('Input must be a positive integer') # Check to see if the guess is above, below or the correct number if guess < number_to_guess: print('Your guess was lower than the number') elif guess > number_to_guess: print('Your guess was higher than the number') else: print('Well done you won!') finished_current_game = True print('Game Over')
0f25b7552ca48fbdc04ee31bd873d899ffae26c6
johnehunt/computationalthinking
/week4/forsample.py
813
4.34375
4
# Loop over a set of values in a range print('Print out values in a range') for i in range(0, 10): print(i, ' ', end='') print() print('Done') print('-' * 25) # Now use values in a range but increment by 2 print('Print out values in a range with an increment of 2') for i in range(0, 10, 2): print(i, ' ', end='') print() print('Done') print('-' * 25) # This illustrates the use of a break statement num = int(input('Enter a number: ')) for i in range(0, 6): if i == num: break print(i, ' ', end='') print('Done') print('-' * 25) # This illustrates the use of a continue statement for i in range(0, 10): print(i, ' ', end='') if i % 2 == 1: # Determine if this is an odd number continue print('its an even number') print('we love even numbers') print('Done')
0e6908ec30831e4ea0218e8af6b0605dae3cef78
johnehunt/computationalthinking
/week4/ranges.py
171
4.1875
4
for i in range(1, 10): print(i, end=', ') print() for i in range(0, 10, 2): print(i, ' ', end='') print() for i in range(10, 1, -2): print(i, ' ', end='')
3a3069f8e96bf2bdcf973dececffb43dc0ca59c4
johnehunt/computationalthinking
/week2/numbers.py
1,867
3.734375
4
x = 1 print(x) print(type(x)) x = 10000000000000000000000000000000000000000000000000000000000000001 print(x) print(type(x)) home = 10 away = 15 print(home + away) print(type(home + away)) print(10 * 4) print(type(10 * 4)) goals_for = 10 goals_against = 7 print(goals_for - goals_against) print(type(goals_for - goals_against)) print(100 / 20) print(type(100 / 20)) res1 = 3 / 2 print(res1) print(type(res1)) print('-' * 10) res1 = 3 // 2 print(res1) print(type(res1)) a = 5 b = 3 print(a ** b) print('Modulus division 4 % 2:', 4 % 2) print('Modulus division 3 % 2:', 3 % 2) print('True division 3/2:', 3 / 2) print('True division -3/2:', -3 / 2) print('Integer division 3//2:', 3 // 2) print('Integer division -3//2:', -3 // 2) int_value = 1 string_value = '1.5' float_value = float(int_value) print('int value as a float:', float_value) print(type(float_value)) float_value = float(string_value) print('string value as a float:', float_value) print(type(float_value)) print('*' * 10) age = int(input('Please enter your age: ')) print(type(age)) print(age) print('*' * 10) exchange_rate = float(input("Please enter the exchange rate to use: ")) print(exchange_rate) print(type(exchange_rate)) print(float(1)) print(int(exchange_rate)) print(2.3 + 1.5) print(1.5 / 2.3) print(1.5 * 2.3) print(2.3 - 1.5) print(1.5 - 2.3) print(12.0 // 3.0) i = 3 * 0.1 print(i) print('+' * 10) f = 3.2e4 + 0.00002e-6 formatString = "%16.20g" print(formatString % f) print(type(f)) c1 = 1j c2 = 2j print('c1:', c1, ', c2:', c2) print(type(c1)) print(c1.real) print(c1.imag) c3 = c1 * c2 print(c3) print('=' * 10) all_ok = True print(all_ok) all_ok = False print(all_ok) print(type(all_ok)) print(int(True)) print(int(False)) print(bool(1)) print(bool(0)) status = bool(input('OK to proceed: ')) print(status) print(type(status)) x = 0 x += 1 print('x =', x)
2acb0005b760b130fc4c553b8f9595c91b828c0e
tainagdcoleman/sharkid
/helpers.py
2,892
4.125
4
from typing import Tuple, List, Dict, TypeVar, Union import scipy.ndimage import numpy as np import math Num = TypeVar('Num', float, int) Point = Tuple[Num, Num] def angle(point: Point, point0: Point, point1: Point) -> float: """Calculates angles between three points Args: point: midpoint point0: first endpoint point1: second endpoint Returns: angle between three points in radians """ a = (point[0] - point0[0], point[1] - point0[1]) b = (point[0] - point1[0], point[1] - point1[1]) adotb = (a[0] * b[0] + a[1] * b[1]) return math.acos(adotb / (magnitude(a) * magnitude(b))) def find_angles(points: List[Point])-> List[float]: """Finds angles between all points in sequence of points Args: points: sequential list of points Returns: angles in radians """ return angle(points[len(points) // 2], points[0], points[-1]) def magnitude(point: Point) -> float: """Finds the magnitude of a point, as if it were a vector originating at 0, 0 Args: point: Point (x, y) Returns: magnitude of point """ return math.sqrt(point[0]**2 + point[1]**2) def dist_to_line(start: Point, end: Point, *points: Point, signed=False) -> Union[float, List[float]]: """Finds the distance between points and a line given by two points Args: start: first point for line end: second point for line points: points to find distance of. Returns: A single distance if only one point is provided, otherwise a list of distances. """ start_x, start_y = start end_x, end_y = end dy = end_y - start_y dx = end_x - start_x m_dif = end_x*start_y - end_y*start_x denom = math.sqrt(dy**2 + dx**2) _dist = lambda point: (dy*point[0] - dx*point[1] + m_dif) / denom dist = _dist if signed else lambda point: abs(_dist(point)) if len(points) == 1: return dist(points[0]) else: return list(map(dist, points)) def gaussian_filter(points:List[Point], sigma=0.3): return scipy.ndimage.gaussian_filter(np.asarray(points), sigma) def distance(point1: Point, point2: Point): x1, y1 = point1 x2, y2 = point2 return math.sqrt((x2 - x1)**2 + (y2 - y1)**2) def coord_transform(points: List[Tuple[int, int]])-> float: start_x, start_y = points[0] end_x, end_y = points[-1] inner = points[1:-1] perp_point_x = start_x - (end_y - start_y) perp_point_y = start_y + (end_x - start_x) ys = dist_to_line((start_x, start_y), (end_x, end_y), *inner, signed=True) xs = dist_to_line((start_x, start_y), (perp_point_x, perp_point_y), *inner, signed=True) return xs, ys def remove_decreasing(xs, ys): maxx = xs[0] for x, y in zip(xs, ys): if x > maxx: yield x, y maxx = x
33a375ed2fb0b278b1304dffb4815c4cfdf67982
rose60730422/writingTest
/writingTest.py
696
3.84375
4
def reverseString(t): reverseString = t[::-1] return reverseString def reverseWords(s): s = s.split(" ") for index, word in enumerate(s) : s[index] = reverseString(word) r = ' '.join(s) return r def countingFactor(n): cnt = 0 for i in range(n): if ((i+1) % 3 == 0) and ((i+1) % 5 == 0): cnt = cnt + 1 elif ((i+1) % 3 != 0) and ((i+1) % 5 != 0): cnt = cnt + 1 return cnt text_A = input('Please enter your string : ') print(reverseString(text_A)) text_B = input('Please enter your sentence : ') print(reverseWords(text_B)) number = input('Please enter your number : ') print(countingFactor(int(number)))
0438c1b364eae318c527df99ea6b1959489e0fce
lakshmanboddoju/Automate_the_boring_stuff_with_python
/11/31-hello_txt_read.py
867
3.734375
4
#! python3 import shelve # Read Operation helloFile = open('C:\\Users\\lakshman\\Desktop\\hello.txt') #helloFileContent = helloFile.read() #print(helloFileContent) print(helloFile.readlines()) helloFile.close() # Write Operation helloFile2 = open('C:\\Users\\lakshman\\Desktop\\hello2.txt', 'w') helloFile2.write('YOLO!\n') helloFile2.write('You Rock!\n') helloFile2.close() # Append Operation helloFile3 = open('C:\\Users\\lakshman\\Desktop\\hello3.txt', 'a') helloFile3.write('YOLO!\n') helloFile3.write('You Rock!\n') helloFile3.close() # Shelve File | Persistent memory for complex stuff to store like lists, etc. shelfFile = shelve.open('mydata') shelfFile['cats'] = ['Zophie', 'Pooka', 'Simon', 'Fat-tail', 'Cleo'] shelfFile.close() shelfFile = shelve.open('mydata') print(shelfFile['cats']) shelfFile.close()
8079ac6be8a7cbfbda9230c0fffeb89170e04f8d
AshWije/Neural-Networks-In-Python
/WithPyTorch/ImageNet_ResNetX_CNN.py
9,451
3.53125
4
################################################################################ # # FILE # # ImageNet_ResNetX_CNN.py # # DESCRIPTION # # Creates a convolutional neural network model in PyTorch designed for # ImageNet modified to 100 classes and downsampled to 3x56x56 sized images # via resizing and cropping. The model is based on the RegNetX image # classifier and modified slightly to fit the modified data. # # Two python classes are defined in this file: # 1. XBlock: The building block used in the model. At stride=1, this block # is a standard building block. At stride=2, this block is a # downsampling building block. # 2. Model: Creates the convolutional neural network model using the # building block class XBlock. # # There are six distinct layers in the model: the stem, encoder level 0, # encoder level 1, encoder level 2, encoder level 3, and the decoder. The # layer details are shown below: # 1. Stem: # Conv(3x3,s=1) # # 2. Encoder level 0: # XBlock(s=1) # # 3. Encoder level 1: # XBlock(s=2) # # 4. Encoder level 2: # XBlock(s=2) # XBlock(s=1) # XBlock(s=1) # XBlock(s=1) # # 5. Encoder level 3: # XBlock(s=2) # XBlock(s=1) # XBlock(s=1) # XBlock(s=1) # XBlock(s=1) # XBlock(s=1) # XBlock(s=1) # # 6. Decoder: # AvgPool # Flatten # Linear # # After being trained for 100 epochs with Adam as the optimizer and a # learning rate schedule of linear warmup followed by cosine decay, the final # accuracy achieved is 70.93%. (Note: training code is not provided in this # file). # ################################################################################ ################################################################################ # # IMPORT # ################################################################################ # torch import torch import torch.nn as nn ################################################################################ # # PARAMETERS # ################################################################################ # data DATA_NUM_CHANNELS = 3 DATA_NUM_CLASSES = 100 # model MODEL_LEVEL_0_BLOCKS = 1 MODEL_LEVEL_1_BLOCKS = 1 MODEL_LEVEL_2_BLOCKS = 4 MODEL_LEVEL_3_BLOCKS = 7 MODEL_STEM_END_CHANNELS = 24 MODEL_LEVEL_0_IDENTITY_CHANNELS = 24 MODEL_LEVEL_1_IDENTITY_CHANNELS = 56 MODEL_LEVEL_2_IDENTITY_CHANNELS = 152 MODEL_LEVEL_3_IDENTITY_CHANNELS = 368 # training TRAINING_DISPLAY = False ################################################################################ # # NETWORK BUILDING BLOCK # ################################################################################ # X block class XBlock(nn.Module): # initialization def __init__(self, Ni, No, Fr=3, Fc=3, Sr=1, Sc=1, G=8): # parent initialization super(XBlock, self).__init__() # identity if ((Ni != No) or (Sr > 1) or (Sc > 1)): self.conv0_present = True self.conv0 = nn.Conv2d(Ni, No, (1, 1), stride=(Sr, Sc), padding=(0, 0), dilation=(1, 1), groups=1, bias=False, padding_mode='zeros') else: self.conv0_present = False # residual self.bn1 = nn.BatchNorm2d(Ni, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) self.relu1 = nn.ReLU() self.conv1 = nn.Conv2d(Ni, No, (1, 1), stride=(1, 1), padding=(0, 0), dilation=(1, 1), groups=1, bias=False, padding_mode='zeros') self.bn2 = nn.BatchNorm2d(No, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) self.relu2 = nn.ReLU() self.conv2 = nn.Conv2d(No, No, (Fr, Fc), stride=(Sr, Sc), padding=(1, 1), dilation=(1, 1), groups=G, bias=False, padding_mode='zeros') self.bn3 = nn.BatchNorm2d(No, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) self.relu3 = nn.ReLU() self.conv3 = nn.Conv2d(No, No, (1, 1), stride=(1, 1), padding=(0, 0), dilation=(1, 1), groups=1, bias=False, padding_mode='zeros') # forward path def forward(self, x): #if TRAINING_DISPLAY: print("\tXBLOCK_INPUT: ", x.shape) # residual res = self.bn1(x) res = self.relu1(res) res = self.conv1(res) #if TRAINING_DISPLAY: print("\tXBLOCK_CONV1: ", res.shape) res = self.bn2(res) res = self.relu2(res) res = self.conv2(res) #if TRAINING_DISPLAY: print("\tXBLOCK_CONV2: ", res.shape) res = self.bn3(res) res = self.relu3(res) res = self.conv3(res) #if TRAINING_DISPLAY: print("\tXBLOCK_CONV3: ", res.shape) # identity if (self.conv0_present == True): x = self.conv0(x) #if TRAINING_DISPLAY: print("\tXBLOCK_CONV0: ", x.shape) # summation x = x + res # return return x ################################################################################ # # NETWORK # ################################################################################ # define class Model(nn.Module): # initialization def __init__(self, data_num_channels, data_num_classes, model_level_0_blocks, model_level_1_blocks, model_level_2_blocks, model_level_3_blocks, model_stem_end_channels, model_level_0_identity_channels, model_level_1_identity_channels, model_level_2_identity_channels, model_level_3_identity_channels): # parent initialization super(Model, self).__init__() # encoder stem self.enc_stem = nn.ModuleList() self.enc_stem.append(nn.Conv2d(data_num_channels, model_stem_end_channels, (3, 3), stride=(1, 1), padding=(1, 1), dilation=(1, 1), groups=1, bias=False, padding_mode='zeros')) # encoder level 0 self.enc_0 = nn.ModuleList() self.enc_0.append(XBlock(model_stem_end_channels, model_level_0_identity_channels)) for n in range(model_level_0_blocks - 1): self.enc_0.append(XBlock(model_level_0_identity_channels, model_level_0_identity_channels)) # encoder level 1 self.enc_1 = nn.ModuleList() self.enc_1.append(XBlock(model_level_0_identity_channels, model_level_1_identity_channels, Sr=2, Sc=2)) for n in range(model_level_1_blocks - 1): self.enc_1.append(XBlock(model_level_1_identity_channels, model_level_1_identity_channels)) # encoder level 2 self.enc_2 = nn.ModuleList() self.enc_2.append(XBlock(model_level_1_identity_channels, model_level_2_identity_channels, Sr=2, Sc=2)) for n in range(model_level_2_blocks - 1): self.enc_2.append(XBlock(model_level_2_identity_channels, model_level_2_identity_channels)) # encoder level 3 self.enc_3 = nn.ModuleList() self.enc_3.append(XBlock(model_level_2_identity_channels, model_level_3_identity_channels, Sr=2, Sc=2)) for n in range(model_level_3_blocks - 1): self.enc_3.append(XBlock(model_level_3_identity_channels, model_level_3_identity_channels)) # encoder level 3 complete the bn - relu pattern self.enc_3.append(nn.BatchNorm2d(model_level_3_identity_channels, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)) self.enc_3.append(nn.ReLU()) # decoder self.dec = nn.ModuleList() self.dec.append(nn.AdaptiveAvgPool2d((1, 1))) self.dec.append(nn.Flatten()) self.dec.append(nn.Linear(model_level_3_identity_channels, data_num_classes, bias=True)) # forward path def forward(self, x): #if TRAINING_DISPLAY: print("MODEL_INPUT: ", x.shape) # encoder stem for layer in self.enc_stem: #if TRAINING_DISPLAY: print("MODEL_ENC_STEM: ", x.shape) x = layer(x) # encoder level 0 for layer in self.enc_0: #if TRAINING_DISPLAY: print("MODEL_ENC0: ", x.shape) x = layer(x) # encoder level 1 for layer in self.enc_1: #if TRAINING_DISPLAY: print("MODEL_ENC1: ", x.shape) x = layer(x) # encoder level 2 for layer in self.enc_2: #if TRAINING_DISPLAY: print("MODEL_ENC2: ", x.shape) x = layer(x) # encoder level 3 for layer in self.enc_3: #if TRAINING_DISPLAY: print("MODEL_ENC3: ", x.shape) x = layer(x) # decoder for layer in self.dec: #if TRAINING_DISPLAY: print("MODEL_DEC: ", x.shape) x = layer(x) # return return x # create model = Model(DATA_NUM_CHANNELS, DATA_NUM_CLASSES, MODEL_LEVEL_0_BLOCKS, MODEL_LEVEL_1_BLOCKS, MODEL_LEVEL_2_BLOCKS, MODEL_LEVEL_3_BLOCKS, MODEL_STEM_END_CHANNELS, MODEL_LEVEL_0_IDENTITY_CHANNELS, MODEL_LEVEL_1_IDENTITY_CHANNELS, MODEL_LEVEL_2_IDENTITY_CHANNELS, MODEL_LEVEL_3_IDENTITY_CHANNELS)
21e93a9e63969f1a8a0ff398cc8b5b1c94668317
dcronin05/timewaster
/main.py
212
3.859375
4
print("Hello world") class AClass(object): def __init__(self, a, b): self.a = a self.b = b def getter(self): return self.a newObj = AClass(3, "hello") print(newObj.getter())
c1c530035fcd38d5b23e00dd66f914206de5d313
iampaavan/Internet_Data_Python
/urllibdata_start.py
910
3.703125
4
# Send data to a server using urllib # TODO: import the request and parse modules import urllib.request import urllib.parse def main(): # url = 'http://httpbin.org/get' url = 'http://httpbin.org/post' # TODO: create some data to pass to the GET request args = { 'Name': 'Paavan Gopala', 'Is_Author': True } # TODO: the data needs to be url-encoded before passing as arguments data = urllib.parse.urlencode(args) # TODO: issue the request with a data parameter as part of the URL #result = urllib.request.urlopen(url + '?' + data) # TODO: issue the request with a data parameter to use POST data = data.encode('utf-8') result = urllib.request.urlopen(url, data=data) print(f"Result Code: {result.status}") print(f"Returned Data ----------------------------------------") print(f"{result.read().decode('utf-8')}") if __name__ == '__main__': main()
0b8333949d8b4a32573cd24b8c83cedd9585e25e
pancham2016/ScubaAdventure
/bubble.py
1,042
3.921875
4
import pygame from pygame.sprite import Sprite class Bubble(Sprite): """A class that manages bubbles released from the diver.""" def __init__(self, sa_game): """create a bubble object at the diver's current position.""" super().__init__() self.screen = sa_game.screen self.settings = sa_game.settings # import the bubble image self.image = pygame.image.load("images/bubble.bmp") self.bubble_rect = self.image.get_rect() self.bubble_rect.topright = sa_game.diver.rect.topright # Store the bubble's position as a decimal value self.y = float(self.bubble_rect.y) def update(self): """Move the bubble up the screen.""" # Update the decimal position of the bubble self.y -= self.settings.bubble_speed # Update the rect position. self.bubble_rect.y = self.y def blit_bubble(self): """Draw the bubble at the diver's current location""" self.screen.blit(self.image, self.bubble_rect.topright)
62d9367a9114d703024070eee7b92f1d4c067f2a
xiaojin9712/data_strcture_review
/two_sum.py
1,005
3.671875
4
A = [-2, 1,2,4,7,11] target = 13 # Time Complexity: O(n^2) # Space Complexity: O(1) def two_sum_brute_force(A, target): for i in range(len(A) - 1): for j in range(i+1, len(A)): if A[i] + A[j] == target: print(A[i], A[j]) return True return False two_sum_brute_force(A, target) # Time Complexity: O(n) # Space Complexity: O(n) def two_sum_hash_table(A, target): ht = dict() for i in range(len(A)): if A[i] in ht: print(ht[A[i]], A[i]) return True else: ht[target - A[i]] = A[i] return False two_sum_hash_table(A, target) # IF THE ARRAY IS SORTED # Time Complexity: O(n) # Space Complexity: O(1) def two_sum(A, target): i = 0 j = len(A) - 1 while i < j: if (A[i] + A[j]) == target: print(A[i], A[j]) return True if (A[i] + A[j]) < target: i += 1 else: j -= 1 return False two_sum(A, target)