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
df273e0b1a4ec97f7884e64e0fe1979623236fb2
bdjilka/algorithms_on_graphs
/week2/acyclicity.py
2,108
4.125
4
# Uses python3 import sys class Graph: """ Class representing directed graph defined with the help of adjacency list. """ def __init__(self, adj, n): """ Initialization. :param adj: list of adjacency :param n: number of vertices """ self.adj = adj self.size = n self.clock = 1 self.post = [0 for _ in range(n)] self.visited = [0 for _ in range(n)] def previsit(self): self.clock += 1 def postvisit(self, v): self.post[v] = self.clock self.clock += 1 def explore(self, v): self.visited[v] = 1 self.previsit() for u in self.adj[v]: if not self.visited[u]: self.explore(u) self.postvisit(v) def deepFirstSearch(self): """ Visits all nodes and marks their post visit indexes. Fills list post[]. """ for v in range(self.size): if not self.visited[v]: self.explore(v) def acyclic(self): """ Checks whether graph has edge in that post visit index of source vertex is less than its end vertex post index. If such edge exists than graph is not acyclic. :return: 1 if there is cycle, 0 in other case. """ self.deepFirstSearch() for v in range(self.size): for u in self.adj[v]: if self.post[v] < self.post[u]: return 1 return 0 if __name__ == '__main__': """ Input sample: 4 4 // number of vertices n and number of edges m, 1 <= n, m <= 1000 1 2 // edge from vertex 1 to vertex 2 4 1 2 3 3 1 Output: 1 // cycle exists: 3 -> 1 -> 2 -> 3 """ input = sys.stdin.read() data = list(map(int, input.split())) n, m = data[0:2] data = data[2:] edges = list(zip(data[0:(2 * m):2], data[1:(2 * m):2])) adj = [[] for _ in range(n)] for (a, b) in edges: adj[a - 1].append(b - 1) graph = Graph(adj, n) print(graph.acyclic())
16753f583825a4a04c044a314ade735202b7076d
ggrecco/python
/basico/zumbis/surfSplitNomeNotas.py
310
3.59375
4
f = open("surf.txt") #maior = 0 notas = [] for linha in f: nome, pontos = linha.split() notas.append(float(pontos)) #if float(pontos) > maior: #maior = float(pontos) f.close() #print(maior) notas.sort(reverse = True) print("1º - {}\n2º - {}\n3º - {}".format(notas[0],notas[1],notas[2]))
e3161b35c014b11888d835507c3eb8de8105b426
ggrecco/python
/basico/zumbis/imprimeParSemIF.py
135
3.953125
4
#imprimir pares de 0 ao digitado sem o if n = int(input("Digite um número: ")) x = 0 while x <= n: print(x, end = " ") x += 2
d8fe9b832e0927a1fe6d869bb10854b4c2d53bee
ggrecco/python
/basico/coursera/verifica_ordenamento_lista.py
198
3.78125
4
def ordenada(lista): b = sorted(lista) print(lista) print(b) if b == lista: return True #print("Iguais") else: return False #print("Diferente")
8c35008e3eafc6f0877dd65325ee051cea3afaf3
ggrecco/python
/basico/zumbis/jogo_2.py
291
3.734375
4
from random import randint secreta = randint(1, 100) while True: chute = int(input("Chute:")) if chute == secreta: print("parabéns, vc acertou o número {}".format(secreta)) break else: print("Alto" if chute > secreta else "Baixo") print("Fim do jogo")
e3d7c97584d737e341caae29dc639be446b80159
ggrecco/python
/basico/zumbis/trocandoLetras.py
311
3.75
4
#ler uma palavra e trocar as vogais por "*" i = 0 troca = "" palavra = input("Palavra: ") j = input("Letra: ") t = input("trocar por: ") while i < len(palavra): if palavra[i] in str(j): troca += t else: troca += palavra[i] i += 1 print("Nova: {}\nAntiga:{}".format(troca,palavra))
3542c66b49e08f505395c9f76b2bbee070677991
ggrecco/python
/basico/coursera/calculadoraVelocidadeDownload_importando_funcao_tempo.py
401
3.75
4
import fun_Tempo def calcVel(k): return k/8 i = 1 while i != 0: n = int(input("Velocidade contratada[(zero) para sair]: ")) t = (float(input("Tamanho do arquivo em MegaBytes: "))) segundos = t / calcVel(n) fun_Tempo.calcTempo(segundos) print("Velocidade máxima de Download {} MB/s\n".format(calcVel(n))) i = n #comentário de modificação nesse 1 arquivo
b49c3aaa2c6ba16a47729c07471b6ca18795fa56
ggrecco/python
/basico/zumbis/latasNecessarias.py
526
3.828125
4
''' usuário informa o tamanho em metros quadrados a ser pintado Cada litro de tinta pinta 3 metros quadrados e a tinta é vendida em latas de 18 litros, que custam R$ 80,00 devolver para o usuário o numero de latas necessárias e o preço total. Somente são vendidas nº inteiro de latas ''' m = float(input("Metros²: ")) if m % 54 != 0:#1 lata tem 18 litros que pintam o total de 54 metros latas = int(m / 54) + 1 else: latas = m / 54 valor = latas * 80 print("{} Latas custando R$ {:.2f}".format(latas,valor))
bd2dbd08dfd85e478fd10e6416536ac6490bdf62
ggrecco/python
/basico/coursera/imprime_retangulo_vazado.py
317
4.03125
4
n = int(input("digite a largura: ")) j = int(input("digite a altura: ")) x = 1 while x <= j: print("#", end="") coluna = 0 while coluna < (n - 2): if x == 1 or x == j: print("#", end="") else: print(end=" ") coluna = coluna + 1 print("#") x = x + 1
59d1bf3ee1afee7ebd9c03797a779f4beae41c18
sohanur-it/programming-solve-in-python3
/cricket-problem.py
476
3.640625
4
#!/usr/bin/python3 T=int(input("Enter the inputs:")) for i in range(1,T+1): RR,CR,RB=input("<required run> <current run> <remaining balls> :").split(" ") RR,CR=[int(RR),int(CR)] RB=int(RB) balls_played=300-RB current_run_rate=(CR/balls_played)*6 current_run_rate=round(current_run_rate,2) print("current run rate:",current_run_rate) required_run_rate=(((RR+1)-CR)/RB)*6 required_run_rate=round(required_run_rate,2) print("required run rate :",required_run_rate)
7971c61b321c45254f4d74d20494dba9b172c5b2
uchicagotechteam/HourVoice
/workbench/data_collection/combine_data.py
2,335
3.71875
4
import json from collections import defaultdict def combine_databases(databases, compared_keys, equality_functions, database_names): ''' @param databases: a list of dicts, where each dict's values should be dictionaries mapping headers to individual data points. For example, [db1, db2] with db1 = {'1': , '2': {'name': 'bar'}} @param compared_keys: a list of lists of corresponding keys to compare. For example, [['name', 'db_name']] would match solely based on comparing the 'name' column of db1 and the 'db_name' column of db2 @param database_names: corresponding names to assign to each database @param equality_functions: binary equality testing functions for each corresponding index of compared_keys, each should return a boolean @return: a combined dict of all the data, using the primary key of the first database as the primary key for the result. For example, with database_names = ['db1', 'db2'], data = {'1': {'db1': {'name': 'foo'}, 'db2': {'db_name': 'Foo'}}, '2': {'db1': {'name': 'bar'}, 'db2': {'db_name': 'Baz'}} Note: all comparisons are done to the first database ''' n = len(databases) if not n: return dict() result = defaultdict(dict) for (key, data) in databases[0].items(): result[key][database_names[0]] = data for (db_keys, equal) in zip(compared_keys, equality_functions): for base_name in databases[0].keys(): base_value = databases[0][base_name][db_keys[0]] for i in range(1,n): for (name, data) in databases[i].items(): test_value = data[db_keys[i]] if equal(base_value, test_value): result[base_name][database_names[i]] = data return result # for name in databases[0].keys(): # result[name] = {db_name: dict() for db_name in database_names} if __name__ == '__main__': db1 = {'A': {'name': 'A', 'id': 1}, 'B': {'name': 'B', 'id': 2}} db2 = {'Ark': {'name2': 'Ark', 'desc': 'I like Noah'}, 'Boo': {'name2': 'Boo', 'desc': 'I like to scare Noah'}} combined = combine_databases( databases=[db1, db2], compared_keys=[['name', 'name2']], equality_functions=[lambda x,y: x[0]==y[0]], database_names=['DB1', 'DB2']) print(combined)
9390fdf52e3768a4828ded73fefccd059537eb22
nguyenl1/evening_class
/python/notes/python0305.py
1,088
4.03125
4
""" Dictionaries Key-values pairs dict literals (bracket to bracket) {'key': 'value' } [ array: list of strings ] Immutable value (int, float, string, tuple) List and dicts cannot be keys """ product_to_price = {'apple': 1.0, "pear": 1.5, "grapes": 0.75} print(product_to_price['apple']) # print(product_to_price[1.0]) #can only access a dictionary through key not value. #update dictionary product_to_price['apple'] = 300 print(product_to_price['apple']) # add to the dictionary product_to_price['avocado'] = 5000 print(product_to_price['avocado']) #checking if key exist if 'apple' in product_to_price: print('apple ' + str(product_to_price['apple'])) #merge dictionaries product_to_price.update({'banana': 0.25}) print(product_to_price) #list of all the keys, values, and items print(list(product_to_price.keys())) print(list(product_to_price.values())) print(list(product_to_price.items())) #order dict print(sorted(product_to_price.keys())) names_and_colors = [('alice', "red"), ('david', 'green')] new_dict = dict(names_and_colors) print(new_dict)
a90e7646813c7645935894105d63434178909703
nguyenl1/evening_class
/python/labs/lab15.py
1,779
3.9375
4
""" Convert a given number into its english representation. For example: 67 becomes 'sixty-seven'. Handle numbers from 0-99. Hint: you can use modulus to extract the ones and tens digit. x = 67 tens_digit = x//10 ones_digit = x%10 Hint 2: use the digit as an index for a list of strings. """ noindex = [0,1,2,3,4,5,6,7,8,9] tens = [" ", " ", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"] teens = ["ten", "eleven", "twelve", "thirteen", "forteen", "fifthteen", "sixteen", "seventeen", "eighteen", "nineteen"] ones = [" ","one", "two", "three", "four", "five", "six", "seven", "eight", "nine"] hundreds = [" ", "one hundred and ", "two hundred and ", "three hundred and ", "four hundred and ", "five hundred and", "six hundred and ", "seven hundred and ", "eight hundred and ", "nine hundred and "] user_input = int(input("Enter a number ")) def eng(): if user_input > 9 and user_input < 20: teen_digit = user_input%10 x = noindex.index(teen_digit) teen = teens[x] print (teen) elif user_input == 0: print("zero") elif user_input > 0 and user_input < 100: tens_digit = user_input//10 x = noindex.index(tens_digit) ten = tens[x] ones_digit = user_input%10 x = noindex.index(ones_digit) one = ones[x] print (ten + one) elif user_input > 99 and user_input < 1000: hundred_index = user_input//100 x = noindex.index(hundred_index) hundred = hundreds[x] tens_digit = (user_input%100)//10 x = noindex.index(tens_digit) ten = tens[x] ones_digit = (user_input%100)%10 x = noindex.index(ones_digit) one = ones[x] print (hundred + ten + one) eng()
e39edeb39458969cef046410d03535f2f5d8a64a
nguyenl1/evening_class
/python/notes/python0225.py
851
4.0625
4
''' def my_add(num_1, num_2): a_sum = num_1 + num_2 return a_sum sum = my_add(5, 6) #the contract between the users and the function print(sum) ''' """ #variables x = 5 print (x) greeting = "hello" print (greeting) bool = 5 > 10 print (bool) """ ''' # my_string = "ThIs Is A StRiNG" # print(my_string.lower()) # def my_add(num_1, num_2): # a_sum = num_1 + num_2 # return a_sum # sum = my_add(5, 6) #the contract between the users and the function # print(sum) ''' # my_string = "ThIs Is A StRiNG" # print(my_string.lower()) # x = 5 # y = x # y += 2 #this is the same as saying y = y + 2 # print (x) # print (y) # name = input ('what is your name? ') # print(f'hello {name}') x = 'a string' user_input = input (' enter something pretty: ') print(x + " is not a " + user_input) print(f'{x} is not a {user_input')
4b3922cdedf4f4c7af87235b94af0f763977b191
nguyenl1/evening_class
/python/labs/lab23final.py
2,971
4.25
4
import csv #version 1 # phonebook = [] # with open('lab23.csv') as file: # read = csv.DictReader(file, delimiter=',') # for row in read: # phonebook.append(row) # print(phonebook) #version2 """Create a record: ask the user for each attribute, add a new contact to your contact list with the attributes that the user entered.""" # phonebook = [] # while True: # name = input("Enter your name. ") # fav_fruit = input("Enter your your favorite fruit. ") # fav_color = input("Enter your your favorite color. ") # phonebook.append({ # 'name': name, # 'fav fruit': fav_fruit, # 'fav color': fav_color}) # with open('lab23.csv', 'a') as csv_file: # writer = csv.writer(csv_file, delimiter = ',') # row = [name,fav_fruit,fav_color] # writer.writerow(row) # cont = input("Want to add another? Y/N ") # if cont != "Y": # break # print(phonebook) """Retrieve a record: ask the user for the contact's name, find the user with the given name, and display their information""" # phonebook = [] # with open('lab23.csv') as file: # read = csv.DictReader(file, delimiter=',') # for row in read: # phonebook.append(row) # print(phonebook) # user_input = input("Please enter the name of the person you would information of. ").lower() # for row in phonebook: # if row['name'] == user_input: # print(row) """Update a record: ask the user for the contact's name, then for which attribute of the user they'd like to update and the value of the attribute they'd like to set.""" # phonebook = [] # with open('lab23.csv') as file: # read = csv.DictReader(file, delimiter=',') # for row in read: # phonebook.append(row) # print(phonebook) # user_input = input("Please enter the name of the person you would information of. ").lower() # for i in phonebook: # if i['name'] == user_input: # print(i) # break # att = input("Which attribute would you like to update? (name, fav fruit, fav color) ") # change = input("What would you like to update it to? ") # if att == "name": # i["name"] = change # print (i) # elif att == "fav fruit": # i["fav fruit"] = change # print (i) # elif att == "fav color": # i['fav color'] = change # print (i) # else: # print("Try again") """ Delete a record: ask the user for the contact's name, remove the contact with the given name from the contact list. """ # phonebook = list() # user_input = input("Please enter the name of the person you would like to delete ").lower() # with open('lab23.csv', 'r') as file: # read = csv.reader(file) # for row in read: # phonebook.append(row) # for i in row: # if i == user_input: # phonebook.remove(row) # with open('lab23.csv', 'w') as writeFile: # writer = csv.writer(writeFile) # writer.writerows(phonebook)
6e52d2a6e99a95375e37dace8a996a9f10ca87cd
nguyenl1/evening_class
/python/notes/python0227.py
647
3.796875
4
# x = 5 # y = 5 # print(x is y) # print(id(x)) #returns ID of an object # truthy falsey # empty lists, strings, None is a falsey value x = [] y = [1,2,3] i = "" j = "qwerty" z = None if x: print(x) if y: print(y) # [1,2,3] if i: print(i) if j: print(j) # qwerty if z: print(z) # my_flag = True while my_flag: #will always run if the conditio is true. print("hey there ") user_input = input("do you want to say hi again?") if user_input == 'n': my_flag = False my_list = [1,2,3,4,5,6] for item in my list: if item == 4: continue print(item) x = 7 y = 34 z = 9 print(6 < y < 100)
3bd0c70f91a87d98797984bb0b17502eac466972
nguyenl1/evening_class
/python/labs/lab18.py
2,044
4.40625
4
""" peaks - Returns the indices of peaks. A peak has a lower number on both the left and the right. valleys - Returns the indices of 'valleys'. A valley is a number with a higher number on both the left and the right. peaks_and_valleys - uses the above two functions to compile a single list of the peaks and valleys in order of appearance in the original data. # """ data = [1, 2, 3, 4, 5, 6, 7, 6, 5, 4, 5, 6, 7, 8, 9, 8, 7, 6, 7, 8, 9] noindex= [0, 1, 2, 3, 4, 5, 6, 7, 8,9, 10, 11, 12, 13,14,15,16,17,18,19,20] def peaks(): length = len(data) middle_index = length//2 first_half = data[:middle_index] second_half = data[middle_index:] # peak = first_half.index('P') peak = data.index(max(first_half)) peak_2 = data.index(max(second_half)) print(f"The index of the peak on the left is {peak}") print(f"The index of the peak on the right is {peak_2}") # peaks() def valleys(): valleys = [] for i in noindex[1:]: if data[i] <= data[i-1] and data[i] <= data[i+1]: valleys.append(i) # return valleys print(f"The indices of the valleys are {valleys}") # valleys() def peaks_and_valleys(): peaks() valleys() peaks_and_valleys() def p_v(): for i in data: print ("x" * i) p_v() #jon's ex: """ def get_data(): data = [1, 2, 3, 4, 5, 6, 7, 6, 5, 4, 5, 6, 7, 8, 9, 8, 7, 6, 7, 8, 9] return data def get_valleys(data): valleys = [] index_list = list(range(len(data))) for i in index_list: if (i-1) in index_list and (i+1) in index_list: # makes the index start at 1 so the indexing is not out of range? if data[i] <= data[i-1] and data[i] <= data[i+1]: valleys.append(i) return valleys def get_peaks(data): peaks = [] index_list = list(range(len(data))) for i in index_list: if (i-1) in index_list and (i+1) in index_list: if data[i] >= data [i-1] and data [i] >= data [i+1]: peaks.append(i) return peaks """
208f0481f2b86a5487202000de30700f754ad873
rxbook/study-python
/06/12.py
125
3.796875
4
def power(x,n): if n == 0: return 1 else: return x * power(x,n-1) print power(2,3) print power(2,5) print power(3,4)
ca672ad960d02bc62c952f5d8bab44670fa03c24
rxbook/study-python
/05/t02.py
115
3.75
4
score = input('Enter your score:') if score >= 85: print 'Good' elif score < 60: print 'xxxxx' else: print 'OK'
530effec6984850539b440dc14870a2bd4af2f71
rxbook/study-python
/05/t13.py
133
3.796875
4
names = ['zhang','wang','zhao','li'] ages = [12,46,32,19] zip(names,ages) #for name,age in zip(names,ages): # print name,'-----',age
5dc0ca50f55cc6967821f52336deffda5530ad04
airuchen/python_practice
/raise_error.py
444
3.8125
4
import sys def displaySalary(salary): if salary<0: raise ValueError('positive') print('Salary = '+str(salary)) while True: try: Salary = float(input('enter Salary:')) displaySalary(Salary) break except OSError as err: print('OS Error: {0}'.format(err)) except ValueError: print('Error: Enter positive value') except: print('Unexpected error:', sys.exc_info()[0])
feefbfb35b341b204fddcbe7dbd8d31acbc13b89
adpoe/CupAndChaucerSim
/INITIAL_EXPERIMENT/time_advance_mechanisms.py
28,390
3.8125
4
import Queue as q import cupAndChaucArrivs as cc """ Discrete time advance mechanisms for airport simulation project. This class will generate 6 hours worth of passenger arrivals, and store the data in two arrays: - One for commuters passengers - One for international passengers For each passenger, also need to generate their wait times for each queue. Or is that done when a passenger queues up? """ """ Goals ------ Generalize this code so it can be used for ANY queuing system. Need to account for: - How many steps? :: Spawn a Server-Queue System for each of these.... link these all together o How many servers at each step? o How many queues at each step? -- Make a class that holds each of these "single step" systems -- interface between these classes -- glue them all together with a start and end point -- make them each a member of the overall system and use the same time advance mechanisms I've already got in place. """ ########################### ### ARRIVAL GENERATION #### ########################### class CupChaucArrivals(): """ Class used to generate one hour of arrivals at a time """ def __init__(self): self.cashier_arrivals = [] self.barista_arrivals = [] def get_arrivals(self): """ Get all the arrivals to the system in the next six hours. Store the values in instance vars. """ hourly_arrivals = cc.generate_hourly_arrivals() arrivals_by_type = cc.gen_customer_type_distribution(hourly_arrivals) self.cashier_arrivals = cc.create_array_of_cashier_arrivals(arrivals_by_type) self.barista_arrivals = cc.create_array_of_barista_arrivals(arrivals_by_type) ########################## #### CHECK-IN QUEUES ##### ########################## #------------------# # C&C Queues # #------------------# class RegisterQueue: """ Class used to model a register line Queue """ def __init__(self): self.queue = q.Queue() self.customers_added = 0 def add_customer(self, new_customer): self.queue.put_nowait(new_customer) self.customers_added += 1 def get_next_customer_in_line(self): if not self.queue.empty(): next_customer = self.queue.get_nowait() self.queue.task_done() else: next_customer = None return next_customer class BaristaQueue: """ Class used to model a register line Queue """ def __init__(self): self.queue = q.Queue() self.customers_added = 0 def add_customer(self, new_customer): self.queue.put_nowait(new_customer) self.customers_added += 1 def get_next_customer_in_line(self): if not self.queue.empty(): next_customer = self.queue.get_nowait() self.queue.task_done() else: next_customer = None return next_customer # # # End C&C Queues # # # ########################### ###### C&C SERVERS ###### ########################### class CashierServer: """ Class used to model a server at the Check-in terminal """ def __init__(self): """ Initialize the class variables """ self.service_time = 0.0 self.busy = False self.customer_being_served = q.Queue() self.customers_added = 0 self.customers_served = 0 self.idle_time = 0.00 def set_service_time(self): """ Sets the service time for a new passenger :param passenger_type: either "commuter" or "international" """ self.service_time = cc.gen_cashier_service_time() self.busy = True def update_service_time(self): """ Updates the service time and tells us if the server is busy or not """ self.service_time -= 0.01 if self.service_time <= 0: self.service_time = 0 self.busy = False if not self.is_busy(): self.idle_time += 0.01 def is_busy(self): """ Call this after updating the service time at each change in system time (delta). Tells us if server is busy. :return: True if server is busy. False if server is NOT busy. """ return self.busy def add_customer(self, new_passenger): """ Adds a customer to the sever and sets his service time :param new_passenger: the passenger we are adding """ # get the type of flight his passenger is on # add the passenger to our service queue self.customer_being_served.put_nowait(new_passenger) # set the service time, depending on what type of flight the customer is on self.set_service_time() # update the count of customers added self.customers_added += 1 def complete_service(self): """ Models completion of our service :return: the customer who has just finished at this station """ if not self.is_busy() and not self.customer_being_served.empty(): next_customer = self.customer_being_served.get_nowait() self.customer_being_served.task_done() self.customers_served += 1 else: next_customer = None return next_customer class BaristaServer: """ Class used to model a server at the Security terminal """ def __init__(self): """ Initialize the class variables """ self.service_time = 0.0 self.busy = None # self.customer = None self.customer_being_served = q.Queue() self.is_barista_class = False self.customers_added = 0 self.customers_served = 0 self.idle_time = 0.0 def set_service_time(self): """ Sets the service time for a new passenger :param passenger_type: either "commuter" or "international" """ self.service_time = cc.gen_barista_service_time() self.busy = True def update_service_time(self): """ Updates the service time and tells us if the server is busy or not """ self.service_time -= 0.01 if self.service_time <= 0: self.service_time = 0 self.busy = False if not self.is_busy(): self.idle_time += 0.01 def is_busy(self): """ Call this after updating the service time at each change in system time (delta). Tells us if server is busy. :return: True if server is busy. False if server is NOT busy. """ return self.busy def add_customer(self, new_customer): """ Adds a customer to the sever and sets his service time :param new_passenger: the passenger we are adding """ # add the passenger to our service queue self.customer_being_served.put_nowait(new_customer) # set the service time, depending on what type of flight the customer is on self.set_service_time() # update the count of customers added self.customers_added += 1 def complete_service(self): """ Models completion of our service :return: the customer who has just finished at this station """ next_customer = None # only try to pull a customer from the queue if we are NOT busy # AND the queue isn't empty # else we just return a None if not self.is_busy() and not self.customer_being_served.empty(): next_customer = self.customer_being_served.get_nowait() self.customer_being_served.task_done() self.customers_served += 1 else: next_customer = None return next_customer ############################# ###### C&C CUSTOMERS ###### ############################# class Customer: """ Class used to model a passenger in our simulation """ def __init__(self, system_time, customer_class, system_iteration, relative_time): self.system_time_entered = system_time self.customer_class = customer_class self.system_iteration = system_iteration self.relative_time = relative_time #--------DEBUGGING------- #if flight_type == "international" and system_time > 1490: # print "here" # #confirm_system_time = (system_time / system_iteration) #confirm_relative_time = str(relative_time) #relative_system_time = system_time / (system_iteration * 360.0) #if not str(math.floor((system_time / system_iteration))) == str(math.floor(relative_time)): # print "something's off." #------------------------ def __eq__(self, other): """Override the default Equals behavior""" if isinstance(other, self.__class__): return self.__dict__ == other.__dict__ return NotImplemented def __ne__(self, other): """Define a non-equality test""" if isinstance(other, self.__class__): return not self.__eq__(other) return NotImplemented def __hash__(self): """Override the default hash behavior (that returns the id or the object)""" return hash(tuple(sorted(self.__dict__.items()))) ########################## #### SIMULATION CLASS #### ########################## class Simulation: """ Class used to house our whole simulation """ def __init__(self): """ Sets up all the variables we need for the simulation """ #----TIME---- # Time variables self.system_time = 0.00 self.delta = 0.01 self.hours_passed = 0 # = number of system iterations self.system_iteration = 0 self.relative_global_time = 0.00 self.time_until_next_arrival_generation = 60.0 #-----ARRIVALS----- # Arrival list self.barista_ARRIVALS = [] self.cashier_ARRIVALS = [] # All arrivals self.arrivals = [self.barista_ARRIVALS, self.cashier_ARRIVALS] #----QUEUES----- # Check-in Queues - separate for first and coach self.register_QUEUE = RegisterQueue() # Security Queues - also separate for first and coach self.barista_QUEUE = BaristaQueue() # All Queues self.queues = [self.register_QUEUE, self.barista_QUEUE] #------SERVERS------- # Register Servers self.CASHIER_server01 = CashierServer() self.check_in_servers = [self.CASHIER_server01] # Barista Servers self.BARISTA_server01 = BaristaServer() # self.BARISTA_server02 = BaristaServer() self.barista_servers = [self.BARISTA_server01] # All servers self.servers = [self.CASHIER_server01, self.BARISTA_server01] #----INTERNAL_DATA COLLECTION----- self.total_cashier_customers_arrived = 0 self.total_cashier_customers_serviced = 0 self.total_barista_customers_arrived = 0 self.total_barista_customers_serviced = 0 self.customers_combined = 0 # Then counters to see how far people are making it in the system.... # Averaged data self.time_in_system = [] self.time_in_system_CASHIER = [] self.avg_time_in_system = 0 self.avg_time_in_system_CASHIER = [] self.time_in_system_BARISTA = [] #-----INTERNAL MECHANISMS------ self.data_users_added_to_REGISTER_QUEUE = 0 self.data_users_added_to_BARISTA_QUEUE = 0 self.data_users_added_to_FIRSTCLASS_SECURITY_QUEUE = 0 self.data_CASHIER_customers_moved_to_EXIT = 0 self.data_BARISTA_customers_moved_to_EXIT = 0 self.data_users_currently_in_system = 0 self.total_server_idle_time = 0.0 self.data_num_customers_wait_over_one_min = 0 def generate_ONE_HOUR_of_arrivals(self): """ Generates six hours of arrivals and stores in our ARRIVAL LIST instance variables. """ # Create instance of arrival class new_arrivals = CupChaucArrivals() # Generate new arrivals new_arrivals.get_arrivals() # Add one to the system iteration (denoted by international flight number) self.hours_passed += 1 # Transfer those values into our simulation, as arrivals for next six hours self.barista_ARRIVALS = new_arrivals.barista_arrivals self.cashier_ARRIVALS = new_arrivals.cashier_arrivals # clean up arrivals, so nothing greater 60, because we'll never reach it for arrival in new_arrivals.cashier_arrivals: if arrival > 59.99999999: new_arrivals.cashier_arrivals.remove(arrival) for arrival in new_arrivals.barista_arrivals: if arrival > 59.99999999: new_arrivals.barista_arrivals.remove(arrival) # Count our arrivals for data collection self.total_cashier_customers_arrived += len(new_arrivals.cashier_arrivals) self.total_barista_customers_arrived += len(new_arrivals.barista_arrivals) print "arrivals generated for hour: " + str(self.hours_passed) def update_servers(self): """ Updates servers after a change of DELTA in system time """ for server in self.servers: server.update_service_time() def collect_and_create_passengers_from_arrivals(self): """ Looks at all arrival lists, and if there is new arrival at the current system time, creates a passenger object for use in the system, and places it in the check-in queue """ relative_time = self.relative_global_time # make sure we're not checking an array that's empty if not len(self.barista_ARRIVALS) == 0: # Then get next available item from INTL FIRST CLASS ARRIVALS if self.barista_ARRIVALS[0] <= relative_time: # create passenger, put it in first class check in queue new_customer = Customer(self.system_time, "barista", self.hours_passed, self.barista_ARRIVALS[0]) self.register_QUEUE.add_customer(new_customer) # pop from the list self.barista_ARRIVALS.pop(0) # make sure we're not checking an array that's empty if not len(self.cashier_ARRIVALS) == 0: # Then get next available item from COMMUTER COACH CLASS ARRIVALS if self.cashier_ARRIVALS[0] <= relative_time: # create passenger, put it in coach class check in queue new_customer = Customer(self.system_time, "cashier", self.hours_passed, self.cashier_ARRIVALS[0]) self.register_QUEUE.add_customer(new_customer) # pop from the list self.cashier_ARRIVALS.pop(0) def move_to_CASHIER_server(self): """ Look at check in servers, and if they are not busy, advance the first item in the correct queue to the correct (and open) check in server """ #>>>>>> Later, change this go through all checkin servers in a loop and do same action. # This code can be very much condensed # If first class check-in server is NOT busy if not self.CASHIER_server01.is_busy(): # de-queue from the FIRST class check-in queue if not self.register_QUEUE.queue.empty(): next_passenger = self.register_QUEUE.queue.get() self.register_QUEUE.queue.task_done() # and move next passenger to server, since it isn't busy self.CASHIER_server01.add_customer(next_passenger) def update_register_queues(self): """ Updates queues after a change of DELTA in system time """ # then check the servers, and if they're free move from queue to server self.move_to_CASHIER_server() # Check all arrivals and if the arrival time matches system time... # Create a passenger and ADD the correct queue self.collect_and_create_passengers_from_arrivals() def update_barista_queues(self): """ Updates queues after a change of DELTA in system time """ # Check all check-in servers... and if they are NOT busy, take their passenger... # Take the passenger, add the correct security queue # First, look at all servers for server in self.check_in_servers: # and if the server is NOT busy # if not server.is_busy(): #if not server.last_customer_served.empty(): # Take the passenger, who must have just finished being served my_customer = server.complete_service() # and move them to the correct security queue if not my_customer == None: # but first make sure that the passenger does not == None if my_customer.customer_class == "cashier": # add to end of simulation self.data_CASHIER_customers_moved_to_EXIT += 1 # data collection for coach time_in_system = self.system_time - my_customer.system_time_entered self.time_in_system.append(time_in_system) self.time_in_system_CASHIER.append(time_in_system) # data collection for commuters self.time_in_system_CASHIER.append(time_in_system) self.total_cashier_customers_serviced += 1 # else, add to barista queue else: # because if they are NOT cashier customers, they must be barista customers self.barista_QUEUE.add_customer(my_customer) def move_to_BARISTA_server(self): """ If servers are not busy, advance next passenger in the security queue to to security server """ # step through all the security servers and check if they are busy for server in self.barista_servers: # if the server isn't busy, we can take the next passenger from security queue # and put him in the server if not server.is_busy(): # first make sure it's not empty if not self.barista_QUEUE.queue.empty(): # and if it's not, grab the next passenger out of it next_customer = self.barista_QUEUE.queue.get() self.barista_QUEUE.queue.task_done() # And move that passenger into the available security server server.add_customer(next_customer) def move_to_EXIT(self): """ Look at Security servers, and if they are NOT busy, someone just finished security screening. This means they've completed the queuing process. --- Once through queuing, go to GATE. Commuters --> Go straight to gate waiting area International --> First check if they missed their flight. - If yes: They leave - If no: They go to international gate """ # step through all the security servers for server in self.barista_servers: # if the server is NOT busy #if not server.is_busy(): #if not server.last_customer_served.empty(): # passenger has completed queuing phase, and can move to gate. # but first, we need to check if they are commuters or international flyers # and in each case, need to handle that accordingly next_customer = server.complete_service() # first make sure that the passenger isn't a NONE if not next_customer == None: # if the passenger is a commuter, they just go to gate if next_customer.customer_class == "barista": self.data_BARISTA_customers_moved_to_EXIT += 1 # data collection for coach time_in_system = self.system_time - next_customer.system_time_entered self.time_in_system.append(time_in_system) self.time_in_system_BARISTA.append(time_in_system) # data collection for commuters self.time_in_system_BARISTA.append(time_in_system) self.total_barista_customers_serviced += 1 def advance_system_time(self): """ Advances the system time by delta --> .01 of a minute - Looks for arrivals at current time - If an arrival is valid, create a passenger object and place it in the proper Queue - Needs to update EVERY QUEUE and SERVER, advance wherever needed """ # every six hours, generate new arrivals, # and perform accounting procedures on ticket # for those arrivals #if self.time_until_international_flight <= 0.0: # self.generate_SIX_HOURS_of_arrivals() # self.collect_revenue() # self.every_six_hours_deduct_operating_costs() # increment the system time by delta self.system_time += self.delta self.time_until_next_arrival_generation -= self.delta # keep track of relative global time self.relative_global_time += self.delta if self.relative_global_time >= 60.0: self.relative_global_time = 0.0 #print "gets system time update" # skip these on the first iteration because we don't have data yet if not self.hours_passed == 0: #DO IT IN REVERSE ORDER # start by updating the servers self.update_servers() # then, if we can pull someone FROM a sever, while not busy, do it self.move_to_EXIT() self.update_barista_queues() # then get passengers from arrivals, and fill the queues self.collect_and_create_passengers_from_arrivals() # then move people into any empty spots in the servers self.move_to_BARISTA_server() self.move_to_CASHIER_server() # every six hours, generate new arrivals, # and perform accounting procedures on ticket # for those arrivals if self.time_until_next_arrival_generation <= 0: self.generate_ONE_HOUR_of_arrivals() self.time_until_next_arrival_generation = 60.0 #print "checks if planes depart" # print self.system_time def run_simulation(self, simulation_time_in_days): """ Use this to run simulation for as long as user has specified, in days While the counter < # of days, keep generating the arrivals every 6 hours and stepping through the simulation """ simulation_time_in_minutes = simulation_time_in_days * 24.0 * 60.0 + 60.0 # = days * 24 hours in a day * 60 minutes in an hour while self.system_time < simulation_time_in_minutes: # then, advance system time by delta: 0.01 self.advance_system_time() print "SIMULATION COMPLETE:" ############################################# ####### DATA REPORTING AND ANALYSIS ######### ############################################# def print_simulation_results(self): """ prints the results of our simulation to the command line/console """ print "###################################" print "####### SIMULATION RESULTS ########" print "###################################" print "#-----System Info-----" print "Total CASHIER customers ARRIVED="+str(self.total_cashier_customers_arrived) print "Total CASHIER customers SERVICED="+str(self.total_cashier_customers_serviced) print "Total BARISTA customers ARRIVED="+str(self.total_barista_customers_arrived) print "Total BARISTA customers SERVICED="+str(self.total_barista_customers_serviced) total_customers_serviced = self.total_barista_customers_serviced + self.total_cashier_customers_serviced print "Total CUSTOMERS (all types) SERVICED="+str(total_customers_serviced) print "-------Averages-------" #sum_time_in_system = sum(self.time_in_system) length_of_time_in_system_list = len(self.time_in_system) #length_of_time_in_system_list = float(length_of_time_in_system_list) #print "SUM OF TIME IN SYSTEM: "+str(sum_time_in_system) #print "LENGTH OF TIME IN SYSTEM: "+str(length_of_time_in_system_list) self.avg_time_in_system = sum(self.time_in_system)/len(self.time_in_system) print "AVG Time In System for ALL CUSTOMERS (who make make it to EXIT)="+str(self.avg_time_in_system) self.time_in_system.sort(reverse=True) longest_time_in_system = self.time_in_system.pop(0) print "Longest time in system="+str(longest_time_in_system) average_time_in_system_cashier = sum(self.time_in_system_CASHIER) / len(self.time_in_system_CASHIER) print "AVG Time in system CASHIER="+str(average_time_in_system_cashier) average_time_in_system_barista = sum(self.time_in_system_BARISTA) / len(self.time_in_system_BARISTA) print "AVG Time in system all BARISTA="+str(average_time_in_system_barista) print "------Internal Mechanisms-------" print ".......Stage 1......" print "Customers added to RegisterQueue="+str(self.register_QUEUE.customers_added) print "......Stage 2......." print "Customers added to BaristaQueue="+str(self.barista_QUEUE.customers_added) print "......Stage 3......." print "CASHIER customers who make it to EXIT="+str(self.data_CASHIER_customers_moved_to_EXIT) print "BARISTA customers who make it to EXIT="+str(self.data_BARISTA_customers_moved_to_EXIT) print ". . . . didn't make it . . . . ." still_in_system = 0 for queue in self.queues: still_in_system += queue.queue.qsize() print "Users STILL in SYSTEM="+str(still_in_system) print "======= GOALS ========" self.total_server_idle_time = 0.0 for server in self.check_in_servers: self.total_server_idle_time += server.idle_time print "AGENTS' Total Idle Time="+str(self.total_server_idle_time) server_count = len(self.servers) print "AGENTS AVG IDLE TIME="+str(self.total_server_idle_time/server_count) print "TIMES GREATER THAN 1 MIN:" wait_times_longer_than_min = [] wait_times_longer_than_2mins = [] wait_times_longer_than_3mins = [] wait_times_longer_than_5mins = [] for time in self.time_in_system: if time > 1.0: # print time wait_times_longer_than_min.append(time) if time > 2.0: wait_times_longer_than_2mins.append(time) if time > 3.0: wait_times_longer_than_3mins.append(time) if time > 5.0: wait_times_longer_than_5mins.append(time) print "TOTAL WAIT TIMES LONGER THAN 1 MINUTE: " + str(len(wait_times_longer_than_min)) print "TOTAL WAIT TIMES LONGER THAN 2 MINUTES: " + str(len(wait_times_longer_than_2mins)) print "TOTAL WAIT TIMES LONGER THAN 3 MINUTES: " + str(len(wait_times_longer_than_3mins)) print "TOTAL WAIT TIMES LONGER THAN 5 MINUTES: " + str(len(wait_times_longer_than_5mins)) print "Percentage of Barista Customers who waited longer than 1 minute: " + str(float(float(len(wait_times_longer_than_min))/self.total_barista_customers_serviced)) print "Percentage of Barista Customers who waited longer than 2 minutes: " + str(float(float(len(wait_times_longer_than_2mins))/self.total_barista_customers_serviced)) print "Percentage of Barista Customers who waited longer than 3 minutes: " + str(float(float(len(wait_times_longer_than_3mins))/self.total_barista_customers_serviced)) print "Percentage of Barista Customers who waited longer than 5 minutes: " + str(float(float(len(wait_times_longer_than_5mins))/self.total_barista_customers_serviced)) print ""
261a80f5080e6ad40aacc3f4921d7e140d19fedd
imran436/Projects-Portfolio-master
/Tech Academy/python projects/#13.py
555
3.9375
4
import time X = 5 print(X) X = X**5 print(X) if X<10: print("our number X is a small value") elif X<100: print("The number is an average value") else: print("the number holds a big value") counter = 0 for counter in range(0, 100,5): print(counter) time.sleep(.25) counter = 0 while counter < X: print(counter*5) time.sleep(.25) if(counter<1): counter = 1; counter = counter *5 dictionary={'orange':'Fruit','milk':'dairy','carrots':'vegitable'} print(dictionary) dictionary['chicken']='Poltry' print(dictionary)
70c66c6ddb26d1ddad9409d84c4932e7dfd718af
Sasithorn04/Python
/ตารางหมากฮอส.py
604
3.9375
4
#โปรแกรมจำลองตารางหมากฮอส #ปรับจากสร้างภาพวาด4เหลี่ยมจตุรัส number = int(input("ป้อนขนาด :")) for row in range(1,number+1) : for column in range(1,number+1) : if (column%2 == 0) & (row%2 == 0) : print("o",end='') elif (column%2 != 0) & (row%2 != 0): print("o",end='') else : print("x",end='') print(" ") ''' oxoxoxox xoxoxoxo oxoxoxox xoxoxoxo oxoxoxox xoxoxoxo oxoxoxox xoxoxoxo '''
ebcd50508c0690db480ba215a31c764c84db3988
harshit-tiwari/Python-Codes
/Simple Calculator/addition.py
689
4.09375
4
import calculate def addFunc(): print("You have chosen Addition") operands = [] number = 0 while True: try: number = int(input("How many numbers do you want to add? : ")) break except ValueError: print("Please enter a number as your input") for i in range(0, number): while True: try: value = int(input("Enter the number %s here : "%(i+1))) break except ValueError: print("Please enter a number as your input") operands.append(value) total = calculate.add(*operands) print("The sum of these numbers is : ", total)
e978a7977ddfd0f0e7559618d3aa1f5282f8ab91
chrissowden14/bank
/FileStore.py
1,592
3.90625
4
class FileStore: def __init__(self): # This creates an open list everytime the program is opened self.cusnames = [] self.cusspaswords = [] self.cusbalance = [] # opening the stored file that collects the old data from customer self.namefile = open("cusnamesfile.txt", "r") self.passfile = open("cuspassfile.txt", "r") self.balancefile = open("cusbalancefile.txt", "r") # this will input the date into the empty list from the stored FileExistsError for line in self.namefile: self.cusnames.append(line[:-1]) self.namefile.close() # check the list of customers passwords for line in self.passfile: self.cusspaswords.append(line[:-1]) self.passfile.close() # checks customer balance for line in self.balancefile: self.cusbalance.append(line[:-1]) self.balancefile.close() # this function will write new date into stored files when its called up def filewrite(self, item): if item == self.cusnames: text = open("cusnamesfile.txt", "w") for i in item: text.write(i + "\n") text.close() elif item == self.cusspaswords: text = open("cuspassfile.txt", "w") for i in item: text.write(i + "\n") text.close() elif item == self.cusbalance: text = open("cusbalancefile.txt", "w") for i in item: text.write(str(i) + "\n") text.close()
b58ef87371085284143fbb0d28d9251d8d97b01f
Subhashriy/python
/11-07-19/substitute.py
200
3.5
4
import re n=int(input("Enter no. of lines:")) a=[] for i in range(n): a.append(input()) str1=re.sub(r'&&','and',a[i]) str1=re.sub(r'\|\|','or',a[i])
0de46d21ae522160a24e89e11919f60365b32288
Subhashriy/python
/17-07-19/tcpclient.py
752
3.5625
4
import socket def main(): host='127.0.0.1' port=5000 #Creting a socket s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) print("Socket Created.") #connect to the server s.connect((host,port)) print('Connected to server.') #send msg to the server data=input('Enter the number to find the factorial: ') print('Enter q to terminate connection.') while data!='q': print(data) #s.send(str.encode(data,'utf-8')) s.send(str.encode(data,'utf-8')) data=s.recv(1024).decode('utf-8') print(data) data=input('Enter the number to find the factorial: ') s.close() if __name__=='__main__': main()
07617bf9783632e43ce3e5e585bc5d844e29f8e1
Subhashriy/python
/17-07-19/avg.py
128
3.90625
4
lst=[int(x) for x in input('Enter the list: ').split(' ')] print('The average of the list is : {}'.format((sum(lst)/len(lst))))
1687e6c73055cb78bb5399468addc38065edfc4f
Subhashriy/python
/17-07-19/random.py
199
3.75
4
import random def randomnum(i,n): print(random.randint(i,n+1)) #print(random.randint(1,100)) i=int(input('Enter the start range:')) n=int(input('Enter the end range:')) randomnum(i,n)
70b744b963b558041e7e60fb910eaa3260c619e9
zacharymollenhour/Fitness_Tracker
/test.py
2,323
3.984375
4
import numpy as np import pandas as pd import csv from datetime import date #Get User Name class Person: "This is a persons data class" def __init__(self): self.userData = [] self.name = '' self.age = 0 self.weight = 0 #Greet User for data about the individual def greet(self): #User Data self.name = input("Enter in your name: ") print(self.name) self.age = input("Enter in your age: ") print(self.age) self.weight = input("Enter in your weight: ") print(self.weight) #Write Inital Data of individual being tracked def updateCSV(self): with open('user_statistics.csv', mode='w') as csv_file: csv_reader = csv.writer(csv_file) csv_reader.writerow(self.name) csv_reader.writerow(self.age) csv_reader.writerow(self.weight) #Class for tracking workout data class Workout: "This is a class to track workout data" def __init__(self): self.date = '' self.workoutType = '' self.weight = 0 self.duration = 0 #Function to get workout information def workoutData(self): today = date.today() self.date = today.strftime("%m/%d/%y") self.workoutType = input("Please enter the workout type:") print(self.workoutType) self.updateWorkoutData() #Class that writes workout data to a csv def updateWorkoutData(self): with open('workout_data.csv', mode='a+',newline='') as csv_file: csv_reader = csv.writer(csv_file) csv_reader.writerow([self.date]) csv_reader.writerow([self.workoutType]) #Menu def menu(self): ans = True while ans: print(""" 1.Add a Workout 2.Delete a Workout """) ans=input("What would you like to do?") if ans == "1": self.workoutData() if ans == "2": "comeback" #Main Function def main(): #Declare a object person1 = Person() workoutObject = Workout() #Call object functions """ person1.greet() person1.updateCSV() """ workoutObject.menu() #workoutObject.workoutData() #workoutObject.updateWorkoutData() main()
ce0dada2eadce554808ced1d97e1c8b88e2a9b7e
devsben/Neopets-Multi-Tool
/classes/__init__.py
288
3.5
4
import sys if sys.version_info[0] < 3: """ If a Python version less than 3 is detected prevent the user from running this program. This will be removed once the final tweaking is completed for Python 2. """ raise Exception("Python 3 is required to run this program.")
39c5729b31befc2a988a0b3ac2672454ae99ea9a
krsatyam20/PythonRishabh
/cunstructor.py
1,644
4.625
5
''' Constructors can be of two types. Parameterized/arguments Constructor Non-parameterized/no any arguments Constructor __init__ Constructors:self calling function when we will call class function auto call ''' #create class and define function class aClass: # Constructor with arguments def __init__(self,name,id): self.name=name self.id=id #print(self.id) #print(self.name) #simple function def show(self): print("name=%s id= %d "%(self.name,self.id)) #call a class and passing arguments obj=aClass("kumar",101) obj2=aClass("rishave",102) obj.show() obj2.show() #second ExAMPLE class Student: def __init__(self,name,id,age): self.name = name; self.id = id; self.age = age #creates the object of the class Student s = Student("John",101,22) #s = Student() TypeError: __init__() missing 3 required positional arguments: 'name', 'id', and 'age' print("*************befoer set print***********") print(getattr(s,'name')) print(getattr(s,'id')) print(getattr(s,'age')) print("**********After set print***********") setattr(s,'age',23) print(getattr(s,'age')) setattr(s,'name','kumar') print(getattr(s,'name')) # Constructor - non parameterized print("************ Non parameters ***********") class Student: def __init__(self): print("This is non parametrized constructor") def show(self,name): print("Hello",name) student = Student() #student.show("Kuldeep")
bcde27b2f96aff6d73cf8cb2836416b57c3e0e56
krsatyam20/PythonRishabh
/filehandling.py
1,001
3.734375
4
''' open(mode,path) mode r :read read() => read all file at a time readline() => line by line read readlines() => line by line read, but line convert into list w :write write() a :append open(path,'a') write() path(file location with file name) ''' x=open(r"C:\Users\User\Desktop\Java.advance.txt") print(x) #print(x.read()) '''print(x.readline()) print(x.readline()) print(x.readline()) print(x.readline()) ''' #print(x.readlines()) readFileandconvertIntoList=x.readlines() '''for rf in readFileandconvertIntoList: print(rf)''' #count line print(len(readFileandconvertIntoList)) wf=open(r"C:\Users\User\Desktop\output.txt",'w') wf.write('Hello\n') wf.write('Hello\n') wf.write('Hello\n') wf.write('Hello\n') wf.write('Hello\n') wf.write('Hello\n') wf.write('Hello\n') wf.close() ''' count word and char in any file'''
5be464d262f21413b369dc140cae381540470ef0
krsatyam20/PythonRishabh
/forloop.py
590
4.09375
4
''' loop : loop is a reserved keyword it`s used for repetaion of any task types of loop 1. For loop 2.while loop ''' for i in range(0,10): print("Rishab %d " %(i)) for i in range(1,21): print(i) #use break keyword print("===========break keyword=================") for i in range(1,21): if(i==8): break; print(i) #continue print("===========continue keyword=================") for d in range(1,21): if(d==12): continue; print(d)
fa517e9e021b1d701a23211c569e6fd201bdb42c
gsingh84/Adventure-Game
/Adventure-game.py
10,666
4.25
4
#All functions call at the end of this program import random treasure = ['pieces of gold!', 'bars of silver!', 'Diamonds!', 'bottles of aged Rum!'] bag = ['Provisions'] #yorn function allow user to enter yes or no. def yorn(): yinput = "" while True: yinput = input("Please Enter Yes or No (Y/N): ") if yinput == 'Y' or yinput == 'y' or yinput == 'n' or yinput == 'N': return yinput #find_treasure function find the random treasure from given list. def find_treasure(ref): new = random.sample(set(treasure),1) from random import randint qty_tr = (randint(1,50), new[0], '%s.'%ref) print() print ('You Found', ' '.join(str(x) for x in qty_tr)) print('---------------------------------') bag.append(qty_tr) show_treasure() print('---------------------------------') #show_treasure function shows the items that available in the bag. def show_treasure(): print('your bag of holding contains:') for list in bag: print (' '.join(str(x) for x in list)) #This is strating point of program, this function gives the intro. def intro(): print("Time for a little adventure!") print() print("You're for a hike, you have a walking stick, backpack, and some provisions") print() print("You have been following a stream bed through a forest, when you see a") print("small stone building. Around you is a forest. A small stream flows out of the") print("building and down a gully.") print() print("Just outside of the small building, by a warm, inviting fire, is an old,") print("possibly ancient man, with long rather mangy beard. He sees you and says:") print() print("\t 'Hello my friend, stay a while and listen...'") print() print("You're not sure why, but you decide to stay and listen as he tells you stories") print("of strange and magical lands of adventure and Treasure!") print() print("After what seems like hours, the old man admits to being a bit hungry. He asks,") print("pointing at your backpack, if you have food in your 'bag of Holding', that") print("you might be willing to share.") print() print("Do you share your provisions?") print("-------------------------------------------------------------------------------") fun_input = yorn() #call the yorn function here to get input from user. if fun_input == "y" or fun_input == "Y": print("The old man hungrily devours all of your provisions with barely a crumb in sight") print() print("He leans close to you and whispers 'Besides gold, silver, and diamonds, if you") print("chosse wisely, there could also be other valuable GEMS!'") print() print('He slips you something of great value...') treasure.insert(0, 'bags of GEMS!') #if user Enter 'y' then it will add (bags of GEMS!) into the treasure list other wise not. print() print("your possible treasures are:") bag.remove(bag[0]) #after sharing provison with old man, this statement will remove provisions from bag other wise provisions remain in the bag. for list in treasure: ge = list.strip() print(ge) find_treasure("from old man") #call the find_treasure function here and pass the argument for where the item found from and also show the items in the bag. elif fun_input == 'N' or fun_input == "n": print("He looks at you wistfully ... for a moment,") print(" then eats the last few crumbs.") print() print('your possible treasures are:') for list in treasure: ge = list.strip() print(ge) #potion function allow user to choose between two potions. def potion(): print("-------------------------------------------------------------------------------") print("The old man stands up and waves his hand towards a rather ornate table close to") print("the building. you didn't notice the table before, but it's really quite out of") print("place in this forest.") print() print("On the ornate table is two bottles of potion, one is blue, and the other is red.") print() print("There is also a note, the note says,") print() print("\t Drink the BLUE potion and believe whatever you want to believe.") print() print("The rest of the note is destroyed and can't be read.") print() print("You turn to the old man, he seems to look much taller and a bit forbidding ...") print() print("\t He points at the table and says 'CHOOSE' ") print() red = ('RED') blue = ('BLUE') pinput = input('Do you choose the RED potion or the BLUE potion (R/B)? ') if pinput == "r" or pinput == "R": print() print('you guzzle the contents of the bottle with the red potion.') print() print("you feel like you're on fire! smoke is pouring out of your nose and ears!") print("when the thick red billowy smoke subsides, the old man is gone and there is a") print("narrow cobblestone trail leading from the small building.") print() print("you follow the cobblestone trail.") return (red) elif pinput == "b" or pinput == "B": print() print("you drink the BLUE potion. Nothing seems to happen ... at first. Then") print("strangely your body tingles , an old man bids you farewell as he leaves the park.") print("you wonder vaguely about something regarding a hike or a forest ...") return (blue) else: print() print("you fail to drink a potion, the old man leaves and you wonder aimlessly though") print("the forest, hopelessly lost!") def dwarf(): max = 6 for counter in range(max): from random import randint dwarfappear = (randint(1,2)) dwarf_r = (randint(1,2)) if dwarfappear == 1: #Here you can see if dwarfappear variable or random number = 1 then dwarf will appear print("-------------------------------------------------------------------------------") print("As you procees along the trail, you encounter a wicked looking") print("dwarf with a long black beard.") print() print("He has a large rusty knife in his hand!") print() print("He seems to be laughing at you as you're trying to decide to attack or to just") print("run away ...") print() print("Do you attack?") print("-------------------------------------------------------------------------------") dwarfinput = yorn() #Here I call the yorn function for asking "do you want to attack" on dwarf if dwarfinput == 'y' or dwarfinput == 'Y' and dwarf_r == 2: #Here I used another random number, you can see above with the name dwarf_r which is for mighty swing print("You take a mighty swing at the dwarf with your stick") print() print("C R A C K ! ! ... you hit the dwarf, it's dead") print() print("Do you want to loot the body?") loot = yorn() #call yorn() function to get input from user. if loot == 'y' or loot == 'Y': find_treasure("from Dwarf") elif dwarfinput == 'y' or dwarfinput == 'Y' and dwarf_r == 1: #If dwarf_r variable or random number = 1 then you will miss the target other wise you hit the dwarf print() print("You take a mighty swing at the dwarf with your stick") print("Whoosh! ... you miss the dwarf, but he runs away") elif dwarfinput == 'n' or dwarfinput == 'N': print("You let out a blood curdling scream, and run very fast!") elif dwarfappear == 2: #Here you can see if dwarfappear variable = 2 then dwarf will not appear print("-------------------------------------------------------------------------------") print("You continue to follow the cobblestone trail.") print() def elves(): from random import randint elves_r = (randint(1,2))# Here again I used randint for elf. print() print("You come to what looks like the end of the 'road'. The trail splits and") print("there appears to be two strange looking houses here.") print() print("The first one, the left, is a very large and elaborate house. There") print("is a very 'fancy' elf standing in front!") print() print("The second house is very small and looks like it's about to fall over. There") print("is a very short elf standing in front!") print() print("Both seem to be beckoning you closer. which elf do you approach? The one by") print("the first house or the one by the second house?") print() while True: try: elves_input = int(input("Choose an elf to approach (1 or 2)? ")) print() if elves_r == 1 and elves_input == 1 or elves_r == 2 and elves_input == 2: #if user enter 1 and random number also 1 or user enter 2 and random number also 2 then elf invites you in. print("you have chosen wisely!") print("... The elf invites you in for a cup of tea (and a gift) ") print() find_treasure('from elf') print("You have had a great adventure and found some amazing treasure") elif elves_r == 1 and elves_input == 2 or elves_input == 1 and elves_r == 2: # other then that if you input value not matched with random number then you choosed the bad elf. print() print("The elf starts to cackle, and begins to incant a spell") print() print("P O O F ! ! he turns you into a giant TOAD!!") print() print("You have had a great adventure and found some amazing treasure") print("... if you're not a giant toad!") if elves_input == 1 or elves_input == 2: break except ValueError: print('Please Enter 1 or 2') intro() print() input('Press Enter to continue..') potion = potion() print(potion) print() input('Press Enter to continue..') dwarf() print() input('Press Enter to continue..') elves() print() print('Thanks for playing')
34f5750734878b8d0d100a5882e2b4a70fbb13f9
nicklip/Google_Python_Developers_Course
/copyspecial.py
4,485
3.828125
4
#!/usr/bin/python # Copyright 2010 Google Inc. # Licensed under the Apache License, Version 2.0 # http://www.apache.org/licenses/LICENSE-2.0 # Google's Python Class # http://code.google.com/edu/languages/google-python-class/ import sys import re import os import shutil import commands """Copy Special exercise The copyspecial.py program takes one or more directories as its arguments. We'll say that a "special" file is one where the name contains the pattern __w__ somewhere, where the w is one or more word chars. The provided main() includes code to parse the command line arguments, but the rest is up to you. Write functions to implement the features below and modify main() to call your functions. Suggested functions for your solution(details below): get_special_paths(dir) -- returns a list of the absolute paths of the special files in the given directory copy_to(paths, dir) given a list of paths, copies those files into the given directory zip_to(paths, zippath) given a list of paths, zip those files up into the given zipfile """ def get_special_paths(the_dir): ''' returns a list of the absolute paths of the special files in the given directory ''' the_paths = [] # Getting the filenames from the directory filenames = os.listdir(the_dir) for filename in filenames: # Finding all of the "special" files special = re.findall(r'__\w+__', filename) if special: # Putting all special files in a list abs_path = os.path.abspath(os.path.join(the_dir, filename)) the_paths.append(abs_path) # Returning list of special files return the_paths def copy_to(paths, to_dir): ''' given a list of paths, copies those files into the given directory ''' # If the directory to copy the files to doesn't exist, create it if not os.path.exists(to_dir): os.mkdir(to_dir) for path in paths: # Getting the files to be copied from each path filenames = os.listdir(path) for filename in filenames: # Getting the full path of each file abs_path = os.path.abspath(os.path.join(path, filename)) # Copying each file to the desired directory if os.path.isfile(abs_path): shutil.copy(abs_path, to_dir) def zip_to(paths, to_zip): ''' given a list of paths, zip those files up into the given zipfile ''' files = [] for path in paths: # Getting the filenames from each path filenames = os.listdir(path) for filename in filenames: # Putting each joined path + filename into a list files.append(os.path.join(path,filename)) # Command to zip the files into a zipfile with the desired name/path cmd = 'zip -j' + ' ' + to_zip + ' ' + ' '.join(files) # A warning to the user of what command is about to run print 'Command to run:', cmd # Running the zip command (status, output) = commands.getstatusoutput(cmd) # If an error happens, print it to the terminal if status: sys.stderr.write(output) sys.exit(1) def main(): # This basic command line argument parsing code is provided. Add code to call your functions below. # Make a list of command line arguments, omitting the [0] element which is the script itself. args = sys.argv[1:] if not args: print "usage: [--todir dir][--tozip zipfile] dir [dir ...]"; sys.exit(1) # todir and tozip are either set from command line or left as the empty string. # The args array is left just containing the directories (paths) todir = '' if args[0] == '--todir': todir = args[1] del args[0:2] tozip = '' if args[0] == '--tozip': tozip = args[1] del args[0:2] # If no arguments, print an error if len(args) == 0: print "error: must specify one or more dirs" sys.exit(1) # +++your code here+++ ## Call your functions # If '--todir' command is called in the args, run the function to copy all of the # files from all the paths to the desired directory. if todir: copy_to(args[0:len(args)], todir) # If '--tozip' command is called in the args, run the function to create a zip file, # with the desired name, of all of the files from all the paths. elif tozip: zip_to(args[0:len(args)], tozip) # Run the function to print all special files from all paths, if no '--todir' or # '--to zipfile' command is included in the args else: paths = [] for dirname in args: paths.extend(get_special_paths(dirname)) print '\n'.join(paths) if __name__ == "__main__": main()
5bd5df1910a6c6765dfeff536eba03ca4878dc6e
TiwariSimona/Hacktoberfest-2021
/g-animesh02/cartoon3.py
2,243
4.0625
4
import cv2 class Cartoonizer: """Cartoonizer effect A class that applies a cartoon effect to an image. The class uses a bilateral filter and adaptive thresholding to create a cartoon effect. """ def __init__(self): pass def render(self, img_rgb): img_rgb = cv2.imread(img_rgb) img_rgb = cv2.resize(img_rgb, (1366, 768)) numDownSamples = 2 # number of downscaling steps numBilateralFilters = 50 # number of bilateral filtering steps # -- STEP 1 -- # downsample image using Gaussian pyramid img_color = img_rgb for _ in range(numDownSamples): img_color = cv2.pyrDown(img_color) # cv2.waitKey(0) # repeatedly apply small bilateral filter instead of applying # one large filter for _ in range(numBilateralFilters): img_color = cv2.bilateralFilter(img_color, 9, 9, 7) # cv2.waitKey(0) # upsample image to original size for _ in range(numDownSamples): img_color = cv2.pyrUp(img_color) # cv2.waitKey(0) # -- STEPS 2 and 3 -- # convert to grayscale and apply median blur img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2GRAY) img_blur = cv2.medianBlur(img_gray, 3) # cv2.waitKey(0) # -- STEP 4 -- # detect and enhance edges img_edge = cv2.adaptiveThreshold(img_blur, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 11,11) # cv2.waitKey(0) # -- STEP 5 -- # convert back to color so that it can be bit-ANDed with color image (x, y, z) = img_color.shape img_edge = cv2.resize(img_edge, (y, x)) img_edge = cv2.cvtColor(img_edge, cv2.COLOR_GRAY2RGB) cv2.waitKey(0) (x, y, z) = img_color.shape img_edge = cv2.resize(img_edge, (y, x)) return cv2.bitwise_and(img_color, img_edge) tmp_canvas = Cartoonizer() file_name = input() # File_name will come here res = tmp_canvas.render(file_name) cv2.imwrite("Cartoon version.jpg", res) cv2.imshow("Cartoon version", res) cv2.waitKey(0) cv2.destroyAllWindows()
5152927f8f259d1d78645fdec94330753225833a
TiwariSimona/Hacktoberfest-2021
/Aryan810/new_search_algorithm.py
1,268
3.71875
4
from threading import Thread import time class SearchAlgorithm1: def __init__(self, list_data: list, element): self.element = element self.list = list_data self.searching = True self.index = None def search(self): Thread(self.forward()) self.reverse() return self.index def reverse(self): len_all = len(self.list) for i in range(len(self.list) - 1): try: if not self.searching: break i = len_all - i if self.list[i] == self.element: self.searching = False self.index = i break except Exception: pass def forward(self): for i in range(len(self.list) - 1): try: if not self.searching: break if self.list[i] == self.element: self.searching = False self.index = i break except Exception: pass list_i = [i for i in range(800, 9800)] print("Searching by my algorithm...") index_element = SearchAlgorithm1(list_i, 8999).search() print(index_element)
f2744631653064a83857180583c831b187a8f53c
TiwariSimona/Hacktoberfest-2021
/ajaydhoble/euler_1.py
209
4.125
4
# List for storing multiplies multiplies = [] for i in range(10): if i % 3 == 0 or i % 5 == 0: multiplies.append(i) print("The sum of all the multiples of 3 or 5 below 1000 is", sum(multiplies))
bbfe214cd8be2137032f9f2fa056302865a9ada2
TiwariSimona/Hacktoberfest-2021
/akashrajput25/Some_py_prog/count_alphabet.py
178
3.671875
4
name=input("Enter your name\n") x=len(name) i=0 temp="" for i in range(x) : if name[i] not in temp: temp+=name[i] print(f"{name[i]}:{name.count(name[i])}")
16ad6fbbb5ab3f9a0e638a1d8fd7c4469d349c11
TiwariSimona/Hacktoberfest-2021
/parisheelan/bmi.py
957
4.15625
4
while True: print("1. Metric") print("2. Imperial") print("3. Exit") x=int(input("Enter Choice (1/2/3): ")) if x==1: h=float(input("Enter height(m) : ")) w=float(input("Enter weight(kg) : ")) bmi=w/h**2 print("BMI= ",bmi) if bmi<=18.5: print("Underweight") elif bmi>=25: if bmi>=30: print("Obese") else: print("Overweight") else: print("Normal") elif x==2: h=float(input("Enter height(in) : ")) w=float(input("Enter weight(lbs) : ")) bmi=(w*703)/h**2 print("BMI= ",bmi) if bmi<=18.5: print("Underweight") elif bmi>=25: if bmi>=30: print("Obese") else: print("Overweight") else: print("Normal") elif x==3: break else: print("wrong input")
c5a68da4e7ffdc1ddc86d247e3092c5eb7d09699
TiwariSimona/Hacktoberfest-2021
/CharalambosIoannou/doubly_linked_list_helper.py
2,632
4
4
class DListNode: """ A node in a doubly-linked list. """ def __init__(self, data=None, prev=None, next=None): self.data = data self.prev = prev self.next = next def __repr__(self): return repr(self.data) class DoublyLinkedList: def __init__(self): """ Create a new doubly linked list. Takes O(1) time. """ self.head = None def __repr__(self): """ Return a string representation of the list. Takes O(n) time. """ nodes = [] curr = self.head while curr: nodes.append(repr(curr)) curr = curr.next return '[' + ', '.join(nodes) + ']' def prepend(self, data): """ Insert a new element at the beginning of the list. Takes O(1) time. """ new_head = DListNode(data=data, next=self.head) if self.head: self.head.prev = new_head self.head = new_head def append(self, data): """ Insert a new element at the end of the list. Takes O(n) time. """ if not self.head: self.head = DListNode(data=data) return curr = self.head while curr.next: curr = curr.next curr.next = DListNode(data=data, prev=curr) def find(self, key): """ Search for the first element with `data` matching `key`. Return the element or `None` if not found. Takes O(n) time. """ curr = self.head while curr and curr.data != key: curr = curr.next return curr # Will be None if not found def remove_elem(self, node): """ Unlink an element from the list. Takes O(1) time. """ if node.prev: node.prev.next = node.next if node.next: node.next.prev = node.prev if node is self.head: self.head = node.next node.prev = None node.next = None def remove(self, key): """ Remove the first occurrence of `key` in the list. Takes O(n) time. """ elem = self.find(key) if not elem: return self.remove_elem(elem) def reverse(self): """ Reverse the list in-place. Takes O(n) time. """ curr = self.head prev_node = None while curr: prev_node = curr.prev curr.prev = curr.next curr.next = prev_node curr = curr.prev self.head = prev_node.prev
1c7ecdea2b8d027f39b67355f76a7b6e9c7fce47
SiyandzaD/analysehackathon
/tests/test.py
494
3.875
4
from analysehackathon.recursion import sum_array from analysehackathon.recursion import fibonacci def test_sum_array(): """ make sure sum_aray works correctly """ assert sum_array([1,2,3]) == 6, 'incorrect' print(sum_array([1,2,3])) assert sum_array([1,2,3,4]) == 10, 'incorrect' def test_fibonacci(): """ make sure sum_aray works correctly """ assert fibonacci(7) == 13, 'incorrect' assert fibonacci(12) == 144, 'incorrect'
932042d87adfba2bdb8d437b2c20d98d2afd7c22
VinayagamD/PythonBatch3
/hello.py
74
3.5
4
a = 10 b = 20 sum = a +b print(sum) print('Hello to python programming')
b6d05ea933a068a2a1716aee977af795764eeaa7
quirosnv/PROYECTO
/Proyecto Buscador en proceso/Buscador.py
5,085
3.890625
4
data = int(input("ingrese 1 si quiere buscar por cantante, 2 por cancion, 3 por album, 4 por año, -1 SALIR: ")) cantante = ['KALEO', 'kaleo', 'Coldplay', 'COLDPLAY', 'The Beatles', 'beatles'] contador = 0 while data != -1: if data == 1: print("Eligio buscar por cantante:") cant= input("Ingrese el nombre de un cantante o banda, para ser buscado: ") if cant == 'kaleo': print("Cancion: Way Down we go") if cant == 'beatles': print("Cancion: Let It Be\n","Cancion: Love Me Do") if cant == 'lp': print("Cancion: Lost On You") if cant == 'status quo': print("Cancion: In the Army Now") if cant == 'coldplay': print("Cancion: Yellow") if cant == 'depeche mode': print("Enjoy The Silence") if cant == 'the cure': print("Cancion: LoveSong\n","Cancion: Friday im in love") contador = contador +1 data = int(input("ingrese 1 si quiere buscar por cantante, 2 por cancion, 3 por album, 4 por año, -1 SALIR: ")) #else: # print("ARTISTA NO ENCONTRADO") if data == 2: print("\n***Eligio buscar por cancion***\n") music = input("\nIngrese el nombre de la cancion para ver su informacion:\n") if music == 'in the army now': print("Artista: Status Quo\n", "Album: In the Army Now\n", "Fecha de lanzamineto: 1986") if music == 'army': print("Cacion relacionada") print("Artista: Status Quo\n", "Album: In the Army Now\n", "Fecha de lanzamineto: 1986") if music == 'lovesong': print("Artist: The Cure\n", "Album: Japanese Whispers\n", "Year: 1989") if music== 'friday im in love' and 'friday': print("Artist: The Cure\n", "Album: Wish\n", "Year: 1992") if music == 'love me do' and 'love': print("Artist: The Beatles\n", "Album: Please Please Me\n" "Year: 1963") if music == 'let it be': print("Artist: The Beatles\n" "Format: MP3\n" "Album: Parachutes\n", "Year: 1970") if music == 'yellow': print("Artist: Coldplay\n" "Title: Yellow\n" "Album: Parachutes\n" "Year: 2000") if music == 'way down we go': print("Artist: KALEO\n", "Album: A/B\n", "Year: 2017") if music == 'lost on you': print("Artist: LP\n", "Album: Lost On You\n", "Year: 2016") contador = contador + 1 data = int(input("ingrese 1 si quiere buscar por cantante, 2 por cancion, 3 por album, 4 por año, -1 SALIR: ")) #else: # print("\nCANCION NO ENCONTRADA\n") if data == 3: print("***Eligio buscar por album***") albu = input("\nIngrese el nombre del album\n") if albu == 'ab': print("Artist: KALEO\n", "Year: 2017") if albu == 'lost on you': print("Artist: LP\n", "Year: 2016") if albu == 'in the army now': print("Artist; Status Quo\n", "Year: 1986") if albu == 'parachutes': print("Artist: Coldplay\n", "Year: 2000") if albu == 'the singles': print("Artist: The Peche Mode\n", "Year: 1990") if albu == 'japanese whisper': print("Artist: The Cure\n", "Year: 1989") if albu == 'wish': print("Artist: The Cure\n", "Year: 1992") if albu == 'please please me': print("Artist: The Beatles\n", "Year: 1970") contador = contador + 1 data = int(input("ingrese 1 si quiere buscar por cantante, 2 por cancion, 3 por album, 4 por año, -1 SALIR: ")) #else: # print("ALBUM NO ENCONTRADO") if data == 4: print("***ELIGIO BUSCAR POR AÑO") year = int(input("Ingrese un año para buscar informacion\n")) if year == 2017: print("Artist: KALEO\n", "Title: Way Down We Go\n", "Album: A/B") if year == 2016: print("Artist: LP\n", "Title: Lost On You\n", "Album: Lost On You") if year == 1986: print("Artist: Status Quo\n", "Title: In The Army Now\n", "Album: In The Army Now") if year == 2000: print("Artist: Coldplay\n", "Title: Yellow\n", "Format: MP3\n","Album: Parachutes") if year == 1990: print("Artist: Depeche Mode\n", "Title: Emjoy the Silence\n", "Album: The Singles") if year == 1989: print("Artist: The Cure\n" "Title: LoveSong\n","Album: Japanese Whispers") if year == 1992: print("Artist: The Cure\n", "Title: Friday Im In Love\n","Album: Wish") if year == 1963: print("Artist: The Beatles\n", "Title: Love Me Do\n", "Album: Please Please Me") if year == 1970: print("Artist: The Beatles\n", "Title: Let It Be\n", "Album: Parachutes") #else: # print("NO SE ENCONTRO INFORMACION POR AÑO") contador = contador +1 data = int(input("ingrese 1 si quiere buscar por cantante, 2 por cancion, 3 por album, 4 por año, -1 SALIR: "))
169e431b852089fcda8a72114582cba0f847afbe
whyalwaysmeee/Machine-Learning-Sklearn-Linear-Model
/Linear Model(Least Square Mothod).py
1,274
4.03125
4
import matplotlib.pyplot as plt from sklearn import datasets, linear_model import numpy as np from sklearn.metrics import mean_squared_error, r2_score # Load the diabetes dataset price = datasets.load_boston() # Use only one feature price_x = price.data[:,np.newaxis,5] # Split the data into training/testing sets price_x_train = price_x[:-20] price_x_test = price_x[-20:] # Split the targets into training/testing sets price_y_train = price.target[:-20] price_y_test = price.target[-20:] # Create linear regression object regr = linear_model.LinearRegression() # Train the model using the training sets regr.fit(price_x_train, price_y_train) # Make predictions using the testing set price_y_pred = regr.predict(price_x_test) # The coefficients print('Coefficients: \n', regr.coef_) # The mean squared error print("Mean squared error: %.2f" % mean_squared_error(price_y_test, price_y_pred)) # Explained variance score: 1 is perfect prediction print('Variance score: %.2f' % r2_score(price_y_test, price_y_pred)) # Plot outputs plt.scatter(price_x_test, price_y_test, color='black') plt.plot(price_x_test, price_y_pred, color='blue', linewidth=3) plt.xticks(()) plt.yticks(()) #display the plot graph plt.show()
08947ee21f916756c6edf64e0f1d1ad5730b59bd
LiangChen204/pythonApi_Test
/runoob/baseException.py
1,868
3.921875
4
#!//usr/local/bin python # -*- coding:utf-8 -*- # 走try try: fh = open("testfile", "w") fh.write("这是一个测试文件,用于测试异常!") except IOError: print("Error: 没有找到文件或读取文件失败") else: print("内容写入文件成功") fh.close() # 捕获异常 try: fh = open("testfile", "r") fh.write("这是一个测试文件,用于测试异常!") except IOError: print("Error1: 没有找到文件或读取文件失败") else: print("内容写入文件成功") fh.close() # finally try: fh = open("testfile", "w") fh.write("这是一个测试文件,用于测试异常!") finally: print("Error2: 没有找到文件或读取文件失败") try: fh = open("testfile", "w") try: fh.write("这是一个测试文件,用于测试异常!!") finally: print("关闭文件") fh.close() except IOError: print("Error3: 没有找到文件或读取文件失败") # 定义函数 def temp_convert(var): try: return int(var) except (ValueError) as Argument: print("参数没有包含数字\n", Argument) # 调用函数 temp_convert('oo') # 定义异常:使用 raise 语句抛出一个指定的异常 class MyError(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) try: raise MyError(2*2) except MyError as e: print("My exception occurred, value:", e.value) # raise MyError('oops!!') # 稍复杂的抛出异常例子 def divide(x, y): try: result = x / y except ZeroDivisionError: print("division by zero!") except TypeError: print("division unsupported!") else: print("result is", result) finally: print("executing finally clause") divide(2, 1) divide(2, 0) divide("2", "1")
5f285c43fbeb0489a57c0c703201abfb2df3a575
andfanilo/streamlit-sandbox
/archives/app_styling.py
567
3.734375
4
import pandas as pd import streamlit as st # https://stackoverflow.com/questions/43596579/how-to-use-python-pandas-stylers-for-coloring-an-entire-row-based-on-a-given-col df = pd.read_csv("data/titanic.csv") def highlight_survived(s): return ['background-color: green']*len(s) if s.Survived else ['background-color: red']*len(s) def color_survived(val): color = 'green' if val else 'red' return f'background-color: {color}' st.dataframe(df.style.apply(highlight_survived, axis=1)) st.dataframe(df.style.applymap(color_survived, subset=['Survived']))
00eb68cef452b9026f89936170f6c21e7ef09e2c
TeenaThmz/List
/list2.py
64
3.5
4
list2=[12,14,-95,3] list=[i for i in list2 if i>=0] print(list)
18785e22dbae3eed4affb39e74eaf9aaffadf949
kooose38/pytools_table
/xai/eli5.py
1,384
3.578125
4
from typing import Any, Dict, Union, Tuple import eli5 from eli5.sklearn import PermutationImportance import numpy as np import pandas as pd class VizPermitaionImportance: def __doc__(self): """ package: eli5 (pip install eli5) support: sckit-learn xgboost lightboost catboost lighting purpose: Visualize the importance of each feature quantity by giving a big picture explanation using a model """ def __init__(self): pass def show_weights(self, model: Any, importance_type: str="gain"): return eli5.show_weights(model, importance_type=importance_type) def show_feature_importance(self, model: Any, x_train: pd.DataFrame, y_train: Union[pd.DataFrame, pd.Series, np.ndarray], x_val: pd.DataFrame, y_val: Union[pd.DataFrame, pd.Series]) -> Tuple[object, object]: ''' warnings: support sklearn model only! By trying both the training data and the validation data, you can lyric whether there is a difference in the distribution of the data. x_train, y_train -> x_val, y_val ''' perm_train = PermutationImportance(model).fit(x_train, y_train) fig1 = eli5.show_weights(perm_train, feature_names=x_train.columns.tolist()) perm_val = PermutationImportance(model).fit(x_val, y_val) fig2 = eli5.show_weights(perm_val, feature_names=x_val.columns.tolist()) return fig1, fig2
c6ea76ace41ca74098a6562ee75c1e6216cb6fe2
plukis/merge_sort
/controllers/merge_sort.py
1,177
3.84375
4
# -*- coding: utf-8 -*- class MergeSort: a_list = [] def _merge_work(self, alist): print("delimito ", alist) if len(alist) > 1: mid = len(alist) // 2 lefthalf = alist[:mid] righthalf = alist[mid:] self._merge_work(lefthalf) self._merge_work(righthalf) i = 0 j = 0 k = 0 while i < len(lefthalf) and j < len(righthalf): if lefthalf[i] < righthalf[j]: alist[k] = lefthalf[i] i = i + 1 else: alist[k] = righthalf[j] j = j + 1 k = k + 1 while i < len(lefthalf): alist[k] = lefthalf[i] i = i + 1 k = k + 1 while j < len(righthalf): alist[k] = righthalf[j] j = j + 1 k = k + 1 print("Mezclando ", alist) return (alist) def run_merge(self): list_new = self._merge_work(self.a_list) return list_new def __init__(self, a_list): self.a_list = a_list
42a76e11702d791ddbff3b132710144b3d684323
qqinxl2015/leetcode
/112. Path Sum.py
1,036
3.859375
4
#https://leetcode.com/problems/path-sum/ # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def hasPathSum(self, root, sum): """ :type root: TreeNode :type sum: int :rtype: bool """ if not root: return False queue = {} queue[root] = root.val while not len(queue) == 0: queueOneLevel = {} for q, v in queue.items(): if q.left == None and q.right == None: if v == sum: return True if not q.left == None: queueOneLevel[q.left] = v + q.left.val if not q.right == None: queueOneLevel[q.right] = v + q.right.val queue = queueOneLevel return False
91ac4bcae6d6e1ba52e2145bdc158800e31d5d6e
qqinxl2015/leetcode
/009. Palindrome Number.py
470
3.796875
4
#https://leetcode.com/problems/palindrome-number/ class Solution: def isPalindrome(self, x): """ :type x: int :rtype: bool """ if x ==0: return True if x < 0: return False if int(x%10) == 0 and x !=0: return False ret = 0 while x > ret: ret = ret*10 + int(x%10) x = int(x/10) return x == ret or x== int(ret/10)
0e5abd4e1435664f4b626bc96a4d57fd2b5f2374
susanpinch/Read-and-Process-Data-Python
/pinchiaroli_susan_assign9_fileioio.py
1,952
3.96875
4
""" file_io_nested.py Write data from a set of nested lists to a file, then read it back in. By: Susan Pinchiaroli Date: 28 Nov 2018 """ data = []#empty list # This is our data data.append(['Susan','Davis',23,7])#append data data.append(['Harold','Humperdink',76,9]) data.append(['Lysistrata','Jones',40,12]) data.append(['Stan','Laurel',60]) data.append(['Rose','Harris',56,9,'Ambassador']) # filename is a string fname = "people.txt"#create file name ffirstobj=open(fname,'w')#open file name to write, so that once we complete the file it will be rewritten each time we code ffirstobj.write('')#write nothing ffirstobj.close()3close file # open file for actual writing fobj = open(fname, "w") line_text='' # write the data file # iterate through the list of people for i in range(len(data)): line = "" # iterate through each datum for the person for j in range(len(data[i])): # convert this datum to a string and append it to our line # NOTE: change this so it doesn't add ',' if this is last datum if j==(len(data[i])-1):#this separates so we know when to add comma and when not to line += str(data[i][j]) else: line += str(data[i][j]) + "," # NOTE: now, write this line to the data file line_text += line +'\n'#write linebreak after each line fobj.write(line_text)#write line_text into code # Don't forget to close the file! fobj.close() print("Done writing the file.") # Now, read the data back # Open the file for reading fobj = open("people.txt","r") # read the whole file into a string raw_dat = fobj.read() print("Read:",raw_dat) # break the string into a list of lines data_list = raw_dat.split("\n") # NOW: process your list of lines, so that you can put the # data back into a new list of lists, called data2 # this should have the exact same format as your original data structure data2 = [] # process data here print("Final data list:") print(data2)
0211584a0d5087701ee07b79328d4eb6c101e962
pintugorai/python_programming
/Basic/type_conversion.py
438
4.1875
4
''' Type Conversion: int(x [,base]) Converts x to an integer. base specifies the base if x is a string. str(x) Converts object x to a string representation. eval(str) Evaluates a string and returns an object. tuple(s) Converts s to a tuple. list(s) Converts s to a list. set(s) Converts s to a set. dict(d) Creates a dictionary. d must be a sequence of (key,value) tuples. and So on ''' x="5" xint = int(x); print("xint = ",xint)
ac7016757e19991066147e75b923b1ef734beb6d
zags4life/tableformatters
/tableformatters/tabledataprovider.py
776
3.75
4
# table_formatters/data_provider.py from abc import ABC, abstractproperty class TableFormatterDataProvider(ABC): '''An ABC that defines the interface for objects to display by a table formatter. Any object displayed by a TableFormatters must implement this ABC. Classes that implement this ABC can using this interface to define what data contained in its class to display ''' @abstractproperty def header_values(self): '''Must return a list of strings, containing the table header values. Note: order of this list is the order that headers will appear''' pass @abstractproperty def row_values(self): '''Must return a list of data to be output by a table formatter.''' pass
22c30808220f095b21eca67c444dc2b46b4026b0
gmayock/kaggle_titanic_competition
/gs-titanic-7-final-submission-code.py
11,102
3.515625
4
# # Load data # Ignore warnings to clean up output after all the code was written import warnings warnings.filterwarnings("ignore") import numpy as np import pandas as pd import os print(os.listdir("../input")) ['train.csv', 'gender_submission.csv', 'test.csv'] # Step 1 is to import both data sets training_data = pd.read_csv("../input/train.csv") testing_data = pd.read_csv("../input/test.csv") # Step two is to create columns which I will add to the respective datasets, in order to know which row came from which dataset when I combine the datasets training_column = pd.Series([1] * len(training_data)) testing_column = pd.Series([0] * len(testing_data)) # Now we append them by creating new columns in the original data. We use the same column name training_data['is_training_data'] = training_column testing_data['is_training_data'] = testing_column # # Combine and process # Now we can merge the datasets while retaining the key to split them later combined_data = training_data.append(testing_data, ignore_index=True, sort=False) # Encode gender (if == female, True) combined_data['female'] = combined_data.Sex == 'female' # Split out Title title = [] for i in combined_data['Name']: period = i.find(".") comma = i.find(",") title_value = i[comma+2:period] title.append(title_value) combined_data['title'] = title # Replace the title values with an aliased dictionary title_arr = pd.Series(title) title_dict = { 'Mr' : 'Mr', 'Mrs' : 'Mrs', 'Miss' : 'Miss', 'Master' : 'Master', 'Don' : 'Formal', 'Dona' : 'Formal', 'Rev' : 'Religious', 'Dr' : 'Academic', 'Mme' : 'Mrs', 'Ms' : 'Miss', 'Major' : 'Formal', 'Lady' : 'Formal', 'Sir' : 'Formal', 'Mlle' : 'Miss', 'Col' : 'Formal', 'Capt' : 'Formal', 'the Countess' : 'Formal', 'Jonkheer' : 'Formal', } cleaned_title = title_arr.map(title_dict) combined_data['cleaned_title'] = cleaned_title # Fill NaN of Age - first create groups to find better medians than just the overall median and fill NaN with the grouped medians grouped = combined_data.groupby(['female','Pclass', 'cleaned_title']) combined_data['Age'] = grouped.Age.apply(lambda x: x.fillna(x.median())) #add an age bin age_bin_conditions = [ combined_data['Age'] == 0, (combined_data['Age'] > 0) & (combined_data['Age'] <= 16), (combined_data['Age'] > 16) & (combined_data['Age'] <= 32), (combined_data['Age'] > 32) & (combined_data['Age'] <= 48), (combined_data['Age'] > 48) & (combined_data['Age'] <= 64), combined_data['Age'] > 64 ] age_bin_outputs = [0, 1, 2, 3, 4, 5] combined_data['age_bin'] = np.select(age_bin_conditions, age_bin_outputs, 'Other').astype(int) # Fill NaN of Embarked combined_data['Embarked'] = combined_data['Embarked'].fillna("S") # Fill NaN of Fare, adding flag for boarded free, binning other fares combined_data['Fare'] = combined_data['Fare'].fillna(combined_data['Fare'].mode()[0]) combined_data['boarded_free'] = combined_data['Fare'] == 0 fare_bin_conditions = [ combined_data['Fare'] == 0, (combined_data['Fare'] > 0) & (combined_data['Fare'] <= 7.9), (combined_data['Fare'] > 7.9) & (combined_data['Fare'] <= 14.4), (combined_data['Fare'] > 14.4) & (combined_data['Fare'] <= 31), combined_data['Fare'] > 31 ] fare_bin_outputs = [0, 1, 2, 3, 4] combined_data['fare_bin'] = np.select(fare_bin_conditions, fare_bin_outputs, 'Other').astype(int) # Fill NaN of Cabin with a U for unknown. Not sure cabin will help. combined_data['Cabin'] = combined_data['Cabin'].fillna("U") # Counting how many people are riding on a ticket from collections import Counter tickets_count = pd.DataFrame([Counter(combined_data['Ticket']).keys(), Counter(combined_data['Ticket']).values()]).T tickets_count.rename(columns={0:'Ticket', 1:'ticket_riders'}, inplace=True) tickets_count['ticket_riders'] = tickets_count['ticket_riders'].astype(int) combined_data = combined_data.merge(tickets_count, on='Ticket') # Finding survival rate for people sharing a ticket # Note that looking at the mean automatically drops NaNs, so we don't have an issue with using the combined data to calculate survival rate as opposed to just the training data combined_data['ticket_rider_survival'] = combined_data['Survived'].mean() # # Finding survival rate for people sharing a ticket (cont'd) # This groups the data by ticket # And then if the ticket group is greater than length 1 (aka more than 1 person rode on the ticket) # it looks at the max and min of the _other_ rows in the group (by taking the max/min after dropping the current row) # and if the max is 1, it replaces the default survival rate of .3838383 (the mean) with 1. This represents there being # at least one known member of the ticket group which survived. If there is no known survivor on that ticket, but there # is a known fatality, the value is replaced with 0, representing there was at least one known death in that group. If # neither, then the value remains the mean. for ticket_group, ticket_group_df in combined_data[['Survived', 'Ticket', 'PassengerId']].groupby(['Ticket']): if (len(ticket_group_df) != 1): for index, row in ticket_group_df.iterrows(): smax = ticket_group_df.drop(index)['Survived'].max() smin = ticket_group_df.drop(index)['Survived'].min() if (smax == 1.0): combined_data.loc[combined_data['PassengerId'] == row['PassengerId'], 'ticket_rider_survival'] = 1 elif (smin==0.0): combined_data.loc[combined_data['PassengerId'] == row['PassengerId'], 'ticket_rider_survival'] = 0 # Finding survival rate for people with a shared last name (same method as above basically) combined_data['last_name'] = combined_data['Name'].apply(lambda x: str.split(x, ",")[0]) combined_data['last_name_group_survival'] = combined_data['Survived'].mean() for last_name_group, last_name_group_df in combined_data[['Survived', 'last_name', 'PassengerId']].groupby(['last_name']): if (len(last_name_group_df) != 1): for index, row in last_name_group_df.iterrows(): smax = last_name_group_df.drop(index)['Survived'].max() smin = last_name_group_df.drop(index)['Survived'].min() if (smax == 1.0): combined_data.loc[combined_data['PassengerId'] == row['PassengerId'], 'last_name_group_survival'] = 1 elif (smin==0.0): combined_data.loc[combined_data['PassengerId'] == row['PassengerId'], 'last_name_group_survival'] = 0 # Finding survival rate for people with a shared last name _and_ fare combined_data['last_name_fare_group_survival'] = combined_data['Survived'].mean() for last_name_fare_group, last_name_fare_group_df in combined_data[['Survived', 'last_name', 'Fare', 'PassengerId']].groupby(['last_name', 'Fare']): if (len(last_name_fare_group_df) != 1): for index, row in last_name_fare_group_df.iterrows(): smax = last_name_fare_group_df.drop(index)['Survived'].max() smin = last_name_fare_group_df.drop(index)['Survived'].min() if (smax == 1.0): combined_data.loc[combined_data['PassengerId'] == row['PassengerId'], 'last_name_fare_group_survival'] = 1 elif (smin==0.0): combined_data.loc[combined_data['PassengerId'] == row['PassengerId'], 'last_name_fare_group_survival'] = 0 # Finding cabin group cabin_group = [] for i in combined_data['Cabin']: cabin_group.append(i[0]) combined_data['cabin_group'] = cabin_group # Adding a family_size feature as it may have an inverse relationship to either of its parts combined_data['family_size'] = combined_data.Parch + combined_data.SibSp + 1 # Mapping ports to passenger pickup order port = { 'S' : 1, 'C' : 2, 'Q' : 3 } combined_data['pickup_order'] = combined_data['Embarked'].map(port) # Encode childhood combined_data['child'] = combined_data.Age < 16 # One-Hot Encoding the titles combined_data = pd.concat([combined_data, pd.get_dummies(combined_data['cleaned_title'], prefix="C_T")], axis = 1) # One-Hot Encoding the Pclass combined_data = pd.concat([combined_data, pd.get_dummies(combined_data['Pclass'], prefix="PClass")], axis = 1) # One-Hot Encoding the cabin group combined_data = pd.concat([combined_data, pd.get_dummies(combined_data['cabin_group'], prefix="C_G")], axis = 1) # One-Hot Encoding the ports combined_data = pd.concat([combined_data, pd.get_dummies(combined_data['Embarked'], prefix="Embarked")], axis = 1) # # Import Classifier (only KNN in the end, see previous notebooks for exploration) new_train_data=combined_data.loc[combined_data['is_training_data']==1] new_test_data=combined_data.loc[combined_data['is_training_data']==0] from sklearn.neighbors import KNeighborsClassifier from sklearn.model_selection import KFold from sklearn.model_selection import cross_val_score k_fold = KFold(n_splits = 10, shuffle=True, random_state=0) from sklearn.model_selection import cross_val_predict from sklearn.metrics import confusion_matrix # # Define features # Here are the features features = ['Pclass', 'Age', 'SibSp', 'Parch', 'Fare', 'female', 'child', 'C_T_Master', 'C_T_Miss', 'C_T_Mr', 'C_T_Mrs', 'C_T_Formal','C_T_Academic', 'C_T_Religious','C_G_A', 'C_G_B', 'C_G_C', 'C_G_D', 'C_G_E', 'C_G_F', 'C_G_G', 'C_G_T', 'C_G_U', 'family_size', 'ticket_riders', 'ticket_rider_survival', 'last_name_group_survival', 'last_name_fare_group_survival'] target = 'Survived' cvs_train_data = new_train_data[features] cvs_test_data = new_test_data[features] cvs_target = new_train_data['Survived'] # # Scale them from sklearn.preprocessing import MinMaxScaler mm_scaler = MinMaxScaler() mms_train_data = mm_scaler.fit_transform(cvs_train_data) mms_test_data = mm_scaler.transform(cvs_test_data) mms_target = new_train_data['Survived'] mms_train_data.shape, mms_test_data.shape, mms_target.shape # # GridSearchCV for KNN from sklearn.model_selection import GridSearchCV # on all features n_neighbors = [14, 16, 17, 18, 19, 20, 22] algorithm = ['auto'] weights = ['uniform', 'distance'] leaf_size = list(range(10,30,1)) hyperparams = {'algorithm': algorithm, 'weights': weights, 'leaf_size': leaf_size, 'n_neighbors': n_neighbors} gd=GridSearchCV(estimator = KNeighborsClassifier(), param_grid = hyperparams, verbose=True, cv=k_fold, scoring = "accuracy") gd.fit(mms_train_data, mms_target) print(gd.best_score_) print(gd.best_estimator_) gd.best_estimator_.fit(mms_train_data, mms_target) prediction = gd.best_estimator_.predict(mms_test_data) submission = pd.DataFrame({ "PassengerId" : new_test_data['PassengerId'], "Survived" : prediction.astype(int) }) submission_name = 'knn_all_feat.csv' submission.to_csv(submission_name, index=False)
f172ed025705f196ebe0c394595dee382a415ccf
jaaaaaaaaack/zalgo
/zalgo.py
1,428
3.96875
4
# zalgo.py # Jack Beal, June 2020 # A small module to give any text a flavor of ancient doom from random import random def validCharacter(char, stoplist): """ Helps to prevent unwanted manipulation of certain characters.""" if char in stoplist: return False else: return True def uniformMangle(s, additives, n=1, p=1, stoplist=[]): """ Convenience function for uniformly mangling longer strings.""" mangled = "" for c in s: mangled += mangle(c, additives, n, p, stoplist) return mangled def mangle(char, additives, n=1, p=1, stoplist=[]): """ Accumulate additive characters from the list of possible additives, up to a maximum n and with average density p, and join them to the input character.""" mangled = "" if validCharacter(char, stoplist): joiners = "" for i in range(int(n)): if random() <= p: joiners += additives[int(random()*len(additives))] mangled += char+joiners return mangled else: return char def main(): testString = "ZALGO.py" additives = ["\u0300","\u0301","\u0302","\u0315","\u031b","\u0327","\u0316","\u0317","\u0318"] stoplist = ["."] greeting = uniformMangle(testString, additives, n=3, p=1, stoplist=stoplist) print(greeting, "- a salt shaker for your text, filled with anxiety and foreboding!") if __name__ == "__main__": main()
cf37344075ac3ebcd091fcfe24de0444742a01be
elliotgreenlee/advent-of-code-2019
/day10/day10_puzzle1.py
2,365
3.734375
4
import math def read_puzzle_file(filename): with open(filename, 'r') as f: points = set() for y, line in enumerate(f): for x, point in enumerate(line): if point is '#': points.add((x, y)) return points def number_slopes(starting_point, other_points): slopes = set() for point in other_points: try: slope = str((point[1] - starting_point[1]) / (point[0] - starting_point[0])) except ZeroDivisionError: slope = str(math.inf) if point[0] > starting_point[0]: slope = 'right' + slope elif point[0] < starting_point[0]: slope = 'left' + slope if point[1] > starting_point[1]: slope = 'above' + slope elif point[1] < starting_point[1]: slope = 'below' + slope slopes.add(slope) if len(slopes) == 278: print(starting_point) return len(slopes) def find_best_station(asteroids): # whichever starting point has the maximum number of slopes is the best all_slope_counts = [] for station_asteroid in asteroids: working_copy_asteroids = asteroids.copy() working_copy_asteroids.remove(station_asteroid) all_slope_counts.append(number_slopes(station_asteroid, working_copy_asteroids)) return max(all_slope_counts) def solve_day10puzzle1(): asteroids = read_puzzle_file("day10_data.txt") return find_best_station(asteroids) def tests_day10puzzle1(): asteroids = read_puzzle_file("day10_test1.txt") if find_best_station(asteroids) != 8: return False asteroids = read_puzzle_file("day10_test2.txt") if find_best_station(asteroids) != 33: return False asteroids = read_puzzle_file("day10_test3.txt") if find_best_station(asteroids) != 35: return False asteroids = read_puzzle_file("day10_test4.txt") if find_best_station(asteroids) != 41: return False asteroids = read_puzzle_file("day10_test5.txt") if find_best_station(asteroids) != 210: return False return True def main(): if tests_day10puzzle1(): print("Day 10 Puzzle 1 answer: ", solve_day10puzzle1()) if __name__ == "__main__": main()
5976699fa85e8eb7237467f8732bdca6df5d350d
jasoncwells/Test_2
/scraper.py
230
3.578125
4
myvar = 'What is happening today' myage = 46 mylist = ['how','now','brown','cow'] mynumlist = [1,2,3,4,5] print myvar print myage print mylist listlength = len(mylist) print listlength stringlength = len(myvar) print stringlength
dd793f5d7f0d88d1a6446c8ce2025904144c2136
cybera/data-science-for-entrepreneurs-workshops
/helpers/color.py
820
3.640625
4
def hex2rgb(color): return tuple(int(color.lstrip('#')[i:i+2], 16) for i in (0, 2 ,4)) # Decimal number to HEX str def dec2hex(n): n = int(n) if (n > 16): return str(hex(n).split('x')[-1]) else: return "0" + str(hex(n).split('x')[-1]) # Gradient starting at color "start" to color "stop" with "steps" colors # Not include start and stop colors to result def gradient(start, stop, steps): out = [] r = hex2rgb(start)[0] g = hex2rgb(start)[1] b = hex2rgb(start)[2] r_step = (hex2rgb(stop)[0] - r) / steps g_step = (hex2rgb(stop)[1] - g) / steps b_step = (hex2rgb(stop)[2] - b) / steps for i in range(steps): r = r + r_step g = g + g_step b = b + b_step out.append("#" + dec2hex(r) + dec2hex(g) + dec2hex(b)) return out
ca8162f61acd25fc40f57615225c78c2d1ad0623
sambapython/batch53
/modules/file1.py
199
3.546875
4
print("name:",__name__) a=100 b=200 c=a+b d=a-b def fun(): print("this is fun in file1") if __name__=="__main__": def fun1(): print("this is fun1") print("this is file1") fun() print(a,b,c,d)
38da743b5276b4924cc7e40aa237daef479aaed8
sambapython/batch53
/app.py
89
3.515625
4
a=raw_input("Enter a value:") b=raw_input("Enter b value:") a=int(a) b=int(b) print (a+b)
b483de5c6c42f4c9234be3dacd50c8828437b260
aishraj/slow-learner
/python/pythonchallenge/001.py
614
3.53125
4
import string import collections def decrypt(cyphertext): values = '' keys = '' for i in range(ord('a'),ord('z')+1): keys += chr(i) j = i - ord('a') values += chr(ord('a') + (j + 2) % 26) transtable = string.maketrans(keys,values) return string.translate(cyphertext,transtable) if __name__ == "__main__": mycyphertext = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr\'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj." print decrypt(mycyphertext)
cdb57be6cb1e664d937ecc44efcd00095bdb7407
azbrainiac/PyStudy
/third.py
702
3.953125
4
for item in [1, 3, 7, 4, "qwerty", [1, 2, 4, 6]]: print(item) for item in range(5): print(item ** 2) wordlist = ["hello", "ass", "new", "year"] letterlist = [] for aword in wordlist: for aletter in aword: if aletter not in letterlist: letterlist.append(aletter) print(letterlist) sqlist = [] for x in range(4, 20): sqlist.append(x**2) print(sqlist) sqlist = [x**2 for x in range(1, 9)] print(sqlist) sqlist = [x**2 for x in range(1, 10) if x % 3 == 0] print(sqlist) letterlist = [ch.upper() for ch in "asshole" if ch not in "eloh"] print(letterlist) print(list(set([ch for ch in "".join(wordlist)]))) print(list(set(s[i] for s in wordlist for i in range(len(s))))) #input("Press Enter")
ad94bc21b8b6a213a11e455e666325fdcf95d890
patpalmerston/Algorithms-1
/making_change/making_change.py
2,323
4.0625
4
#!/usr/bin/python import sys def making_change(amount, denominations=[1, 5, 10, 25, 50]): # base case if amount <= 2: return 1 # starting a cache equal to the size of the amount, plus an initial default of 1 for index of zero cache = [1] + [0] * amount # loop through the coins in our list for coin in denominations: # loop through the range of the outer loop coin and our amount + 1 # first outer loop iteration starts at index of 1, then 5, then 10, then 25, then 50, as our index starts in the range dictated by the value of our denominations outer loop. for i in range(coin, amount + 1): # print('coin:', coin, f'amount: {amount} + 1 = ', amount +1) # print("i: ", i, "i - coin = ", i-coin) # inner loop index starts from the index equal to the value of coin and will iterate however many times that that index can be subtracted from 'amount + 1'. Our Cache indexes will be given a value every time the current index(1-11) minus the coin value from the denominations list, is less than our original amount of '10'. Each iteration of the outer loop will start our inner loop at the index equal to the value of the the outer loop coin. cache[i] += cache[i - coin] # default value of cache[0] = 1 # then we cycle through cache[1]-cache[11] subtracting the coin value of "1 cent", from the current loop index # giving each loop that is able complete this task a value of 1 in the cache index # when we hit cache[11] and minus the coin of '1', we return the value of amount and restart the loop # print(cache, cache[amount]) # print('cache amount', cache[amount]) # this counts how many times the loop was able to generate the value of amount return cache[amount] if __name__ == "__main__": # Test our your implementation from the command line # with `python making_change.py [amount]` with different amounts if len(sys.argv) > 1: denominations = [1, 5, 10, 25, 50] amount = int(sys.argv[1]) print("There are {ways} ways to make {amount} cents.".format( ways=making_change(amount, denominations), amount=amount)) else: print("Usage: making_change.py [amount]")
5f89f65fa211fff9288edd96e534a90baaca6919
hklgit/PythonStudy
/pythonCodes/com/coocaa/study/类/Student.py
885
3.9375
4
class Student(object): # 把一些我们认为必须绑定的属性强制填写进去。 # 通过定义一个特殊的__init__方法,在创建实例的时候,就把name,score等属性绑上去: # 特殊方法“__init__”前后分别有两个下划线!!! # 注意到__init__方法的第一个参数永远是self,表示创建的实例本身,因此,在__init__方法内部,就可以把各种属性绑定到self,因为self就指向创建的实例本身。 # 这个跟构造器很类似 def __init__(self, name, age): self.name = name self.age = age # Student的一个对象 # stu = Student() # 注意: 我竟然犯了一个错误,__int__ 然后就是报错: # TypeError: object() takes no parameters stu = Student('kerven',20) print(stu.age) # print(stu) # <__main__.Student object at 0x00000000026A8128>
becc6a966f455b1d32d7633c9f7cfb53e110b033
kelvinng2017/chat1
/test2.py
225
3.890625
4
while True: print("請輸入密碼:", end='') password = input() if int(password) == 1234567: print("歡迎光臨!敬請指教") break else: print("密碼錯誤!請在重新輸入")
c538c8864abefaab9f3e97af43283c2bc0efc63f
randeeppr/fun
/desired_days.py
1,188
4.0625
4
#!/usr/bin/python # # This program prints the desired day(s) in between start date and end date # import datetime,sys,getopts def getDesiredDay(start_date,end_date,desired_day): v1 = value_of_start_day = weekdays[start_date.strftime("%a")] v2 = value_of_desired_day = weekdays[desired_day] #print(v1) #print(v2) if v1 == v2: return start_date else: start_date = start_date + datetime.timedelta(days=(abs(v2-v1))) return start_date weekdays = { "Mon" : 1, "Tue" : 2, "Wed" : 3, "Thu" : 4, "Fri" : 5, "Sat" : 6, "Sun" : 7 } start_date = datetime.datetime(2019, 04, 8, 00, 00) end_date = datetime.datetime(2019, 04, 30, 00, 00) desired_day = sys.argv[1] #print(start_date.strftime("%Y-%m-%d")) #print(start_date.strftime("%a")) start_date = getDesiredDay(start_date,end_date,desired_day) print("Next {0} is {1}".format(desired_day,start_date.strftime("%Y-%m-%d"))) while start_date <= end_date: print(start_date.strftime("%Y-%m-%d")) start_date= start_date + datetime.timedelta(days=7) sys.exit(0) #output example ''' [root@4a178e708f64 fun]# ./desired_days.py Thu Next Thu is 2019-04-11 2019-04-11 2019-04-18 2019-04-25 ''' [root@4a178e708f64 fun]#
0d261b64fc0fee1629ebb3e24483ea4ecd89ad07
Jav10/Matplotlib-Plotting
/UNO/backToBackBarCharts.py
488
3.59375
4
#Matplotlib Plotting #Autor: Javier Arturo Hernández Sosa #Fecha: 30/Sep/2017 #Descripcion: Ejecicios Matplotlib Plotting - Alexandre Devert - (18) #Gráficas de barras espalda con espalda import numpy as np import matplotlib.pyplot as plt women_pop=np.array([5., 30., 45., 22.]) men_pop=np.array([5., 25., 50., 20.]) X=np.arange(4) plt.barh(X, women_pop, color='r') #Hacemos negativos los valores de la población de hombres para que #se vea el efecto plt.barh(X, -men_pop, color='b') plt.show()
1e618d71d615ae0f419c6d78f9684f028d8f4aa6
jip174/cs362--Software-Eng-2
/week4/test/teststring_testme.py
480
3.765625
4
import testme from unittest import TestCase import string class teststring(TestCase): def test_input_string(self): ts = testme.inputString() count = 0 for x in ts: if x.isalpha() == True or x == '\0': count += 1 print(x) else: print("Invalid input") break self.assertEqual(count, 6) #self.assertTrue(ts.isalpha() == True)
b74c84a5554423d4fcb488945748ebbe64bdd716
jip174/cs362--Software-Eng-2
/week4/test/tester_testme.py
864
3.8125
4
import testme from unittest import TestCase import string class testchar(TestCase): def test_input_char(self): tc = testme.inputChar() letters = string.ascii_letters if (tc.isalpha() == True): #print(tc) self.assertTrue(tc.isalpha() == True) else: temp = " " for temp in tc: if tc in string.punctuation: temp = tc self.assertEqual(tc, temp) class teststring(TestCase): def test_input_string(self): ts = testme.inputString() count = 0 for x in ts: if x.isalpha() == True or x == '\0': count += 1 print(x) else: print("Invalid input") break self.assertEqual(count, 6)
4891587a4606af3b4d6e284ac033185117abbf14
peluche/mooc_algo2
/graphs/dfs_topological_search.py
1,058
3.875
4
#!/usr/bin/env python3 explored = {} current_label = 0 def is_explored(vertex): return explored.get(vertex) != None def explore(vertex): explored[vertex] = True def tag(vertex): global current_label explored[vertex] = current_label current_label -= 1 def dfs(graph, vertex): explore(vertex) for node in graph[vertex]: if not is_explored(node): dfs(graph, node) tag(vertex) def dfs_loop(graph): """ generate a topological order of the directed graph /!\ graph must be directed, graph shouldn't have any cycle """ for vertex, _ in graph.items(): if not is_explored(vertex): dfs(graph, vertex) def main(): """ A--->B--->D `-->C--´ E--´ """ graph = { 'A': ['B', 'C'], 'B': ['D'], 'C': ['D'], 'D': [], 'E': ['C'], } global current_label global explored explored = {} current_label = len(graph) dfs_loop(graph) print(explored) if __name__ == '__main__': main()
d902702bc0e0c3168d745fdf7dfda52fbff1c3d0
Jeniffersc/Curso-Introducao-a-Ciencia-da-Computacao-com-Python-Parte-1
/Programas da 3a week/Tarefa de programação/Exercícios 2 - FizzBuzz parcial, parte 1.py
100
4.1875
4
num = int(input("Digite um número inteiro: ")) if num % 3 == 0: print ("Fizz") else: print (num)
29781302370b185924aca0e0384ab49f4af4764c
Jeniffersc/Curso-Introducao-a-Ciencia-da-Computacao-com-Python-Parte-1
/Programas da 7a week/Tarefa de programação Lista de exercícios - 6/Exercício 2 - Retângulos 2.py
456
4
4
larg = int(input("Digite o número da largura do retângulo: ")) alt = int(input("Digite o número da altura do retângulo: ")) x=larg y=alt cont=larg while y > 0: while x > 0 and x <= larg: if y==1 or y==alt: print ("#", end="") else: if x==1 or x==cont: print ("#", end="") else: print(" ", end="") x = x - 1 print () y = y - 1 x = larg
1d326577cedbfe93c61026649efd049a720ded66
Jeniffersc/Curso-Introducao-a-Ciencia-da-Computacao-com-Python-Parte-1
/Programas da 3a week/Praticar tarefa de programação Exercícios adicionais (opcionais)/Exercício 1 - Distância entre dois pontos.py
277
3.828125
4
import math x1 = int(input("Digite o primeiro x: ")) y1 = int(input("Digite o primeiro y: ")) x2 = int(input("Digite o segundo x: ")) y2 = int(input("Digite o segundo y: ")) dis = math.sqrt ((x1 - x2)**2 + (y1 - y2)**2) if dis > 10: print("longe") else: print ("perto")
2c6eb6b2fbcc6a1cd440d3c0fff85fdb58e0d72f
maimoonmaimu/codeketa
/set1-5.py
104
3.546875
4
m,a,i=input().split() if(m>a): if(m>i): print(m) elif(a>i): print(a) else: print(i)
91cbaa9c8b92230b76a14a687875b71358fe260f
lx36301766/AtlanLeetCode
/src/pl/atlantischi/leetcode/medium/Medium486.py
2,964
3.78125
4
""" 给定一个表示分数的非负整数数组。 玩家1从数组任意一端拿取一个分数,随后玩家2继续从剩余数组任意一端拿取分数,然后玩家1拿,……。 每次一个玩家只能拿取一个分数,分数被拿取之后不再可取。直到没有剩余分数可取时游戏结束。最终获得分数总和最多的玩家获胜。 给定一个表示分数的数组,预测玩家1是否会成为赢家。你可以假设每个玩家的玩法都会使他的分数最大化。 示例 1: 输入: [1, 5, 2] 输出: False 解释: 一开始,玩家1可以从1和2中进行选择。 如果他选择2(或者1),那么玩家2可以从1(或者2)和5中进行选择。如果玩家2选择了5,那么玩家1则只剩下1(或者2)可选。 所以,玩家1的最终分数为 1 + 2 = 3,而玩家2为 5。 因此,玩家1永远不会成为赢家,返回 False。 示例 2: 输入: [1, 5, 233, 7] 输出: True 解释: 玩家1一开始选择1。然后玩家2必须从5和7中进行选择。无论玩家2选择了哪个,玩家1都可以选择233。 最终,玩家1(234分)比玩家2(12分)获得更多的分数,所以返回 True,表示玩家1可以成为赢家。 注意: 1 <= 给定的数组长度 <= 20. 数组里所有分数都为非负数且不会大于10000000。 如果最终两个玩家的分数相等,那么玩家1仍为赢家。 """ import numpy as np class Solution: # 递归 def PredictTheWinner(self, nums): """ :type nums: List[int] :rtype: bool """ return self.winnter(nums, 0, len(nums) - 1) >= 0 def winnter(self, nums, start, end): if start == end: return nums[start] else: pick_first = nums[start] - self.winnter(nums, start + 1, end) pick_last = nums[end] - self.winnter(nums, start, end - 1) return max(pick_first, pick_last) # 二阶动态规划 def PredictTheWinner2(self, nums): """ :type nums: List[int] :rtype: bool """ n = len(nums) dp = np.zeros([n, n]) # dp = [[0] * n for i in range(n)] for i in range(0, n - 1)[::-1]: for j in range(i + 1, n): a = nums[i] - dp[i + 1][j] b = nums[j] - dp[i][j - 1] dp[i][j] = max(a, b) # print("%s %s" % (i, j)) print(dp) return dp[0][n - 1] >= 0 # 一阶动态规划 def PredictTheWinner3(self, nums): """ print("%s %s" % (i, j)) :type nums: List[int] :rtype: bool """ def main(): nums = [1, 5, 2, 4, 6] # nums = [2, 4, 3, 4, 55, 1, 2, 3, 1, 2, 4, 3, 4, 5, 1] solution = Solution() ret = solution.PredictTheWinner2(nums) print(ret) if __name__ == '__main__': main() # print(__name__)
0b241bfd9a912c87ef304cb43ace9ffb90cce82c
cyro809/trabalho-tesi
/sentimusic/distance_utils.py
1,284
4
4
#! /usr/bin/env python # -*- coding: utf-8 -*- import math # --------------------------------------------------------------------------- # Função calculate_distance(): Calcula a distancia euclidiana entre dois pontos # - vec1: Vetor 1 # - vec2: Vetor 2 # - num: Número de dimensões espaciais # --------------------------------------------------------------------------- def calculate_distance(p1,p2, num): result = 0 for i in range(0,num): result += (p1[i] - p2[i])**2 return math.sqrt(result) # --------------------------------------------------------------------------- # Função get_minimum_distance_label(): Calcula a menor distancia entre a # musica e os centroides retornando o # grupo a qual ela pertence # - centers: Centroides de cada grupo # - music: Coordenadas da musica no espaço # --------------------------------------------------------------------------- def get_minimum_distance_label(centers, music): min_distance = 1000 label = 0 for i in range(0, len(centers)): distance = calculate_distance(music, centers[i], len(centers[i])) if distance < min_distance: min_distance = distance label = i return label
7faefdd7192a19669f3b7a0e73e08b2b769ed15c
chulhee23/today_ps
/hanbit/dfs_bfs/ice_frame.py
810
3.640625
4
# 얼음 틀 모양 주어졌을 때 # 생성되는 최대 아이스크림 수 # 2차원 배열 # 1은 막힘 -> 방문. # 0은 열림 -> 아직 방문X. # 0 인접한 0들 묶음 갯수를 파악 def dfs(x, y): # 범위 벗어나면 종료 if x <= -1 or x >= n or \ y <= -1 or y >= m: return False # 방문 전 if graph[x][y] == 0: # 방문 처리 graph[x][y] = 1 # 상하좌우 재귀 호출 dfs(x-1, y) dfs(x, y-1) dfs(x+1, y) dfs(x, y+1) return True return False n, m = map(int, input()) graph = [] for i in range(n): graph.append(list(map(int, input().split()))) result = 0 for i in range(n): for j in range(m): if dfs(i, j) == True: result += 1 print(result)
3b05df07dcddc639466ba683231cfeff56ba44d8
chulhee23/today_ps
/data_structure/stack/stack.py
547
3.921875
4
class Stack: def __init__(self): self.top = [] def __len__(self): return len(self.top) def __str__(self): return str(self.top[::1]) def push(self, item): self.top.append(item) def pop(self): if not self.isEmpty(): return self.top.pop(-1) else: print("stack underflow") exit() def isEmpty(self): return len(self.top) == 0 stack = Stack() stack.push(2) stack.push(1) stack.push(3) print(stack) stack.pop() print(stack)
101eea3d60903038cf55472c0ef04b5591e0190e
chulhee23/today_ps
/BOJ/15000-19999/17413.py
1,793
3.515625
4
from collections import deque import sys word = list(sys.stdin.readline().rstrip()) i = 0 start = 0 while i < len(word): if word[i] == "<": # 열린 괄호를 만나면 i += 1 while word[i] != ">": # 닫힌 괄호를 만날 때 까지 i += 1 i += 1 # 닫힌 괄호를 만난 후 인덱스를 하나 증가시킨다 elif word[i].isalnum(): # 숫자나 알파벳을 만나면 start = i while i < len(word) and word[i].isalnum(): i += 1 tmp = word[start:i] # 숫자,알파벳 범위에 있는 것들을 tmp.reverse() # 뒤집는다 word[start:i] = tmp else: # 괄호도 아니고 알파,숫자도 아닌것 = 공백 i += 1 # 그냥 증가시킨다 print("".join(word)) # nums = list(str(i) for i in range(10)) # stacking = False # queueing = False # for c in s: # if c.isalpha() or c in nums: # if queueing: # queue.append(c) # else: # stacking = True # stack.append(c) # elif c == '<': # stacking = False # queueing = True # while stack: # tmp = stack.pop() # ans += tmp # queue.append(c) # elif c == '>': # queueing = False # queue.append(c) # while queue: # ans += queue.popleft() # else: # # 공백 # if stacking: # stacking = False # while stack: # ans += stack.pop() # ans += c # elif queueing: # queue.append(c) # else: # ans += c # if stacking: # while stack: # tmp = stack.pop() # ans += tmp # print(ans)
3597f00172708154780a6e83227a7930e034d166
csu100/LeetCode
/python/leetcoding/LeetCode_225.py
1,792
4.5
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/1/31 10:37 # @Author : Zheng guoliang # @Version : 1.0 # @File : {NAME}.py # @Software: PyCharm """ 1.需求功能: https://leetcode-cn.com/problems/implement-stack-using-queues/ 使用队列实现栈的下列操作: push(x) -- 元素 x 入栈 pop() -- 移除栈顶元素 top() -- 获取栈顶元素 empty() -- 返回栈是否为空 2.实现过程: """ from queue import Queue class MyStack: def __init__(self): """ Initialize your data structure here. """ self.stack = Queue() def push(self, x): """ Push element x onto stack. """ if self.stack.empty(): self.stack.put(x) else: temp = Queue() temp.put(x) while not self.stack.empty(): temp.put(self.stack.get()) while not temp.empty(): self.stack.put(temp.get()) def pop(self): """ Removes the element on top of the stack and returns that element. """ if self.stack.empty(): raise AttributeError("stack is empty!") return self.stack.get() def top(self): """ Get the top element. """ if self.stack.empty(): raise AttributeError("stack is empty!") a=self.stack.get() self.push(a) return a def empty(self): """ Returns whether the stack is empty. """ return True if self.stack.empty() else False if __name__ == '__main__': mystack = MyStack() print(mystack.empty()) for i in range(4): mystack.push(i * i) print(mystack.empty()) while not mystack.empty(): print(mystack.pop())
0efc9e2b00e3c6ad7251b21c0dbdda5fe5a748ff
csu100/LeetCode
/python/leetcoding/LeetCode_206.py
994
3.984375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/1/24 14:42 # @Author : Zheng guoliang # @Site : # @File : LeetCode_206.py # @Software: PyCharm """ 1.需求功能: https://leetcode.com/problems/reverse-linked-list/description/ 2.实现过程: """ from leetcoding.ListNode import ListNode class Solution: def reverseList(self, head): if head is None or head.next is None: return head head_node = None while head: node = head.next head.next = head_node head_node = head head = node return head_node def printList(head): while head: print(head.val) head = head.next if __name__ == '__main__': a1 = ListNode(1) a2 = ListNode(2) a3 = ListNode(3) a4 = ListNode(4) a5 = ListNode(5) a1.next = a2 a2.next = a3 a3.next = a4 a4.next = a5 solution = Solution() result = solution.reverseList(a1) printList(result)
0768a12697cd31a72c3d61ecfa4eda9a1aa0751e
csu100/LeetCode
/python/leetcoding/LeetCode_232.py
1,528
4.46875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/1/31 17:28 # @Author : Zheng guoliang # @Version : 1.0 # @File : {NAME}.py # @Software: PyCharm """ 1.需求功能: https://leetcode-cn.com/problems/implement-queue-using-stacks/submissions/ 使用栈实现队列的下列操作: push(x) -- 将一个元素放入队列的尾部。 pop() -- 从队列首部移除元素。 peek() -- 返回队列首部的元素。 empty() -- 返回队列是否为空。 2.实现过程: """ class MyQueue: def __init__(self): """ Initialize your data structure here. """ self._myqueue = [] def push(self, x): """ Push element x to the back of queue. """ if len(self._myqueue) < 1: self._myqueue.append(x) else: temp = self._myqueue[::-1] temp.append(x) self._myqueue = temp[::-1] def pop(self): """ Removes the element from in front of queue and returns that element. """ if len(self._myqueue) < 1: raise AttributeError("queue is empty!") return self._myqueue.pop() def peek(self) -> int: """ Get the front element. """ if len(self._myqueue) < 1: raise AttributeError("queue is empty!") return self._myqueue[-1] def empty(self) -> bool: """ Returns whether the queue is empty. """ return True if len(self._myqueue) < 1 else False
0341229309f1cf0e9add85b69c248e2f13e9f819
ZhouYzzz/TF-CT-ResCNN
/test/test_decorator.py
328
3.734375
4
def print_args(func): def wrapped_func(*args, **kwargs): print(func.__name__, func.__doc__) for a in args: print(a) for k, v in kwargs: print(k, v) return func(*args, **kwargs) return wrapped_func @print_args def add(x: int, y: int): """:Add two integers""" return x + y print(add(1, 2))
71a23a3ac6f35438be6d943dad386d2f33c01c84
DenisoDias/python-password-generator
/password_gen.py
1,181
3.734375
4
from random import choice import argparse import string arg = argparse.ArgumentParser(add_help=True) arg.add_argument('-s', '--size', default=20, nargs="?", type=int, help='Parameter to set size of password you will generate') arg.add_argument('-q', '--quantity', default=10, nargs="?", type=int, help="Parameter to set how much passwords you want to generate each time you run the script") arg.add_argument('-n', '--numbers', nargs="?", const=True, default=False, help='Parameter to set just numbers in the password') arg.add_argument('-l', '--letters', nargs="?", const=True, default=False, help='Parameter to set just letters in the password') arguments = arg.parse_args() def password_generator(args): if args.numbers: password_chars = (list(string.digits)) elif args.letters: password_chars = (list(string.ascii_letters)) else: password_chars = (list(string.digits) * 3) + (list(string.ascii_letters) * 3) + list(string.punctuation) password = "" for char in range(args.size): password += choice(password_chars) return password for passwd_number in range(arguments.quantity): print(password_generator(arguments))
ef0de30520dcecfae1031318a469f4202c02091c
jeanjoubert10/Atwood-machine
/atwood machine1.py
3,357
3.5
4
# Simple atwood machine in python on osX import turtle from math import * import time win = turtle.Screen() win.bgcolor('white') win.setup(500,900) win.tracer(0) win.title("Atwood machine simulation") discA = turtle.Turtle() discA.shape('circle') discA.color('red') discA.shapesize(3,3) discA.up() discA.goto(0,300) pen1 = turtle.Turtle() pen1.ht() pen1.color('black') pen1.up() pen1.goto(-200,380) # Ceiling pen1.down() pen1.pensize(10) pen1.goto(200,380) pen1.up() pen1.goto(-200,-300) #Floor pen1.down() pen1.goto(200,-300) pen1.pensize(1) pen1.up() pen1.goto(0,380) pen1.down() pen1.color('blue') # Rope to pulley pen1.goto(0,300) pen = turtle.Turtle() pen.ht() pen.up() starty = 0 massA = 2 # CHANGE MASS OF BOXES massB = 1 boxA = turtle.Turtle() boxA.shape('square') boxA.color('green') boxA.shapesize(massA,massA) boxA.up() boxA.goto(-100,starty) boxA.down() boxA.goto(100,starty) boxA.goto(-30,starty) boxA.up() boxB = turtle.Turtle() boxB.shape('square') boxB.color('green') boxB.shapesize(massB,massB) boxB.up() boxB.goto(30,starty) top_rope = 300 start_time = time.time() g = -9.8 vA = 0 uA = 0 vB = 0 uB = 0 net_force = massA*g - massB*g # if positive A will drop print("Net force: ",net_force) aA = net_force/(massA+massB) print("a for box A = ",aA) aB = -aA pen2 = turtle.Pen() pen2.ht() pen2.up() Game_over = False count = 0 while not Game_over: t = time.time() - start_time count+=1 vA = aA*t vB = aB*t yA = (uA*t + 1/2*aA*t*t + starty)*5 # start height or s0 yB = (uB*t + 1/2*aB*t*t + starty)*5 boxA.goto(boxA.xcor(),yA) boxB.goto(boxB.xcor(),yB) # Draw rope pen.clear() pen.up() pen.goto(boxA.xcor(),boxA.ycor()) pen.down() pen.goto(boxA.xcor(),top_rope) pen.lt(90) pen.goto(boxB.xcor(),top_rope) pen.goto(boxB.xcor(),boxB.ycor()) #Write Data: if count%40==0: pen2.clear() pen2.goto(0,400) pen2.write("time: {:.2f}s".format(t),align='center',font = ('Courier',15, 'normal')) pen2.goto(0,-330) pen2.write("mass A: {}kg\tmass B: {}kg".format(massA,massB),align='center',font = ('Courier',15, 'normal')) pen2.goto(0,-360) pen2.write("Va: {:.2f}m/s\tVb: {:.2f}m/s".format(vA,vB),align='center',font = ('Courier',15, 'normal')) pen2.goto(0,-390) pen2.write("Aa: {:.2f}m/s^2\tAb: {:.2f}m/s^2".format(aA,aB),align='center',font = ('Courier',15, 'normal')) pen2.goto(0,-420) pen2.write("distance: {:.2f}m".format((yA-starty)/5),align='center',font = ('Courier',15, 'normal')) win.update() if boxA.ycor()<=-250 or boxB.ycor()<=-250: print('done') Game_over = True #Final figures: pen2.clear() pen2.goto(0,400) pen2.write("time: {:.2f}s".format(t),align='center',font = ('Courier',15, 'normal')) pen2.goto(0,-330) pen2.write("mass A: {}kg\tmass B: {}kg".format(massA,massB),align='center',font = ('Courier',15, 'normal')) pen2.goto(0,-360) pen2.write("Va: {:.2f}m/s\tVb: {:.2f}m/s".format(vA,vB),align='center',font = ('Courier',15, 'normal')) pen2.goto(0,-390) pen2.write("Aa: {:.2f}m/s^2\tAb: {:.2f}m/s^2".format(aA,aB),align='center',font = ('Courier',15, 'normal')) pen2.goto(0,-420) pen2.write("distance: {:.2f}m".format((yA-starty)/5),align='center',font = ('Courier',15, 'normal'))
708e40f6392f05d6e0b04e32c600328e052d153e
IracemaLopes/Data_Visualiazation_with_Matplotlib
/annotating_a_plot_of_time_series_data.py
444
3.984375
4
import pandas as pd import matplotlib.pyplot as plt fig, ax = plt.subplots() # Read the data from file using read_csv climate_change = pd.read_csv("climate_change.csv", parse_dates=["date"], index_col=["date"]) # Plot the relative temperature data ax.plot(climate_change.index, climate_change["relative_temp"]) # Annotate the date at which temperatures exceeded 1 degree ax.annotate(">1 degree", xy=[pd.Timestamp('2015-10-06'), 1]) plt.show()
995c55f01fcece72677e88b3518bcce98e8f4522
yassir-23/Algebre-application
/Systemes.py
1,765
3.703125
4
from os import * from Fonctions import * def Systemes(): while True: system('cls') print(" #-----------------------------# Menu #-----------------------------#") print(" 1 ==> Système de n équations et n inconnus.") print(" 0 ==> Quitter.") print(" #------------------------------------------------------------------#") choix = input(" Entrer votre choix : ") if choix == '1': n = int(input(" Entrer le nombre n : ")) print(" Entrer les coefficients : ") A = Matrice(n, n) print(" Entrer les nombres de la partie à droite : ") b = Matrice(n, 1) if n > 0: resultat(Multiplication_Matrice(Matrice_Inv(A, n), b, n, 1, n), n) else: print(" Le système n'est pas un système de Cramer") system('PAUSE') elif choix == '0': break #------------------------------------------------------------------------------# '''def Elimination_gauss(X, n): det = 1 pivot = 0 for i in range(n): if X[i][i] == 0: for j in range(n): if X[j][i] != 0: X[i], X[j] = X[j], X[i] pivot = X[i][i] break if pivot != 0: for ligne in range(i, n): a = X[ligne][i] for j in range(i, n+1): X[ligne][j] -= (a * X[i][j] / pivot) else: break Xn = [] for i in range(n, 0, i-1): for j in range(n-1): if j = 0: x = X[n-1][n] x -= X[i][j] x /= X[i][n-1] X.append(x)'''
3a9a3220f024406f7120421cb00e17427810bb09
devdw98/TIL
/Language/Python/파이썬으로 배우는 알고리즘 트레이딩/lesson05.py
913
3.546875
4
#5-1 def myaverage(a,b): return (a+b)/2 #5-2 def get_max_min(data_list): return (max(data_list), min(data_list)) #5-3 def get_txt_list(path): import os org_list = os.listdir(path) ret_list = [] for x in org_list: if x.endswith("txt"): ret_list.append(x) return ret_list #5-4 def BMI(kg, cm): m = cm * 0.01 result = kg / (m*m) if result < 18.5 : print('마른 체형') elif (18.5 <= result) and (result < 25.0): print('표준') elif (25.0 <= result) and (result < 30.0): print('비만') else: print('고도비만') #5-5 while 1: height = input("Height (cm): ") weight = input("Weight (kg): ") BMI(float(height), float(weight)) #5-6 def get_triangle_area(width, height): return width * height / 2 #5-7 def add_start_to_end(start, end): result = 0 for i in range(start,end+1,1): result += i return result
6e42680389e94466abc769aec4e8eba49d9a853d
hexavi42/eye-see-u
/proofOfConcept/grayscale.py
782
3.546875
4
import argparse from os import path from PIL import Image def main(): parser = argparse.ArgumentParser(description='Grayscale an Image') parser.add_argument('-p', '--path', type=str, default=None, help='filepath of image file to be analyzed') parser.add_argument('-o', '--outFile', type=str, default=None, help='filepath to save new image at') args = parser.parse_args() filename, file_extension = path.splitext(args.path) img = Image.open(args.path) newImg = img.convert("L") if args.outFile is not None: filename, file_extension = path.splitext(args.outFile) else: filename, file_extension = path.splitext(args.path) filename+="_Gray" newImg.save(filename,"PNG") return if __name__ == "__main__": main()
0be7bc8211b56c825d410b76816af2d89eb19f6d
Alb4tr02/holbertonschool-higher_level_programming
/0x03-python-data_structures/10-divisible_by_2.py
318
3.984375
4
#!/usr/bin/python3 def divisible_by_2(my_list=[]): new_list = [] if my_list is None or len(my_list) == 0: return (None) else: for i in my_list: if (i % 2) == 0: new_list.append(True) else: new_list.append(False) return (new_list)
c537a01c9337f80af03e9209217d1a7dd25fbad9
Alb4tr02/holbertonschool-higher_level_programming
/0x04-python-more_data_structures/0-square_matrix_simple.py
221
3.625
4
#!/usr/bin/python3 def square_matrix_simple(matrix=[]): if matrix is None: return newm = matrix.copy() for i in range(0, len(newm)): newm[i] = list(map(lambda x: x*x, newm[i])) return newm
2003141f132187e8281b81d69561fe78131a948a
Alb4tr02/holbertonschool-higher_level_programming
/0x04-python-more_data_structures/6-print_sorted_dictionary.py
216
4.03125
4
#!/usr/bin/python3 def print_sorted_dictionary(a_dictionary): if a_dictionary is None: return list = (sorted(a_dictionary.items())) for i in list: print("{}{} {}".format(i[0], ":", i[1]))
cc43bddce55b547f89fb76b6636a278204121d0f
Alb4tr02/holbertonschool-higher_level_programming
/0x01-python-if_else_loops_functions/8-uppercase.py
194
4.09375
4
#!/usr/bin/python3 def uppercase(str): for a in str: c = ord(a) if c >= ord('a') and c <= ord('z'): c -= 32 print("{:c}".format(c), end="") print("")
74c99c3b0c9b9bd9adc3d84ec71d466169be8a1f
PuchatekwSzortach/convolutional_network
/examples/mnist.py
2,112
3.546875
4
""" A simple MNIST network with two hidden layers """ import tqdm import numpy as np import sklearn.utils import sklearn.datasets import sklearn.preprocessing import net.layers import net.models def main(): print("Loading data...") mnist = sklearn.datasets.fetch_mldata('MNIST original') X_train, y_train = mnist.data[:60000].reshape(-1, 28, 28).astype(np.float32), mnist.target[:60000].reshape(-1, 1) X_test, y_test = mnist.data[60000:].reshape(-1, 28, 28).astype(np.float32), mnist.target[60000:].reshape(-1, 1) encoder = sklearn.preprocessing.OneHotEncoder(sparse=False).fit(y_train) y_train = encoder.transform(y_train) y_test = encoder.transform(y_test) # Stack images so they are 3D, scale them to <0, 1> range X_train = np.stack([X_train], axis=-1) X_test = np.stack([X_test], axis=-1) layers = [ net.layers.Input(sample_shape=(28, 28, 1)), net.layers.Convolution2D(filters=20, rows=14, columns=14), net.layers.Convolution2D(filters=10, rows=15, columns=15), net.layers.Flatten(), net.layers.Softmax() ] model = net.models.Model(layers) batch_size = 128 epochs = 2 X_test, y_test = sklearn.utils.shuffle(X_test, y_test) print("Initial accuracy: {}".format(model.get_accuracy(X_test, y_test))) for epoch in range(epochs): print("Epoch {}".format(epoch)) X_train, y_train = sklearn.utils.shuffle(X_train, y_train) batches_count = len(X_train) // batch_size for batch_index in tqdm.tqdm(range(batches_count)): x_batch = X_train[batch_index * batch_size: (batch_index + 1) * batch_size] y_batch = y_train[batch_index * batch_size: (batch_index + 1) * batch_size] model.train(x_batch, y_batch, learning_rate=0.01) print("Accuracy: {}".format(model.get_accuracy(X_test, y_test))) model.save("/tmp/model.p") loaded_model = net.models.Model.load("/tmp/model.p") print("Loaded model's accuracy: {}".format(loaded_model.get_accuracy(X_test, y_test))) if __name__ == "__main__": main()
9003c2fc01c18745533b9995186de30fc99f4fc4
KulaevaNazima/files
/files4.py
1,348
3.859375
4
#Cоздайте текстовый файл python.txt и запишите в него текст #1 из Classroom: #Затем, считайте его. Пробежитесь по всем его словам, и если слово содержит #букву “t” или “T”, то запишите его в список t_words = [ ]. После окончания списка, #выведите на экран все полученные слова. Подсказка: используйте for. python = open ('/home/nazima/python.txt', 'w') python.writelines ("""PyThon is a widely used high-level programming language for general-purpose programming, created by Guido van Rossum and first released in 1991. An interpreted language, PyThon has a design philosophy that emphasizes code readability (notably using whitespace indentation to delimit code blocks rather than curly brackets or keywords), and a syntax that allows programmers to express concepts in fewer lines of code than might be used in languages such as C++ or Java.""") python.close () python = open ('/home/nazima/python.txt', 'r') letter1= "t" letter2= "T" for line in python.readlines (): for words in line.split (): t_words= [] if letter1 in words: t_words.append (words) print (t_words) if letter2 in words: t_words.append (words) print (t_words)
5cb813598d9e52af2c1f514da781de4d22285190
singediguess/my-python-note
/using_str/using_str.py
495
4.0625
4
str1 = 'I am {}, I love {}' str2 = str1.format('k1vin', 'coding') print (str2) print('---') #using index str3 = '{0:10} : {1:3d}' table = {'c++':16, 'html':15, 'python':17} for name, nmb in table.items(): print (str3.format(name, nmb)) print('---') #using '%' import math print ('pi = %6.4f' % math.pi) print('---') #dictionary problems print (table.items()) print (table['c++']) print (table['html']) print('---') #input name= input('Give me your name: ') print ('Welcome,', name, '!!')