blob_id
stringlengths
40
40
repo_name
stringlengths
6
108
path
stringlengths
3
244
length_bytes
int64
36
870k
score
float64
3.5
5.16
int_score
int64
4
5
text
stringlengths
36
870k
8d0e0484f0ab22e0a866b9861a1226c74bd57215
snehadasa/holbertonschool-low_level_programming
/0x1C-makefiles/5-island_perimeter.py
685
4.09375
4
#!/usr/bin/python3 """to calculate the perimeter of an island that is described in the grid""" def island_perimeter(grid): perimeter = 0 for row in range(len(grid)): for column in range(len(grid[row])): if grid[row][column] == 0: continue if column == 0 or grid[row][column - 1] == 0: perimeter += 1 if column == len(grid[row]) - 1 or grid[row][column + 1] == 0: perimeter += 1 if row == 0 or grid[row - 1][column] == 0: perimeter += 1 if row == len(grid) - 1 or grid[row + 1][column] == 0: perimeter += 1 return perimeter
6e05bf9215f6fb061724959f3cb2de1fb4c5bf39
Rxdxxn/Operatori-Python
/problema 2.py
157
3.734375
4
a=10 b=3 print(a,"+",b,"=",a+b) print(a,"-",b,"=",a-b) print(a,"//",b,"=",a//b) print(a,"%",b,"=",a%b) print(a,"*",b,"=",a*b) print(a,"**",b,"=",a**b)
8ffdf6884cf30dc7561e207ccb7bde5585fcb35a
nijinchandran/pythonprograms
/data collections/list/limit.py
111
3.78125
4
limit=int(input("enter limit")) for i in range(limit): e=int(input("enter elmnt")) l.append(e) print(l)
2254917d4778a811f2c891a09041aed3ee42dd48
peterg79/regenmaschine
/regenmaschine/watering.py
1,902
3.6875
4
"""Define an object to interact with generic watering data/actions.""" import datetime from typing import Awaitable, Callable class Watering: """Define a watering object.""" def __init__(self, request: Callable[..., Awaitable[dict]]) -> None: """Initialize.""" self._request: Callable[..., Awaitable[dict]] = request async def log( self, date: datetime.date = None, days: int = None, details: bool = False ) -> list: """Get watering information for X days from Y date.""" endpoint: str = "watering/log" if details: endpoint += "/details" if date and days: endpoint = f"{endpoint}/{date.strftime('%Y-%m-%d')}/{days}" data: dict = await self._request("get", endpoint) return data["waterLog"]["days"] async def pause_all(self, seconds: int) -> dict: """Pause all watering for a specified number of seconds.""" return await self._request( "post", "watering/pauseall", json={"duration": seconds} ) async def queue(self) -> list: """Return the queue of active watering activities.""" data: dict = await self._request("get", "watering/queue") return data["queue"] async def runs(self, date: datetime.date = None, days: int = None) -> list: """Return all program runs for X days from Y date.""" endpoint: str = "watering/past" if date and days: endpoint = f"{endpoint}/{date.strftime('%Y-%m-%d')}/{days}" data: dict = await self._request("get", endpoint) return data["pastValues"] async def stop_all(self) -> dict: """Stop all programs and zones from running.""" return await self._request("post", "watering/stopall") async def unpause_all(self) -> dict: """Unpause all paused watering.""" return await self.pause_all(0)
07a9ebd9f3068629a84f9a6939c58e0d7e3878e9
bakil/pythonCodes
/turtle/turtle_miniTrangle.py
1,049
3.859375
4
import turtle def draw_trangle(temp_t,length): temp_t.begin_fill() temp_t.fillcolor("green") for i in range(3): temp_t.forward(length) temp_t.left(120) temp_t.end_fill() def draw_threeTrangle(temp_t,length): draw_trangle(temp_t,length) temp_t.forward(length) draw_trangle(t,length) temp_t.left(120) temp_t.forward(length) temp_t.left(-120) draw_trangle(t,length) window = turtle.Screen() t = turtle.Turtle() t.speed(0) t.color("blue") trangleSideLen = 20 for trangle in range(4): t.penup() t.setposition(0,0) t.forward(trangle*2*trangleSideLen) t.pendown() draw_threeTrangle(t,trangleSideLen) for trangle in range(3): t.penup() t.setposition(0,0) t.left(60) t.forward(trangle*2*trangleSideLen) t.left(-60) t.pendown() draw_threeTrangle(t,trangleSideLen) for trangle in range(1,4): t.penup() t.setposition(0,0) t.forward(8*trangleSideLen) t.left(120) t.forward(trangle*2*trangleSideLen) t.left(60) t.forward(2*trangleSideLen) t.left(180) t.pendown() draw_threeTrangle(t,trangleSideLen) window.exitonclick()
8fb142d6e4f207faeb43db8661cc26395096311a
MRivadavia/Math-With-Python
/Aula4.py
1,080
4.46875
4
""""Programa que trabalha com funções II """ from fractions import Fraction a = Fraction() # Por definição, o numerador é zero e o denominador é 1. A variável 'a' recebe a fração 0/1. print(a) # Portanto, retorna zero. b = Fraction(3 / 4) # A função Fraction recebe em seu argumento uma fração e retorna a mesma fração. print(b) # A saída será 3/4. c= Fraction('1.2') # Se a função Fraction receber em seu argumento um número racional, a variável 'c' receberá # um tipo de dado fractions.Fraction, ou seja, uma fração. print(c) # A saída impressa na tela será 6/5. d = Fraction(1.1) # Quando se insere no argumento de Fraction um número decimal não entre aspas, o python # retornará uma fração aproximada ao valor decimal 1.1. print(d) e = Fraction(1.1).limit_denominator() # Quando se insere no argumento de Fraction um número decimal não entre # aspas, e utiliza o método limit_denominator() para converter em fração irredutível. print(e) # Exemplo: Seja um círculo de raio 12 cm e uma circunferência de
bcdc76eb3b35a975f9cb4138d767326da5966f20
joaopvgus/ADS
/10 - padaria.py
2,145
3.828125
4
## menu: 1 - cadastrar produto, 2 - venda de produto, 3 - total de vendas, 4 - ver estoque 0 - sair ## CADASTRAR PRODUTO ## pedir NOME ## pedir PRECO ## pedir QUANTIDADE ## imprimir NOME - PRECO - QUANTIDADE ## VENDA DE PRODUTO ## pedir NOME ## pedir QUANTIDADE ## imprimir valor total da venda ## TOTAL DE VENDAS ## imprimir o total de vendas ## VER ESTOQUE ## imprimir estoque ## SAIR ## encerra o sistema lista_de_produtos = [] vendas = 0 opcao = '10' while (opcao != '0'): opcao = input(' 1 - cadastrar produto \n 2 - venda de produto \n 3 - total de vendas \n 4 - ver estoque \n 0 - sair \n\n') if opcao == '1': nome = input('Digite o nome do item: ') valor = float(input('Digite o valor do item: ')) quantidade = float(input('Digite a quantidade do item: ')) novo_item = [nome, valor, quantidade] lista_de_produtos.append(novo_item) print(f'{nome} - {str(valor)} - {str(quantidade)}') elif opcao == '2': nome = input('Digite o nome do item: ') quantidade = float(input('Digite a quantidade do item: ')) nao_tem = True for produto in lista_de_produtos: if produto[0] == nome: nao_tem = False if quantidade <= produto[2]: total = quantidade * produto[1] produto[2] -= quantidade print(f'total: {total}') vendas += total else: print('Ter a gente tem, mas tá em falta') if nao_tem: print('Nunca nem vi') elif opcao == '3': print(f'TOTAL DE VENDAS: {vendas}') elif opcao == '4': for produto in lista_de_produtos: print(f'NOME: {produto[0]} - PREÇO {produto[1]} - QNT.: {produto[2]}') elif opcao != '0': print('Escolha uma opção válida') elif opcao == '0': print('Encerrando') print('Até a próxima')
e7ee8b0d81417998498c14211746d96433d69348
BeauNimble/KEEEPERAI
/mould.py
14,247
3.609375
4
# Importeren van packages import pandas as pd import datetime from timey import new_time def mouldChangeCapacity(start_date, end_date): mould_change_capacity = pd.read_excel('Mould change capacity.xlsx', header=0) # The amount of mould changes that can be done mould_change_capacity['Date'] = mould_change_capacity['Date'].astype(str) mould_change_capacity = mould_change_capacity.set_index('Date') morning_shift = mould_change_capacity['Morning shift'] # The capacity of the morning shift afternoon_shift = mould_change_capacity['Afternoon shift'] # The capacity of the afternoon shift night_shift = mould_change_capacity['Night shift'] # The capacity of the night shift change_capacity = {} # The dict containing all the mould change capacities of every planning day date = start_date # The date that the planning starts while date <= end_date: if str(date) in mould_change_capacity.index: # Fill up with the given capacity for each date change_capacity[str(date)] = [morning_shift[str(date)], afternoon_shift[str(date)], night_shift[str(date)]] else: change_capacity[str(date)] = [4, 3, 3] # Fills up the (standard) capacity for each date date = new_time(date.year, date.month, date.day+1) return change_capacity def mouldChange(begin_time, end_time, mc, machine, order, mould, when): # Adds the mould change to the list """ :param begin_time: The time that the mould change starts :param end_time: The time that the mould change ends :param mc: The list containing all the mould changes :param machine: The machine that the mould is changed on :param order: The order that the mould is changed for :param mould: The mould that is changed :param when: In what stadium the mould change happens :return: Adds the mould change to the list """ mc.append([machine, begin_time, end_time, mould, when, order]) def problems(mould): # Calculates the amount of problems in mould changes and returns them """ :param mould: The list containing the mould changes (time) :return: The number of problems and a list containing the problematic mould changes (mould and time) """ problem = 0 # The amount of problems between mould changes. when = [] for i in range(len(mould)): change = 0 # The number of mould changes at the current time for j in range(i, len(mould)): if mould[j][1] <= mould[i][1] <= mould[j][2] or mould[j][1] <= mould[i][2] <= mould[j][2]: change += 1 if change > 1: # If there is more than 1 mould change at a time problem += 1 when.append([mould[i][0], mould[i][1].strftime("%d %X"), mould[i][2].strftime("%d %X")]) return problem, when def problem(begin, end, changes): # Tests whether there is a problem to have a new mould change """ :param begin: The time the new mould change starts :param end: The time the new mould change ends :param changes: The list containing the mould changes planned untill now :return: True or False depending on whether or not there has already been planned a mould change """ for i in range(len(changes)): if changes[i][1] <= begin <= changes[i][2] or changes[i][1] <= end <= changes[i][2]: return True # There is already a mould changes scheduled during this time return False # There is no problem planning the new mould change def printMould(changes, track): # Prints the mould changes schedule as a dataframe """ :param changes: The list of all mould changes with their machines included :param track: Keeps track of information, like the number of (conflicting) mould changes :return: Adds the schedule of all mould changes to an excel file and retuns the amount of changes """ print(str(len(changes)) + " mould changes scheduled") p, prob = problems(changes) track.conflicted_mould = p # The number of conflicted mould changes if p > 0: print(str(p) + " mould schedule problems") else: print("No problems planning moulds") sched = pd.DataFrame(columns=['Order', 'Work ctr', 'Mould', 'Start Time', 'Finish Time', 'When']) # Makes the dataframe for the output for i in range(len(changes)): new_row = {'Order': changes[i][5], 'Work ctr': changes[i][0], 'Mould': changes[i][3], 'Start Time': changes[i][1].strftime("%d %X"), 'Finish Time': changes[i][2].strftime("%d %X"), 'When': changes[i][4]} sched = sched.append(new_row, ignore_index=True) # adds new row to the dataframe under the existing rows sched = sched.sort_values(by=['Start Time', 'Finish Time']) sched.to_excel("Mould-planning.xlsx") return len(changes) def getMouldMachineTime(quantity, mould, work_center, mld): """ :param quantity: The quantity of the order :param mould: The mould of the order :param work_center: The work center to plan the order on :param mld: A dataframe containing the cycle times for items and moulds on certain work centers :return: If possible an estimation of the duration to make a certain quantity of a dummy product """ if str(mould) != 'nan' and str(mould) != 'None': # If a mould is given, with which the cycle time can be estimated md = mld.loc[mld['Mould'] == mould] # Only look at the part of the dataframe with the correct mould number_w = 0 # The number of work centers to get the average cycle time from cycle_time_cbnd = float(0) # The combined average cycle time of all those work centers for m in md.index: # For each instance of the mould if md['Mean zcs'][m] != 'nan' and md['Mean zcs'][m] != 'None': number_w += 1 cycle_time_cbnd += md['Mean zcs'][m].astype(float) if number_w > 0: # If there were instances of the mould being used in the data cycle_time = cycle_time_cbnd / number_w time = cycle_time * quantity return datetime.datetime.fromtimestamp(time) if str(work_center) != 'nan' and str(work_center) != 'None': # If the machine is given mchn = pd.read_excel("avg_machine_times.xlsx", header=0) mchn['Work center'] = mchn['Work center'].astype(str) mchn = mchn.set_index('Work center') if work_center in mchn.index: cycle_time = mchn.loc[work_center, 'total'] # Get the cycle time from the work center time = cycle_time * quantity return datetime.datetime.fromtimestamp(time) return False def ChangeMould(work_center_id, product, old_mould, m_date, mould_changes, mould_change_capacity): """ :param work_center_id: The number of the work center that the mould is changed on :param product: The product that is the reason the mould needs to be changed :param old_mould: The mould that was previously on the work center :param m_date: The current date and time of the planning of the work center :param mould_changes: The list containg all the mould changes that have already happened :param mould_change_capacity: A list containing the number of mould changes that can still happen for each shift each day :return: The mould change is scheduled and the date and time that the mould change ends is returned """ """ Get a possible datetime for the mould change to start when there is still capacity left """ begin = m_date # The date and time that the mould change begins change = False # True if the mould change can happen at this time according to the capacity while not change: if not str(datetime.datetime(begin.year, begin.month, begin.day)) in mould_change_capacity.keys(): # The mould change tries to be scheduled outside the allowed date range return False if 6 <= begin.hour <= 14: # 6am - 2pm if mould_change_capacity[str(datetime.datetime(begin.year, begin.month, begin.day))][0] > 0: # The capacity allows a mould change mould_change_capacity[str(datetime.datetime(begin.year, begin.month, begin.day))][0] -= 1 # The capacity gets decreased change = True # The mould change will get planned else: begin = new_time(begin.year, begin.month, begin.day, begin.hour+1, begin.minute, begin.second) elif 14 <= begin.hour <= 22: # 2pm - 10pm if mould_change_capacity[str(datetime.datetime(begin.year, begin.month, begin.day))][1] > 0: # The capacity allows a mould change mould_change_capacity[str(datetime.datetime(begin.year, begin.month, begin.day))][1] -= 1 change = True else: begin = new_time(begin.year, begin.month, begin.day, begin.hour+1, begin.minute, begin.second) elif 22 <= begin.hour <= 24 or 0 <= begin.hour <= 6: # 10 pm - 6am if mould_change_capacity[str(datetime.datetime(begin.year, begin.month, begin.day))][2] > 0: # The capacity allows a mould change mould_change_capacity[str(datetime.datetime(begin.year, begin.month, begin.day))][2] -= 1 change = True else: begin = new_time(begin.year, begin.month, begin.day, begin.hour+1, begin.minute, begin.second) """ Get the time that the changes of the old and new mould are done """ add_time = getMouldChangeTime(product.moulds, type_when="in") add_time += getMouldChangeTime(old_mould, type_when="out") finished = new_time(begin.year, begin.month, begin.day, begin.hour, begin.minute + add_time, begin.second) """ Find whether there are problems scheduling the mould change If there is a problem, the change will be tried to be scheduled 10 min later """ if not problem(begin, finished, mould_changes): # There isn't a conflict while changing the mould (only 1 change at a time) mouldChange(begin, finished, mould_changes, work_center_id, product.order, product.moulds, "Change between moulds") else: # There is a conflict while changing the mould at this time if 6 <= begin.hour <= 14: # 6am - 2pm mould_change_capacity[str(datetime.datetime(begin.year, begin.month, begin.day))][0] += 1 # Turn back the change in capacity elif 14 <= begin.hour <= 22: # 2pm - 10pm mould_change_capacity[str(datetime.datetime(begin.year, begin.month, begin.day))][1] += 1 elif 22 <= begin.hour <= 24 or 0 <= begin.hour <= 6: # 10 pm - 6am mould_change_capacity[str(datetime.datetime(begin.year, begin.month, begin.day))][2] += 1 m_date = new_time(begin.year, begin.month, begin.day, begin.hour, begin.minute + 10, begin.second) return ChangeMould(work_center_id, product, old_mould, m_date, mould_changes, mould_change_capacity) # Plan the mould change again return finished # There is no conflict, so return the time when the mould change is done def getInsertChangeTime(mould): insert_complexity = pd.read_excel('Insert changes times per mould.xlsx', header=0) insert_complexity = insert_complexity[ ['Number of mould', 'Change on machine', 'In mould shop (easy)', 'In mould shop (complex)']] insert_complexity = insert_complexity.set_index('Number of mould') # The complexity of insert changes insert_complexity_time = pd.read_excel('Insert changes times per mould.xlsx', usecols="I:K", header=0) if mould in insert_complexity.index: change1 = str(insert_complexity.loc[mould, 'Change on machine']) change2 = str(insert_complexity.loc[mould, 'In mould shop (easy)']) change3 = str(insert_complexity.loc[mould, 'In mould shop (complex)']) if change1 != 'nan' and change1 != 'None': return int(insert_complexity_time['Change on machine.1'][ 1]) # .1 because there are 2 columns with the same header name if change2 != 'nan' and change2 != 'None': return int(insert_complexity_time['In mould shop (easy).1'][1]) if change3 != 'nan' and change3 != 'None': return int(insert_complexity_time['In mould shop (complex).1'][1]) return int(insert_complexity_time['In mould shop (easy).1'][1]) def getMouldChangeTime(mould, type_when="both"): df_mould = sizeMould() # A dataframe containing the complexity of the mould changes complexity = df_mould['complexity'] if type_when == "both": switch = { "laborious": int(df_mould["laborious"][2]), "medium": int(df_mould["medium"][2]), "easy": int(df_mould["easy"][2]) } elif type_when == "in": switch = { "laborious": int(df_mould["laborious"][1]), "medium": int(df_mould["medium"][1]), "easy": int(df_mould["easy"][1]) } elif type_when == "out": switch = { "laborious": int(df_mould["laborious"][0]), "medium": int(df_mould["medium"][0]), "easy": int(df_mould["easy"][0]) } if not str(mould) in df_mould.index: # The mould has no changeover time data time = switch.get("medium", "Invalid size") # Use average time else: size = complexity[str(mould)] # get complexity of mould change if not type(size) is str: # if mould is in dataframe more than once try: size = size[0] except: size = "medium" time = switch.get(size, "Invalid size") return time def sizeMould(): """ :return: The dataframe containing the moulds and their complexity """ df_mould = pd.read_excel('mold complexity-co time.xlsx', header=0) df_mould = df_mould.set_index('Number of mould') # Sets the mould as the index of the dataframe return df_mould
a756d666a66345272980aa0c0af9232fe8b2d0e1
rohithkumar282/K-Nearest-Neighbour-DigitsMNIST
/KNN_SML_Assignment3.py
3,003
3.53125
4
#!/usr/bin/env python # coding: utf-8 # In[5]: import numpy as np import pandas as pd import math from sklearn import metrics from sklearn.preprocessing import scale from collections import Counter from scipy.spatial import distance Xtrain= pd.read_csv('mnist_train_digits.csv',header =None) Xtest= pd.read_csv('mnist_test_digits.csv', header =None) x_train = np.array(Xtrain.iloc[:, 1:]) y_train = np.array(Xtrain.iloc[:, 0]) x_test = np.array(Xtest.iloc[:, 1:]) y_test = np.array(Xtest.iloc[:, 0]) y_train = y_train.reshape((y_train.shape[0],1)) y_test = y_test.reshape((y_test.shape[0],1)) class kNN(): def __init__(self): pass def fit(self, X, y): self.data = X self.targets = y def euclidean_distance(self, X): """ Computes the euclidean distance between the training data and a new input example or matrix of input examples X """ # input: single data point if X.ndim == 1: l2 = np.sqrt(np.sum((self.data - X)**2, axis=1)) # input: matrix of data points if X.ndim == 2: n_samples, _ = X.shape l2 = [np.sqrt(np.sum((self.data - X[i])**2, axis=1)) for i in range(n_samples)] return np.array(l2) def predict(self, X, k=1): """ Predicts the classification for an input example or matrix of input examples X """ # step 1: compute distance between input and training data dists = self.euclidean_distance(X) # step 2: find the k nearest neighbors and their classifications if X.ndim == 1: if k == 1: nn = np.argmin(dists) return self.targets[nn] else: knn = np.argsort(dists)[:k] y_knn = self.targets[knn] max_vote = max(y_knn, key=list(y_knn).count) return max_vote if X.ndim == 2: knn = np.argsort(dists)[:, :k] y_knn = self.targets[knn] if k == 1: return y_knn.T else: n_samples, _ = X.shape max_votes = [max(y_knn[i], key=list(y_knn[i]).count) for i in range(n_samples)] return max_votes kVals = [1,3,5,10,20,30,40,50,60] accuracies = [] for k in kVals: knn = kNN() knn.fit(x_train, y_train) predicted_label=[] for i in range(x_test.shape[0]): predicted_label.append(knn.predict(x_test[i], k)) i=0 correct=0 for i in range(x_test.shape[0]): if predicted_label[i] == y_test[i]: correct+=1 accuracies.append((correct/x_test.shape[0])*100) k = 0 for k in range(len(kVals)): print("k=%d, accuracy=%.2f%%" % (kVals[k], accuracies[k] * 100)) i = np.argmax(accuracies) print("k=%d achieved highest accuracy of %.2f%% on validation data" % (kVals[i],accuracies[i])) plt.plot(kVals,accuracies) plt.xlabel(' K ') plt.ylabel(' Accuracies ') plt.show() # In[ ]: # In[ ]:
29691b448c5ef4ac3801cd8b34934bb1e8faf689
jiwoo-kimm/dsc-algorithm
/kimna/keypad.py
1,494
3.75
4
def handlength(hand, number): number = str(number) location_x = {'1': 0, '2': 0, '3': 0, '4': 1, '5': 1, '6': 1, '7': 2, '8': 2, '9': 2, '*': 3, '0': 3, '#': 3} location_y = {'1': 0, '2': 1, '3': 2, '4': 0, '5': 1, '6': 2, '7': 0, '8': 1, '9': 2, '*': 0, '0': 1, '#': 2} hand_x = location_x[hand] hand_y = location_y[hand] number_x = location_x[number] number_y = location_y[number] result = abs(hand_x - number_x) + abs(hand_y - number_y) return result def solution(numbers, hand): answer = '' left = '*' right = '#' for number in numbers: if number in [1, 4, 7]: answer += 'L' left = str(number) elif number in [3, 6, 9]: answer += 'R' right = str(number) else: lefthand = handlength(left, number) righthand = handlength(right, number) if lefthand < righthand: answer += 'L' left = str(number) elif lefthand > righthand: answer += 'R' right = str(number) else: if (hand == 'right'): answer += 'R' right = str(number) else: answer += 'L' left = str(number) return answer
bd920c03cf3c4d7eb66f97f07833dc78cba5edf5
maximkavm/ege-inf
/23/Количество программ с обязательным этапом/7 - 13633.py
442
4.0625
4
""" Сколько существует программ, для которых при исходном числе 2 результатом является число 30 и при этом траектория вычислений содержит число 15? +1 *2 *3 """ def f(x, y): if x < y: return f(x + 1, y) + f(x * 2, y) + f(x * 3, y) elif x == y: return 1 else: return 0 print(f(2, 15) * f(15, 30)) # Ответ: 42
b04d98143b8d793056e17f5549edd13102312387
harsilspatel/ProjectEuler
/58. Spiral primes.py
736
3.875
4
#def isPrime(n): # # Assuming inputs are non-even numbers # for i in range(3, int(n**(1/2)) + 1, 2): # if n % i == 0: # return False # return True def eratosthenesSieve(n): primesDictionary = {i:True for i in range(2, n+1)} rootN = n**(1/2) for i in range(2, int(rootN) + 1): if primesDictionary[i]: j = i**2 while j <= n: primesDictionary[j] = False j += i return primesDictionary primeNumbers = eratosthenesSieve(10**7) theSum = 1 totalNumbers = 4 primes = 3 i = 3 while primes/totalNumbers > 0.20: i += 2 square = i**2 for x in [square-(i-1), square-(i-1)*2, square-(i-1)*3]: if primeNumbers[x]: primes += 1 totalNumbers += 3 # print(i, primes, totalNumbers, primes/totalNumbers) print(i+2)
a40d51e273b75dc835273118df49a0aa04dfe01a
shalu169/lets-be-smart-with-python
/GUI1.py
237
3.640625
4
import math def squares(a, b): count = 0 for i in range(a,b+1): p = i**.5 print(p) inti = int(p) deci = p- inti if deci == 0: count = count + 1 print(count) squares(1,10)
93afa044a3497155faa2582dd682bbc1f1db701b
peitaosu/Cardiff
/diff.py
1,025
3.515625
4
import os, sys, importlib, time def diff_file(file_before, file_after, file_output_name = None): """diff file and save as file args: file_before (str) file_after (str) file_output_name (str) returns: saved_file (str) """ file_name = os.path.basename(file_before) file_ext = file_name.split(".")[-1] file_differ = importlib.import_module("format." + file_ext + ".differ") if file_output_name == None: file_output_name = str(time.time()) saved_file = file_differ.make_diff(file_before, file_after, file_output_name) return saved_file def diff(file_before, file_after): """diff file and return the diff object args: file_before (str) file_after (str) returns: file_diff (object) """ file_name = os.path.basename(file_before) file_ext = file_name.split(".")[-1] file_differ = importlib.import_module("format." + file_ext + ".differ") return file_differ.diff(file_before, file_after)
01211fd4c4b41a98fdf04b8ea03cf6435f906ff1
JosephLevinthal/Research-projects
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/226/users/4160/codes/1836_2603.py
194
3.734375
4
from numpy import* from numpy.linalg import* a = array(eval(input("Digite uma matriz: "))) #vetor auxiliar pra coluna: a= a for i in range(4): a[:,i] = sorted(a[:,i],reverse=True) print(a)
a05af100906f069f8c59c5001740a18be8119b84
bloomfieldfong/Mancala
/prueba_mancala.py
5,430
3.875
4
from funciones import valid_move, print_board, play, winner, corrida_juego, possible_movess import random import copy # Funciona porque el random es uniforme y esto hace que en muchas # iteraciones el valor esperado sea aproximado a 1/6 de la cantidad de iteraciones ##Define el board que tendremos y el turno del jugador # 0 1 2 3 4 5 6 7 8 9 0 1 2 3 #board = [0,0,0,1,0,0,0,4,4,4,4,4,4,0] board = [4,4,4,4,4,4,0,4,4,4,4,4,4,0] turn = 0 prueba = [9,10,11,12,8,7] contador= [0,0,0,0,0,0] iteracion = 10000 porcentaje = [] over = True #Inicio del juego print_board( board[7:14], board[0:7]) while(over): if turn == 0 and over == True: move = int(input("Ingrese su movimiento (0-5): ")) if move <6 and valid_move(board, move): ## nos indica quien es el turno board, turn, over = play(0,board, move) print("##########################################") print("Movimiento nuestro", move) print_board( board[7:14], board[0:7]) elif turn == 1 and over == True: #move = int(input("Ingrese su movimiento (0-5):v ")) ##regresa los posibles movimiento para el board actual contador = [0, 0, 0, 0, 0, 0] porcentaje = [] ##MONTE CARLO## for i in range(0, iteracion): ## quien fue el ganador de todo el juego que se esta simulando try: boardTry = copy.deepcopy(board) possible_move = possible_movess(boardTry, prueba) move = random.choice(possible_move) if move in possible_move: if valid_move(boardTry, move): winner = corrida_juego(boardTry, move) ##AQUI if move == 7 and winner == 1: contador[0] = contador[0] + winner elif move == 8 and winner == 1: contador[1] = contador[1] + winner elif move == 9 and winner == 1: contador[2] = contador[2] + winner elif move == 10 and winner == 1: contador[3] = contador[3] + winner elif move == 11 and winner == 1: contador[4] = contador[4] + winner elif move == 12 and winner == 1: contador[5] = contador[5] + winner except: a =1 movimiento = max(contador) if valid_move(board, (contador.index(movimiento) + 7)) and turn == 1: if contador.index(movimiento) == 0: board, turn, over = play(1,board, 7) print(turn) print("##########################################") contador.reverse() print(contador) print("##########################################") print("Movimineto de IA: 7" ) print_board( board[7:14], board[0:7]) elif contador.index(movimiento) == 1: board, turn, over = play(1,board, 8) print(turn) print("##########################################") contador.reverse() print(contador) print("##########################################") print("Movimineto de IA: 8") print_board( board[7:14], board[0:7]) elif contador.index(movimiento) == 2: board, turn, over = play(1,board, 9) print(turn) print("##########################################") contador.reverse() print(contador) print("##########################################") print("Movimineto de IA: 9",) print_board( board[7:14], board[0:7]) elif contador.index(movimiento) == 3: board, turn, over = play(1,board, 10) print(turn) print("##########################################") contador.reverse() print(contador) print("##########################################") print("Movimineto de IA: 10") print_board( board[7:14], board[0:7]) elif contador.index(movimiento) == 4: board, turn, over = play(1,board, 11) print(turn) print("##########################################") contador.reverse() print(contador) print("##########################################") print("Movimineto de IA: 11") print_board( board[7:14], board[0:7]) elif contador.index(movimiento) == 5: board, turn, over = play(1,board, 12) print(turn) print("##########################################") contador.reverse() print(contador) print("##########################################") print("Movimineto de IA: 12") print_board( board[7:14], board[0:7]) #valid_move(board,12) #print(corrida_juego(board, 12))
7375ed056f4eb4787daf75f91d00719cde81bed7
yangxiaodong1/ygblcrm
/test/day9.6晚上/直接插入.py
362
3.734375
4
'''扫描,当前元素''' def insert_sort(arr): count = len(arr) for i in range(1,count): j=i-1 # 扫描元素 key = arr[i] # 比较元素 while j>=0 and key<arr[j]: arr[j+1] = arr[j] j -=1 arr[j+1] = key return arr if __name__=="__main__": arr = [12,33,4] print(insert_sort(arr))
796db3056ae4bb4fcdc8e363ea3c18a06bb12cc4
ISPritchin/Olympiad
/800/Оформлено/Эпическая игра.py
289
3.5625
4
def gcd(a, b): if b == 0: return a else: return gcd(b, a % b) a, b, n = map(int, input().split()) while True: r = gcd(a, n) if r > n: print("1") break n -= r r = gcd(b, n) if r > n: print("0") break n -= r
3f3d82d40c4ac46bdb0874b71b0a3958668238a3
dngur807/ScriptTermProject
/공부내용/Practice/PythonPractice_Jeasun/클래스 상속.py
834
4
4
class Person: #부모 클래스 def __init__(self, name, phoneNumber): self.Name = name self.PhoneNumber = phoneNumber def PrintInfo(self): print("name : {0} , PhoneNumber : {1}".format(self.Name, self.PhoneNumber)) class Student(Person): #자식클래스 (Person에서 상속받음) def __init__(self, name, phoneNumber, subject, studentID): Person.__init__(self,name,phoneNumber) self.Subject = subject self.StudentID = studentID def PrintInfo(self): print("Name:{0}, Phone Number: {1}, subjet : {2}, id : {3}" .format(self.Name, self.PhoneNumber,self.Subject, self.StudentID)) student =Student("a","b","c","d") person = Person("1","2") #둘이 당연히 다른객체 니깐 다른 값이 나온다. person.PrintInfo() student.PrintInfo()
9da472b410593f5298a1e7cc921073c0c5789084
TravenYu/ICS4U1c-2018-19
/Working/OOP/practice_address.py
1,137
3.921875
4
class Address(): def __init__(self): self.address_line1 = "" self.address_line2 = "" self.postal_code = "" self.city = "" self.province = "" self.country = "" def print_address(addr): print(addr.address_line1) if addr.address_line2 != "": print(addr.address_line2) print(addr.city + ", " + addr.postal_code + ", " + addr.province) print(addr.country) def main(): home_address = Address() home_address.address_line1 = "123 Main St." home_address.address_line2 = "Unit #2" home_address.postal_code = "L3R 8M1" home_address.city = "Markham" home_address.province = "Ontario" home_address.country = "Canada" work_address = Address() work_address.address_line1 = "8101 Leslie St." work_address.postal_code = "L4A 9E3" work_address.city = "Thornhill" work_address.province = "Ontario" work_address.country = "Canada" # print out the addresses print(" **** HOME ADDRESS ****") print_address(home_address) print("") print(" **** WORK ADDRESS ****") print_address(work_address) main()
a6cd8ac9bd933f28e6fcce888187b16e1d3764c1
drakohha/Python
/Test/Game_kosti.py
7,846
3.609375
4
from random import * import os def fun_proverki(i,j): #функция проверки ввода в заданном диапозоне while True: try: n=int(input()) if n>=i and n<=j: break else: print("Не верный ввод, введите число в диапозоне от ",i," до ",j) except ValueError: print("Не верный ввод, введите число в диапозоне от ",i," до ",j) return n def fun_igra(game_type): # функция игры while True: # Выбор начальных пораметров if game_type==1 : name=input("Введите ваще имя ") name_2="компьютер" elif game_type==3: name=input("Введите ваще имя ") name_2=name+' вторая рука' elif game_type==2: name=input("Введите ваще имя ") name_2=input("Введите имя второго игрока") print("Введите начальный банк от 100 до 1000$ : ") bank=fun_proverki(100,1000) if game_type==2: bank_2=bank print("Введите ставку для игрока ",name," от 100 до 500$ : ") stavka=fun_proverki(100,500) os.system('clear') print ("Правила просты : выбрости кости суммой больше чем соперник! Вперед!") while True: # Бросок костей и их сравнивание print("Введите цифру 1 чтобы бросить кости!") brosok=fun_proverki(1,1) if brosok==1: kubik_1=randint(1,6) print("первоя кость прокатилась по столу и выдала : ",kubik_1) kubik_2=randint(1,6) print("Вторая кость перевернулась и показала :",kubik_2) summa=kubik_1+kubik_2 print("Общая сумма у ",name, " получилась :",summa) print("Теперь очередь Соперника !") kubik_3=randint(1,6) print("первоя кость прокатилась по столу и выдала : ",kubik_3) kubik_4=randint(1,6) print("Вторая кость перевернулась и показала :",kubik_4) summa_2=kubik_3+kubik_4 print("Общая сумма у ",name_2," получилась :",summa_2) if summa>summa_2: # Если игрок выигрывает bank=bank+stavka print("Вы выйграли! банк ",name," составляет : ",bank) if game_type==2: bank_2=bank_2-stavka print("у вашего противника ",name_2," банк составляет :",bank_2) print("Продолжить такую рискованую игру или остановиться?") print("1- продолжить! 2- закончить! 3-изменить ставку") flag_igru=fun_proverki(1,3) os.system('clear') if(flag_igru==1): # Продолжить ли игру! continue elif flag_igru==3: #Изменить ставку print("Введите новую ставку : ") stavka=fun_proverki(100,500) else: break elif summa==summa_2: print("Ничья ! Вы остались при своих") print("Продолжить такую рискованую игру или остановиться?") print("1- продолжить! 2- закончить! 3-изменить ставку") flag_igru=fun_proverki(1,3) os.system('clear') if(flag_igru==1): # Продолжить ли игру! continue elif flag_igru==3:#Изменить ставку print("Введите новую ставку : ") stavka=fun_proverki(100,500) else: break else: #Если игрок проигрывет! bank=bank-stavka print("Вы проиграли! банк ",name," составляет : ", bank) if game_type==2: bank_2=bank_2+stavka print("у вашего противника ",name_2," банк составляет :",bank_2) if bank<0: #Если кончилься банк print("У ",name," не осталось денег , игра закончена") break if game_type==2: if bank_2<0: #Если кончилься банк print("У ",name_2," не осталось денег , игра закончена") break else: # Продолжить ли игру print("Продолжить такую рискованую игру или остановиться?") print("1- продолжить! 2- закончить! 3-изменить ставку") flag_igru=fun_proverki(1,3) os.system('clear') if(flag_igru==1): # Продолжить ли игру! continue elif flag_igru==3:#Изменить ставку print("Введите новую ставку : ") stavka=fun_proverki(100,500) else: break break i=0 j=0 game_type=0 print("Добро пожаловать в игру кости ! \n") while True: #цикл начала игры и ее повторения до выхода из игры print("Выберите тип игры : \n 1-игра против компьютера \n 2- игра против другова игрока \n 3- игра сам с сабой О_о\n 0- выход из игры ") game_type=fun_proverki(0,3) if game_type==0: #Выход из игры break if game_type==1: # Игра против компьютера os.system('clear') print("Игра против компьютера") fun_igra(1) if game_type==2: # Игра против другого игрока os.system('clear') print('Игра против другово игрока!') fun_igra(2) if game_type==3: # Игра сам с сабой О_о os.system('clear') print("Игра сам с сабой О_о ") fun_igra(3)
8fa6c697be99474bb7db1c4d4c6b987498ec5c9f
saurabhmehta04/charming_python
/basics/designPatterns/StructuralPattern/decorator.py
950
4.09375
4
from functools import wraps def make_blink(function): ''' Defines the decorator''' # This makes the decorator transparent in terms of its name and docstring @wraps(function) # Define the inner function def decorator(): ret = function() return "<blink>" + ret + "</blink>" return decorator # Apply the decorator here ! @make_blink def hello_world(): ''' Original function''' return "hello World !" # check the result of decorating print(hello_world()) # check if the function name is still the name of the function being decorated print( hello_world.__name__) # => prints name of the function, (otherwise "decorator") since we use @wraps(func), docstring is also passed. # check if the decorating is still the same as that of the function being decorated print( hello_world.__doc__) # => prints the doc string "Original function" doc string, otherwise None, because of wraps(func)
bc6c9c4eaabf75764d2fdebac69264b54da7179f
jjkyun/tensorflow
/2._cost.py
1,115
3.6875
4
''' Lecturer: Sung Kim 여기서는 Cost Function을 조금 더 깊게 살펴본다 - Cost Function 설계할 때 산꼭대기 경사가 하나(Convex Function)인지 확인!! ''' import tensorflow as tf import matplotlib.pyplot as plt x_data = [1,2,3] y_data = [1,2,3] W = tf.Variable(tf.random_normal([1]), name = 'weight') X = tf.placeholder(tf.float32, shape = [None]) Y = tf.placeholder(tf.float32, shape = [None]) # Our hypothesis for Linear model W*X hypothesis = W*X ## 예측값 - 실제값 cost = tf.reduce_mean(tf.square(hypothesis - Y)) ## Cost를 minimize하는 함수를 직접 만듬 learning_rate = 0.1 gradient = tf.reduce_mean((W*X-Y)*X) descent = W - learning_rate * gradient update = W.assign(descent) ## optimizer = tf.train.GradientDescentOptimizer(learning_rate = 0.1) ## train = optimizer.minimize(cost) sess = tf.Session() sess.run(tf.global_variables_initializer()) for step in range(21): sess.run(update, feed_dict={X: x_data, Y: y_data}) print(step, sess.run(cost, feed_dict={X: x_data, Y:y_data}), sess.run(W)) ## cost가 점점 낮아지는 것을 확인할 수 있다
3315ce6d3b7ad68c4e5beea0f8af95b3d40ef7ac
franklingu/leetcode-solutions
/questions/wiggle-sort-ii/Solution.py
826
3.953125
4
""" Given an integer array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3].... You may assume the input array always has a valid answer.   Example 1: Input: nums = [1,5,1,1,6,4] Output: [1,6,1,5,1,4] Explanation: [1,4,1,5,1,6] is also accepted. Example 2: Input: nums = [1,3,2,2,3,1] Output: [2,3,1,3,1,2]   Constraints: 1 <= nums.length <= 5 * 104 0 <= nums[i] <= 5000 It is guaranteed that there will be an answer for the given input nums.   Follow Up: Can you do it in O(n) time and/or in-place with O(1) extra space? """ class Solution: def wiggleSort(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ nums.sort() half = len(nums[::2]) nums[::2], nums[1::2] = nums[:half][::-1], nums[half:][::-1]
d8a0754e9e9b5c2bd8c46d3ee9bca5d84576a40b
kyzhouhzau/Python
/frequence statistic.py
473
3.578125
4
#!/usr/bin/env python3 # -*- coding:utf-8-*- # 词频统计 import collections import re def get_words(file): with open(file) as f: words_box = [] for line in f: words_box.extend(re.split(r'[;\.\s]*', line)) new_words_box = [] for word in words_box: if word.isalpha(): new_words_box.append(word) return collections.Counter(new_words_box) a = get_words('zhou.txt') print(a.most_common(20))
6d55447ab313a2be076ab47aea35f60d61f27e83
erjan/coding_exercises
/count_items_matching_rule.py
1,205
3.921875
4
class Solution: def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int: num_items = 0 for item in items: type_i = item[0] color_i = item[1] name_i = item[2] print(type_i, color_i, name_i) rule1 = (ruleKey == "type" and ruleValue == type_i) rule2 = (ruleKey == "color" and ruleValue == color_i) rule3 = (ruleKey == "name" and ruleValue == name_i) if rule1: num_items+=1 elif rule2: num_items+=1 elif rule3: num_items+=1 return num_items items = [["phone","blue","pixel"],["computer","silver","lenovo"], ["phone","gold","iphone"]] ruleKey = "color" ruleValue = "silver" ''' #this problem is about knowing how to iterate!!!! nested for loop on this one gives me error - dont go one level deeper , it will start iterating over letters in each word!! e.g. phone, blue, pixel: for i in item: i[0] - p i[1] - h i[2] - o instead of actual items! nested loop on item produces letters!! '''
83cf547fa636612c4013167b131e133fbcc2510e
NoahLE/Coding-Challenges
/hr-Python-String-Validators.py
866
4.34375
4
def StringValidator(VString): # --- print True of the string contains any of the following characters, otherwise, print False --- isAlphaNum = False isAlpha = False isDigit = False isLower = False isUpper = False for character in VString: # True if alphanumeric if character.isalnum(): isAlphaNum = True # True if alphabetical if character.isalpha(): isAlpha = True # True if digits if character.isdigit(): isDigit = True # True if lowercase if character.islower(): isLower = True # True if uppercase if character.isupper(): isUpper = True print(f'{isAlphaNum} \n{isAlpha} \n{isDigit} \n{isLower} \n{isUpper}') pass if __name__ == "__main__": s = input() StringValidator(s)
64a7d2aa44754d2a192ec13aad3418a8defd09e0
107318041ZhuGuanHan/TQC-Python-Practice
/_6_list/609/main.py
2,797
4.34375
4
# matrix_1 = [[1, 2], [3, 4]] # matrix_2 = [[5, 6], [7, 8]] # matrix_3 = matrix_1 + matrix_2 # -> ★不能這樣搞,這樣會變成 matrix_3 = [[1, 2], [3, 4], [5, 6], [7, 8]] # ★要用元素相加的方式 # 1.建3個 2*2 的矩陣 2. 可以試著把那3個 2*2 的矩陣放在同一個list裡面 matrix_1 = [[0 for column in range(0, 2)] for row in range(0, 2)] matrix_2 = [[0 for column in range(0, 2)] for row in range(0, 2)] matrix_3 = [[0 for column in range(0, 2)] for row in range(0, 2)] print("Enter matrix 1: ") # 矩陣1的輸入 for row in range(0, 2): for column in range(0, 2): matrix_1[row][column] = int(input("[%d, %d]: " % (row + 1, column + 1))) print("Enter matrix 2: ") # 矩陣2的輸入 for row in range(0, 2): for column in range(0, 2): matrix_2[row][column] = int(input("[%d, %d]: " % (row + 1, column + 1))) for row in range(0, 2): # 矩陣3的元素計算 for column in range(0, 2): matrix_3[row][column] = matrix_1[row][column] + matrix_2[row][ column] print("Matrix 1: ") print("**%d %d**" % (matrix_1[0][0], matrix_1[0][1])) print("**%d %d**" % (matrix_1[1][0], matrix_1[1][1])) print("Matrix 2: ") print("**%d %d**" % (matrix_2[0][0], matrix_2[0][1])) print("**%d %d**" % (matrix_2[1][0], matrix_2[1][1])) print("Sum of 2 matrices:") print("**%d %d**" % (matrix_3[0][0], matrix_3[0][1])) print("**%d %d**" % (matrix_3[1][0], matrix_3[1][1])) # 參考答案在print這邊就是寫3個雙重for迴圈,可以不用那麼麻煩用格式化輸出 # ---------------------------------------------------------------------- # 自己練習參考答案的思路 matrix_1 = [[0 for column in range(0, 2)] for row in range(0, 2)] matrix_2 = [[0 for column in range(0, 2)] for row in range(0, 2)] print("Enter matrix 1: ") for row in range(0, 2): for column in range(0, 2): matrix_1[row][column] = int(input("[%d, %d]: " % (row + 1, column + 1))) print("Enter matrix 2: ") for row in range(0, 2): for column in range(0, 2): matrix_2[row][column] = int(input("[%d, %d]: " % (row+1, column+1))) print("Matrix 1: ") for row in range(0, 2): print("**", end='') for column in range(0, 2): print(matrix_1[row][column], end=' ') print("**") print("Matrix 2: ") for row in range(0, 2): print("**", end='') for column in range(0, 2): print(matrix_2[row][column], end=' ') print("**") print("Sum of 2 matrices: ") for row in range(0, 2): print("**", end='') for column in range(0, 2): print((matrix_1[row][column] + matrix_2[row][column]), end=' ') print("**")
3f09a29ce6f3d26cfc470b3f532e25dddcacc9c0
sknaht/algorithm
/python1/data_structure.py
375
3.609375
4
class ListNode: def __init__(self, x): self.val = x self.next = None def __repr__(self): if self: return "{} -> {}".format(self.val, repr(self.next)) class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Tree: def __init__(self, nums): return None
823990477f7dbcbc9bdf6e6912e35a92ed274dc1
monikpatel125/monik
/matrix.py
192
3.765625
4
#!/usr/bin/env python # coding: utf-8 # In[2]: x=int(input("enter row:")) y=int(input("enter col:")) def a(x,y): l=[i*j for j in range(y) for i in range(x)] return l print(a(y,x))
6247f75781854cb241e943491db4de59ab57ae44
bnavalniy/PyClass
/homeWorks/2/Task5Reiting.py
420
3.625
4
my_list = [7, 5, 3, 3, 2] num = int(input("Enter the N: ")) if num in my_list: position_to_insert = my_list.index(num) + my_list.count(num) my_list.insert(position_to_insert, num) else: for ind, el in enumerate(my_list): if num > el: my_list.insert(ind, num) break elif num < my_list[-1]: my_list.insert(len(my_list), num) break print(my_list)
d09e645bdcec69cb9cf80bbcf97e2699faf3485f
rfaulkner/project_euler
/p19.py
583
3.53125
4
#/env/bin/python # -*- coding: utf-8 -*- """ Project Euler - problem 14 """ __author__ = "ryan faulkner" __date__ = "12/3/2012" __license__ = "GPL (version 2 or later)" import sys from datetime import datetime, timedelta def main(): end = datetime(year=2000, month=12, day=31) cur_time = datetime(year=1901, month=1, day=1) day = timedelta(days=1) count = 0 while cur_time <= end: if int(cur_time.day) == 1 and int(cur_time.weekday()) == 6: count += 1 cur_time += day print count if __name__ == "__main__": sys.exit(main())
1a775713a7e1d3297d1601ad308b098b5c8c3479
sastafeva/GB_Algorithms
/Lesson_1_scheme/les_1_task_8.py
1,212
4.3125
4
# Вводятся три разных числа. # Найти, какое из них является средним (больше одного, но меньше другого). # В условиях задачи не указано, что на вход подаются целые числа. Принимаем любые. # По условиям, мы не делаем проверку на корректность ввода. # Значит на вход подаются точно числа и они все разные. a = float(input('Введите первое число: ')) b = float(input('Введите второе число: ')) c = float(input('Введите третье число: ')) if a > b: if a > c: if b > c: # получим c < b < a m = b else: # получим b < c < a m = c else: # получим b < a < c m = a else: if b > c: if a > c: # получим b < a < c m = a else: # получим a < c < b m = c else: # получим a < b < c m = b print('Среднее между введенными числами: ', m)
f3f427e6d78ec38f98eea3ea0bb15a3ef89c3190
MifengbushiMifeng/Pygo
/practice/practice3/first_PY_11.py
606
3.78125
4
# coding=utf-8 # practice Generator in Python # list L = [x * x for x in range(10)] print L g = (x * x for x in range(10)) print g for n in g: print n def fib(max): n, a, b = 0, 0, 1 while n < max: print b a, b = b, a + b n = n + 1 fib(100) def fib2(max): n, a, b = 0, 0, 1 while n < max: yield b a, b = b, a + b n = n + 1 g2 = fib2(10) for i in g2: print i def odd(): print 'step 1' yield 1 print 'step 2' yield 3 print 'print 3' yield 5 o = odd() print o.next() print o.next() print o.next()
051c46b199dc610419248e1f41fb1e3e1b1ebb7e
ivanbelichki/flash_cards_app
/flash_cards.py
4,342
3.609375
4
import random # CONSTANTS CARDS_FILE = 'cards.txt' QA_DIVIDER = ':' ADD_KEY = 'a' PLAY_KEY = 'p' VIEW_KEY = 'v' REMOVE_KEY = 'r' QUIT_KEY = 'q' VALID_KEYS = [ADD_KEY, REMOVE_KEY, PLAY_KEY, VIEW_KEY, QUIT_KEY] # driver def __main__(): choice = '' while choice != QUIT_KEY: choice = start() if choice == ADD_KEY: add_cards() elif choice == PLAY_KEY: play() elif choice == REMOVE_KEY: remove_cards() elif choice == VIEW_KEY: view_cards() print(f'\nSee you next time!\n') # start menu def start(): # print app menu print(f''' Welcome to the Flash Card App! Enter '{ADD_KEY}' to Add new Cards Enter '{REMOVE_KEY}' to remove Cards Enter '{VIEW_KEY}' to View all Cards Enter '{PLAY_KEY}' to Play! or '{QUIT_KEY}' to Quit ''') # get valid user choice user_in = '' while user_in not in VALID_KEYS: user_in = input('Enter your choice: ') return user_in # Flash Card Game Loop def play(): f = open(CARDS_FILE, "r") cards = f.readlines() # keep track of used cards n = -1 used = [-1] # game loop user_in = '' while user_in != QUIT_KEY: # check if all cards used all_cards_used = len(used) == len(cards) + 1 if all_cards_used: print('\n') print("Congrats! You've done all questions") return # find random card index while n in used: n = random.randint(0, len(cards)-1) card = cards[n].split(QA_DIVIDER) # print flash card print('\n') print(f'QUESTION: {card[0]}\n') input("Press 'Enter' for answer\n") print(f'ANSWER: {card[1]}') # keep track of used card index used.append(n) # get user choice user_in = input(f"Press 'Enter' for next question or {QUIT_KEY}' to quit: ") f.close() # add flash cards to deck def add_cards(): count = 0 # adding card loop user_in = '' while user_in != QUIT_KEY: # enter question user_in = input(f'Enter the question, or {QUIT_KEY} to quit: ') if user_in == QUIT_KEY: break question = user_in # enter answer user_in = input(f'Enter the answer, or {QUIT_KEY} to quit: ') if user_in == QUIT_KEY: break answer = user_in # write to flash card to file write_to_file(question, answer) # print flash card print(f''' Flash Card entered: Q: {question} A: {answer} ''') count += 1 if count > 0: print(f'Thanks for entering {count} card(s)') # remove flash cards from deck def remove_cards(): choice = '' while choice != QUIT_KEY: # print flash card deck view_cards() # get user input to delete card print('\n') choice = input(f'''Enter the number of the Card you wish to remove, or {QUIT_KEY} to quit ''') if choice == QUIT_KEY: break try: choice = int(choice) except: print('Please Enter a valid Card number') continue f = open(CARDS_FILE, "r") cards = f.readlines() if choice > len(cards) or choice < 0: print('Please Enter a valid Card number') continue # delete card from data strucutre cards.remove(cards[choice]) # overwrite card file with new cards w = open(CARDS_FILE, "w") w.write(''.join(cards)) w.close() f.close() # print flash cards def view_cards(): f = open(CARDS_FILE, "r") cards = f.readlines() print('\n') print(f'{len(cards)} cards:') print('\n') # get [question, answer] list of flash cards cards = [card.split(QA_DIVIDER) for card in cards] # list cards by number for i, card in enumerate(cards): print(f'{i}) QUESTION: {card[0]}, ANSWER: {card[1]}') f.close() # write flash card to file def write_to_file(question, answer): f = open(CARDS_FILE, "a") f.write(question + QA_DIVIDER + answer + '\n') f.close() __main__()
c9a2fc2908535238c16306a2c1e30de6a396a392
HamzaIlyas/EventRegistration
/main.py
6,462
3.53125
4
import json ContactsList = [] LeadsList = [] class Contacts: contactscount = 0 def __init__(self, name, email, phone): self.Name = name self.Email = email self.Phone = phone Contacts.contactscount += 1 def getcontactscount(self): print("Total Contacts %d" % Contacts.contactscount) def displaycontact(self): print("Name : ", self.Name, ", Email : ", self.Email, ", Phone : ", self.Phone) class Leads: leadscount = 0 def __init__(self, name, email, phone): self.Name = name self.Email = email self.Phone = phone Leads.leadscount += 1 def getleadscount(self): print("Total Leads %d" % Leads.leadscount) def displaylead(self): print("Name : ", self.Name, ", Email : ", self.Email, ", Phone : ", self.Phone) def addregistrant(registrant): if registrant.Email or registrant.Phone: contact_phones = {contact.Phone for contact in ContactsList} contact_emails = {contact.Email for contact in ContactsList} lead_phones = {lead.Phone for lead in LeadsList} lead_emails = {lead.Email for lead in LeadsList} if registrant.Phone in contact_phones and registrant.Phone: print("Registrant already exists in ContactsList phone matched") for contact in ContactsList: if contact.Phone == registrant.Phone and contact.Phone: if contact.Email: registrant.Phone = contact.Phone registrant.Email = contact.Email else: registrant.Phone = contact.Phone ContactsList.remove(contact) ContactsList.append(Contacts(registrant.Name, registrant.Email, registrant.Phone)) elif registrant.Email in contact_emails and registrant.Email: print("Registrant already exists in ContactList email matched") for contact in ContactsList: if contact.Email == registrant.Email and contact.Email: if contact.Phone: registrant.Phone = contact.Phone registrant.Email = contact.Email else: registrant.Email = contact.Email ContactsList.remove(contact) ContactsList.append(Contacts(registrant.Name, registrant.Email, registrant.Phone)) elif registrant.Phone in lead_phones and registrant.Phone: print("Registrant exists in Leadslist phone matched, moved to ContactsList") for lead in LeadsList: if lead.Phone == registrant.Phone and lead.Phone: if lead.Email: registrant.Phone = lead.Phone registrant.Email = lead.Email else: registrant.Phone = lead.Phone LeadsList.remove(lead) ContactsList.append(Contacts(registrant.Name, registrant.Email, registrant.Phone)) elif registrant.Email in lead_emails and registrant.Email: print("Registrant exists in Leadslist email matched, moved to ContactsList") for lead in LeadsList: if lead.Email == registrant.Email and lead.Email: if lead.Phone: registrant.Phone = lead.Phone registrant.Email = lead.Email else: registrant.Email = lead.Email LeadsList.remove(lead) ContactsList.append(Contacts(registrant.Name, registrant.Email, registrant.Phone)) else: ContactsList.append(Contacts(registrant.Name, registrant.Email, registrant.Phone)) print("Registrant not exists in ContactList or Leadslist, new contact added to ContactsList") # Registration form starts --------------- # print('Webinar Registration Form') # name = input('Enter your name : ') # email = input('Enter your email : ') # phone = input('Please input your 10 digit phone no. : ') # while len(phone) != 10 or not phone.isdigit(): # print('You have not entered a 10 digit value! Please try again.') # phone = input('Please input your 10 digit phone no. : ') # Registration form ends --------------- # Given Contacts ContactsList.append(Contacts('Alice Brown', None, 1231112223)) ContactsList.append(Contacts('Bob Crown', '[email protected]', None)) ContactsList.append(Contacts('Carlos Drew', '[email protected]', 3453334445)) ContactsList.append(Contacts('Doug Emerty', None, 4564445556)) ContactsList.append(Contacts('Egan Fair', '[email protected]', 5675556667)) # Given Leads LeadsList.append(Leads(None, '[email protected]', None)) LeadsList.append(Leads('Lucy', '[email protected]', 3210001112)) LeadsList.append(Leads('Mary Middle', '[email protected]', 3331112223)) LeadsList.append(Leads(None, None, 4442223334)) LeadsList.append(Leads(None, '[email protected]', None)) # Given Registrants registrant1 = Contacts("Lucy Liu", "[email protected]", None) registrant2 = Contacts("Doug", "[email protected]", 4564445556) registrant3 = Contacts("Uma Thurman", "[email protected]", None) Data = { "registrant1": { "name": registrant1.Name, "email": registrant1.Email, "phone": registrant1.Phone, }, "registrant2": { "name": registrant2.Name, "email": registrant2.Email, "phone": registrant2.Phone, }, "registrant3": { "name": registrant3.Name, "email": registrant3.Email, "phone": registrant3.Phone, } } jsonStr = json.dumps(Data) with open('data.json', 'w') as file: json.dump(jsonStr, file) # Read JSON file # with open('data.json', 'r') as j: # print(json.load(j)) print("\nContacts in the Starting ContactsList :\n") for contact in ContactsList: print(contact.Name, contact.Email, contact.Phone) print("\nLeads in the Starting LeadsList :\n") for lead in LeadsList: print(lead.Name, lead.Email, lead.Phone) print("\nAdding First Registrant...") addregistrant(registrant1) print("\nAdding Second Registrant...") addregistrant(registrant2) print("\nAdding Third Registrant...") addregistrant(registrant3) print("\nContacts in the Final ContactsList :\n") for contact in ContactsList: print(contact.Name, contact.Email, contact.Phone) print("\nLeads in the Final LeadsList :\n") for lead in LeadsList: print(lead.Name, lead.Email, lead.Phone)
62442337801a9008bacb26a6306274202eff2e31
Tokyo113/leetcode_python
/暴力递归到动态规划/code_04_cardsinLine.py
1,181
3.53125
4
#coding:utf-8 ''' @Time: 2019/11/17 10:18 @author: Tokyo @file: code_04_cardsinLine.py @desc: 给定一个整型数组arr,代表数值不同的纸牌排成一条线。玩家A和玩家B依次拿走每张纸 牌,规定玩家A先拿,玩家B后拿,但是每个玩家每次只能拿走最左或最右的纸牌,玩家A 和玩家B都绝顶聪明。请返回最后获胜者的分数。 ''' def win1(arr): if len(arr) == 0 or arr is None: return 0 return max(f(arr, 0, len(arr)-1), s(arr, 0, len(arr)-1)) def f(arr, L, R): if L == R: return arr[L] return max(arr[L] + s(arr, L+1, R), arr[R] + s(arr, L, R-1)) def s(arr, L, R): if L == R: return 0 return min(f(arr, L+1, R), f(arr, L, R-1)) def winner(arr): return max(f1(arr, 0, len(arr)-1), g1(arr, 0, len(arr)-1)) def f1(arr, L, R): if L == R: return arr[L] return max(arr[L] + g1(arr, L+1, R), arr[R]+g1(arr, L, R-1)) def g1(arr, L, R): if L == R: return 0 return min(f1(arr, L+1, R), f1(arr, L, R-1)) if __name__ == '__main__': a = [1,100,45,67,8,34,21,2,9] b = [1,9,1] print(win1(a)) print(winner(b))
d55fd3f5e9604b19b1f569b6657cd83164c488b1
nhatminh2h/LiDAR
/writetofile.py
1,234
3.609375
4
import serial import numpy as np from math import cos, sin,radians, pi print("Enter name of file to write to: ") filename = input() f = open(f'{filename}.txt',"w+") #Arduino port here port = 'com3' ArduinoSerial = serial.Serial(port, 115200)#serial port object #data arrays #theta, phi, r = ([0] for i in rannge(3))#RAW data in polar #x, y , z = ([0] for i in range(3))#3D coordinate def format(f): return "%.0f" %f def readSerial(): return (ArduinoSerial.readline().decode("utf-8")) def write_to_file(): print("scanning...") while (readSerial != "--End of Scan--"): temp_t = int(readSerial()) temp_p = 135 - int(readSerial())#adjusting for v_angle offset temp_r = int(readSerial()) if (temp_r > 5):#filter data with small distance x = ((temp_r*cos(radians(temp_p))*cos(radians(temp_t)))) y = ((temp_r*cos(radians(temp_p))*sin(radians(temp_t)))) z = ((temp_r*sin(radians(temp_p)))) x = format(x) y = format(y) z = format(z) f.write(str(x)) f.write(",") f.write(str(y)) f.write(",") f.write(str(z)) f.write("\n") write_to_file()
8ad816ec9ccc197d330eb8a57bbad01099bacc63
136772/MyPython
/Mycode/learn/3.py
366
3.90625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' @author:JaNG @email:[email protected] ''' ''' name = iter(['jang','rourou','book']) print(name.__next__()) print(name.__next__()) print(name.__next__()) ''' def cash_money(amount): while amount>0: amount -= 1 yield '取了{},还剩{}'.format(1,amount) temp = cash_money(5) for i in temp: print(i)
828989ed02016bba346d6773417ac75d19341812
aneverov/python_stepik
/2_3_1.py
242
3.578125
4
a=int(input()) b=int(input()) c=int(input()) d=int(input()) print(end='\t') for i in range(c,d+1): print(i,end='\t') print() for j in range(a,b+1): print(j,end='\t') for k in range(c,d+1): print(k*j,end='\t') print()
b909624061d689f0a821a6d4c79a71e0c0d08702
Ghong-100/Python
/Practice/Exception.py
1,235
4.03125
4
class Overflow(Exception): def __init__(self, msg): self.msg = msg def __str__(self): return self.msg try: print("한자리 숫자 계산기") num1 = int(input("첫번째 :")) num2 = int(input("두번째 :")) if num1 > 9 or num2 > 9: raise Overflow("입력값 : {0}, {1}".format(num1, num2)) print("{0} / {1} = {2}".format(num1, num2, int(num1/num2))) except ValueError: print("[에러] 잘못된 값을 입력하였습니다.") except Overflow as err: print("[에러] 오버플로우") print(err) finally: print("계산기 끝났어유") exit() try: print("나누기 전용 계산기") nums = [] nums.append(int(input("첫번째 숫자를 입력하세요 : "))) nums.append(int(input("두번째 숫자를 입력하세요 : "))) #nums.append(int(nums[0]/nums[1])) #num1 = int(input("첫번째 숫자를 입력하세요 : ")) #num2 = int(input("두번째 숫자를 입력하세요 : ")) print("{0} / {1} = {2}".format(nums[0], nums[1], nums[2])) except ValueError: print("[에러] 잘못된 값을 입력하였습니다.") except ZeroDivisionError as err: print(err) except Exception as err: print("[에러] ", err)
56630c725dfd1089707b6acbc7915e33fba79ee5
dylanlee101/leetcode
/code_week16_810_816/clone_graph.py
1,807
3.9375
4
''' 给你无向 连通 图中一个节点的引用,请你返回该图的 深拷贝(克隆)。 图中的每个节点都包含它的值 val(int) 和其邻居的列表(list[Node])。 class Node { public int val; public List<Node> neighbors; }   测试用例格式: 简单起见,每个节点的值都和它的索引相同。例如,第一个节点值为 1(val = 1),第二个节点值为 2(val = 2),以此类推。该图在测试用例中使用邻接列表表示。 邻接列表 是用于表示有限图的无序列表的集合。每个列表都描述了图中节点的邻居集。 给定节点将始终是图中的第一个节点(值为 1)。你必须将 给定节点的拷贝 作为对克隆图的引用返回。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/clone-graph ''' """ # Definition for a Node. class Node: def __init__(self, val = 0, neighbors = []): self.val = val self.neighbors = neighbors """ class Solution: def __init__(self): self.visited = {} def cloneGraph(self, node): """ :type node: Node :rtype: Node """ if not node: return node # 如果该节点已经被访问过了,则直接从哈希表中取出对应的克隆节点返回 if node in self.visited: return self.visited[node] # 克隆节点,注意到为了深拷贝我们不会克隆它的邻居的列表 clone_node = Node(node.val, []) # 哈希表存储 self.visited[node] = clone_node # 遍历该节点的邻居并更新克隆节点的邻居列表 if node.neighbors: clone_node.neighbors = [self.cloneGraph(n) for n in node.neighbors] return clone_node
6ed47cda0891e8accd10dc2437f6f3ba5f0c1be9
Douphing/Python
/desfio008.py
181
3.71875
4
medida = float(input(' Uma distancia em metros: ')) cm = medida * 100 mm = medida * 1000 print('a medida de {}m cor' 'responde a {:.0f}cm e {:.0f}mm'.format(medida, cm, mm))
2a2b51427baf92beeb239794ef6ab544bc52ce2e
alecownsyou/Programming-11-Files_
/alec.py
2,128
3.890625
4
count = 0 print ("\nBonjour") print ("Question 1: Qu'elle années est-ce que chapitre est sur?") answer1=input("Mis seulement les numéros\nExample: 1990\n") if answer1.lower()== "1920": print ("Correcte") count += 1 else: print ("Incorrect") print ("\nQuestion 2: Vrai ou faux: Est-ce qu'il y a du racisme dans Canada") answer2=input("Répondre avec Vrai ou Faux\n") if answer2.lower()== "vrai": print ("Correcte") count += 1 else: print ("Incorrect") print ("\nQuestion 3: Qui etait nommée une juge en Alberta") answer3=input ("A)Emily Murphy\nB)Mackenzie King\nC)Lionel Conacher\nD)Bobbie Rosenfeld\nMis seulement un lettre\n") if answer3 == "a" : print("Correcte") count += 1 else: print ("Incorrect") print ("\nQuestion 4: Quoi est-ce que Frederick Banting et Charles Best invente?") answer4=input ("Mis seulement le nom du invention\n") if answer4.lower() == "insulin" : print("Correcte") count += 1 else: print ("Incorrect") print ("\nQuestion 5: Qui est le gouverneur général?") answer5=input ("Mis tout le nom\n") if answer5.lower() == "julian byng" : print("Correcte") count += 1 else: print ("Incorrect") print ("\nQuestion 6:Combien des Canadiens écoutaient les émissions américaines?") answer5=input ("A)20 000\nB)50 000\nC)100 000\nD)300 000\nMis seulement un lettre\n") if answer5.lower() == "d" : print("Correcte") count += 1 else: print ("Incorrect") print ("\nQuestion 7:Quoi est-ce que Wilfird <<Wop>> May fait?") answer5=input ("A)Acteur\nB)Athlète\nC)Pilote\nD)Politicien\nMis seulement un lettre\n") if answer5.lower() == "c" : print("Correcte") count += 1 else: print ("Incorrect") print ("\nQuestion 7:Quand est-ce que le prohibition finis dans États-Unis?") answer5=input ("Mis seulement les numéros\nExample: 1990\n") if answer5.lower() == "1933" : print("Correcte") count += 1 else: print ("Incorrect") print ("\nFinis\nRésultat") print ("Score total: " + str(count) + "/8") division = float(count)/float(8) multiply = float(division*100) result = round(multiply) print ("Pourcentage total", int(result), "%") quit=input ("Est-ce que vous voules quitter?\n") if quit.lower() == "oui" : sys.exit
5e94cd487cb871407c1b21b157822f6a9a7b3a57
madeibao/PythonAlgorithm
/py股票的最大利润2.py
399
3.53125
4
from typing import List class Solution(object): def maxProfit(self, prices: List[int]) -> int: if len(prices)==0: return 0 profit = -float("inf") temp = prices[0] for i in range(1, len(prices)): temp = min(temp, prices[i]) profit = max(profit,prices[i]-temp) return profit if __name__ == "__main__": s = Solution() nums = [7,1,5,3,6,4] print(s.maxProfit(nums))
b4075e145f757632bd4549fd94a15ceeee864967
pele98/Object_Oriented_Programming
/OOP/Exercise5/Excercise5_5/main.py
886
3.953125
4
# File name: main # Author: Pekka Lehtola # Description: main file for player dictionary game. from player_class import * from dice_class import * #Creating all of the objects. matti = Player(1, "matti", "koskinen") pekka = Player(2, "pekka", "lehtola") linda = Player(3, "linda", "laine") #Creating list of players and their id.s players = [matti, pekka, linda] players_id = [matti.get_id(), pekka.get_id(), linda.get_id()] #Dice objects dice_1 = Dice(1) dice_2 = Dice(2) dice_3 = Dice(3) dices = [dice_1, dice_2, dice_3] #Creating dictionary from the objects. player_dict = dict(zip(players_id, dices)) #Firstly prints the name from players list #then rolls the dice from dictionary. for object in range(0, 3): print(players[object].get_first_name(), "rolled the dice and the result is: ") player_dict[object+1].roll_the_dice() print(player_dict[object+1]) print()
bce71f36112cbef787a50ffa8dffb444c50f5ce5
phporath/GIS-Tools
/ArcPy/calculoAzimute.py
674
3.6875
4
-Em "Pre-Logic Script Code" digite: def LookUp(eInic, eFim, nInic, nFim): eFimInic = eFim - eInic nFimInic = nFim - nInic rumo = abs(math.degrees(math.atan(abs(eFimInic / nFimInic)))) if (eFimInic>0 and nFimInic>0): azimute = abs(rumo) elif (eFimInic>0 and nFimInic<0): azimute = abs(rumo - 180) elif (eFimInic<0 and nFimInic<0): azimute = abs(rumo + 180) elif (eFimInic<0 and nFimInic>0): azimute = abs(rumo - 360) return azimute -No campo abaixo "Nome do campo=" digite apenas: LookUp(!eInic!, !eFim!, !nInic!, !nFim!) abs(math.degrees(math.atan(abs(( !eFim! - !eInic! ) / ( !nFim! - !nInic! )))))
b717c00c5b9d44d9837f1fc2c40d46e1710c54b9
BaoLocPham/ThePongGame
/Ball.py
628
3.875
4
from turtle import Turtle class Ball(Turtle): def __init__(self): super().__init__() self.shape('circle') self.color('white') self.penup() self.x_move = 10//2 self.y_move = 10//2 def move(self): self.goto(self.xcor()+self.x_move, self.ycor()+self.y_move) def bouncing_wall(self): # self.setheading(360 - self.heading()) self.y_move *= -1 def bouncing_paddle(self): # self.setheading(self.heading()-90) self.x_move *= -1 def refresh(self): self.goto(0, 0) self.x_move *= -1 self.y_move *= -1
4044156bfd391934aafdd18c791f65dc5725f3c9
ybai62868/heterocl
/tvm/tests/verilog/unittest/testing_util.py
2,177
3.53125
4
"""Common utilities for test""" class FIFODelayedReader(object): """Reader that have specified ready lag.""" def __init__(self, read_data, read_valid, read_ready, lag): self.read_data = read_data self.read_valid = read_valid self.read_ready = read_ready self.read_ready.put_int(1) self.lag = list(reversed(lag)) self.data = [] self.wait_counter = 0 self.wait_state = False def __call__(self): """Logic as if always at pos-edge""" if not self.wait_state: if (self.read_ready.get_int() and self.read_valid.get_int()): self.data.append(self.read_data.get_int()) self.wait_counter = self.lag.pop() if self.lag else 0 self.wait_state = True if self.wait_state: if self.wait_counter == 0: self.read_ready.put_int(1) self.wait_state = False else: self.wait_counter -= 1 self.read_ready.put_int(0) class FIFODelayedWriter(object): """Auxiliary class to write to FIFO """ def __init__(self, write_data, write_valid, write_ready, data, lag): self.write_data = write_data self.write_valid = write_valid self.write_ready = write_ready self.write_valid.put_int(0) self.lag = list(reversed(lag)) self.data = list(reversed(data)) self.wait_counter = 0 self.wait_state = True def __call__(self): """Logic as if always at pos-edge""" if not self.wait_state: if self.write_ready.get_int(): self.wait_counter = self.lag.pop() if self.lag else 0 self.wait_state = True if self.wait_state: if self.wait_counter == 0: if self.data: self.write_valid.put_int(1) self.write_data.put_int(self.data.pop()) self.wait_state = False else: self.write_valid.put_int(0) else: self.write_valid.put_int(0) self.wait_counter -= 1
af51195335f604dfa270c2f8ca55ac1c9d396101
Meao/py
/repl/4-3Memorizing.py
1,008
3.640625
4
from collections import deque # queue LIFO & FIFO # LIFO - Last in first out # FIFO - First in first out class MemorizingDict(dict): history = deque(maxlen=10) def set(self, key, value): self.history.append(key) # MemorizingDict.history self[key] = value # memDict = dict() memDict[key] = value def get_history(self): return self.history # print(MemorizingDict.__bases__) d = MemorizingDict() d.set("boo", 500100) # 1 переменная history = deque(maxlen=10) является атрибутом класса, и доступна и как MemorizingDict.history и как: d = MemorizingDict() d.history print(d.get_history()) d1 = MemorizingDict() d1.set("baz", 100500) # 2 переменная self.history создаётся в момент инициализации объекта, а значит принадлежит объекту и доступна только как: d1 = MemorizingDict() d1.history print(d1.get_history())
cb507a83ea7c686115f9a4c3b3f0ae7ec9c111aa
paulohenriquegama/Blue_Modulo1-LogicaDeProgramacao
/Aula16/oo1.py
1,238
4.0625
4
'''class Heroi: def __init__(self,nome, idade = 30,habilidade = 'magia'): self.nome = nome self.idade = idade self.habilidade = habilidade def usar_habilidade(self): print(f"{self.nome} está usando sua habilidade: {self.habilidade}.") nome = input("Digite o nome: ") heroi = Heroi(nome) heroi.idade = 32 print(vars(heroi)) for a,v in heroi. ''' class Pessoa: def __init__(self, nome, sexo, cpf, ativo): self.__nome = nome self.__sexo = sexo self.__cpf = cpf self.__ativo = ativo def desativar(self): self.ativo = False print('Apessoa foi desativada com sucesso') def get_nome(self): return self.__nome def set_nome(self, nome): self.__nome = nome @property def nome(self): return self.__nome @nome.setter def nome(self, nome): self.__nome = nome if __name__ == '__main__': pessoa1 = Pessoa('Marcos', 'M', '123456', True) pessoa1.desativar() pessoa1.ativo = True print(pessoa1.ativo) pessoa1.nome = "Paulo" print(pessoa1.nome) #utilizando getter e setters pessoa1.set_nome('Joao') print(pessoa1.get_nome()) print(pessoa1.nome)
9303781bcce886a995672e64f3f5278a17f1a2d6
mareliefi/code-wars
/find_odd_even.py
292
3.8125
4
def find_outlier(integers): array_even = [] array_odd = [] for i in integers: if i % 2 == 0: array_even.append(i) else: array_odd.append(i) if len(array_even) == 1: return array_even[0] else: return array_odd[0]
bd43b876e62f971bfb2461cd678ee86b508b8e13
sanusiemmanuel/DLBDSMLUSL01
/Unit_4_Feature_Engineering/4_1_Numerical_feature_scaling.py
2,189
3.71875
4
# IU - International University of Applied Science # Machine Learning - Unsupervised Machine Learning # Course Code: DLBDSMLUSL01 # Numerical feature scaling #%% import libraries import pandas as pd from sklearn.preprocessing import MinMaxScaler from sklearn.preprocessing import StandardScaler from sklearn.preprocessing import RobustScaler #%% generate sample data Table = {\ 'Customer-ID': [1, 2, 3, 4, 5], \ 'Gender': ['M', 'F', 'M',' F', 'F'], \ 'Work-type': [1, 2, 2, 3, 3], \ 'Client-satisfaction': [3, 0, 4, 3, 5], \ 'Number-occupants': [2, 4, 2, 1, 2], \ 'Consumption': [70, 140, 65, 40, 65]} TDF = pd.DataFrame(data=Table) #%% apply Min-Max Scaling on the feature 'Consumption' MMS = MinMaxScaler().fit_transform(TDF[['Consumption']]) TDF['Consumption'] = MMS print(TDF['Consumption']) # console output: # 0.30 # 1 1.00 # 2 0.25 # 3 0.00 # 4 0.25 print(TDF['Consumption'].describe()) # console output: # count 5.000000 # mean 0.360000 # std 0.376497 # min 0.000000 # 25% 0.250000 # 50% 0.250000 # 75% 0.300000 # max 1.000000 #%% apply standardization on the feature 'Consumption' TDF = pd.DataFrame(data=Table) ST = StandardScaler().fit_transform(TDF[['Consumption']]) TDF['Consumption'] = ST print(TDF['Consumption']) # console output: # 0 -0.178174 # 1 1.900524 # 2 -0.326653 # 3 -1.069045 # 4 -0.326653 print(TDF['Consumption'].describe()) # console output: # Name: Consumption, dtype: float64 # count 5.000000e+00 # mean -3.330669e-17 # std 1.118034e+00 # min -1.069045e+00 # 25% -3.266526e-01 # 50% -3.266526e-01 # 75% -1.781742e-01 # max 1.900524e+00 #%% apply Robust Scaling to the column 'Consumption' RS = RobustScaler().fit_transform(TDF[['Consumption']]) TDF['Consumption'] = RS print(TDF['Consumption']) # console output: # 0 1.0 # 1 15.0 # 2 0.0 # 3 -5.0 # 4 0.0 print(TDF['Consumption'].describe()) # console output: # Name: Consumption, dtype: float64 # count 5.00000 # mean 2.20000 # std 7.52994 # min -5.00000 # 25% 0.00000 # 50% 0.00000 # 75% 1.00000 # max 15.00000
d0c74d45d1f300ce6590ff145e6af834330b1165
mkm14/store
/创作.py
1,656
3.8125
4
brand = ("欢迎来到娱乐商城") print("--------------------------",brand,"----------------------") tips = ("未成年人禁止娱乐") print("--------------------------",tips,"---------------------------") nem = input("请输入您的名字:") if nem=='阮红英': print('欢迎荣耀段位的大神来到娱乐城') elif nem=='张宇航': print('欢迎王者20性段位的大神来到娱乐城') elif nem=='王赛': print('欢迎王者段位10星的大神来到娱乐城') elif nem=='诗磊': print('欢迎王者段位5星的大神来到娱乐城') else: print('三分靠技术,七分靠运气') age =input("请输入您的年龄:") age = int(age) if age >= 18: print("欢迎来到本娱乐城") elif age >=0 and age<18: breakpoint("未成年人禁止娱乐") else: breakpoint('未成年人禁止娱乐') import random num = random.randint(0, 1000) count = 0 i = 1 gold = 5000 while i <= 20: count = count + 1 chose = input("请输入本次猜的数据:") chose = int(chose) if gold <=0: print("您的金币为0不能继续游戏") break elif chose > num: gold = gold - 500 print("大了","金币剩余",gold) elif chose < num: gold = gold - 500 print("小了","金币剩余",gold) elif gold <=0: print("您的金币为0不能继续游戏") else: gold = gold + 10000 print("恭喜,本次猜中,本次幸运数字为:",num,",本次猜了," ,count,"次,","金币剩余",gold) break i = i + 1
3f20a0d4af6f64d76cd4c4f9fe0a838f6a4b4693
shaan2348/hacker_rank
/itertools_product.py
297
4.25
4
# we have to print the cartesian product of two sets # using product function from itertools module # "*" infront of any thing in print unpacks the list or tuple or set from itertools import product a = [int(x) for x in input().split()] b = [int(x) for x in input().split()] print(*product(a,b))
b1fd94840c71bff364a7edbd2239c073352e856a
cassiocamargos/Python
/learn-py/listas-py/a5.py
680
3.921875
4
# 5- O cardápio de uma lanchonete é dado pela tabela de preços abaixo. Escreva um programa que leia a quantidade de cada item comprado por um determinado cliente e imprima o valor total da sua compra. # Hambúrguer R$ 8,00 # Batata frita R$ 12,00 # Refrigerante R$ 3,00 # Cerveja R$ 5,00 # Doce R$ 3,00 h = int(input('Quantidade de hamburgueres pedidos: ')) * 8 b = int(input('Quantidade de batatas fritas pedidas: ')) * 12 r = int(input('Quantidade de refrigerantes pedidos: ')) * 3 c = int(input('Quantidade de cervejas pedidas: ')) * 5 d = int(input('Quantidade de doces pedidos: ')) * 3 total = h + b + r + c + d print(f'\nTotal da conta: R$ {total:.2f}')
36a43e1fdfb944d3937d2da8a5308f10c9f3f020
AshishMaheshwari5959/InfyTQ
/Programming Fundamentals using Python/Day 5/Exercises/Exercise 29: Collaborative Exercise – Level 2.py
1,408
4.3125
4
''' Write a python program which merges the content of two given lists and sorts the merged list. Write the following functions to achieve the above functionalities: def merge_lists(list1,list2): Returns the merged list. Use keyword arguments to pass the lists in method invocation Note: Merge the lists such that elements in list1 is followed by elements in list2. Sample Input Expected Ouput [1,2,3,4,1] [2,3,4,5,4,6] [1,2,3,4,1,2,3,4,5,4,6] def sort_list(merged_list): Sorts the merged list and returns the sorted list Sample Input Expected Ouput [1,2,3,4,1,2,3,4,5,4,6] [1,1,2,2,3,3,4,4,4,5,6] Also write the pytest test cases to test the program. ''' # Solution #PF-Exer-29 def merge_lists(list1,list2): #Write your logic here new_merge_list=[] for i in list1: new_merge_list.append(i) for j in list2 : new_merge_list.append(j) return new_merge_list def sort_list(merged_list): #Write your logic here for i in range (0,len(merged_list)): for j in range (i+1,len(merged_list)): if merged_list[i]>merged_list[j]: merged_list[i],merged_list[j] = merged_list[j],merged_list[i] return merged_list #Provide different values for list1 and list2 and test your program merged_list=merge_lists(list1=[1,2,3,4,1] ,list2=[2,3,4,5,4,6]) print(merged_list) sorted_merged_list=sort_list(merged_list) print(sorted_merged_list)
484df1a1d7072e8dd44e42d2fe96c67cfe54d23f
Cutshadows/productHunt
/ejercicio.py
212
3.625
4
from random import randrange inputvalue="" while inputvalue != "n": dado1=randrange(1, 7) print("dado2:", dado2) print("suma:", dado1+dado2) inputvalue=input("quires tirar otra vez los datos (s/n)")
b74a24fcc0251b5b7b3e1f5c37aeefcfe249cfe7
priyancbr/PythonProjects
/ListOperations.py
666
3.953125
4
MyList = ['One','two',3] print(MyList) MyList[1] = 'TWO IN CAPS' MutatedList = MyList print(MyList) NextList = [4, 'five'] print(NextList) LatestList = MyList + NextList print(LatestList) LatestList.append('Six') print(LatestList) Vari = LatestList.pop() print(Vari) print(LatestList) PoppedItem = LatestList.pop(3) print(PoppedItem) print(LatestList) LetterList = ['a','d','b','k','t','g','l'] print(LetterList) print(LetterList.sort()) print(LetterList) NumberList = [1,6,4,3,9,7,5] print(NumberList) print(NumberList.sort()) print(NumberList) MixedList = ['b','v','f',5,2,4,'a',1,'t'] print(MixedList) #print(MixedList.sort()) print("See below") print(MixedList)
d36d8b215b10220a6e4d7ced418d84426fedd63d
superstones/LearnPython
/Part1/week2/chapter9/exercise/User.py
540
3.609375
4
class User(): def __init__(self, first_name, last_name, age, sex): self.first_name = first_name self.last_name = last_name self.age = age self.sex = sex def describe_user(self): print("\nfirst_name:" + self.first_name.title()) print("last_name:" + self.last_name.title()) print("age:" + self.age.title()) print("sex:" + self.sex.title()) def greet_user(self): full_name = self.first_name + '' + self.last_name print("Hello, " + full_name.title())
9506986694271d7e0a6bd18395ba81464af03027
e-hamilton/hello_ml
/Log_Regression.py
2,745
3.875
4
""" This is a basic Logistic Regression program I wrote in an effort to dip my toes into Scikit-learn's machine learning tools. It evaluates unigrams and bigrams in several categories of the 20 Newsgroups dataset and produces a confusion matrix. This project doesn't follow a single tutorial; I looked at several and picked elements from each. The resources I used are listed at the end of this file. -Emily Hamilton, February 2019 """ import sys from sklearn.linear_model import LogisticRegression from sklearn.metrics import confusion_matrix from numpy import newaxis import matplotlib.pyplot as plt import seaborn as sns from Utilities.Spinner import * from Utilities.Newsgroups import * def LR_run(solver, dataset): # Train Logistic Regression-- can test different solvers, but I believe # this classification problem warrants a 'multi_class=multinomial' # setting per: # https://scikit-learn.org/stable/modules/multiclass.html LR = LogisticRegression(solver=solver, multi_class='multinomial') LR.fit(dataset.train.x, dataset.train.y) predicted = LR.predict(dataset.test.x) return LR, predicted if __name__ == "__main__": # Get training and testing data categories = ['alt.atheism', 'soc.religion.christian', 'comp.graphics', 'sci.electronics', 'rec.autos', 'rec.motorcycles', 'rec.sport.baseball', 'rec.sport.hockey'] dataset = Newsgroups(categories) dataset.load() # Run Logistic Regression to get LR model and prediction LR, predicted = spinnerTask(LR_run, 'lbfgs', dataset, message=('Modeling data (this may take a few ' + 'minutes)...')) total_score = LR.score(dataset.test.x, dataset.test.y) print("\nTotal Score:", total_score) # Produce Confusion Matrix c_matrix = confusion_matrix(dataset.test.y, predicted) c_matrix_norm = c_matrix.astype('float') / c_matrix.sum(axis=1)[:, newaxis] fig, ax = plt.subplots(figsize=(10,10)) palette = sns.cubehelix_palette(40, start=1, rot=-.75, dark=.2, light=.95) sns.heatmap(c_matrix_norm, annot=True, xticklabels=dataset.target_names, yticklabels=dataset.target_names, cmap=palette) plt.title('Logistic Regression Confusion Matrix') plt.ylabel('Actual Classification') plt.xlabel('Predicted Classification') plt.show() """ RESOURCES: * https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html * https://scikit-learn.org/stable/tutorial/text_analytics/working_with_text_data.html * https://scikit-learn.org/0.19/datasets/twenty_newsgroups.html * https://www.kaggle.com/c/word2vec-nlp-tutorial#part-1-for-beginners-bag-of-words * http://fastml.com/classifying-text-with-bag-of-words-a-tutorial/ * https://towardsdatascience.com/multi-class-text-classification-with-scikit-learn-12f1e60e0a9f """
fe2e44c4b877dd8b8527b67af51fa7ac962227b4
xaviergoby/Helicopter-Emergency-Medical-Service-HEMS-Drone
/flight_performance.py
4,500
4.125
4
"""This file calculates the following flight performance parameters: Max ascent speed, Max Descent speed, Max horizontal flight speed, Max ascent acceleration, Max Descent acceleration, Max horizontal flight acceleration, Max range, Hovering endurance, Cruising endurance, Wind speed resistance.""" import numpy as np def value_printer(): """prints all values based on inputs in a formatted way"""#todo: add all wanted items print("Max ascent speed = "+ max_ascent_speed() + " m/s") print("Max ascent acceleration = " + ascent_acc() + " m/s^2") print("Max ascent acceleration = " + descent_acc() + " m/s^2") print("Max acceleration = " + acc() + " m/s^2") velocity_vector = np.array([1.0, 2.0, 3.0]) acc_vector = np.array([3.0,0.0,0.0]) attitude_vector = np.array([0.4,0.20,0.10]) thrust_magnitude = 10 thrust_vector = thrust_magnitude*attitude_vector dragcoef = 0.3 drag_vector = -1*velocity_vector *dragcoef dronemass = 10 def add_force(acc_vector, force, mass): return acc_vector+ force/mass print(add_force(acc_vector,thrust_vector,dronemass)) def max_ascent_speed(): #todo: find a relation for max ascent speed print("this is not yet implemented") def max_descent_speed(): #todo: find a relation for max descent speed print("this is not yet implemented") def max_horizontal_speed(): # todo: find a relation for max horizontal speed print("this is not yet implemented") def ascent_acc(thrust, drone_mass, g=9.81, drag = 0.): """ This function uses Newton's second law to generate a maximum ascent acceleration number :param thrust: float in Newton :param drone_mass: float in kg :param g: float specifying gravitational acceleration default value = 9.81 m/s^2 :param drag: float specifying drag in ascent in Newton :return: max ascent acceleration in m/s^2 This should be a positive number """ output = (thrust - drone_mass * g - drag) / drone_mass return output def descent_acc(thrust, drone_mass, g=9.81, drag = 0.): """ This function uses Newton's second law to generate a maximum descent acceleration number :param thrust: float in Newton :param drone_mass: float in kg :param g: float specifying gravitational acceleration default value = 9.81 m/s^2 :param drag: float specifying drag in descent in Newton :return: max descent acceleration in m/s^2 this should be a negative number """ output = (-thrust - drone_mass * g + drag) / drone_mass return output def acc(thrust, attitude_tilt, drone_mass, g=9.81, drag = 0. ): """ 2d situation :param thrust: float in Newton :param attitude_tilt: float in rad :param drone_mass: float in kg :param g: float specifying gravitational acceleration default value = 9.81 m/s^2 :param drag: doesn't even have a direction this calculation is worthless """ weight = drone_mass*g vertical_acc = thrust*np.cos(attitude_tilt)-drag-weight horizontal_acc= thrust*np.sin(attitude_tilt)-drag return vertical_acc,horizontal_acc def max_acc(thrust,drone_mass, g=9.81, drag): #assuming g is positive acc = np.array([0.0,0.0,0.0]) weight = np.array([0.0,0.0,-1*drone_mass*g])#assuming [x,y,z) Z pointing up #add weight thrust and drag to the accelerationacc acc = acc + thrust + weight + drag return acc def powerusage(thrust_needed_to_hover): somerelation=1 powerusage_at_this_thrust = thrust_needed_to_hover*somerelation#TODO: find relation between powerusage and thrust return powerusage_at_this_thrust def endurance_hover(drone_mass, g=9.81, battery_size): weight = drone_mass*g thrust_needed_to_hover = weight powerusage_at_this_thrust = powerusage(thrust_needed_to_hover) endurance = battery_size/powerusage_at_this_thrust return endurance def endurance_cruise(drone_mass, g=9.81, battery_size) weight = drone_mass * g thrust_needed_to_cruise = #TODO: add thrust_needed_to_cruise powerusage_at_this_thrust = powerusage(thrust_needed_to_cruise) endurance = battery_size / powerusage_at_this_thrust return endurance def max_range(cruise_speed, drone_mass, g=9.81, battery_size): """ :param cruise_speed: :param drone_mass: :param g: :param battery_size: :return: """ return cruise_speed*(drone_mass, g=9.81, battery_size) def max_wind_speed_resistance(): # todo: find a relation for max wind speed resistance print("this is not yet implemented")
0c44d8b7fa9c8db3c7cab1467653a7bc37d2a9c0
bevishe/Leetcode
/leetcode/easy/demo1.py
1,092
3.546875
4
class Solution: def countAndSay(self, n: int) -> str: string = '' for i in range(1, n + 1): # 每层返回一个字符串 if i == 1: string += '1' else: len_string = len(string) new_string = '' for j in range(0, len_string): if j + 1 <= len_string - 1 and string[j] == string[j + 1]: new_string = new_string + '2' + string[j] j = j + 2 if j > len_string - 1: break elif j + 1 <= len_string - 1 and string[j] != string[j + 1]: new_string = new_string + '1' + string[j] j += 1 elif j == len_string: string = new_string else: new_string = new_string + '1' + string[j] string = new_string return string if __name__ == '__main__': print(Solution().countAndSay(3))
e073ffc77039e43a6e8819512eb2aa795e289294
waleed-aa/SQL
/db.py
1,551
4
4
import sqlite3 #Connect to sqlite and create sales db file #connection = sqlite3.connect('sales.db') # Cursor object to invoke methods for SQL #cursor = connection.cursor() class Customer: def __init__(self, cust_id=-1, name="", age=-1, gender="", city=""): self.cust_id = cust_id self.name = name self.age = age self.gender = gender self.city = city self.connection = sqlite3.connect('sales.db') self.cursor = self.connection.cursor() def retrieve_customer(self, cust_id): self.cursor.execute(""" SELECT * FROM CUSTOMERS WHERE customer_id = {}""".format(cust_id)) results = self.cursor.fetchone() self.cust_id = cust_id self.name = results[1] self.age = results[2] self.gender = results[3] self.city = results[4] self.connection = sqlite3.connect('sales.db') self.cursor = self.connection.cursor() def add_customer(self): self.cursor.execute(""" INSERT INTO CUSTOMERS VALUES ({}, '{}', {}, '{}', '{}') """.format(self.cust_id, self.name, self.age, self.gender, self.city,)) self.connection.commit() p1 = Customer(5, 'John', 40, 'male', 'Brazil') connection = sqlite3.connect('sales.db') cursor = connection.cursor() p1.add_customer() cursor.execute("SELECT * FROM CUSTOMERS") result_set = cursor.fetchall() print(result_set) connection.close() # Instantiate a person object c1 = Customer() c1.retrieve_customer() print(c1.age)
672920d6ef0503145714305b35b3d3687b1268c3
Horn1998/LeetCode
/树/144.二叉树的前序遍历(树,栈).py
664
3.859375
4
#参考答案 time 87 room 5.34 # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def preorderTraversal(self, root): if root == None: return [] stack, ans = [root, ], [] while stack != []: pre_node = stack.pop() ans.append(pre_node.val) if pre_node != None: if pre_node.right != None: stack.append(pre_node.right) if pre_node.left != None: stack.append(pre_node.left) return ans
5c99a4dea2cea6cc872657deff79c22a42b2321a
alu0100757507/prct06
/src/ aproximacionpi.py
337
3.6875
4
#!/usr/bin/python import sys def aproximacion(n): suma=0.0 for i in range(1,n+1): x_i=(i-1.0/2)/float(n) fx_i=4.0/(1+x_i**2) suma=suma + fx_i pi=(1.0/float(n))*suma return pi n=int(sys.argv[1]) veces = int(sys.argv[2]) for repetir in range(1,veces+1) print'El valor de pi es:pi=%1.35f' % aproximacion(n)
0bd4b19898f239e8374cb3f6e28c3eb1c6134466
mrjamrd/diplopython
/cap10/practica.py
522
3.90625
4
import sqlite3 conexion = sqlite3.connect("persona") cursor = conexion.cursor() cursor.execute("""CREATE TABLE IF NOT EXISTS personas( id_persona INTEGER PRIMARY KEY AUTOINCREMENT, nombre varchar(255), apellido varchar(255), edad varchar(255) ) """) conexion.commit() cursor.execute("INSERT INTO personas VALUES(null,'Jose','Baez','26')") conexion.commit() cursor.execute("SELECT * FROM personas where apellido='matias' ") personas = cursor.fetchall() for persona in personas: print(persona) conexion.close()
f94e27071f3211ce7928b6c5c203c28d4ea3e9be
Dmitrygold70/rted-myPythonWork
/Day07/execption_examples/ab_menu/ab_menu_with8.py
1,567
3.8125
4
FILENAME = "data.txt" a = b = 0 while True: print(""" A = {}; B = {} Set (A) Set (B) (S)ave (L)oad (Q)uit """.format(a, b)) option = input("enter option:").lower() if option == 'a': try: a = int(input("enter a new value for A:")) except ValueError: print("error: not an int!") elif option == 'b': try: b = int(input("enter a new value for B:")) except ValueError: print("error: not an int!") elif option == 's': f = None try: f = open(FILENAME, 'w') f.write("{}\n{}".format(a, b)) except FileNotFoundError: print("cannot find the file:", FILENAME) except PermissionError: print("cannot write to:", FILENAME) else: print("data saved successfully to: " + FILENAME) finally: if f is not None: f.close() elif option == 'l': try: with open(FILENAME) as f: a = int(f.readline()) b = int(f.readline()) except FileNotFoundError: print("cannot find the file:", FILENAME) except PermissionError: print("cannot write to:", FILENAME) except ValueError: print(FILENAME, "is corrupted (does not contain two lines of ints)") else: print("data loaded successfully from: " + FILENAME) elif option == 'q': break else: print("error: invalid option")
ee33b62f4ef3e6784c0aa32be6050caa9281e220
shivamkc01/MachineLearning_Algorithm__from_scratch
/Decision_Tree_scratch.py
6,062
3.53125
4
""" Decision Tree implentation from scratch This code you can use for learning purpose. programmed by Shivam Chhetry ** 11-08-2021 """ import numpy as np from collections import Counter from sklearn import datasets from sklearn.model_selection import train_test_split """ Calculating Entropy -> Entropy measure of purity in a node. Range[0,1] 0 - Best purity 1 - worst purity formula:- H(s) = -p(+)log(p+) - p(-)log(p(-)) p+ = % of +ve class p- = % of -ve class p(X) = #x/n where, #x is no of occurrences n is no of total samples E = - np.sum([p(X).log2(p(X))]) """ def entropy(y): hist = np.bincount(y) # this will calculate the number of occurrences of all class labels ps = hist / len(y) return -np.sum([p * np.log2(p) for p in ps if p > 0]) """ Let's create a helper class to store the information for our node. we want to store 1. The best split feature(feature) 2. The best split threshold 3. The left and the right child trees 4. If we are at a leaf node we also want to store the actual value , the most common class label """ class Node: def __init__( self, feature=None, threshold=None, left=None, right=None, *, value=None ): self.feature = feature self.threshold = threshold self.left = left self.right = right self.value = value """ Now we create a helper function to determine if we are at a leaf node """ def is_leaf_node(self): return self.value is not None class DecisionTree: # applying some stopping criteria to stop growing # e.g: maximum depth, minimum samples at node, no more class distribution in node def __init__(self, min_samples_split=2, max_depth=100, n_feats=None): self.min_samples_split = min_samples_split self.max_depth = max_depth self.n_feats = n_feats self.root = None def fit(self, X, y): self.n_feats = X.shape[1] if not self.n_feats else min(self.n_feats, X.shape[1]) self.root = self._grow_tree(X, y) def _grow_tree(self, X, y, depth=0): n_samples, n_features = X.shape n_labels = len(np.unique(y)) # Applying stopping criteria if ( depth >= self.max_depth or n_labels == 1 or n_samples < self.min_samples_split ): leaf_value = self._most_common_label(y) return Node(value= leaf_value) # If we didn't need stopping criteria then we select the feature indices feat_idxs = np.random.choice(n_features, self.n_feats, replace=False) # greedy search : Loop over all features and over all thresholds(all possible feature values. best_feat, best_thresh = self._best_criteria(X, y, feat_idxs) # grow the children that result from the split left_idxs, right_idxs = self._split(X[:, best_feat], best_thresh) left = self._grow_tree(X[left_idxs, :], y[left_idxs], depth + 1) right = self._grow_tree(X[right_idxs, :], y[right_idxs], depth + 1) return Node(best_feat, best_thresh, left, right) def _best_criteria(self, X, y, feat_idxs): best_gain = -1 split_idx, split_thresh = None, None for feat_idx in feat_idxs: X_column = X[:, feat_idx] thresholds = np.unique(X_column) for threshold in thresholds: gain = self._information_gain(y, X_column, threshold) if gain > best_gain: best_gain = gain split_idx = feat_idx split_thresh = threshold return split_idx, split_thresh def _information_gain(self, y, X_column, split_thersh): """ IG = E(parent) - [weighted average].E(childern) Example: S = [0,0,0,0,0,1,1,1,1,1], S1=[0,0,1,1,1,1,1], S2=[0,0,0] IG = E(S0) -[(7/10)*E(S1)+(3/10)*E(S2)] IG = 1 - [(7/10)*0.863+(3/10)*0] = 0.395 Note: The higher the information gain that specific way of spliting decision tree will be taken up. """ # parent E parent_entropy = entropy(y) # generate split left_idxs, right_idxs = self._split(X_column, split_thersh) if len(left_idxs) == 0 or len(right_idxs) == 0: return 0 # weighted avg child E n = len(y) n_left_samples, n_right_samples = len(left_idxs), len(right_idxs) entropy_left, entropy_right = entropy(y[left_idxs]), entropy(y[right_idxs]) child_entropy = (n_left_samples/n) * entropy_left + (n_right_samples/n) * entropy_right # return IG ig = parent_entropy - child_entropy return ig def _split(self, X_column, split_thersh): left_idxs = np.argwhere(X_column <= split_thersh).flatten() right_idxs = np.argwhere(X_column > split_thersh).flatten() return left_idxs, right_idxs def predict(self,X): # traverse tree return np.array([self._traverse_tree(x, self.root) for x in X]) def _traverse_tree(self, x, node): if node.is_leaf_node(): return node.value if x[node.feature] <= node.threshold: return self._traverse_tree(x, node.left) return self._traverse_tree(x, node.right) def _most_common_label(self, y): # counter will calculate all the no of occurrences of y counter = Counter(y) most_common = counter.most_common(1)[0][0] # returns tuples, and we want only value so we again say index 0 [0] return most_common if __name__ == '__main__': data = datasets.load_breast_cancer() X = data.data y = data.target X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=1234 ) clf = DecisionTree(max_depth=10) clf.fit(X_train, y_train) def accuracy(y_true, y_pred): acu = np.sum(y_true == y_pred)/len(y_pred) return acu y_pred = clf.predict(X_test) acc = accuracy(y_test, y_pred) print("Accuracy : ", acc)
62dcc3715eeda8479f378e7b984c82932c852f53
zubairwazir/code_problems
/classical_algorithms/python/kadanes_algorithm.py
724
4.25
4
''' Kadane's Algorithm is a standard technique used majorly for problems like: Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. ''' def kadanes_algorithm(nums): max_ending_here = 0 max_so_far = float('-inf') for i in range(len(nums)): max_ending_here = max_ending_here+nums[i] max_so_far = max(max_so_far, max_ending_here) if max_ending_here < 0: max_ending_here = 0 return max_so_far nums = [-2,1,-3,4,-1,2,1,-5,4] print(kadanes_algorithm(nums)) # Output= 6 nums = [-1] print(kadanes_algorithm(nums)) #output= -1
c6473ab50e311b26b10d9a8591a8fa2581677eb6
gutierrezalexander111/PycharmProjects
/homework/Agutierrez_homework_3_09_27.py
1,611
3.984375
4
VOWELS = 'aeiou' def AskUserForSentence(): while True: word_list = raw_input('Please enter exactly 3 words followed by a space or type to quit to exit' "\n") if not word_list: continue elif word_list == 'quit': exit() word_list4 = LowercaseSentence(word_list) word_list2 = SplitSentenceIntoList(word_list4) word_list3 = ConvertStringSequenceToListType(word_list2) if len(word_list3) != 3: print "wtf try again" else: len(word_list) == 3 ConvertWordToPigLatin(word_list3) continue def LowercaseSentence(words): words = words.lower() return words def SplitSentenceIntoList(words): words = words.split(" ") return words def ConvertStringSequenceToListType(word_list): word_list2 = list(word_list) return word_list2 def ConvertWordToPigLatin(word_list): word_list = ConvertStringSequenceToListType(word_list) for word in word_list: if word[0] in VOWELS: word += "hay" PrintThreeWordPhrase(word) else: for word in word_list: if word[0] not in VOWELS: AppendLetter(word) PrintThreeWordPhrase(AppendLetter(word)) return word def IsVowel(word): if word[0] in 'aeiou': return word def RemoveFirstLetter(word): word = word.strip(word[0]) return word def AppendLetter(word): word += word[0] + "ay" word = RemoveFirstLetter(word) return word def PrintThreeWordPhrase(phrase): print(phrase), AskUserForSentence()
91eac07c8f414968f39a2a1788b4588f675eb563
ebertn/Neural-Network-Color-Picker
/python/neuralnetwork.py
4,326
4.125
4
import numpy as np from scipy.optimize import minimize import math class NeuralNetwork: # Format is the number of units in each layer, ex: (5, 5, 3) for 3 layer NN # with 5 inputs, 5 units in hidden layer, and 3 outputs def __init__(self, format, X, y): self.format = format self.X = X self.y = y # No. training examples self.m = np.size(X, 0) # Includes input/output self.num_layers = len(format) self.lambda_const = 1 # Initiate Theta to random weights self.Theta = self.__genRandWeights() vec = self.__unrollTheta() print(self.costFunc(vec)) @classmethod def fromCsv(self, format, fileName): """ Construct a neural network using data from a csv file, as opposed to passing data directly. Doesn't work currently, only works for color_picker dataset Args: format: Network layer architecture. Same as __init__ fileName: File location of the data and labels, where the data is the first n (number of inputs) columns, and the labels is the last column of the csv matrix Returns: A NeuralNetwork object with the data and labels from the csv """ reader = np.loadtxt(open(fileName, "rb"), delimiter=",", skiprows=1) data_and_labels = np.matrix( list(reader) ) (m, n) = data_and_labels.shape data_range = list(range(0, n - 1)) data = np.matrix( data_and_labels[:, data_range] ).astype('float') labels = np.matrix( data_and_labels[:, n - 1] ).astype('intc') labelsMatrix = np.zeros((m, format[-1]), dtype=int) for i in range(0, m): labelsMatrix[i, labels[i]] = 1 return NeuralNetwork(format, data, labelsMatrix) def train(self): unrolled_theta = self.__unrollTheta() res = minimize(rosen, unrolled_theta, tol=1e-6) def __genRandWeights(self): randTheta = [] # For each matrix of weights for i in range(self.num_layers - 1): # Range of random values [-ep_init, ep_init] ep_init = math.sqrt(6) / math.sqrt(self.format[i] + self.format[i + 1]) randTheta.append(np.random.rand(self.format[i + 1], self.format[i] + 1)) randTheta[-1] = np.asmatrix(randTheta[-1] * 2 * ep_init - ep_init) return randTheta def __unrollTheta(self): unrolled_theta = np.array([]) for mat in self.Theta: unrolled_theta = np.append(unrolled_theta, mat.ravel()) return unrolled_theta def __reshapeTheta(self, vec): reshaped_theta = [] start_pos = 0 for mat in self.Theta: end_pos = start_pos + mat.size elements = vec[start_pos:end_pos] reshaped = np.reshape(elements, mat.shape) reshaped_theta.append(reshaped) start_pos = end_pos return reshaped_theta @staticmethod def sigmoid(x): return 1 / (1+ np.exp(-x)) def costFunc(self, Theta): Theta = self.__reshapeTheta(Theta) m = self.m J = 0 # Forward Propagation a = [] a.append(np.concatenate((np.ones((m, 1)), self.X), axis=1)) z = [] for i in range(self.num_layers - 1): next_z = a[i] * Theta[i].T z.append(next_z) if(i == self.num_layers - 2): next_a = self.sigmoid(z[i]) else: ones_array = np.ones((np.size(z[i], 0), 1)) next_a = np.concatenate((ones_array, self.sigmoid(z[i])), axis=1) a.append(next_a) # Hypothesis hx = a[-1] # Unregularized cost J = np.multiply(-self.y, np.log(hx) - np.multiply(1 - self.y, np.log(1 - hx))) J = (1/m) * J.sum() # Regularization term reg = 0 for mat in Theta: reg = reg + np.power(mat[:, 1:mat.shape[1]], 2).sum() reg = (self.lambda_const / (2 * m)) * reg J = J + reg return J
f81941c7510ca1c3d2fae55b7e738ca7a4b25e1f
kate-whalen/fibonacci
/tests/test_app.py
533
3.78125
4
import unittest from app.app import fibonacci class TestApp(unittest.TestCase): def test_fibonacci(self): reader = fibonacci() self.assertEqual(next(reader), 0), "Should be 0" self.assertEqual(next(reader), 1), "Should be 1" self.assertEqual(next(reader), 1), "Should be 1" self.assertEqual(next(reader), 2), "Should be 2" self.assertEqual(next(reader), 3), "Should be 3" self.assertEqual(next(reader), 5), "Should be 5" if __name__ == '__main__': unittest.main()
13423657952cfb9ed72e0de81e56b392157c0d25
Oleg-Lo/Home_tasks
/Урок 4. Практическое задание/task_3.py
991
4.34375
4
""" Задание 3. Приведен код, формирующий из введенного числа обратное по порядку входящих в него цифр и вывести на экран. Сделайте профилировку каждого алгоритма через cProfile и через timeit Сделайте вывод, какая из трех реализаций эффективнее и почему """ def revers(enter_num, revers_num=0): if enter_num == 0: return else: num = enter_num % 10 revers_num = (revers_num + num / 10) * 10 enter_num //= 10 revers(enter_num, revers_num) def revers_2(enter_num, revers_num=0): while enter_num != 0: num = enter_num % 10 revers_num = (revers_num + num / 10) * 10 enter_num //= 10 return revers_num def revers_3(enter_num): enter_num = str(enter_num) revers_num = enter_num[::-1] return revers_num
6598a77630a3f5b1062aa4984631d35524047d2c
mike10004/adventofcode2017
/advent04/count_valid_passphrases.py
1,410
4.0625
4
#!/usr/bin/env python3 import re import sys def to_multiset(token): """ Creates a multiset from a string. A multiset is a set of tuples (c, n) where c is a character and n is a count of that character in the string.""" counts = {} for ch in token: try: count = counts[ch] except KeyError: count = 0 counts[ch] = count + 1 multiset = set() for ch in counts: multiset.add((ch, counts[ch])) return frozenset(multiset) def parse_tokens(passphrase): return re.split(r'\s+', passphrase.strip()) def is_tokens_not_anagrams(passphrase): tokens = parse_tokens(passphrase) multisets = [to_multiset(token) for token in tokens] return len(multisets) == len(set(multisets)) def is_tokens_unique(passphrase): tokens = parse_tokens(passphrase) return len(tokens) == len(set(tokens)) def main(): tokens_unique_count = 0 tokens_not_anagrams_count = 0 total = 0 for passphrase in sys.stdin: tokens_unique_count += 1 if is_tokens_unique(passphrase) else 0 tokens_not_anagrams_count += 1 if is_tokens_not_anagrams(passphrase) else 0 total += 1 print("{} of {} passphrases have unique tokens".format(tokens_unique_count, total)) print("{} of {} passphrases have anagram-unique tokens".format(tokens_not_anagrams_count, total)) if __name__ == '__main__': exit(main())
cf35247077964ded1a604d3b2c4de53c120ba3eb
binh748/queer-asian-stories
/src/web_scraping.py
7,412
3.734375
4
"""This module contains functions to scrape gaysiandiaries.com and https://gaysianthirdspace.tumblr.com/.""" # Need to go back and clean this code so I'm not creating a soup every time. # I should just pass soup into the function. from bs4 import BeautifulSoup import requests def create_soup(url): """Creates a BeautifulSoup object for a URL.""" response_text = requests.get(url).text soup = BeautifulSoup(response_text, 'html5lib') return soup def create_soups(urls): """Creates a list of BeautifulSoup objects for a list of URLs.""" soups = [] for url in urls: soup = create_soup(url) soups.append(soup) return soups def gd_get_num_pages(base_url): """Returns the number of Gaysian Diary pages. A page can contain multiple blog posts.""" soup = create_soup(base_url) return int(soup.find_all('a', class_='jump_page')[-1].text) def gd_get_page_urls(base_url): """Returns a list of URLs for each page in the Gaysian Diaries. A page can contain multiple blog posts. Args: base_url: Gaysian Diaries home page URL. """ page_urls = [base_url] num_pages = gd_get_num_pages(base_url) for i in range(2, num_pages+1): page_urls.append(f'{base_url}page/{i}') return page_urls def gd_get_blog_urls(base_url): """Returns a list of URLs for each blog post in the Gaysian Diaries. Args: base_url: Gaysian Diaries home page URL. """ page_urls = gd_get_page_urls(base_url) blog_urls = [] for url in page_urls: soup = create_soup(url) for element in soup.find_all(class_='post_title'): blog_urls.append(element.findNext().get('href')) return blog_urls def gd_get_blog_title(blog_url): """Returns the title of the Gaysian Diaries blog post.""" soup = create_soup(blog_url) return soup.find(class_='post_title').text def gd_get_blog_date(blog_url): """Returns the publishing date of the Gaysian Diaries blog post.""" soup = create_soup(blog_url) return soup.find(class_='post_date').text def gd_get_blog_text(blog_url): """Returns the text of the Gaysian Diaries blog post.""" paragraphs = [] soup = create_soup(blog_url) # Start for loop at index 1 since # first paragrahph is a generic content warning. for element in soup.find_all('p')[1:]: paragraphs.append(element.text) text = '\n\n'.join(paragraphs) # Adding two line breaks for readability return text def gd_get_blog_num_notes(blog_url): """Returns the number of tumblr notes for the Gaysian Diaries blog post. To learn more about tumblr notes, visit: https://tumblr.zendesk.com/hc/en-us/articles/231855888-Notes.""" soup = create_soup(blog_url) if soup.find(class_='notes'): num_notes = len(soup.find(class_='notes').find_all('li')) return num_notes return 0 def gd_get_blog_dicts(base_url): """Returns a list of dicts of key information for each Gaysian Diaries blog post. Args: base_url: Gaysian Diaries home page URL. """ blog_urls = gd_get_blog_urls(base_url) blog_dicts = [ {'title': gd_get_blog_title(blog_url), 'date': gd_get_blog_date(blog_url), 'num_notes': gd_get_blog_num_notes(blog_url), # Will get filled in when combining with Google Analytics data 'unique_pageviews': None, 'url': blog_url, 'text': gd_get_blog_text(blog_url)} for blog_url in blog_urls ] return blog_dicts def g3s_get_tag_page_url(base_url): """Returns list of Gaysian Third Space tag page URLs. A tag page is a page belonging to a specific tag such as body image, career, coming out, etc. The tags are listed on the post directory page: https://gaysianthirdspace.tumblr.com/tags. Args: base_url: Gaysian Third Space post directory page. """ soup = create_soup(base_url) tag_pages = [] for element in soup.find('div', class_='body-text').find_all('a'): tag_pages.append(element.get('href')) return tag_pages def g3s_get_num_tag_pages(url): """Returns the number of tag pages in the Gaysian Third Space. A tag page is a page belonging to a specific tag such as body image, career, coming out, etc. The tags are listed on the post directory page: https://gaysianthirdspace.tumblr.com/tags.""" soup = create_soup(url) if soup.find(class_='next'): return int(soup.find(class_='next').get('data-total-pages')) return 1 def g3s_get_blog_urls(urls): """Returns list of URLs for all Gaysian Third Space blog posts. Args: urls: Gaysian Third Space tag page urls. """ blog_urls = [] for url in urls: urls_to_scrape = [url] num_pages = g3s_get_num_tag_pages(url) if num_pages > 1: for i in range(2, num_pages+1): urls_to_scrape.append(f'{url}/page/{i}') soups = create_soups(urls_to_scrape) for soup in soups: for element in soup.find_all(class_='meta-item post-notes'): blog_urls.append(element.get('href').replace('#notes', '')) # Using set to return all unique blog_urls since some may be repeating due # to having mutliple tags featured in Post Directory page return list(set(blog_urls)) def g3s_get_blog_title(blog_url): """Returns the title of the Gaysian Third Space blog post.""" soup = create_soup(blog_url) if soup.find(class_='title'): return soup.find(class_='title').text if soup.find(class_='link-title'): return soup.find(class_='link-title').text return None def g3s_get_blog_date(blog_url): """Returns the publishing date of the Gaysian Third Space blog post.""" soup = create_soup(blog_url) return soup.find(class_='meta-item post-date').text def g3s_get_blog_text(blog_url): """Returns the text of the Gaysian Third Space blog post.""" paragraphs = [] soup = create_soup(blog_url) for element in soup.find_all('p'): paragraphs.append(element.text) text = '\n\n'.join(paragraphs) # Adding two line breaks for readability return text def g3s_get_blog_num_notes(blog_url): """Returns the number of tumblr notes for the Gaysian Third Space blog post. To learn more about tumblr notes, visit: https://tumblr.zendesk.com/hc/en-us/articles/231855888-Notes.""" soup = create_soup(blog_url) if soup.find(class_='meta-item post-notes'): num_notes = int(soup.find(class_='meta-item post-notes') \ .text.split()[0].replace(',', '')) return num_notes return 0 def g3s_get_blog_dicts(blog_urls): """Returns list of dicts of key information for each Gaysian Third Space blog post. Args: blog_urls: List of URLs for all Gaysian Third Space blog posts. """ counter = 0 blog_dicts = [] for blog_url in blog_urls: blog_dicts.append( {'title': g3s_get_blog_title(blog_url), 'date': g3s_get_blog_date(blog_url), 'num_notes': g3s_get_blog_num_notes(blog_url), # Will get filled in when combining with Google Analytics data 'unique_pageviews': None, 'url': blog_url, 'text': g3s_get_blog_text(blog_url)}) counter += 1 print(counter) return blog_dicts
910f11ecb2eb361038bbcff8e72b1646b30c0c02
Princeshaw/Algorithmic-problems-with-python
/leetCode Solutions/98 Validate Binary Search Tree.py
752
3.828125
4
# url : https://leetcode.com/problems/validate-binary-search-tree/ # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isValidBST(self, root: TreeNode) -> bool: return self.validation(root, float("-inf"), float("+inf")) def validation(self, root, minVal, maxVal): if root is None: return True if root.val <= minVal or root.val >= maxVal: return False validateLeft = self.validation(root.left, minVal, root.val) validateRight = self.validation(root.right, root.val, maxVal) return validateLeft and validateRight
78c7ea3ad609b9ba0ddf901063d9d52a0cdde1eb
kittykatcode/Tkinter_projects
/ProjectFiles/buttons.py
325
4.0625
4
from tkinter import * root = Tk() def myclick(): mylable = Label(root, text="i clicked a button", fg='green').pack() mybutton = Button(root, text='Click me', command=myclick , fg='black', bg='red') #SHORTER WAY OF RIITING SAME THING #mybutton = Button(root, text='Click me').pack() mybutton.pack() root.mainloop()
25ba0293602d3424dd1ea12a7c7c4a3ed38438cb
Manoj431/Python
/Basics/Solution_1.1.py
295
3.796875
4
#Defining a Class, Object, Method and its Signature class Solution: def area(self,side): calc = side**2 print(f"The area of a square field is {calc} sq.metre") sol = Solution() #Object creation of class Solution sol.area(8) #Calling the method through object
a8aff1bbde01deb84541dd3cd6ba3d0e59a882be
Arnav235/ESC180
/lab8/main.py
2,172
3.515625
4
import numpy as np def print_matrix(m_lol): for i in range(len(m_lol)): print(m_lol[i]) def get_lead_ind(row): for i in range(len(row)): if row[i] != 0: return i return len(row) def get_row_to_swap(M, start_i): left_most_0 = len(M) -1 left_most_idx = start_i for i in range(start_i, len(M)): for j in range(len(M[i])): if j >= left_most_0: break if M[i][j] != 0: left_most_0 = j left_most_idx = i return left_most_idx def add_rows_coefs(r1, c1, r2, c2): np_r1 = np.array(r1) np_r2 = np.array(r2) return (c1*np_r1 + c2*np_r2).tolist() def eliminate(M, row_to_sub, best_lead_ind): for i in range(row_to_sub +1, len(M)): coef = M[i][best_lead_ind] / M[row_to_sub][best_lead_ind] M[i] = add_rows_coefs(M[i], 1, M[row_to_sub], -coef) def forward_step(M): for i in range(len(M)): print("The matrix is currently:") print_matrix(M) print("Now looking at row {}".format(i)) swap_row = get_row_to_swap(M, i) swap_lead_ind = get_lead_ind(M[swap_row]) print("Swapping rows {} and {} so that the entry {} in the current row is non-zero".format(i, swap_row, swap_lead_ind)) M[i], M[swap_row] = M[swap_row], M[i] print("Adding row {} to rows below it to eliminate coefficients in column {}".format(swap_lead_ind, swap_lead_ind)) eliminate(M, i, swap_lead_ind) def backward_step(M): print("Backward Step----------------") for i in range(len(M) -1, 0, -1): lead_ind = get_lead_ind(M[i]) print("Adding row {} to rows above it to eliminate coefficients in column {}".format(i, lead_ind)) M.reverse() eliminate(M, len(M) - 1 -i, lead_ind) M.reverse() print("The matrix is currently:") print_matrix(M) print("Now dividing each row by the leading coefficient") for i in range(len(M)): lead_num = M[i][ get_lead_ind(M[i]) ] M[i] = (np.array(M[i]) / lead_num).tolist() print("The matrix is currently:") print_matrix(M) def solve(M, b): for i in range(len(M)): M[i].append(b[i]) forward_step(M) backward_step(M) np_arr = np.array(M) return np_arr[:, -1].tolist() M = [[ 1, -2, 3], [3, 10, 1], [ 1, 5, 3]] x = [1, 20, 3] print(solve(M, np.matmul(np.array(M), np.array(x) )))
fdd88ac43cd14c21c4ee0c78a8625aea38e6d274
jianyu-m/plato
/plato/algorithms/base.py
836
3.9375
4
""" Base class for algorithms. """ from abc import ABC, abstractmethod from plato.trainers.base import Trainer class Algorithm(ABC): """Base class for all the algorithms.""" def __init__(self, trainer: Trainer, client_id=None): """Initializing the algorithm with the provided model and trainer. Arguments: trainer: The trainer for the model, which is a trainers.base.Trainer class. model: The model to train. """ super().__init__() self.trainer = trainer self.model = trainer.model self.client_id = client_id @abstractmethod def extract_weights(self): """Extract weights from a model passed in as a parameter.""" @abstractmethod def load_weights(self, weights): """Load the model weights passed in as a parameter."""
4ca7cdf873629be20298399a03ddc3bc56b4b704
mathvolcano/leetcode
/0429_levelOrder.py
638
3.5625
4
""" 429. N-ary Tree Level Order Traversal https://leetcode.com/problems/n-ary-tree-level-order-traversal/ """ """ # Definition for a Node. class Node: def __init__(self, val=None, children=None): self.val = val self.children = children """ class Solution: def levelOrder(self, root: 'Node') -> List[List[int]]: if not root: return None traversal = [[root.val]] lvl = root.children while lvl: traversal += [[c.val for c in lvl]] nxt_lvl = [] for c in lvl: nxt_lvl += c.children lvl = nxt_lvl return traversal
6bc804cc9cadc5e44fab604a09ff2dd2b4cd80d6
wawdh01/Shell-Scripting
/prog3.py
135
4.21875
4
n = int(input("Enter a Number:")) if (n % 2 == 0): print("The given number is EVEN") else: print("The given number is ODD")
49a8697d8f43c031ea5b5ae11e756b612a75df42
Predator111111/store1
/多线程_抢面包.py
1,360
3.828125
4
from threading import Thread import time bread = 0 #面包 money = 10000 class MakeBread(Thread): def run(self) -> None: global bread,money while True: if bread <500 and money>0: time.sleep(0.5) bread += 1 print("做了",bread,"个面包") elif bread>=500 and money>0: time.sleep(3) elif money<=0: break class TakeBread(Thread): username = "" count = 0 def run(self) -> None: global bread,money while True: if bread>0: bread -= 1 self.count +=1 money -= 5 print(self.username, "抢了", self.count, "花了", 2 * self.count) if money <= 0: print("没钱了") break elif bread<=0: time.sleep(1) c1 = MakeBread() c2 = MakeBread() c3 = MakeBread() g1 = TakeBread() g2 = TakeBread() g3 = TakeBread() g4 = TakeBread() g5 = TakeBread() g6 = TakeBread() g1.username = "hehe" g2.username = "wqwq" g3.username = "rtrt" g4.username = "ffgg" g5.username = "vbvb" g6.username = "popo" c1.start() c2.start() c3.start() g1.start() g2.start() g3.start() g4.start() g5.start() g6.start()
7fb5b25047718b5c7850a31069bb6e04342167eb
AK-1121/code_extraction
/python/python_17942.py
145
3.8125
4
# Compare values of keys in Python list with multiple dictionaries for dd in List1: if dd["a"] &gt; 1.3 * dd["b"]: print dd["value"]
e72daa9cae0a8a785c7560b49fa653911dfe5a19
seattlechem/Python2
/Week5/MathDojo.py
797
3.671875
4
class MathDojo(object): def __init__(self): self.total = 0 def add(self, *args): for arg in args: if type(arg) == list or type(arg) == tuple: for i in arg: self.total += i else: self.total += arg return self def subtract(self, *args): for arg in args: if type(arg) == list or type(arg) == tuple: for i in arg: self.total -= i else: self.total -= arg return self def result(self): print self.total return self md = MathDojo() md.add(2).add(2,5).subtract(3,2).result() md.add([3, 5, 7, 8], [2, 4.3, 1.25]).subtract(2, [2, 3], [1.1, 2.3]).result()
929e1aab0104f454a9340e681cc8affaf047b412
Explorerqxy/review_practice
/001.py
716
3.78125
4
#数组中重复的数字 def duplicate(numbers, length): if numbers == None or length <= 0: return False for i in range(length): if numbers[i] < 0 or numbers[i] > length -1: return False res = [] for i in range(length): while numbers[i] != i: if numbers[i] == numbers[numbers[i]]: res.append(numbers[i]) return res #swap numbers[i] and numbers[numbers[i]] numbers[i], numbers[numbers[i]] = numbers[numbers[i]], numbers[i] return False #代码中尽管有一个两重循环,但每个数字最多只要交换两次就可以找到属于它的位置,因此总的时间复杂度是O(n)
ad1cd419424da71ce78d01dd3d990aab1ea92b0d
hmchen47/Programming
/Python/MIT-CompThinking/MIT6.00SC/quizs/quiz1/q2.py
211
3.828125
4
#!/usr/bin/python # _*_ coding: utf-8 _*_ # Quiz 1 2011 - Q2 # # What does the following code print? T = (0.1, 0.1) x = 0.0 for i in range(len(T)): for j in T: x += i + j print x print i
f11d9eedd3036ee28ceb0065e3ad8a9f2f2e2300
RadkaValkova/SoftUni-Web-Developer
/Programming Basics Python/Exam Problems 20042019/Easter Bake.py
602
3.6875
4
import math cakes_number = int(input()) total_sugar = 0 total_flour = 0 max_sugar = -100000000 max_flour = -100000000 for i in range(1, cakes_number + 1): sugar = int(input()) flour = int(input()) if sugar > max_sugar: max_sugar = sugar if flour > max_flour: max_flour = flour total_sugar += sugar total_flour += flour package_sugar = math.ceil(total_sugar / 950) package_flour = math.ceil(total_flour / 750) print(f'Sugar: {package_sugar}') print(f'Flour: {package_flour}') print(f'Max used flour is {max_flour} grams, max used sugar is {max_sugar} grams.')
5c60113a4638b37853590d42046bd551f0f322d5
igorvalamiel/material-python
/Exercícios - Mundo 2/042.py
607
4.0625
4
print('Digite o valor dos três lados de um triângulo.') x = float(input('Primeira medida:')) y = float(input('Segunda medida:')) z = float(input('Terceira medida:')) a = x + y b = x + z c = y + z if a >= z and b >= y and c >= x: if x == y == z: print('Você poderá construir um triângulo equilátero.') elif x == y != z or x == z != y or y == z != x: print('Você poderá construir um triângulo isóceles.') elif x != y != z != x: print('você poderá construir um triangulo escaleno.') else: print('Com essas medidas não é possível montar um triângulo.')
229ae899b0038d651e8771869a9d87cf209456bd
TrangDuLam/Numerical-Analysis
/midtern02/Q6.py
351
3.890625
4
#!/usr/bin/env python3 # Q6, 106061121, 莊裕嵐 # solving nonlinear equation # Please solve the following equation: # # exp(x) + log(x) = 0.9 # import numpy as np from ee4070 import * def function(x) : return np.exp(x) + np.log(x) - 0.9 def main() : x0 = 1 zero = Newton_root(x0, function, epsilon = 10 ** -9 ) print(zero) main()
cfa695f34c280123c50a58520e48c2f906d764c3
BrayanKellyBalbuena/Programacion-I-ITLA-
/Fundamento Programacion/Tarea 4 desiciones/48.py
675
3.84375
4
def cont(): m = input("Digite S para continuar o N para salir\n") if m == "S": cal() elif m == "N": print("Goog bye") else: print(" !Error !Debe ser S o N\n") cont() def cal(): try: num = int(input("Digite un numero entero\n")) if num == 0: print ("Numero no valido\n") cal() except (ValueError): print("!Error! Deben ser un numero entero \n") cal() if num < 100: x = 0 pri = 1 while pri <= num: if num % pri == 0: x += 1 pri += 1 else: print(num,"no es menor que 100 por lo tanto no se puede proceder") cal()
a0b8af0da4bfed01008a2675af76192eb19a32c3
am8265/BioinformaticsAlgorithms
/Course1/FrequentWords.py
1,046
4.09375
4
#!/usr/bin/env python #####Frequent Words Problem######### import re import sys from PatternCount import PatternCount# A module that has a function that computes count of pattern in a given Text def FrequentWords(text,k): count=[]#a list to store the pattern count for each kmers freq_patterns=[]#stores Most frequent kmer patterns for i in xrange(len(text)-k+1): pattern=text[i:i+k] count.append(PatternCount(text,pattern)) maxCount=sorted(count)[-1]#maximum VALUE of occurence of a kmer pattern in Text for i in xrange(len(text)-k+1): if count[i]==maxCount: freq_patterns.append(text[i:i+k])#There would be many duplicates freq_patterns=list(set(freq_patterns))#removing all duplicates by using set function and converting it back to list return freq_patterns #text='' k=int(raw_input("Enter k for kmer:")) #fh=open(sys.argv[1],'r') #for line in fh: # line=line.rstrip().strip('') # text=text+line print FrequentWords('TAAACGTGAGAGAAACGTGCTGATTACACTTGTTCGTGTGGTAT',k)
acd6a391bfd54f419aa667eefbb1a028ea39bef0
Rock-it-science/capstone-individual-exercise
/sortArray.py
497
4.0625
4
def sortArray(int_arr): # Super quick bubble sort implementation isSorted = False while not isSorted: isSorted = True # Changes to false if we have to swap; if we don't swap that's a clean pass and we can break for i in range(0, len(int_arr) - 1): if int_arr[i] > int_arr[i+1]: # Need to swap isSorted = False temp = int_arr[i] int_arr[i] = int_arr[i+1] int_arr[i+1] = temp return int_arr
945d70868ce14d6726bdfbc2d14ec98eca8e4b7a
KadeWilliams/us_states_map_game
/main.py
1,078
3.703125
4
import turtle import pandas as pd screen = turtle.Screen() screen.title("U.S. States Game") image = 'blank_states_img.gif' screen.addshape(image) turtle.shape(image) count = 0 df = pd.read_csv('50_states.csv') states = df.state.to_list() correct_answers = [] while len(correct_answers) < 50: answer_state = screen.textinput(title=f'{len(correct_answers)}/50 States Correct', prompt="What's a state's name?").title() if answer_state == 'Exit': missing_states = [state for state in states if state not in correct_answers] states_to_learn = pd.DataFrame(missing_states) states_to_learn.to_csv('states_to_learn.csv') break if answer_state not in states: continue correct_answers.append(answer_state) x = int(df[df.state == answer_state].x) y = int(df[df.state == answer_state].y) answer_state_turtle = turtle.Turtle() answer_state_turtle.penup() answer_state_turtle.hideturtle() answer_state_turtle.goto(x, y) answer_state_turtle.write(answer_state)
73fb901a37579b7a12f20fcc3cd29a10a93cd2f6
chengwenhua626/data_structure
/10.15/遍历二叉树.py
758
3.8125
4
# 前序遍历复杂方法 def perOrder1(self, node): if not node: return None print(node.data) self.perOrder(node.left) self.perOrder(node.right) # 前序遍历数(简单方法) def perOrder(self, node): stack = [node] while len(stack) > 0: print(node.data, end=' ') if node.right: stack.append(node.right) if node.left: stack.append(node.left) node = stack.pop() # 中序遍历 def in_order_stack(self, node): stack = [] while node or len(stack) > 0: while node: stack.append(node) node = node.left if len(stack) > 0: node = stack.pop() print(node.data, end=' ') node = node.right
6275d4e14c8f6937903e43f54c97d4181aaacecb
bearbin/gcse-cs
/countUntilZero.py
218
3.75
4
#!/usr/bin/python3 import sys sum = 0 while True: userI = input() try: userI = int(userI) except: sys.stderr.write("Non-integer entered!\n") break else: sum += userI if userI < 1: break print(sum)
4e66a8a78084b1b46a4b8522c8d517699b8796bf
KelvinTMacharia/learningpy
/fxnassignment2.py
511
3.90625
4
class Mydict(): def __init__(self): pass def add(self, key, value): self[key] = value dictone = Mydict() dictone.key = input("enter Key: ") dictone.value = input("enter value: ") dictone.key1 = input("enter key1: ") dictone.value1 = input("enter value1: ") c=dictone.add = {dictone.key: dictone.value, dictone.key1: dictone.value1} list = [(k, v) for k, v in Mydict.items(c)] my_list = str(list) m=my_list.replace("(", "[") n=m.replace(")", "]") print(n)
351e0c7d87f0da9211c12753b7d39c3641e941e5
almiradecena/vigenerecipher
/kasiski.py
4,385
4.09375
4
## Get the longest repeated substring in a string ## https://www.geeksforgeeks.org/longest-repeating-and-non-overlapping-substring/ def longestRepeatedSubstring(str): n = len(str) LCSRe = [[0 for x in range(n + 1)] for y in range(n + 1)] res = "" # To store result res_length = 0 # To store length of result # building table in bottom-up manner index = 0 for i in range(1, n + 1): for j in range(i + 1, n + 1): # (j-i) > LCSRe[i-1][j-1] to remove # overlapping if (str[i - 1] == str[j - 1] and LCSRe[i - 1][j - 1] < (j - i)): LCSRe[i][j] = LCSRe[i - 1][j - 1] + 1 # updating maximum length of the # substring and updating the finishing # index of the suffix if (LCSRe[i][j] > res_length): res_length = LCSRe[i][j] index = max(i, index) else: LCSRe[i][j] = 0 # If we have non-empty result, then insert # all characters from first character to # last character of string if (res_length > 0): for i in range(index - res_length + 1, index + 1): res = res + str[i - 1] return res ## Get the factors of a number ## https://www.tutorialspoint.com/How-to-Find-Factors-of-Number-using-Python def get_factors(num): factors=[] for i in range(1,num+1): if num%i==0: factors.append(i) return factors # Get a list of substrings given a key length x def get_substrings(string, x): substr = [] for i in range(len(string)): if i < x: substr.append([string[i]]) continue substr[i%x].append(string[i]) return substr # Get repeating letters (frequency) in a string as a dictionary def get_repeating_letters(string): repeating = {} for c in string: if c in repeating: repeating[c] += 1 else: repeating[c] = 1 return repeating # Get value closest to num def get_closest(arr, num): closest = arr[0] j = 0 for i in range(len(arr)): if(abs(0.065-arr[i]) < abs(0.065-closest)): closest = arr[i] j = i return closest, j ################### Getting Input ########################## #ciph_tx = 'yswbhxdomstjwjfcbyldlwrnbthxanyskqhyldownydmwxetznfxbscmskrrkiwdsyrje' (From HW) # Get cipher text ciph_tx = input("Please Enter Ciphertext: ") ciph_tx = ciph_tx.strip().lower() while not ciph_tx.isalpha(): print("Only letters (A-Z) please!") ciph_tx = input("Ciphertext: ") ciph_tx = ciph_tx.strip().lower() # Get longest repeated substring repeat = longestRepeatedSubstring(ciph_tx) # Ensure repeated substring is longer than 1 letter long if len(repeat) <= 1: print('Kasiski test failed!!!!!!!!!') exit() first = ciph_tx.find(repeat, 0, len(ciph_tx)) # first occurence of repeated substring in string second = ciph_tx.find(repeat, first+1, len(ciph_tx)) # second occurence of repeated substring in string print('Repeated substring is ' + repeat + ' at', first, 'and', second) multiple = second-first factors = get_factors(multiple) ioc = [] # Closest ioc to 0.065 for all factors for factor in factors: # Get substrings for factor substrings = get_substrings(ciph_tx, factor) # Calculate index of coincidence for each factor factor_ioc = [] # Ioc for each factor for string in substrings: n = len(string) repeating_letters = get_repeating_letters(string) # Calculate index of coincidence frequency = 0 for letter in repeating_letters: m = repeating_letters[letter] frequency += m*(m - 1) curr_ioc = (1/(n*(n-1)))*frequency # Ioc for current substring factor_ioc.append(round(curr_ioc, 4)) closest, _ = get_closest(factor_ioc, 0.065) # closest ioc to 0.065 ioc.append(closest) closest, i = get_closest(ioc, 0.065) # final closest ioc from all factors and factor it corresponds to print(closest, factors[i]) print('Keyword length is ', factors[i])
3ebb9d37b812b188e08c1d66ac7d3dc63517f20b
pombredanne/MI
/ankit/BitManipulation/BitSwapOddEven.py
473
3.953125
4
#!/usr/local/bin/python2.7 def update(num,ithPos,upBit): mask=~(1<<ithPos); return (num & mask)|(upBit<<ithPos); def swapOddEven(num): i=0; odd=0; even=0; while(i<32): odd=(num & (1<<(i+1))); even=(num & (1<<(i))); if(odd!=even): # swap odd and even bits odd will have even n even odd num=update(num,i+1,even); num=update(num,i,odd); i=i+2; return num; n=10; newn=swapOddEven(n); print "number after swap is %d" %newn;