blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
64db6bc4f55091426605b6cb05edf8ea3c92a917
keumdohoon/STUDY
/keras/keras79_diabetes_dnn.py
3,845
3.5
4
from sklearn.datasets import load_diabetes import numpy as np import matplotlib.pyplot as plt from sklearn import datasets from sklearn.decomposition import PCA from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split # import some data dataset = load_diabetes() print(dataset) print(dataset.keys()) print(dataset['feature_names']) x = dataset.data y = dataset.target # scatter graph import matplotlib.pyplot as plt plt.figure(figsize = (20, 10)) for i in range(np.size(x, 1)): plt.subplot(2, 5, i+1) plt.scatter(x[:, i], y) plt.title(dataset.feature_names[i]) plt.xlabel('columns') plt.ylabel('target') plt.axis('equal') plt.legend() plt.show() from sklearn.preprocessing import MinMaxScaler print(x.shape) # (442, 10), 여기서의 10은 데이터가 age, sex, bm1, bp, s1, s2, s3, s4, s5, s6 총 10가지로 구성되어있기 때문이다. print(y.shape) # (442,) scaler = MinMaxScaler() x = scaler.fit_transform(x) print(x) #나중 데이터에서 0 이나 1인 데이터를 뽑아주기 위해서 minmax scaler을 사용하여 x를 변환해준다. # pca = PCA(n_components=2) # pca.fit(x_scaled) # x_pca = pca.transform(x_scaled) # print(x_pca) # print(x_pca.shape) #(442, 2) #train test split x_train, x_test, y_train, y_test = train_test_split(x, y, random_state=66, shuffle=True, train_size = 0.8) print(x_train.shape) #(353, 10) print(x_test.shape) #(89, 10) print(y_train.shape) #(353,) print(y_test.shape) #(89,) ### 2. 모델 from keras.models import Sequential from keras.layers import Dense, Dropout model = Sequential() model.add(Dense(5, input_shape= (10, )))#dnn모델이기에 위에서 가져온 10이랑 뒤에 ',' 가 붙는다. model.add(Dense(10, activation= 'relu')) model.add(Dropout(0.5)) model.add(Dense(20, activation= 'relu')) model.add(Dropout(0.5)) model.add(Dense(400, activation= 'relu')) model.add(Dropout(0.3)) model.add(Dense(400, activation= 'relu')) model.add(Dropout(0.3)) model.add(Dense(200, activation= 'relu')) model.add(Dropout(0.3)) model.add(Dense(400, activation= 'relu')) model.add(Dropout(0.2)) model.add(Dense(100, activation= 'relu')) model.add(Dense(500, activation= 'relu')) model.add(Dense(40, activation= 'relu')) model.add(Dropout(0.2)) model.add(Dense(300, activation = 'relu')) model.add(Dropout(0.2)) model.add(Dense(1)) model.summary() # EarlyStopping from keras.callbacks import EarlyStopping, TensorBoard, ModelCheckpoint es = EarlyStopping(monitor = 'loss', patience=50, mode = 'auto') cp = ModelCheckpoint(filepath='./model/{epoch:02d}-{val_loss:.4f}.hdf5', monitor='val_loss', save_best_only=True, mode='auto') tb = TensorBoard(log_dir='graph', histogram_freq=0, write_graph=True, write_images=True) ### 3. 훈련 model.compile(loss='mse', optimizer='adam', metrics=['mse']) hist = model.fit(x_train, y_train, epochs=100, batch_size=70, verbose=1, validation_split=0.025, callbacks=[es, cp, tb]) ### 4. 평가, 예측 loss, mse = model.evaluate(x_test, y_test, batch_size=32) print('loss:', loss) print('mse:', mse) y_predict = model.predict(x_test) print(y_predict) # RMSE 구하기 from sklearn.metrics import mean_squared_error def RMSE(y_test, y_predict): return np.sqrt(mean_squared_error(y_test, y_predict)) print("RMSE : ", RMSE(y_test, y_predict)) # R2 구하기 from sklearn.metrics import r2_score r2 = r2_score(y_test, y_predict) print("R2 : ", r2) plt.subplot(2,1,1) plt.plot(hist.history['loss'], c='black', label ='loss') plt.plot(hist.history['val_loss'], c='yellow', label ='val_loss') plt.ylabel('loss') plt.legend() plt.subplot(2,1,2) plt.plot(hist.history['mse'], c='red', label ='mse') plt.plot(hist.history['val_mse'], c='green', label ='val_mse') plt.ylabel('mse') plt.legend() plt.show() #loss: 3954.6966868196982 #mse: 3954.696533203125
cb974ea332ca6f35e7bdd4667d2d84e0f3cbe623
dhruvbaldawa/project_euler
/0022-name-scores.py
1,208
4.125
4
""" Problem 22 Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score. For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 53 = 49714. What is the total of all the name scores in the file? """ def the_obvious_way(): f = open("names.txt") names = f.read()[1:-1] # eliminating the first and last " names = names.split('","') # a workaround to skip the csv parsing names.sort() # the preceding space is because we want alphabets with indices 1..26 letters = list(" ABCDEFGHIJKLMNOPQRSTUVWXYZ") sum_ = 0 for name in names: ind = names.index(name) + 1 # since array indexing starts from 0 total = sum([letters.index(x) for x in name]) score = ind * total sum_ = sum_ + score return sum_ print "Answer by the obvious way:", the_obvious_way()
de4edcd922cce339fb8fb90694c6b3585dafeba6
ismk/Python-Examples
/trip.py
835
3.90625
4
def hotel_cost(nights): return 140 * nights def plane_ride_cost(city): if(city == "Charlotte"): return 183 elif(city == "Tampa"): return 220 elif(city == "Pittsburgh"): return 222 elif(city == "Los Angeles"): return 475 def rental_car_cost(days): totalcost = days * 40 if(days >= 7): totalcost = totalcost - 50 elif(days >= 3): totalcost = totalcost - 20 return totalcost def trip_cost(city,days,spending_money): return (hotel_cost(days) + plane_ride_cost(city) + rental_car_cost(days)) + spending_money #print (trip_cost("Los Angeles", 5, 600)) usrcity = input (str(("city ?"))) usrdays = input ("days ?") usrmon = input ("extra money ?") print (trip_cost(usrcity,usrdays,usrmon))
31221785ba5391d1ecedbe7b3c096c8ba80d77a9
viviayi/LeetCode
/toLowerCase.py
426
3.65625
4
# -*- coding: utf-8 -*- """ Created on Thu Dec 12 17:16:24 2019 @author: 11104510 实现函数 ToLowerCase(),该函数接收一个字符串参数 str,并将该字符串中的大写字母转换成小写字母,之后返回新的字符串。 """ class Solution: def toLowerCase(self, str: str) -> str: return str.lower() if __name__ == '__main__': sl = Solution() print(sl.toLowerCase('Hello'))
64b1a6b5847bb39822445f8e1a597fa44c10104b
Edwar2-2/TestingSistemas
/ene-jun-2020/JOSE EDUARDO ONOFRE SUAREZ/Practica5/Contenedor.py
798
3.703125
4
class contenedor: def volumencontenedor(lista1,lista2): listaC = [] suma = 0 for i in range(0,len(lista1)): listaC.append(lista1[i]*lista2[i]) for i in range(0,len(listaC)): suma+= listaC[i] return suma if __name__ == "__main__": n = int(input("Escriba el numero de contenedores a usar:")) contenedores = [] volumenes = [] for i in range(0,n): contenedores.append(int(input("Escriba el numero de contenedores de la posicion {}:".format(i+1)))) volumenes.append(int(input("Escriba el volumen del contenedor en la posicion {}:".format(i+1)))) #print(contenedores) print("-----Mostrando el resultado-----\n") print(contenedor.volumencontenedor(contenedores,volumenes))
9eb3a80f93ad8f4ba48d0acba4da9ff9e30194d1
ssawo/python-365-days
/python-fundamentals/day-1/assignment-operators.py
868
4.53125
5
# This lab explores basic Python assignment operators with examples """ Examples include: += | Equivalent to x = x+5 -= | Equivalent to *= | Equivalent to /= | Equivalent to Others %= | Equivalent to //= | Equivalent to **= | Equivalent to """ # This example if short-hand for x = x+x - x = 10 x += x print('x = x + x ', x) #or x = 10 y = 20 x += y # simplifies x = x + y print(x) # This example is a short-hand for x = x-x x = 10 y = 5 x -= y print(x) # This example is a short-hand for x = x*x x = 5 y = 5 x *= y print(x) # This example is a short-hand for x = x/x x = 10 y = 5 x /= y print(x) # This example is a short-hand for x = x % x x = 20 y = 4 x %= y print(x) # This example is a short-hand for x = x // x x = 30 x //= x print(x) # This example is a short-hand for x = x ** x x = 20 y = 2 x **= y print(x)
b26804f399438e0a6d5f63a5487c95619507a56e
phalt/hash_things
/hash_things/hash_dict.py
700
4.0625
4
# -*- coding: utf-8 -*- """Hash Dictionaries.""" from typing import Dict def hash_dict(data: Dict) -> int: """ Hashes a Dictionary recursively. List values are converted to Tuples. WARNING: Hashing nested dictionaries is expensive. """ cleaned_dict: Dict = {} def _clean_dict(data: Dict) -> Dict: d: Dict = {} for k, v in data.items(): if isinstance(v, list) or isinstance(v, set): d[k] = tuple(v) elif isinstance(v, dict): d[k] = hash_dict(v) else: d[k] = v return d cleaned_dict = _clean_dict(data) return hash(tuple(sorted(cleaned_dict.items())))
00e1705f1e407a7ca369b52bdac70a90865142ff
inudevs/ithaca-prob-type-model
/deprecated /generator.py
544
3.5
4
from converter import convert_file from parser import parse_page names = [] for year in range(2008, 2020): for month in [3, 6, 9, 11]: for grade in [1, 2, 3]: for subject in [1]: # math only names.append( '{}-{:02d}-{}-{}'.format(year, month, grade, subject)) print(names) for name in names: try: pages = convert_file(name) for page in pages: parse_page(page) except RuntimeError: print('[!] {}.pdf not found'.format(name)) pass
a73191314940f1775a22c0e81c4afc663b3b897b
Phillip-Kemper/image-sentiment-analysis-ml
/machine-learning/model/trainModel.py
2,343
3.53125
4
import numpy as np import pandas as pd from scipy.io import loadmat import matplotlib.pyplot as plt import scipy.optimize as opt import dataRetrieval.dataRetrieval as getData import model.neuralNetworkBackpropagation as ml import sys CSV_FILE = "../dataRetrieval/sources/fer2013.csv" trainingData, evalData = getData.load_fer(CSV_FILE) # print(trainingData) y = trainingData["emotion"].values print(len(y)) # getting labels for training # y = pd.get_dummies(trainingData['emotion']).values width, height = 48, 48 datapoints = trainingData['pixels'].tolist() # getting features for training X = [] for xseq in datapoints: xx = [int(xp) for xp in xseq.split(' ')] X.append(xx) X = np.asarray(X) X = np.array([ml.min_max_norm(x) for x in X.T]).T num_labels = 3 num_input = 2304 num_hidden = 1539 # first tried 25 neurons in hidden layer, now applying rule of thumb # The number of hidden neurons should be 2/3 the size of the input layer, plus the size of the output layer. _lambda = 1 epsilon = np.math.pow(10, -4) initialTheta1 = ml.randomTheta(num_input, num_hidden) initialTheta2 = ml.randomTheta(num_hidden, num_labels) initialThetaVector = np.append(np.ravel(initialTheta1, order='F'), np.ravel(initialTheta2, order='F')) EPOCH_NUMBER = 60 for i in range(EPOCH_NUMBER): print('currently at epoch') print(i) thetaOpt = initialThetaVector thetaOpt = opt.fmin_cg(maxiter=200, f=ml.costFunction, x0=thetaOpt, fprime=ml.onlyGrad, args=(num_input, num_hidden, num_labels, X, y.flatten(), _lambda)) theta1 = np.reshape(thetaOpt[:num_hidden * (num_input + 1)], (num_hidden, num_input + 1), 'F') theta2 = np.reshape(thetaOpt[num_hidden * (num_input + 1):], (num_labels, num_hidden + 1), 'F') initialThetaVector = np.append(np.ravel(initialTheta1, order='F'), np.ravel(initialTheta2, order='F')) pred = ml.predict(theta1, theta2, X, y) with open("out_trainModel1.txt", "a") as myfile: myfile.write("Epoch Number:") myfile.write("\n") myfile.write(str(i)) myfile.write("\n") temp = np.mean(pred == y.flatten()) * 100 myfile.write(str(temp)) myfile.write("\n") if i == EPOCH_NUMBER: myfile.write("END") np.save('FinalModel1.npy', thetaOpt)
95c10215f48a4cf84af09be568de522f0ada3eb4
Sktank/wordSuggestions
/parse.py
1,051
3.640625
4
__author__ = 'spencertank' from errors import raiseError import verify frequenciesFileNotFoundError = "The word frequencies file could not be found!" misspelledFileNotFoundError = "The misspelled words file could not be found!" def getWordFrequencies(frequenciesFilename): try: f = open(frequenciesFilename, 'r') except IOError: raiseError(frequenciesFileNotFoundError) frequencies = f.read() frequencyList = frequencies.split('\n') for i, item in enumerate(frequencyList): frequencyList[i] = item.split(',') verify.frequenciesCheckIntegrity(frequencyList) sorted(frequencyList, key=lambda item: int(item[1])) return frequencyList def getMisspelledWords(misspelledFilename): #read in the input file try: f = open(misspelledFilename, 'r') except IOError: raiseError(misspelledFileNotFoundError) misspelled = f.read() misspelledWordsList = misspelled.split('\n') verify.misspelledCheckIntegrity(misspelledWordsList) return misspelledWordsList
7c312b310cc4291da0e1f167a4fafbc54127e26b
HannibalCJH/Leetcode-Practice
/231. Power of Two/Python: Solution.py
213
3.6875
4
class Solution(object): def isPowerOfTwo(self, n): """ :type n: int :rtype: bool """ power = 1 while power < n: power *= 2 return power == n
e464ad15cde0de22563734bf064990566b8ef66d
msaitejareddy/Python-programs
/sep 17/readfile.py
428
3.515625
4
#how to read wickets data without loop from wickets.txt file #infile=open('wickets.txt','r') #wickets=infile.readline() #print(wickets) #wickets=infile.readline() #print(wickets) #wickets=infile.readline() #print(wickets) #how to read no of wickets taken by each bowler using while loop from wickets.txt file infile=open('wickets.txt','r') wickets=infile.readline() while(wickets): print(wickets) wickets=infile.readline()
a52631de3758aa260fa4c09782379078dc7fd432
mmmarchetti/cev_python
/exercises/exe112/moeda.py
981
3.609375
4
class Calculo: def __init__(self, num, aum=0, dim=0, cond=True): self.num = num self.aum = aum self.dim = dim self.cond = cond def conta(self): result_metade = (self.num / 2) if self.cond: result_metade = f'R${result_metade:0.2f}' result_dobro = self.num * 2 if self.cond: result_dobro = f'R${result_dobro:0.2f}' result_aumento = self.num + (self.num * (self.aum / 100)) if self.cond: result_aumento = f'R${result_aumento:0.2f}' result_diminui = self.num - (self.num * (self.dim / 100)) if self.cond: result_diminui = f'R${result_diminui:0.2f}' print(f'Preço analisado: R${self.num:0.2f}') print(f'Dobro do preço: {result_dobro}') print(f'Metade do preço: {result_metade}') print(f'{self.aum}% de aumento: {result_aumento}') print(f'{self.dim}% de reduação: {result_diminui}')
d58d22b6b461d9de33aaa7204dcaec5ddf60717a
tongpf/ichw
/pyassign1/planets.py
1,296
4
4
import turtle import math def firststep(p,a,b): a = a*5.0 b = b*5.0 c = a - math.sqrt(a**2-b**2) p.shape("circle") p.pensize(3) p.penup() p.forward(c) p.left(90) p.pendown() def drawcircle(p,sz): sz = sz * 5.0 d = 2 * math.pi * sz p.forward((d/360)*(400.0/(sz+1))) p.left(400.0/(sz+1)) def drawellipse(p,a,b,rad): a = a*5.0 b = b*5.0 rad = (math.pi * rad / 180.0)*(400.0/(a+1)) x=a*math.cos(rad) - math.sqrt(a**2-b**2) y=b*math.sin(rad) p.goto(x,y) wn = turtle.Screen() Sun = turtle.Turtle() Sun.color("orange") Mer = turtle.Turtle() Mer.color("purple") Ven = turtle.Turtle() Ven.color("yellow") Ear = turtle.Turtle() Ear.color("blue") Mar = turtle.Turtle() Mar.color("red") Jup = turtle.Turtle() Jup.color("gray") Sat = turtle.Turtle() Sat.color("brown") firststep(Sun,0,0) firststep(Mer,8,8) firststep(Ven,12,12) firststep(Ear,16,16) firststep(Mar,23,22.5) firststep(Jup,60,55) firststep(Sat,80,70) for i in range(3600): drawellipse(Sun,0,0,i+1) drawellipse(Mer,8,8,i+1) drawellipse(Ven,12,12,i+1) drawellipse(Ear,16,16,i+1) drawellipse(Mar,23,22.5,i+1) drawellipse(Jup,60,55,i+1) drawellipse(Sat,80,70,i+1) wn.exitonclick()
84078a344ca008afff0b64a150f38d13f3360f9e
weiguxp/pythoncode
/ProblemSets/ParseFile.py
344
3.546875
4
def ParseF(n): ''' opens file n and returns a list of words n = name of file ''' fin = open(n) myList = [] for line in fin: word = line.strip() myList.append(word) return myList def ParsePartF(n, l): ''' Opens a file and parses the first l words n = file name l = desired length of list''' myList = ParseF(n) return myList[:l]
1264def3c3a4199f548a6f9dea1d9824aa5b97b1
JVvix/tkToDo
/dictionary.py
370
3.8125
4
# stacgkoverflow.com/questions/2397754/how-can-i-create-an-array-list-of-dictionaries-in-python #dictlistGOOD = list( {} for i in xrange(listsize) ) #dictlistGOOD[0]["key"] = "value" dictlistGOOD = list( {} for i in range(listsize) ) dictlistGOOD[0]["key1"] = "value0" dictlistGOOD[1]["key1"] = "value1" for i in range(dictlistGOOD): print(dictlistGOOD[i])
2f62f182de4abf7b2db6eb93924624f7f1e3cc7f
ziGFriedman/My_programs
/Character_table_output.py
874
3.921875
4
'''Вывод таблицы символов''' # Первые 128 символов по таблице Unicode такие же как и в таблице символов ASCII. # Выведем их, начиная с пробела, кодовый номер которого 32. # Чтобы привести вывод к табличной форме будем переходить на новую строку после # каждого десятого выведенного на экран символа. Для этого в коде ниже используется # оператор if. # Функция chr() возвращает символ из таблицы Unicode, соответствующий переданному # коду-числу. for i in range(32, 128): print(chr(i), end=' ') if (i - 1) % 10 == 0: print() print()
cb1e2664537744c9171c1bdf7e7fc324daaf009c
SADDLOVE/HomeWork
/nodmod.py
652
3.5625
4
#Задание выданное на лекции от 18.10.2021 #Напишите программу, которая получает на вход два натуральных числа и определяет их НОД с помощью модифицированного алгоритма Евклида a = [64168, 358853, 6365133, 17905514, 549868978] b = [82678, 691042, 11494962, 23108855, 298294835] vivod = [] print(a) print(b) for i in range(len(a)): while b[i] != 0: a[i], b[i] = b[i], a[i] % b[i] if a[i] == 1: vivod.append("Взаимопростые") else: vivod.append(a[i]) print(vivod)
3c5960fd3f39f4c5ba6b26135a6a09dbeb1cf165
pradeepraja2097/Python
/python basic programs/array.py
161
3.78125
4
def sum(arr): sum=0 for i in arr: sum+=i print(sum) return(sum) arr=[] arr=[1,3,2] answer=sum(arr) print("answer is" + str(answer))
de668dfdb154730c611ddfd0e70dcbbf185c2870
kushrami/Python-Crash-Course-book-Exercise
/Exercise_11_2_test.py
473
3.640625
4
import unittest import Exercise_11_2 as module class CityCountry(unittest.TestCase): def test_city_country(self): formatted_name = module.CityCountryFunc('santiago','chille') self.assertEqual(formatted_name, 'santiago, chille') def test_city_country_population(self): formatted_name = module.CityCountryFunc('santiago','chille',5000000) self.assertEqual(formatted_name, 'santiago, chille,population - 5000000') unittest.main()
c5e4f0f618350f718171e0089942065dfab73d26
bbster/PythonBigdata
/workspace/11-method/practice2.py
549
3.96875
4
def grade(avg): if avg >= 90 and avg <= 100: return 'A' elif avg >= 80 and avg <=89: return 'B' elif avg >= 70 and avg <=79: return 'C' elif avg >= 60 and avg <=69: return 'D' else : return 'F' def calc(x,y): total = x + y avg = total / 2 return avg def output(avg): print(grade(avg), '학점입니다') def main(): x = int(input('국어 점수 입력 : ')) y = int(input('영어 점수 입력 : ')) avg = calc(x, y) output(avg) main()
89710983d91b130a8b63f6b15bdb393df2b164c8
tejachil/ECE2524-Chiluvuri
/HW3/mult2.py
1,990
3.9375
4
#!/usr/bin/env python2 # ECE 2524 Homework 3 Problem 1 (Nayana Teja Chiluvuri) import sys import argparse import fileinput # argument parser parser = argparse.ArgumentParser(description='Process some integers.') parser.add_argument('files', nargs='*', type=str, default=sys.stdin) parser.add_argument('--ignore-blank', action='store_true', dest='ignore_blank', help='ignores the blank lines in the file') parser.add_argument('--ignore-non-numeric', action='store_true', dest='ignore_non_numeric', help='ignores the non-numeric lines in the file') args = parser.parse_args() product = 1.0 # initialize the product to 1 # condition if positional arguments are supplied if(len(sys.argv) > 1): for line in fileinput.input(args.files): # condition for if <ENTER> is pressed on the stdin without anything being entered if line == '\n': if args.ignore_blank: continue else: print product product = 1.0 # condition for the enf of file elif len(line) == 0: break # condition if something is entered on the stdin else: try: product *= float(line) except Exception as err: # exception if what is entered is not a number if args.ignore_non_numeric: continue else: sys.stderr.write(str(err)) sys.exit(1) # condition if no positional arguments are supplied (basically same as mult.py) # did it like this instead of the top condition to prevent buffering problem with for line in... else: while(1): line = sys.stdin.readline() # read each line of the stdin # condition for if <ENTER> is pressed on the stdin without anything being entered if line == '\n': print product product = 1.0 # condition for the enf of file elif len(line) == 0: break # condition if something is entered on the stdin else: try: product *= float(line) except Exception as err: # exception if what is entered is not a number sys.stderr.write(str(err)) sys.exit(1) # print the product and exit print product sys.exit(0)
ce51fbe0fc2c85ad5dd93e9060d2f9c3216ed983
LanonD/PythonBasics
/variables.py
823
4.15625
4
# -*- coding: utf-8 -*- # #Esto es un comentario """ esto es un heredoc (comentario) """ mensaje = """ esto es un mensaje, neta xd """ nombre = "Luis" apellido = 'Vázquez' #Esta es la preferida nombre_completo = nombre + ' ' +apellido print(nombre_completo) print(len(nombre.upper())) print(nombre.lower()) print(nombre.upper()) print(nombre.replace('L', 'x')) #Formateo de cadenas mensaje_de_saludo = 'hola soy %s' % nombre print(mensaje_de_saludo) ####################################### nombre_dado = input("dime tu nombre: ") longitud_nombre = 'hola la longitud de tu nombre es de %s letras' % len(nombre_dado) if len(nombre_dado)>10: print("su nombre es demasiado largo, ingrese uno más corto") nombre_dado = input("dime tu nombre: ") if len(nombre_dado)<=10: print(longitud_nombre)
81b5abb30f2d1d493d05992076633b1af56b7186
econpy/yav1
/parse_log.py
1,363
3.59375
4
from pandas import read_csv import os import sys from libv1.logparser import CleanLogData """ ABOUT: This script parses a single YaV1 log located in the `rawlogs` folder. Just pass the date of the log file you want to clean and it will output a new CSV file in the `cleanlogs` folder. USE: python parse_log.py 2014-02-01 """ basedir = os.path.realpath('.') # Take the date of the log file from the command line if len(sys.argv) == 2: logdate = sys.argv[1] logfilepath = '%s/rawlogs/%s_alert.log' % (basedir, logdate) if not os.path.exists(logfilepath): sys.exit('ERROR: %s does not exist.' % logfilepath) # Read a raw log file into a DataFrame. in_df = read_csv(logfilepath) # Clean the log and export it to a CSV file. out_df = CleanLogData(in_df) outfilepath = '%s/cleanlogs/%s_alert.csv' % (basedir, logdate) out_df.to_csv(outfilepath, index=False) print 'Success! Cleaned log file saved to: %s' % outfilepath else: sys.exit(''' **** ERROR **** --------------- Please run the script again by passing the date of a log file in your rawlogs folder. For example: python parse_log.py 2013-02-01 which will clean the log file located at ./rawlogs/2014-02-01_alert.log and create a new file at ./cleanlogs/2014-02-01_alert.csv ''')
69eb0c3d99d59be7c9e014ede201d46a37694ce1
zhengqiangzheng/PythonCode
/basicpy/itertolls.py
447
3.765625
4
from itertools import combinations, groupby, permutations, combinations_with_replacement a = [1, 2, 3, 4, ] b = [4, 5, 6] # print(list(permutations(a, 3))) # len(a)! print(list(combinations(a, 3))) print(list(combinations_with_replacement(a, 3))) def small_than3(x): return x < 3 groupby_obj = groupby(a, key=small_than3) groupby_obj_lambda = groupby(a, key=lambda x: x < 3) for key, value in groupby_obj: print(key, list(value))
fd8fc61c99158c7fc25b757fe894fcb0b982cf64
dahyunhong/CCSF_Classes
/CS110A/exercise1.6.py
1,151
4.375
4
rad = float(input("Enter the radius:")) Area=3.14*rad*rad Circumference=2*3.14*rad print("The area is {}".format(Area)) print("The circumference is {}".format(Circumference)) # 2. Write a program to take the input of two numbers and then swap their values. Your code should display the original and the modified values of the variables . # For example: # Enter First variable: 5 # Enter Second variable: 10 # Original First=5 # Original Second=10 # New First=10 # New Second=5 first = input("Enter First variable: ") second = input("Enter Second variable: ") print("Original First is {}" .format(first)) print("Original Second is {}" .format(second)) temp = first first = second second = temp print("New First is {}" .format(first)) print("New Second is {}" .format(second)) # 3. Write a program in python to convert temperature from Celsius to Fahrenheit. Celsius = float(input("input Celsius; ")) F = (Celsius * (9/5)) +32 print("Fahrenheit is {}" .format(F)) # (0°C × 9/5) + 32 = 32°F F = float(input("input Fahrenheit; ")) Celsius = (F-32) *(5/9) print("celsius is {}" .format(Celsius)) # (32°F − 32) × 5/9 = 0°C
f71095b64b8ab9df1cb036aa3a18ad1cc10ec4b9
vaishali-khilari/COMPETITIVE-PROGRAMMING
/leetcode/Sorted matrix .py
1,139
4.4375
4
Given an NxN matrix Mat. Sort all elements of the matrix. Example 1: Input: N=4 Mat=[[10,20,30,40], [15,25,35,45] [27,29,37,48] [32,33,39,50]] Output: 10 15 20 25 27 29 30 32 33 35 37 39 40 45 48 50 Explanation: Sorting the matrix gives this result. Example 2: Input: N=3 Mat=[[1,5,3],[2,8,7],[4,6,9]] Output: 1 2 3 4 5 6 7 8 9 Explanation: Sorting the matrix gives this result. Your Task: You don't need to read input or print anything. Your task is to complete the function sortedMatrix() which takes the integer N and the matrix Mat as input parameters and returns the sorted matrix. code:- class Solution: def sortedMatrix(self,N,mat): total=N *N op=[] for i in mat: for j in i: op.append(j) op.sort() res=[] x=[] p=0 q=N while total: for i in range(p,q): res.append(op[i]) x.append(res) res=[] p+=N q+=N total-=N return x
5de0150031379492688c3044673c9bb2f3b4b2a5
xodhks0626/pythonStudy
/practice/recursiveFunction.py
560
3.765625
4
# Recursive Function (재귀 함수) : 자기 자신을 다시 호출하는 함수 def recursive_function(): print("재귀함수") recursive_function() # recursive_function() # 마지막에 나타나는 오류 메시지는 재귀의 최대 깊이를 초과했다는 내용이다. => 무한대로 재귀 호출을 할 수 없다. def re_function(i): if i == 100: return print(i, '번째 재귀 함수에서', i+1, '번째 재귀 함수를 호출.') re_function(i+1) print(i, '번째 재귀 함수 종료.') re_function(1)
8b04f8bd99a5c011091f1f589a44187ecf715c51
JCYTop/ML
/100-Days-Of-ML-Code/Day 2/Day 2 Simple Linear Regression.py
1,123
3.984375
4
# step 1: Preprocess The Data ********* # 处理数据 import pandas as pd import numpy as np import matplotlib.pyplot as plt dataset = pd.read_csv("stduentscores.csv") X = dataset.iloc[:, :1].values Y = dataset.iloc[:, 1].values from sklearn.model_selection import train_test_split X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=1 / 4, random_state=0) # step 2: 训练集使用简单线性回归模型来训练 ********* from sklearn.linear_model import LinearRegression regressor = LinearRegression() # 使用线性模型进行训练数据接口 .fit regressor = regressor.fit(X_train, Y_train) # print(regressor) # step 3: Predicting the Result ********* # 预测结果 Y_pred = regressor.predict(X_test) print(Y_pred) # step 4: Visualization # 可视化 # .scatter 实现散点图 # .plot 实现预测函数 plt.scatter(X_train, Y_train, edgecolors="red") plt.plot(X_train, regressor.predict(X_train), color="blue") # plt.show() # step 5: Test # 测试结果可视化 plt.scatter(X_test, Y_test, edgecolors="yellow") plt.plot(X_test, regressor.predict(X_test), color="black") plt.show()
6df5140aebb1674b6efe8797a8353da3c6990b03
akesiraju/raspberrypi
/sensors/samples/keytest.py
171
3.609375
4
import keyboard print('hello') while True: if keyboard.is_pressed('up'): print('up') if keyboard.is_pressed('down'): print('down') break
f442b53c0433300429f49731389790ac08de324e
Rajadeivani/deivani5756
/num_div_less_N.py
114
3.546875
4
N=int(input()) count=0 for i in range(2,N): if(N%i==0): count=count+1 if(count>0): print("yes")
7cd58df5896359649fcdc77ad8e68ea1f10891b4
anishsundaram/atbs-solutions
/Test Program.py
242
4.15625
4
print("enter a number") number = int(input()) def collatz(number): if(number % 2 ==0): print(str(number // 2)) return number // 2 else: print(str(3*number+1)) collatz(number)
53bb6403b34dd5260bb20066d2387ad25dd60221
tuanbieber/code-tour
/10-remove-duplicates-from-sorted-array.py
636
3.53125
4
class Solution: def __init__(self): pass def function1(self, nums): if len(nums) == 0: return 0 if len(nums) == 1: return 1 i = 0 for j in range(1, len(nums)): if nums[i] != nums[j]: i += 1 nums[i] = nums[j] return i + 1 def main(): solution1 = Solution() nums = [0,0,1,1,1,2,2,3,3,4] res = solution1.function1(nums) print('this is res ', res) if __name__ == '__main__': main() # https://leetcode.com/explore/challenge/card/may-leetcoding-challenge/537/week-4-may-22nd-may-28th/3338/
3e8b40c9cc79176053b6fbd41b8faf19aa3f81c9
BenSandeen/autonomous_vehicle_flocking
/traffic_light.py
6,451
3.859375
4
import enum import random from copy import deepcopy import math from constants import * class LightColor(enum.Enum): green = 'green' yellow = 'yellow' red = 'red' class TrafficLight: def __init__(self, position): """These directions represent the color for a car travelling in the given direction. E.g., a car travelling right would look at `self.right` """ self.up = LightColor.green self.down = LightColor.green self.left = LightColor.red self.right = LightColor.red self.position = deepcopy(position) self.yellow_duration = 6 # Since lights facing in opposite directions should always change together, we use a single timer for each pair self.up_and_down_time_until_light_change = random.randint(40, 60) self.left_and_right_time_until_light_change = math.inf # Used to change lights more quickly when cars are waiting at a red light self.car_is_waiting_on_light = self.reset_cars_waiting_on_lights() def reset_cars_waiting_on_lights(self): return {UP: 0, DOWN: 0, LEFT: 0, RIGHT: 0} def add_car_waiting_on_light(self, direction_of_travel): """Increments counter for number of cars waiting on a light :param direction_of_travel: Direction in which the car is travelling """ # if direction_of_travel == UP: # self.car_is_waiting_on_light[UP] += 1 self.car_is_waiting_on_light[direction_of_travel] += 1 def get_rgb_color_value(self, light_color): if light_color == LightColor.green: return GREEN elif light_color == LightColor.yellow: return YELLOW elif light_color == LightColor.red: return RED def get_light_for_direction_of_travel(self, direction): if direction == UP: return self.up elif direction == DOWN: return self.down elif direction == LEFT: return self.left elif direction == RIGHT: return self.right def change_lights_possibly(self): """Handles changing the lights. Doesn't actually change until this method has been called a certain number of times, for simplicity. This way we can just have the main loop call into this every iteration and this will handle how frequently to change the lights """ if self.up_and_down_time_until_light_change >= 0: # Lights change faster depending on how many cars are waiting on them self.up_and_down_time_until_light_change -= ( 1 + self.car_is_waiting_on_light[LEFT] + self.car_is_waiting_on_light[RIGHT]) else: self.car_is_waiting_on_light = self.reset_cars_waiting_on_lights() self.up = self.get_next_light_color(self.up) self.down = self.get_next_light_color(self.down) assert self.up == self.down # If the lights turned red, then turn the other lights green if self.up == LightColor.red: self.left = self.get_next_light_color(self.left) self.right = self.get_next_light_color(self.right) assert self.left == self.right self.left_and_right_time_until_light_change = self.get_light_duration(self.left) self.up_and_down_time_until_light_change = self.get_light_duration(self.up) return if self.left_and_right_time_until_light_change >= 0: self.left_and_right_time_until_light_change -= ( 1 + self.car_is_waiting_on_light[UP] + self.car_is_waiting_on_light[DOWN]) else: self.car_is_waiting_on_light = self.reset_cars_waiting_on_lights() self.left = self.get_next_light_color(self.left) self.right = self.get_next_light_color(self.right) assert self.left == self.right # If the lights turned red, then turn the other lights green if self.left == LightColor.red: self.up = self.get_next_light_color(self.up) self.down = self.get_next_light_color(self.down) assert self.up == self.down self.up_and_down_time_until_light_change = self.get_light_duration(self.up) self.left_and_right_time_until_light_change = self.get_light_duration(self.left) return def get_next_light_color(self, light_color): if light_color == LightColor.green: return LightColor.yellow elif light_color == LightColor.yellow: return LightColor.red elif light_color == LightColor.red: return LightColor.green def get_light_duration(self, light_color): if light_color == LightColor.green: return random.randint(40, 60) elif light_color == LightColor.yellow: return self.yellow_duration # Red lights wait on lights in other direction to become red before changing elif light_color == LightColor.red: return math.inf def draw(self): top_left = (self.position['x'] * CELLSIZE, self.position['y'] * CELLSIZE) top_right = (self.position['x'] * CELLSIZE + CELLSIZE, self.position['y'] * CELLSIZE) bottom_left = (self.position['x'] * CELLSIZE, self.position['y'] * CELLSIZE + CELLSIZE) bottom_right = (self.position['x'] * CELLSIZE + CELLSIZE, self.position['y'] * CELLSIZE + CELLSIZE) center = (self.position['x'] * CELLSIZE + 0.5 * CELLSIZE, self.position['y'] * CELLSIZE + 0.5 * CELLSIZE) # Light for traffic heading up... pygame.draw.polygon(DISPLAYSURF, self.get_rgb_color_value(self.up), [bottom_left, center, bottom_right]) # ...for traffic heading down... pygame.draw.polygon(DISPLAYSURF, self.get_rgb_color_value(self.down), [top_left, top_right, center]) # ...for traffic heading left... pygame.draw.polygon(DISPLAYSURF, self.get_rgb_color_value(self.left), [center, top_right, bottom_right]) # ...for traffic heading right... pygame.draw.polygon(DISPLAYSURF, self.get_rgb_color_value(self.right), [bottom_left, top_left, center])
a274da569cbbc4cd0432dce71234fbe6ab0b0915
frclasso/CodeGurus_Python_mod1-turma1_2019
/Cap03/script6.py
477
4.125
4
# strings # -*-coding:utf-8-*- frase1 ="Eu adoro maças" frase2 = "Bem vindos ao curso de Python da Code Cla" # concatenacao + #print(frase1 + frase2) # repetição * #print(frase1 * 100) # indices em Python iniciam por zero (0) dentro de colchetes print(frase1[0]) # primeiro indice 'E' print(frase1[-1]) # ultimo indice 's' # fatias/slices [:] # print(frase1[0:2]) # imprime do primeiro indice (0) até o terceiro exclusive 'u' # print(frase1[3:8]) print(len(frase1)
1ee086daf263bdc9dd81a5691a90912ce5a76ff3
Jyllove/Python
/DataStructures&Algorithms/Sort/mergesort.py
475
4.09375
4
def MergeSort(lists): if len(lists) <= 1: return lists num = len(lists)//2 left = MergeSort(lists[:num]) right = MergeSort(lists[num:]) return Merge(left,right) def Merge(left,right): l, r = 0, 0 result = [] while l<len(left) and r<len(right): if left[l] <=right[r]: result.append(left[l]) l += 1 else: result.append(right[r]) r += 1 result += list(left[l:]) result += list(right[r:]) return result print MergeSort([1,2,3,4,5,6,7,90,21,23,45])
8876ede3a3cf5135e86e17291bfceafdde5f1767
PJH6029/Lecture
/oop1_fraction/main.py
2,474
4.21875
4
from fraction import Fraction from fraction_handler import FractionCalculator # main.py는 건드리지 않아도 되지만, 읽어볼만 한 내용 def take_fraction_input(n): # 유효한 두 정수를 받는 함수 while True: tmp = input(f'{n}: Enter the numerator and denominator of the fraction(both are integers): ').split() if len(tmp) != 2: print("[Error] You should enter two numbers") else: # num(numerator): 분자 # denom(denominator): 분모 num, denom = tmp[0], tmp[1] if not (num.isdigit() and denom.isdigit()): print("[Error] Both should be integers") elif int(denom) == 0: print('[Error] Denominator cannot be a zero') else: num, denom = int(num), int(denom) print(f'* Input success: {num}, {denom}') return num, denom def take_operator_input(): # 유효한 연산자를 받는 함수 while True: op = input('Enter the operator[+ - * /]: ') if op not in ['+', '-', '*', '/']: print("[Error] Operator should be one of (+, -, *, /)") else: return op if __name__ == '__main__': quit_process = False while not quit_process: command = input('Enter any key(\'q\' to quit): ') if command == 'q': quit_process = True continue tmp_num1, tmp_denom1 = take_fraction_input(1) fraction1 = Fraction(tmp_num1, tmp_denom1) tmp_num2, tmp_denom2 = take_fraction_input(2) fraction2 = Fraction(tmp_num2, tmp_denom2) op = take_operator_input() fraction_handler = FractionCalculator() if op == '+': result_fraction = fraction_handler.add_fraction(fraction1, fraction2) elif op == '-': result_fraction = fraction_handler.sub_fraction(fraction1, fraction2) elif op == '*': result_fraction = fraction_handler.mul_fraction(fraction1, fraction2) else: if fraction2.is_zero(): print("[Error] The divisor cannot be zero\n") continue else: result_fraction = fraction_handler.div_fraction(fraction1, fraction2) print("-----Result-----") print(f"As fraction: {result_fraction.to_string()}") print(f"As decimals: {result_fraction.to_decimals()}") print()
15a5618a8d2009bb95fbab107440abac21af18a7
Arjitg450/Python-Programs
/char_count.py
582
3.890625
4
def char_count(text,char): count=0 for c in text: if c==char: count+=1 return count while True: inp=input("enter the file name\n") inp1=input("enter the char whose rep value you want to know\n") inp2=str(inp1) with open(inp+".txt") as f: text=f.read() print("rep value :",char_count(text,inp2)) print("total no of char :",len(text)-text.count("\n")) aa=(char_count(text,inp2)/(len(text)-text.count("\n"))) bb=str(aa*100) print("percentage of",inp2,"in file named",inp,"is :",(bb) +"%")
c06cecc0ffa14d816cee6a12e35e1c01ef406a35
wangning11/first
/31_冒泡排序.py
243
3.53125
4
arr = [4,9,2,7,1,0,3] def buddle_sort(arr): n = len(arr) for j in range(0,n-1): for i in range(0,n-1-j): if arr[i] > arr[i + 1]: arr[i], arr[i + 1] =arr[i + 1], arr[i] buddle_sort(arr) print(arr)
de8784741867166cb2393e248ac996b12eeec8b7
sangeetjena/datascience-python
/Dtastructure&Algo/sort/merge_sort.py
809
4.125
4
#logic behind is that it will keep deviding all the elements and up to reach the single elements # the n keep forming sorted arrays and merge two to create one sorted array and that again #sorted with others left. def merge_sort(value): if len(value)>1: mid= len(value)//2 left=value[:mid] right=value[mid:] left=merge_sort(left) right=merge_sort(right) value=[] while len(left)>0 and len(right)>0: if left[0]>right[0]: value.append(left[0]) del left[0] else: value.append(right[0]) del right[0] for i in left: value.append(i) for i in right: value.append(i) return value lst=[1,5,4,3] res=merge_sort(lst) print(res)
542c4ddf4653c08c766b94cee73e40f4a57c23b3
Crisescode/leetcode
/Python/Sort/1235. maximum_profit_in_job_scheduling.py
2,470
3.796875
4
#! /usr/bin/env python # -*- coding: utf-8 -*- # https://leetcode-cn.com/problems/maximum-profit-in-job-scheduling/ # We have n jobs, where every job is scheduled to be done from startTime[i] # to endTime[i], obtaining a profit of profit[i]. # # You're given the startTime , endTime and profit arrays, you need to output # the maximum profit you can take such that there are no 2 jobs in the subset  # with overlapping time range. # # If you choose a job that ends at time X you will be able to start # another job that starts at time X. # For example: # Input: startTime = [1, 2, 3, 4], endTime = [3, 4, 5, 6], # profit = [50, 10, 40, 70] # Output: 120 # Explanation: The subset chosen is the first and fourth job. # Time range [1-3]+[3-6] , we get profit of 120 = 50 + 70. from typing import List class Solution: def jobScheduling( self, startTime: List[int], endTime: List[int], profit: List[int] ) -> int: profit_time_range = [] for index in range(len(profit)): start = startTime[index] end = endTime[index] pay = profit[index] profit_time_range.append((start, end, pay)) print(profit_time_range) count = [] for i in range(len(profit_time_range)): for j in range(i, len(profit_time_range)): if profit_time_range[j][0] >= profit_time_range[i][1]: count.append((profit_time_range[i], profit_time_range[j])) print(count) if __name__ == "__main__": start_time = [1, 2, 3, 4, 6] end_time = [3, 5, 10, 6, 9] profit = [20, 20, 100, 70, 60] import itertools # H = sorted(zip(start_time, itertools.repeat(1), end_time, profit)) # print(H) # res = 0 # import heapq # while H: # t = heapq.heappop(H) # print(t) # if t[1]: # heapq.heappush(H, (t[2], 0, res + t[3])) # else: # res = max(res, t[2]) # print(res) import bisect jobs = sorted(zip(start_time, end_time, profit), key=lambda v: v[1]) print(jobs) dp = [[0, 0]] for s, e, p in jobs: # bisect.insort(dp, [s + 1]) # print(dp) i = bisect.bisect(dp, [s + 1]) - 1 print(i) print(dp) if dp[i][1] + p > dp[-1][1]: dp.append([e, dp[i][1] + p]) # print(dp[-1][1]) # Solution().jobScheduling(start_time, end_time, profit)
29da0e7ab10f8c1dc2ca19f7430a276d0cf0d067
pskugit/organic-fractal-trees
/python/fractal_trees.py
2,535
4.25
4
from tkinter import * import random import math #Initialization parameters MIN_LEN = 5 STEM_SIZE = 100 WIN_WIDTH = 900 WIN_HEIGHT = 600 def branch(len, level, x, y, angle): ''' Generates and draws a new branch to the current tree. Is calles recursively to build the full tree. :param len: int specifies the length of the branch :param level: int keeps track of the level of the branch within the tree :param x: int spawn position x :param y: int spawn position y :param angle: angle of the branch relative to the tree ''' #recursion termination when branches get too small if (len > MIN_LEN): #GET BRACH PROPERTIES #length rlength = random.random() *len + len / 2 #angle rangle = random.random() * 2 * math.pi * 0.03 + 2 * math.pi * 0.03 #thickness thickness = 2*len/(level+12) #color (based on length) rgb = (30, 210 * (MIN_LEN / len), 80) #destination point x_to = x + math.sin(angle) * rlength y_to = y + math.cos(angle) * rlength #this block defines if three instead of two branches will be created and on which side the third branch will be attached ramount = random.random() * 100 rside = random.random() * 100 if (rside > 50): rside = 1 else: rside = -1 #DRAWING THE BRANCH # additional line for anti aliasing if (thickness > 1): l = c.create_line(x, y, x_to, y_to, width=thickness+0.5, fill=_from_rgb(tuple((int(v + 30) for v in rgb)))) # main line l = c.create_line(x, y, x_to, y_to, width=thickness, fill=_from_rgb(tuple((int(v) for v in rgb)))) # RECURSION # scaling factor for the next level of branches scale = 0.78 # recursive call 1 (positive angle) branch(len*scale, level+1, x_to, y_to, angle + rangle) # recursive call 2 (negative angle) branch(len * scale, level + 1, x_to, y_to, angle - rangle) # recursive call 3 (random angle) if (ramount > 60): branch(len * scale, level + 1, x_to, y_to, angle + rside*2.5*rangle) def _from_rgb(rgb): return "#%02x%02x%02x" % rgb if __name__ == '__main__': root = Tk() root.geometry('%dx%d'%(WIN_WIDTH,WIN_HEIGHT)) c = Canvas(root, width=WIN_WIDTH, height=WIN_HEIGHT, bg="white") branch(STEM_SIZE, 1, WIN_WIDTH / 2, WIN_HEIGHT, math.pi) c.pack() root.mainloop()
0c0d3ecd29026fe4facfbb0dbb8542d07e197bd9
oliviaclyde/hello-world
/practice-python/String_Lists.py
768
4.46875
4
# # Ask the user for a string and print out whether this string is a palindrome or not. # # (A palindrome is a string that reads the same forwards and backwards.) #1st way: convert to string and reverse order a = "qwertytrewq" b = str(a)[::-1] def isPalindrome(): if a == b: print("Your string is a palindrome!") else: print("Your string is NOT a palindrome!") isPalindrome() #2nd way: convert to list, reverse, join back to string and compare equality def checkPalindrome(): a = str(input("Please enter a string of letters: ")) newA = list(a) b = (newA[::-1]) (''.join(newA)) (''.join(b)) if newA == b: print("Is Palindrome!") else: print("NOT Palindrome.") checkPalindrome()
89edad569fe88f2f87e0d888be8a3a90e89c722e
JHolderguru/Eng-57-Python-basics
/LIST_BASICS.py
1,525
4.6875
5
#Lists #lists are exactly what you expect. they are lists #they are organized with index. This means starts at 0 # list can hold any data type #example #syntax #[] this bracket makes a list. my_stingy_landlords = ["Alfredo", "Betty", "Joanna", "Mr .Sumersbee", 123, True] # index [ 0 1 2 3] # neg index [ -6 -5 -4 -3 -2 -1 #printing all of the list print(my_stingy_landlords) #access on entry of the list #use the index with the list # special = my_cringy_landlords [2] # print(special) #best way is as follows print(my_stingy_landlords[2]) # #listclass # print(type(my_cringy_landlords)) # #str class because [2] is a string # print(type(my_cringy_landlords[2])) #REASSIGN my_stingy_landlords [-2] = "PAtty" print(my_stingy_landlords) my_stingy_landlords [-1] = "Hotel of mom and dad" print(my_stingy_landlords) #Remove an Entry from a list #remove hotel from list #list.pop is set to pop the -1(the last one unless you specify) my_stingy_landlords [-1] = "Hotel of mom and dad" my_stingy_landlords.pop() print(my_stingy_landlords) #add to list #Filipe to the list #list.append is set by default to append at the last entry my_stingy_landlords.append("Filipe") print(my_stingy_landlords) #remove from list #.remove(object) is set by default to remove the first item set to the value my_stingy_landlords.append("Joanna") print(my_stingy_landlords) my_stingy_landlords.remove("Joanna") print(my_stingy_landlords)
61ef893a88ea867280875ceff87a3fd416fda387
movermeyer/django-laconicurls
/laconicurls/obfuscation.py
1,206
3.84375
4
#The base27 idea comes from this guy who was using base31 to cut out vowels. #I've also removed the 4 numbers that look like vowels to prevent any unintentional calculator gags #http://jeffreypratt.net/safely-base-36-encoding-integers.html BASE27_ALPHABET = '256789BCDFGHJKLMNPQRSTVWXYZ' def base27_encode(n): """Encode a number in the unoffensive base 27 format >>> base27_encode(0) '2' >>> base27_encode(26) 'Z' >>> base27_encode(27) '52' """ if n == 0: return BASE27_ALPHABET[0] result = "" while (n > 0): result = BASE27_ALPHABET[n % len(BASE27_ALPHABET)] + result n = int(n / len(BASE27_ALPHABET)) return result def base27_decode(encoded): """Decode a number from the unoffensive base27 format >>> base27_decode('2') 0 >>> base27_decode('Z') 26 >>> base27_decode('52') 27 >>> base27_decode('ZZZZ') 531440 """ result = 0 for i in range(len(encoded)): place_value = BASE27_ALPHABET.index(encoded[i]) result += place_value * (len(BASE27_ALPHABET) ** (len(encoded) - i - 1)) return result if __name__ == "__main__": import doctest doctest.testmod()
84174ba5f3f4395db99c4f48a6da2a9e016b487e
chusehwan/python
/Part1/test_cities.py
434
3.546875
4
import unittest from chapter_11_2 import city_functions class test_city_country(unittest.TestCase): def test_full_loc_name(self): message = city_functions('santiago', 'chile',123000) self.assertEqual(message, 'santiago chile - 123000') def test_full_loc_pop_name(self): message = city_functions('santiago', 'chile',123000) self.assertEqual(message, 'santiago chile - 123000') unittest.main()
8c91c5ea7456e46d50569472af4ebb05c72b7427
andrew-yt-wong/ITP115
/ITP 115 .py/Labs/ITP115_L5_1_Wong_Andrew.py
3,760
3.828125
4
# Andrew Wong, awong827@usc.edu # ITP 115, Spring 2020 # Lab 5-1 import random def main(): quitProgram = False articles = ['a', 'the'] nouns = ['person', 'place', 'thing'] verbs = ['danced', 'ate', 'frolicked'] while not quitProgram: print("\tWelcome to the Sentence Generator\n\tMenu") print("\t1) View Words\n\t2) Add Words\n\t3) Remove Words") print("\t4) Generate Sentence\n\t5) Exit\n") option = input("> ") if option.isdigit(): optionInt = int(option) if optionInt == 1: print("articles: [", end="") for word in articles: print("\'" + word + "\'", end="") if word != articles[len(articles) - 1]: print(", ", end="") print("]\nnouns: [", end="") for word in nouns: print("\'" + word + "\'", end="") if word != nouns[len(nouns) - 1]: print(", ", end="") print("]\nverbs: [", end="") for word in verbs: print("\'" + word + "\'", end="") if word != verbs[len(verbs) - 1]: print(", ", end="") print("]\n") elif optionInt == 2: validOption = False while not validOption: newAdd = input("Enter 1) for nouns or 2) for verbs: ") if newAdd.isdigit(): newAddInt = int(newAdd) if newAddInt == 1: nouns.append(input("Enter the word: ")) validOption = True print("") elif newAddInt == 2: verbs.append(input("Enter the word: ")) validOption = True print("") else: print("Invalid Choice.\n") else: print("Invalid Choice.\n") elif optionInt == 3: validOption = False while not validOption: newRemove = input("Enter 1) for nouns or 2) for verbs: ") if newRemove.isdigit(): newRemoveInt = int(newRemove) removeWord = input("Enter the word: ") if newRemoveInt == 1: if removeWord in nouns: nouns.remove(removeWord) else: print("word not in list") validOption = True print("") elif newRemoveInt == 2: if removeWord in verbs: verbs.remove(removeWord) else: print("word not in list") validOption = True print("") else: print("Invalid Choice.\n") else: print("Invalid Choice.\n") elif optionInt == 4: print(random.choice(articles), random.choice(nouns), random.choice(verbs), random.choice(articles), random.choice(nouns), "\n") elif optionInt == 5: print("Program will exit\nHave a great day!") quitProgram = True else: print("Invalid Choice.\n") else: print("Invalid Choice.\n") main()
e1a590b11e1d580695f648e3e1afa89c4477b966
shhuan/algorithms
/py/topcoder/TCCC 2003 Semifinals 2/TelephoneGame.py
4,432
3.515625
4
# -*- coding: utf-8 -*- import math,string,itertools,fractions,heapq,collections,re,array,bisect class TelephoneGame: def howMany(self, connect1, connect2, numPeople): """ 分成两组,使得相交的区间最少 :param connect1: :param connect2: :param numPeople: :return: """ connections = [(connect1[i], connect2[i]) for i in range(len(connect1))] collections = sorted(connections, key=lambda x: x[0]) print(connections) crosses = [connections[0]] for i in range(1, connections): if self.crosses(crosses[-1], connections[i], numPeople): crosses.append(connections[i]) connections = [crosses[0]] res = 0 for i in range(1, crosses): if self.cross(connections[-1], crosses[i], numPeople): res += 1 else: connections.append(crosses[i]) return res def cross(self, connection1, connection2, numPeople): if connection1[0] > connection2[0]: connection1, connection2 = connection2, connection1 l1, r1 = connection1 l2, r2 = connection2 if l1 < l2 < r1 < r2: return True return False return 0 # CUT begin # TEST CODE FOR PYTHON {{{ import sys, time, math def tc_equal(expected, received): try: _t = type(expected) received = _t(received) if _t == list or _t == tuple: if len(expected) != len(received): return False return all(tc_equal(e, r) for (e, r) in zip(expected, received)) elif _t == float: eps = 1e-9 d = abs(received - expected) return not math.isnan(received) and not math.isnan(expected) and d <= eps * max(1.0, abs(expected)) else: return expected == received except: return False def pretty_str(x): if type(x) == str: return '"%s"' % x elif type(x) == tuple: return '(%s)' % (','.join( (pretty_str(y) for y in x) ) ) else: return str(x) def do_test(connect1, connect2, numPeople, __expected): startTime = time.time() instance = TelephoneGame() exception = None try: __result = instance.howMany(connect1, connect2, numPeople); except: import traceback exception = traceback.format_exc() elapsed = time.time() - startTime # in sec if exception is not None: sys.stdout.write("RUNTIME ERROR: \n") sys.stdout.write(exception + "\n") return 0 if tc_equal(__expected, __result): sys.stdout.write("PASSED! " + ("(%.3f seconds)" % elapsed) + "\n") return 1 else: sys.stdout.write("FAILED! " + ("(%.3f seconds)" % elapsed) + "\n") sys.stdout.write(" Expected: " + pretty_str(__expected) + "\n") sys.stdout.write(" Received: " + pretty_str(__result) + "\n") return 0 def run_tests(): sys.stdout.write("TelephoneGame (1050 Points)\n\n") passed = cases = 0 case_set = set() for arg in sys.argv[1:]: case_set.add(int(arg)) with open("TelephoneGame.sample", "r") as f: while True: label = f.readline() if not label.startswith("--"): break connect1 = [] for i in range(0, int(f.readline())): connect1.append(int(f.readline().rstrip())) connect1 = tuple(connect1) connect2 = [] for i in range(0, int(f.readline())): connect2.append(int(f.readline().rstrip())) connect2 = tuple(connect2) numPeople = int(f.readline().rstrip()) f.readline() __answer = int(f.readline().rstrip()) cases += 1 if len(case_set) > 0 and (cases - 1) in case_set: continue sys.stdout.write(" Testcase #%d ... " % (cases - 1)) passed += do_test(connect1, connect2, numPeople, __answer) sys.stdout.write("\nPassed : %d / %d cases\n" % (passed, cases)) T = time.time() - 1430752249 PT, TT = (T / 60.0, 75.0) points = 1050 * (0.3 + (0.7 * TT * TT) / (10.0 * PT * PT + TT * TT)) sys.stdout.write("Time : %d minutes %d secs\n" % (int(T/60), T%60)) sys.stdout.write("Score : %.2f points\n" % points) if __name__ == '__main__': run_tests() # }}} # CUT end
eb19b715a50c6241f907c6075dfb445c7d0701ae
mnipshagen/monty
/2018/10/Solution/final_countdown.py
1,629
4.0625
4
""" This module starts a countdown with a really dramatic ending. Viewer discretion is advised Uses the time and webbrowser modules. """ import time import webbrowser class NegativeError(Exception): """ Just some error to avoid counting down from negative numbers. """ pass def countdown(seconds): """ Counts down from seconds to 0, then becomes really dramatic. Args: seconds: second number to count down from """ print("\nBRACE YOURSELF!\n") # you really should # countdown function while seconds > 0: # print time left print(seconds, "%s left!" %("seconds" if seconds > 1 else "second")) time.sleep(1) # pause seconds -= 1 # one more second passed print("\nAND BOOOOOM!") webbrowser.open('https://www.youtube.com/watch?v=DLzxrzFCyOs') def countdown_starter(): """ Gets a user input, checks for validity, then starts the countdown. """ valid = False while not valid: try: # try casting to int seconds = int(input("Please enter the seconds to count down: ")) # cannot count down properly from a negative number if seconds <= 0: raise NegativeError() # input was valid, so we can start the countdown and leave the loop valid = True countdown(seconds) except ValueError: # non-integer inputs produce ValueErrors print("Please type in only integer numbers!") except NegativeError: print("Please type in only positive numbers!") # start main function countdown_starter()
3b6ec3fc0a486dc5227ad77a210150ad0e96e31d
selutin99/econometrica
/core/base_functions.py
2,434
3.640625
4
import core.checker as ch def range(data): """ Find range of data list :param data: list of int or float values :return: max value of list minus min value of list """ if ch.check_list(data): return max(data) - min(data) def capacity(data): """ Find length of list :param data: list of int or float values :return: list length """ if ch.check_list(data): return len(data) def mode(data): """ Calculate most common use element in list :param data: list of int or float values :return: mode of list """ if ch.check_list(data): most = max(list(map(data.count, data))) return list(set(filter(lambda x: data.count(x) == most, data))) def median(data): """ Calculate median of data list :param data: list of int or float values :return: median """ if ch.check_list(data): data.sort() print(data) if len(data) % 2 != 0: return data[len(data) // 2] else: return (data[(len(data) // 2) - 1] + data[len(data) // 2]) / 2 def frequency(data): """ Find frequencies of list :param data: list of int or float values :return: list with dictionary of frequencies and sum of frequencies """ if (ch.check_list(data) == True): return [{x: data.count(x) for x in data}, len(data)] def quartile(data): """ Find Q1 and Q3 :param data: list of int or float values :return: dictionary with quartiles """ if ch.check_list(data): data.sort() if len(data) == 2: return {'q1': data[0], 'q3': data[1]} h = (len(data) + 1) // 4 if len(data) % 2 == 0: q1 = (data[h - 1] + data[h]) / 2 else: q1 = data[h - 1] h = 3 * (len(data) + 1) // 4 if len(data) % 2 == 0: q3 = (data[h - 1] + data[h]) / 2 else: q3 = data[h - 1] return {'q1': q1, 'q3': q3} def expected_value(x, p): """ Find expected value of 2 datasets :param x: list of int or float values :param p: list of float values :return: value of expected value """ if ch.check_list(x) and ch.check_list(p): if ch.check_equality(x, p): if ch.check_probability(p): m = 0 for xi, pi in zip(x, p): m += xi * pi return m
79f30ebe02801e5a6e8a98b08aeaa53dde72a1a9
balaramhub1/Python_Test
/String Formatting/strtest_01.py
245
3.84375
4
''' Created on Apr 28, 2014 @author: ROCKSTAR ''' from datetime import datetime fname="balaram" sname="behera" print(fname,"is my name",sname,"is my surname") print("hello {}, your age is {}".format(fname,sname)) print(datetime.now())
59b5cbd3981729c24fb9aa2f3f32174d78e5b843
TrickFF/helloworld
/type_str.py
2,502
4.21875
4
friend = 'Максим Макс' print(friend) print(type(friend)) say = 'Всем "двинутым" привет!' print(say) # Из строки можно получить символ по индексу = [переменная][индекс]. Индекс начинается с 0 first_letter = friend[0] print('Первая буква имени друга - ', first_letter) # индекс [-1] - адрес последней буквы строки last_letter = friend[-1] print('Последняя буква имени друга - ', last_letter) # Срезы - часть строки. [переменная][start:end] # start - начальный индекс, end - кол-во смволов вправо # [переменная][:end] - срез с начала строки # [переменная][1:] - срез до конца строки short_name = friend[:4] short_name2 = friend[3:] print('Обычно его называют - ', short_name) print('но иногда и - ', short_name2) # len(переменная) - определяет длину строки a = len(friend) print('Количество букв в имени друга - ', a) # len(переменная) - определяет длину строки # [переменная].find('[символ]') - поиск символов в строке # [переменная].split() - разбиение строки через пробел. Если несколько слов через пробел, то делится на несколько строк # В качестве разделителя можно указывать и другие символы, например, [переменная].split(';') # [переменная].isdigit() - проверка состоит ли строка из одних чисел # [переменная].upper() - приведение строки к верхнему регистру # [переменная].lower() - приведение строки к нижнему регистру print() print('Есть ли в имени друга буква к, какой у нее индекс? ', friend.find('кс')) print('Разделим его имя пробелом ', friend.split()) print('Имя друга состоит из цифр? ', friend.isdigit()) print('Имя друга буквами верхнего регистра - ', friend.upper()) print('Имя друга буквами нижнего регистра - ', friend.lower())
b59c11ab8b66839c2010bf88a1b7130da307405f
CircleZ3791117/CodingPractice
/source_code/627_SwapSalary.py
1,810
3.734375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'circlezhou' ''' Description: Given a table salary, such as the one below, that has m=male and f=female values. Swap all f and m values (i.e., change all f values to m and vice versa) with a single update query and no intermediate temp table. For example: | id | name | sex | salary | |----|------|-----|--------| | 1 | A | m | 2500 | | 2 | B | f | 1500 | | 3 | C | m | 5500 | | 4 | D | f | 500 | After running your query, the above salary table should have the following rows: | id | name | sex | salary | |----|------|-----|--------| | 1 | A | f | 2500 | | 2 | B | m | 1500 | | 3 | C | f | 5500 | | 4 | D | m | 500 | ''' ''' Solution: UPDATE table SET column = ... CASE [WHEN ... THEN ...] ELSE ... END caution: equal -> = not == ''' def getSQLStatement(): sql_str = "UPDATE salary SET sex=(CASE WHEN (sex='m') THEN 'f' WHEN (sex='f') THEN 'm' ELSE sex END)" # wrong: sql_str = "UPDATE salary SET sex=(CASE WHEN (sex=='m') THEN 'f' WHEN (sex=='f') THEN 'm' ELSE sex END)" return sql_str ''' Better Solution ''' # 1. CASE [WHEN ... THEN ...] ELSE ... END # This method is faster than the other two methods def get getSQLStatement(): sql_str = "UPDATE salary SET sex= CASE WHEN sex='m' THEN 'f' ELSE 'm' END" return sql_str # 2. IF(condion, y, n) def get getSQLStatement(): sql_str = "UPDATE salary SET sex= IF(sex='m', 'f', 'm')" return sql_str # 3. use XOR to exchange two value # you can use XOR to exchange two values in nearly all cases # For example: # a = 1, b = 0 . You can switch value like this: # b = a ^ b => b = 1 # a = a ^ b => a = 0 def get getSQLStatement(): sql_str = "UPDATE salary SET sex= CHAR(ASCII('m') ^ ASCII('f') ^ ASCII(sex))" return sql_str
789f820b0a17736c93207d544bd42139b61fb246
mkiterian/word_count
/counting.py
195
3.96875
4
def words(string): the_words = string.split() the_words = [int(word) if word.isdecimal() else word for word in the_words] return {word: the_words.count(word) for word in the_words}
30b7a4d0425a26e0b471c7df17545830e84b6dd1
yeboahd24/python202
/Design Pattern/document.py
720
3.953125
4
#!usr/bin/env/python3 class Document: def __init__(self): self.characters = [] self.cursor = 0 self.filename = '' def insert(self, character): self.characters.insert(self.cursor, character) self.cursor += 1 def delete(self): del self.characters[self.cursor] def save(self): with open(self.filename, 'w') as f: f.write(''.join(self.characters)) def forward(self): self.cursor += 1 def back(self): self.cursor -= 1 doc = Document() doc.filename = "test_document" doc.insert('h') doc.insert('e') doc.insert('l') doc.insert('l') doc.insert('o') print("".join(doc.characters)) doc.back() doc.delete() doc.insert('p') print("".join(doc.characters))
c165c320edd793b406d12a6aef953c827a311557
andrealmar/learn-python-the-hard-way
/ex3/ex3.py
1,014
4.4375
4
# just print the phrase between parenthesis print "I will not count my chickens" # print Hens and do a little math of 25 + (30 / 6) = 30 print "Hens", 25.0 + 30.0 / 6.0 # print Roosters and the math: 100 - ()(25 * 3) % 4) print "Roosters", 100.0 - 25.0 * 3.0 % 4.0 # print the statement below print "Now I will count the eggs:" # math print 3.0 + 2.0 + 1.0 - 5.0 + 4.0 % 2.0 - 1.0 / 4.0 + 6.0 # print the statement below print "Is it true that 3 + 2 < 5 - 7?" # more math but here Python interpreter will output False print 3.0 + 2.0 < 5.0 - 7.0 # output the statement + the math print "What is 3 + 2?", 3.0 + 2.0 # output the statement + the math print "What is 5 - 7?", 5.0 - 7.0 # output the statement print "Oh, that's why it's False." # output the statement print "How about some more." # output the statement + True print "Is it greater?", 5.0 > -2.0 # output the statement + True print "Is it greater or equal?", 5.0 >= -2.0 # output the statement + False print "Is it less or equal?", 5.0 <= -2.0
ae7827b4b2ac0d954ff0072728456d4ee53a5c88
Ing-Josef-Klotzner/python
/2017/hackerrank/compare_the_triplets.py
2,105
3.875
4
#!/usr/bin/python3 import os import sys # # Complete the solve function below. # def solve(a0, a1, a2, b0, b1, b2): al = 0 bob = 0 if a0 > b0: al += 1 if a1 > b1: al += 1 if a2 > b2: al += 1 if a0 < b0: bob += 1 if a1 < b1: bob += 1 if a2 < b2: bob += 1 return str(al) + " " + str(bob) if __name__ == '__main__': # f = open(os.environ['OUTPUT_PATH'], 'w') a0A1A2 = input().split() a0 = int(a0A1A2[0]) a1 = int(a0A1A2[1]) a2 = int(a0A1A2[2]) b0B1B2 = input().split() b0 = int(b0B1B2[0]) b1 = int(b0B1B2[1]) b2 = int(b0B1B2[2]) result = solve(a0, a1, a2, b0, b1, b2) # f.write(' '.join(map(str, result))) # f.write('\n') # f.close() print(result) #Alice and Bob each created one problem for HackerRank. A reviewer rates the two challenges, awarding points on a scale from 1 to 100 for three categories: problem clarity, originality, and difficulty. #We define the rating for Alice's challenge to be the triplet A, and the rating for Bob's challenge to be the triplet B. #Your task is to find their comparison points by comparing a[0] with b[0], a[1] with b[1], and a[2] with b[2]. #If a[i] > b[i], then Alice is awarded 1 point. #If a[i] < b[i], then Bob is awarded 1 point. #If a[i] = b[i], then neither person receives a point. #Comparison points is the total points a person earned. #Given A and B, can you compare the two challenges and print their respective comparison points? #Input Format #The first line contains space-separated integers, , , and , describing the respective values in triplet . #The second line contains space-separated integers, , , and , describing the respective values in triplet . #Constraints #1 <= a[i] <= 100 #1 <= b[i] <= 100 #Output Format #Print two space-separated integers denoting the respective comparison points earned by Alice and Bob. #Sample Input #5 6 7 #3 6 10 #Sample Output #1 1 #Alice's comparison score is 1, and Bob's comparison score is 1. Thus, we print 1 1 (Alice's comparison score followed by Bob's comparison score) on a single line.
7268c213ec43f96e7bf661529ca632f39adec473
memsql/memsql-loader
/memsql_loader/util/attr_dict.py
817
3.53125
4
class AttrDict(dict): def __getattr__(self, key): try: return self.__getitem__(key) except KeyError: # This lets you use dict-type attributes that aren't keys return getattr(super(AttrDict, self), key) def __setattr__(self, key, value): return self.__setitem__(key, value) def __str__(self): return self.__repr__() def __repr__(self): return '%s(%s)' % (self.__class__.__name__, dict.__repr__(self)) @staticmethod def from_dict(source): def _transform(d): """ Turns a nested dict into nested AttrDict's """ for k, v in d.iteritems(): if isinstance(v, dict): d[k] = _transform(v) return AttrDict(d) return _transform(source)
b1ed530bc19418c2c73b66820b86cb3ea5a200a8
Ubastic/coding-challenges
/leetcode/solutions/easy/hamming-distance/solution.py
241
3.6875
4
class Solution: def hammingDistance(self, x: int, y: int) -> int: diff = 0 while x or y: x, f = divmod(x, 2) y, s = divmod(y, 2) diff += f != s return diff
1bcbcadd32851565b62afd40201969cbde88ffa1
k-schmidt/Coding_Problems
/code_rust/binary_search.py
883
4.03125
4
""" Binary Search """ def binary_search_recur(array, key, low, high): if low > high: return -1 mid = low + ((high - low) // 2) if array[mid] == key: return mid elif key < array[mid]: return binary_search_recur(array, key, low, mid - 1) else: return binary_search_recur(array, key, mid + 1, high) def binary_search(array, key): return binary_search_recur(array, key, 0, len(array) - 1) def binary_search_iter(array, key): low = 0 high = len(array) while low <= high: mid = low + ((high - low) // 2) if array[mid] == key: return mid elif key < array[mid]: high = mid - 1 else: low = mid + 1 return -1 # Not found if __name__ == '__main__': a = [1, 2, 3, 4, 5, 6] print(binary_search(a, 5)) print(binary_search_iter(a, 5))
44cd53b72e5c8e2e3c50385c439689a3b52989a5
ivan-yosifov88/python_basics
/Nested Loops - Lab/05. Travelling.py
281
3.96875
4
command = input() while command != "End": budget = float(input()) total_save_money = 0 while total_save_money < budget: save_money = float(input()) total_save_money += save_money else: print(f"Going to {command}!") command = input()
230fe2159e5862b0d6fafac53f5684886d3fe3e3
HaymanLiron/46_python_exercises
/q18.py
432
4.125
4
def is_pangram(string): # checks if string contains all letters of alphabet at least once # capitalization is not important string = string.lower() letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w','x', 'y', 'z'] for _ in string: if _ in letters: letters.remove(_) return False if letters else True
776fcc6cab9bb156cb266eb43e8d00113bb39075
elsandkls/SNHU_IT140_itty_bitties
/banking_transactions.py
7,149
3.515625
4
# Get the filepath from the command line import sys import re #import variables F1= sys.argv[1] F2= sys.argv[2] #print(F1,"\n",F2) #Read Files in. #___________ functions _____________ #open files def openMyFiles(FileName): myFile = open(FileName, 'r') FileContent = myFile.read() myFile.close() return(FileContent) #print("--------------\n\n") # #write file def writeMyFiles(FileName, FileContent): myFile = open(FileName, 'w') myFile.write(FileContent) myFile.close() #print("--------------\n\n") # def load2dArrayFromFileData(FileContent): records = [] #define the expected end of record delimiter row_delimiter= '\n' #check to see how many lines exist. line_count = len(re.findall(row_delimiter,FileContent)) #parse the file by line into a list record_row = re.split(row_delimiter, FileContent) #print(line_count,": full list\n", record_row, "\n") #next we need to parse each line into it's seperate column entries #define your column delimiter # interestingly "|" causes findall to return null character positions for each character in the string. # "\|" returns the delimiter. column_delimiter= "\|" #check to see how many columns there are, remember it's the number plus 1 i=0 #test with the first row (0) column_count = len(re.findall(column_delimiter,record_row[i])) #print("first record list\n", record_row[i], "\n Delimiters counted: ", column_count, "\n") #loop through the rows parsing the columns up. for i in range(0,line_count,1): list_of_columns= re.split(column_delimiter,record_row[i]) #print(i," ", str(list_of_columns)) #add column list to records list, to return to program records.append(list_of_columns) #print(records) return(records) #----------- next function ---------------- def securityCheck(account_number,account_pin,FileContent): security_check = int(0) account_selected = int(0) #print("securityCheck") #print(len(FileContent)) #print(FileContent) for a in range(0,len(FileContent),1): # ACCOUNT NUMBER | PIN CODE | BALANCE #print(a, " ", account_number, "", account_pin, "", FileContent[a]) if account_number == FileContent[a][0]: # check pin if account_pin == FileContent[a][1]: security_check = 1 account_selected = a #print("Confirmed \n") #print("--------------\n\n") return(security_check, account_selected) #----------- next function ---------------- def balanceCheck(account_number,account_pin,FileContent): #print("balanceCheck") balance_start = 0 # ACCOUNT NUMBER | PIN CODE | BALANCE #print(account_number,"",account_pin,"",FileContent) if account_number == FileContent[0]: # check pin if account_pin == FileContent[1]: #pull balance balance_start = FileContent[2] #print("--------------\n\n") return(balance_start) #----------- next function ---------------- def balanceAddition(account_number, account_pin, amount_change, FileContent): #print("balanceAddition") # ACCOUNT NUMBER | PIN CODE | BALANCE #print(account_number,"",account_pin,"",FileContent) if account_number == FileContent[0]: # check pin if account_pin == FileContent[1]: #pull balance current_balance = int(FileContent[2]) amount_change = int(amount_change) FileContent[2] = current_balance + amount_change #print("Deposit Completed!\n Current Balance: ",FileContent[2]) #print("--------------\n\n") #----------- next function ---------------- def balanceSubtraction(account_number, account_pin, amount_change, FileContent): #print("balanceSubtraction") # ACCOUNT NUMBER | PIN CODE | BALANCE #print(account_number,"",account_pin,"",FileContent) if account_number == FileContent[0]: # check pin if account_pin == FileContent[1]: #pull balance current_balance = int(FileContent[2]) amount_change = int(amount_change) if current_balance >= amount_change : FileContent[2] = current_balance - amount_change else: #print("Insufficient Funds!") boo = 0 #print("Withdrawal Completed!\n Current Balance: ",FileContent[2]) #print("--------------\n\n") #----------- next function ---------------- def GenrateFiletoExport(ClientList): # Generate the string to export back out to the file. # ACCOUNT NUMBER | PIN CODE | BALANCE #print(ClientList) FileContent = str("") FileRow = str("") row_delimiter= '\n' column_delimiter= "|" line_count = len(ClientList) #print("--------------\n\n") for r in range(0,line_count,1): column_count = len(ClientList[r]) FileRow = "" for c in range(0,column_count,1): #print(r,":",c,":",column_count,":",ClientList[r][c]) if c < (column_count-1): FileRow = FileRow + str(ClientList[r][c]) + column_delimiter else: FileRow = FileRow + str(ClientList[r][c]) #print(FileRow) FileContent = FileContent + FileRow + row_delimiter #print("--------------\n\n") #print(FileContent) return(FileContent) #----------- end function ---------------- # Begin Program FileContent1 = openMyFiles(F1) # Let's look at the contents # ACCOUNT NUMBER | PIN CODE | BALANCE #print(FileContent1) FileContent1_list = load2dArrayFromFileData(FileContent1) #print(FileContent1_list) #print("--------------\n\n") FileContent2 = openMyFiles(F2) # Let's look at the contents # 0 1 2 3 # COMMAND | AMOUNT | ACCOUNT NUMBER | PIN CODE #print(FileContent2) FileContent2_list = load2dArrayFromFileData(FileContent2) #print(FileContent2_list) #print("--------------\n\n") # Begin Automated Sequence # ##COMMAND will be either add or sub for i in range(0, len(FileContent2_list),1): secure = int(0) acc = int(999) # make these variables more human readable. command_code = FileContent2_list[i][0] amount = FileContent2_list[i][1] account_num = FileContent2_list[i][2] # Account Number pin_code = FileContent2_list[i][3] # Pin Code # process command code if command_code == "add": # If the command is add, you will add to balance secure,acc = securityCheck(account_num,pin_code,FileContent1_list) if secure == 1: balanceCheck(account_num,pin_code,FileContent1_list[acc]) balanceAddition(account_num,pin_code,amount, FileContent1_list[acc]) elif command_code == "sub": # If the command is sub, you will subtract from balance. secure,acc = securityCheck(account_num,pin_code,FileContent1_list) if secure == 1: balanceCheck(account_num,pin_code,FileContent1_list[acc]) balanceSubtraction(account_num,pin_code,amount, FileContent1_list[acc]) else: #print("--------------\n\n") #print("Exit Program") #print("--------------\n\n") boo = 0 FileContent = GenrateFiletoExport(FileContent1_list) writeMyFiles(F1, FileContent) # # Starting with BALANCE in the account files # If you are asked to subtract an amount that would put the account below zero # if the pin code you are provided does not match the pin code in the account record, the transaction is ignored.
4cc2d8833ddfbdd5b9924b7a4350cc1576ac12fa
connormclaud/euler
/python/Problem 024/solution.py
1,144
3.515625
4
#!/usr/bin/python # -*- coding: utf-8 -*- # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # Task description: # Find 3 millionth permutation of all digits in lexographic order # Solution: # one liner in python as itertools.permutations # alredy produce it in lexographic order from itertools import permutations, islice answer = [ "".join(item) for item in islice( permutations('0123456789'), 3000000, 3000001)][0] print('3 millionth permutation of all digits is', answer) #
72b205cff44cd1ad0ba0eda13807aac97e581add
metheoryt/itstep-python
/1_intro/c_logical_ops.py
1,339
4.09375
4
""" Логические операции Операции, возвращащие в качестве результата булево значение - True/False """ # Приведение к bool assert bool(0) is False assert bool('') is False assert bool([]) is False assert bool(None) is False assert bool(-1) is True assert bool('a') is True assert bool([1]) is True # Сравнение assert 2 > 1 is True assert 2 < 1 is False assert 2 == 2 is True assert 2 != 2 is False assert 3 >= 3 is True assert 3 <= 4 is False # составные выражения с помощью and-or-not # https://docs.python.org/3/reference/expressions.html#operator-precedence assert not 1 == 0 # not инвертирует значение assert 2 == 2 and 3 != 2 # and вернёт True если оба операнда True (иначе False) assert 2 == 2 or 3 == 2 # or вернёт True если хотя бы один операнд True (иначе False) # is - вернёт True если оба операнда - один и тот же объект assert 1 is 1 # in - вернёт True если операнд слева входит в операнд справа (обычно это коллекция) assert 'black' in ['red', 'green', 'black'] assert 'black' in 'the black cat' # так тоже можно
e139015faf7aa0cb28b05d618e6e945d7dd544d0
rk385/tathastu_week_of_code
/Day1/program4.py
152
3.765625
4
CP=int(input("enter the cost price:")) SP=int(input("enter the selling price")) Profit=SP-CP print("profit is:",Profit) SP=CP+(Profit*(1.05)) print(SP)
bec7379c510dfef2aba44341f8862ba03b4cf34d
JackNoordhuis/SDD
/Prelim/Tasks/Week #4/Sausages in a Can.py
217
3.953125
4
##################### # Sausages in a Can # ##################### rows = eval(input("Rows: ")) loops = 0 while loops < rows: loops += 1 print("Row " + str(loops) + ": " + str((3 * loops * (loops - 1) + 1)))
a8b20c6e001500fc4a83223e089a9e5773ac2d02
TrisAXJ/py-study
/demo2/demo2.py
5,023
4.03125
4
# -*- codeing = utf-8 -*- # @Author:TRISA QQ:1628791325 trisanima.cn # @Time : 1/12/2021 5:38 PM # @File : demo2.py # @Software: PyCharm # namelist = ["小张", "小王", "小李"] ''' #namelist = [] #定义一个空的列表 namelist = ["小张", "小王", "小李"] testlist = [1, "测试"] # 列表中可以存储混合类型 print(type(testlist[0])) print(type(testlist[1])) print(namelist[0]) print(namelist[1]) print(namelist[2]) ''' ''' for name in namelist: print(name) #print(len(namelist)) # len()可以得到列表长度 length = len(namelist) i = 0 while i<length: print(namelist[i]) i += 1 ''' # print(namelist[0:2:1]) # 增: 【append】 # 在末尾追加一个元素作为整体 ''' print("----增加前名单列表数据----") for name in namelist: print(name) nametemp = input("请输入添加学生的姓名:") namelist.append(nametemp) # 在末尾追加一个元素 print("----增加后名单列表数据----") for name in namelist: print(name) ''' # 增: 【extend】 # 逐一追加列表 ''' a = [1,2] b = [3,4] a.append(b) # 当列表当作一个元素,加入到a列表中 print(a) # [1,2,[3,4]] 列表嵌套 a.extend(b) # 将b列表中的每个元素,逐一追加到a列表中 print(a) ''' # 增: 【insert】 # 指定下标位置插入元素 ''' a = [0,1,2] a.insert(1,3) # 第一个变量表示下标,第二个表示元素(对象) print(a) # 【0,3,1,2】 ''' # 删: 【del】,【 ''' movieName = ["加勒比海盗","黑客帝国","第一滴血","指环王","速度与激情","指环王"] print("----删除前电影列表数据----") for name in movieName: print(name) #del movieName[2] # 在指定位置删除一个元素 #movieName.pop() # 弹出末尾最后一个元素 #movieName.remove("指环王") # 直接删除指定内容的元素(重复只会删除第一个) print("----删除后电影列表数据----") for name in movieName: print(name) ''' # 改: 【 ''' print("----修改前名单列表数据----") for name in namelist: print(name) namelist[1] = "小红" # 修改指定下标的元素内容 print("----修改后名单列表数据----") for name in namelist: print(name) ''' # 查: 【in, not in】 ''' findName = input("请输入你要查找的学生姓名:") if findName in namelist: print("找到了相同名字") else: print("没有找到") ''' # index索引 mylist = ["a","b","c","a","b"] ''' print(mylist.index("a",1,4)) # 可以查找指定下标范围的元素,并返回找到对应数据的下标 print(mylist.index("a",1,3)) # 范围区间,左闭右开 [1,3) # 找不到会报错 ''' # count统计 ''' print(mylist.count("c")) # 统计某个元素出现次数 ''' # 排序和反转 ''' a = [1,4,2,3] print(a) a.reverse() # 将列表所有元素反转 print(a) a.sort() # 排序升序 print(a) a.sort(reverse=True)# 排序降序 print(a) ''' # 嵌套 #schoolNames = [[],[],[]] # 有三个元素的空列表,每个元素都是一个空列表 ''' schoolName = [["北京大学","清华大学"],["南开大学","天津大学","天津大学"],["山东大学","中国海洋大学"]] print(schoolName[0][0]) ''' ################################### # 综合练习:8个老师 3个办公室随机分配 ''' import random offices = [[],[],[]] names = ["a","b","c","d","e","f","g","h"] for name in names: index = random.randint(0,2) offices[index].append(name) i = 1 for office in offices: print("办公室%d 的人数为:%d"%(i,len(office))) i += 1 for name in office: print("%s"%name,end="\t") print("\n") print("-"*20) ''' ###################################################### # 课后作业 products = [["iphone",6888],["MacPro",14800],["小米5",2499],["Coffee",31],["Book",60],["Nike",699]] print("-"*6 + " 商品列表 " + "-"*6) i = 0 for product in products: products[i].insert(0, i) for name in product: print("%s" % name, end="\t") i += 1 print("\n", end="") buy = [] for i in range(100): num = input("请输入要加入购物车的产品序号:") if num.isdigit(): num = int(num) if num < 0 or num > len(products)-1: print("输入有误,请重新输入") continue else: buy.append(num) elif num.isalpha() and num == "q": break else: print("输入有误,请重新输入") continue buy.sort() print("-"*6 + "购物车中的商品" + "-"*6) price = 0 i = 0 for thing in buy: i = 0 for product in products: if product[0] == int(thing): for name in product: print("%s" % name,end="\t") print("\n",end="") price += products[i][2] i += 1 print("商品总价是:%d" % price)
553186729974dfaff8398beaca45f2845bf8da60
SejalChourasia/python-assignment
/python assignment11/Module4/Question-06/flatter_list.py
265
3.671875
4
l=[[int(i) for i in range(10)]for j in range(10)] print('Unflattened list',l) flatten=[i for sublist in l for i in sublist if i<5] ''' for sublist in l: for i in sublist: flatten.append(i) ''' print('flattened list with less than 5 ',flatten)
d4c067a8e6a72107f7668d2686188e516433a409
shivapk/Programming-Leetcode
/Python/Misc/topological.py
881
3.796875
4
from collections import defaultdict class Graph: def __init__(self,vertices): self.graph = defaultdict(list) self.v = vertices def addEdge(self,u,v): self.graph[u].append(v) def dfs(self): visited=[False]*(self.v) sorted=[] for s in range(self.v): if visited[s]==False: self.relax(s,visited,sorted) print (sorted) def relax(self,s,visited,sorted): visited[s]=True print (s) for v in (self.graph[s]): if visited[v]==False: self.relax(v,visited,sorted) sorted.insert(0,s) g= Graph(6) g.addEdge(5, 2); g.addEdge(5, 0); g.addEdge(4, 0); g.addEdge(4, 1); g.addEdge(2, 3); g.addEdge(3, 1); print ("Following is a Topological Sort of the given graph") g.dfs()
72d52d2f755abbb7bcdd69bb91a17d48c7d736ec
chng3/Python_work
/第十章练习题/learning_C.py
149
3.640625
4
# 10-2 C语言学习笔记 filename = 'learning_python.txt' with open(filename) as f: contents = f.read().replace('Python', 'C') print(contents)
4fd851c1de50c0cd836c3331f18bbcaec065146a
ChristinaROK/TIC
/20210506.py
865
3.90625
4
# Programmers 오픈채팅방 level-2 def solution(record): id2name = {} res = [] for history in record: h_list = history.split() if h_list[0] in ["Enter","Change"]: id2name[h_list[1]]=h_list[-1] if h_list[0] == "Enter": res.append(f"{h_list[1]},님이 들어왔습니다.") elif h_list[0] == "Leave": res.append(f"{h_list[1]},님이 나갔습니다.") answer = [id2name[txt.split(",")[0]]+txt.split(",")[1] for txt in res ] return answer # 통과! # shortest def solution(record): id2name = {r.split()[1] : r.split()[-1] for r in record if r.split()[0] != "Leave"} return [f"{id2name[r.split()[1]]}님이 들어왔습니다." if r.split()[0] == "Enter" else f"{id2name[r.split()[1]]}님이 들어왔습니다." for r in record if r.split()[0]!= "Change"]
377c7554b950594435546456d978f2b999cfd882
afcarl/word_sampling
/main.py
2,149
3.75
4
#! /usr/bin/env python # Main file to be executed from the command line import sys import re from alias_method import AliasMethod def initialize_sampler(file_path): """ Load the corpus in the given file_path, count al the words, and create a sampler to sample the words from the distribution of word occurences in the corpus. :param file_path: File path name string where the corpus to be loaded can be found :return An alias method sampler to sample random words """ # Define a regex to split the input into word tokens word_tokenize_regex = r'(\w+)' regex_pattern = re.compile(word_tokenize_regex) # Define the dictionary that is used to count the words count_dict = dict() # Open the file and read line by line with open(file_path) as f: for line in f: # Extract all words in the current line result = regex_pattern.findall(line.lower()) # Update the count dictionary for word in result: if word in count_dict: count_dict[word] += 1 else: count_dict[word] = 1 # Extract all the (word, count) tuples and pass them to the AliasMethod constructor items = count_dict.items() return AliasMethod(items) def get_n_samples(random_word_sampler, n): """ Generate n samples from the given word sampler. :param random_word_sampler A AliasMethod instance that can sample from the distribution :param n The number of words to generate :return A generator that generates n samples drawn from the random_word_sampler distribution. """ for i in xrange(n): yield random_word_sampler.sample() def main(): """ Main function to be run """ # get the arguments file_path = sys.argv[1] nb_of_samples = int(sys.argv[2]) # Create the sampler random_word_sampler = initialize_sampler(file_path) # Sample ant print the words for sample in get_n_samples(random_word_sampler, nb_of_samples): print sample if __name__ == "__main__": main()
86c028eabe0f0999b9ea2a61d680e501abed7a06
dhd12391/LearnPyData
/my-code/suitcase_task1.py
1,201
3.984375
4
""" Coding Challenge: The Traveling Suitcase Scenario: Travis traveled to Chicago and took the Clark Street #22 bus up to Dave's office. He left his briefcase on the bus! Try to get it back! Task 1: Travis doesn't know the number of the bus he was riding. Find likely candidates by parsing the data just downloaded and identifying vehicles traveling northbound of Dave's office. Dave's office is located at: latitude 41.980262 longitude -87.668452 """ #rt22.xml file is the dataset containing the current buses running along Route 22 u = urllib.urlopen('http://ctabustracker.com/bustime/map/getBusesForRoute.jsp?route=22') data = u.read() f = open('rt22.xml', 'wb') f.write(data) f.close() #Searching for northbound buses past the office from xml.etree.ElementTree import parse office_latitude = 41.980262 doc = parse('rt22.xml') for bus in doc.findall('bus'): bus_direction = bus.findtext('d') if bus_direction.startswith('North'): bus_latitude = float(bus.findtext('lat')) if bus_latitude > office_latitude: #checking if northbound bus is north of office bus_id = bus.findtext('id') print(bus_id, bus_latitude) # printing likely candidates
c984ed15c578160106cddc6510e2ba4ea763f978
ZeroTwoooo/pp
/pp1/thing.py
235
3.546875
4
from getpass import getpass username = raw_input("What is your username ") passw = getpass("Set your password ") if passw == "dev123": print("Login Succsess! \n Welcome, "+ username +"!") else: print("Incorrect password")
1065bb2a8f51b68dc127fa2ca145690dbc70df3b
u8913557/codeTraining
/Hackerrank/30 Days of Code/Day25_Running_Time_and_Complexity.py
430
3.9375
4
import math number = input() for i in range(int(number)): str_num = input() int_num = int(str_num) if(int_num==1): print("Not prime") else: k = 2 for j in range(2, int(math.sqrt(int_num))+1): if(int_num%k==0): break k = k + 1 if(k<=math.sqrt(int_num)): print("Not prime") else: print("Prime")
e83f16d9f57269ca7d2a408cd7c5fadda6eb690c
NamanRai11t/bad_loan_classifier
/helpers.py
4,476
3.71875
4
import csv import numpy as np import matplotlib.pyplot as plt #Load data from csv file, and break it into an data list of lists (feature set) and a y list. def load_data(filename, split=0.8, features=[], blacklist=[], shuffle=True): ''' load_data(filename, split=0.8, features=[], blacklist=[], shuffle=True) -> X_train, y_train, X_test, y_test Loads data from a csv file to four numpy arrays, X_train, y_train, X_test and y_test. split determines the portion of the data to be sent to the training set. features is a whitelist of features from the headers. blacklist is a blacklist of features from the headers. You cannot use both features and blacklist. shuffle determines if the data will be shuffled after being loaded. ''' if len(features)>0 and len(blacklist)>0: raise ValueError("You can use one of the features or blacklist lists, but not both.") with open(filename, 'r') as source: data = [] csv_reader = csv.reader(source) for row in csv_reader: data.append(row) feature_set = data[0] data = data[1:] #Processing the blacklist or the features list. if features == []: selected_indices = [feature_set.index(k) for k in feature_set if not k in blacklist] else: selected_indices = [feature_set.index(k) for k in features] data = np.array(data) data = data[:, selected_indices] if shuffle: np.random.shuffle(data) training_length = int(data.shape[0] * split) X_train = data[:training_length-1, :-1] y_train = data[:training_length-1, -1] X_test = data[training_length:, :-1] y_test = data[training_length:, -1] return X_train, y_train, X_test, y_test def load_test_data(filename, features=[], blacklist=[]): '''load_test_data(filename, features=[], blacklis[]) -> X_test, test_ids Special function to load test data for Analyticity 2018. features and blacklist are is in load_data(). ''' if len(features)>0 and len(blacklist)>0: raise ValueError("You can use one of the features or blacklist lists, but not both.") with open(filename, 'r') as source: data = [] csv_reader = csv.reader(source) for row in csv_reader: data.append(row) feature_set = data[0] data = data[1:] test_ids = np.array(data)[:, 0] #Processing the blacklist or the features list. if features == []: selected_indices = [feature_set.index(k) for k in feature_set if not k in blacklist] else: selected_indices = [feature_set.index(k) for k in features] X_test = np.array(data) X_test = X_test[:, selected_indices] return X_test, test_ids def mean(l): '''mean(l) -> number returns the mean of a given list. ''' return sum(l)/len(l) def round(array, threshold): '''round(array, threshold) -> array rounds the numbers in a 1D array. If an element is greater than or equal to the threshold, it is rounded up to 1. Otherwise, rounds down to 0. Only rounds numbers between 1 and 0. ''' if threshold < 0 or threshold > 1: raise ValueError("threshold cannot be greater than 1 or less than 0.") array = np.array( [ 1 if element >= threshold else 0 for element in array ] ) return array def normalise_data(X, normalise_indices=[], zero_to_one=True): '''normalise_data(X, normalise_indices=[], zero_to_one=True) -> X Normalises a dataset. normalise_indices is the list of indices to be normalised. zero_to_one sets whether the normalisation is on the range 0 to 1 or -1 to 1. ''' # If all indices are to be normalised. if normalise_indices == []: normalise_indices = range(len(X[0])) for i in normalise_indices: nu = 0 if zero_to_one else nmean(X[:,i]) X[:,i] = ( ( X[:,i] - nu ) / (max(X[:, i]) - min(X[:, i]) ) ) return X def plot_helper(X, y, features, feature_set): '''plot_helper(X, y, features, feature_set) -> None Helper function to save figures of the frequency distribution of features. features is a list of the indices of the features you want to plot. feature_set is the list of titles of the features. ''' for feature in features: plt.figure(1, (25,5)) ax1 = plt.subplot(121) job_fails = [X[k, feature] for k in range(X.shape[0]) if y[k] == 1] ax1.hist(job_fails) ax1.set_title("Number of people with " + feature_set[feature] + " x who are defaulters") ax2 = plt.subplot(122) job_success = [X[k, feature] for k in range(X.shape[0]) if y[k] == 0] ax2.hist(job_success) ax2.set_title("Number of people with " + feature_set[feature] + " x who are not defaulters") plt.savefig(feature_set[feature] + '.png') plt.clf()
e682ca43a6fda34f222d60a7bdff78e366fdea2c
VAIBHAV-2303/Super_ASCII_Brothers
/src/mario.py
2,408
3.5
4
''' [MM] ][ This file contains the Mario class which generates mario itself and its movement function ''' from person import Person class Mario(Person): '''Mario class''' def __init__(self): '''Initialization''' Person.__init__(self) self.lives = 3 self.posx = 20 self.posy = 20 self.inair = False self.inairtime = None self.bulletarr = [] self.superpower = False def shoot(self): '''Shooting function''' self.bulletarr.append([self.posx, self.posy]) def supershoot(self): '''Special power shoot''' self.bulletarr.append([self.posx, self.posy]) self.bulletarr.append([self.posx - 1, self.posy]) self.bulletarr.append([self.posx + 1, self.posy]) def lose(self, Globalvar, Enemyarr, brickarr, coinarr, springarr, pipearr): '''Loosing life''' self.inair = False self.lives -= 1 Enemyarr.clear() for _ in range(10): self.move('a', Globalvar, Enemyarr, brickarr, coinarr, springarr, pipearr) self.posx = 20 self.posy = 20 # Corrected Code if Globalvar.waterx <= 20 and Globalvar.waterx + 15 >= 20: for _ in range(10): self.move('a', Globalvar, Enemyarr, brickarr, coinarr, springarr, pipearr) self.posx = 20 self.posy = 20 def bossmove(self, character, Boss): '''Movement during boss round''' if character == 'a': if self.posy > 1: self.posy -= 1 elif character == 'd': if self.posy < Boss.posY - 10: self.posy += 1 elif character == 'w': if not self.inair: self.inair = True self.posx -= 1 self.inairtime = 1 if self.inair: self.inairtime += 1 if self.inairtime == 3: self.posx -= 1 if self.inairtime == 7: self.posx -= 1 if self.inairtime == 12: self.posx -= 1 if self.inairtime == 17: self.posx += 1 if self.inairtime >= 20: self.posx += 1 def Superjump(self): '''Spring jump''' self.inair = True self.posx -= 4 self.inairtime = 1
60e1baaa09c99bf19d130c042efd854451a5bf2f
cesar-rayo/robot_fw_example
/libraries/ReadData.py
420
3.65625
4
import csv import json def read_csv_file(filename): data = [] with open(filename, 'r') as csvfile: reader = csv.reader(csvfile) for row in reader: data.append(row) return data def read_json_file(filename): data = {} try: with open(filename, 'r') as json_file: data = json.load(json_file) except Exception as e: print(e) return data
3b88407101133fa7f84f16100a6c9d8755e3ff01
sudo-hemant/test
/geeksForGeeks/backtracking/combinations-sum.py
1,634
3.6875
4
def combinationalSum(arr, x): def find_sum(curr_pos, curr_arr, arr, length, find): # index out of range or greater than required value if curr_pos == length or find < 0: return # sum = required value if find == 0: result.append(curr_arr[:]) return # appending the element to be included curr_arr.append(arr[curr_pos]) # including the curr element but not increasing the pos bcos we can include the same element multiple times find_sum(curr_pos, curr_arr, arr, length, find - curr_arr[-1]) # removing the element added above to find a case when element 'll not be included curr_arr.pop() # not including the current element even once find_sum(curr_pos + 1, curr_arr, arr, length, find) result = [] arr = set(arr) arr = list(arr) arr.sort() find_sum(0, [], arr, len(arr), x) return result if __name__ == '__main__': test_cases = int(input()) for cases in range(test_cases): n = int(input()) a = list(map(int,input().strip().split())) s = int(input()) result = combinationalSum(a,s) if(not len(result)): print("Empty") continue for i in range(len(result)): print("(", end="") size = len(result[i]) for j in range(size - 1): print(result[i][j], end=" ") if (size): print(result[i][size - 1], end=")") else: print(")", end="") print()
8f47e5bd0face86b3b978442e7d71eb04bf6458e
XiaoTaoWang/JustForFun
/Project-Euler/Problem-4.py
858
3.9375
4
# -*- coding: utf-8 -*- """ Created on Wed Mar 02 19:12:44 2016 @author: wxt """ """ Problem 4: A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers. """ def bruteforce(): largest = 0 f1 = f2 = 0 for i in xrange(100, 1000): for j in xrange(i, 1000): product = i * j string = str(product) if string == string[::-1]: if product > largest: largest = product f1 = i f2 = j return largest, f1, f2 if __name__ == '__main__': res = bruteforce() print 'The largest palindrome is {0}, which is the product of {1} and {2}'.format(*res)
2c54e834ce30d9a3092d3be3508194d3bc58af9c
AILearnerNTHU/PySnake
/PySnake-term/PySnakeGame/Map.py
614
3.609375
4
from enum import Enum class MapEnum(Enum): Wall = 'w' Ground = 'g' Fruit = 'f' Snake = 's' class MapObject(object): def __init__(self): self._filetype = MapEnum.Ground @property def FileType(self): return self._filetype @FileType.setter def FileType(self, value): self._filetype = value class Map(): def __init__(self,Height,Width): global World World = [[MapObject()]* int(Width) for i in range(int(Height))] @property def World(self): global World return World
e6bafc3229ba3788892985ea2a18fe51c665fc10
jiabraham/Card-Games
/black_jack/game_scalable.py
8,723
3.8125
4
#!/usr/bin/python3 import actions import cards import copy import math import player import random #Global variables, deck and cards_dealt vectors simulate a standard card deck deck = cards.setDeck() cards_dealt = cards.setCardsDealt() #Welcome messages def main(): print("\n \n \n \n \n \n \n \n\n \n \n \n \n \n \n \n \n \n \n \n \n \n") print("Welcome to Jojo's Blackjack Corner!!") print("") player_number = input("How many players(1-5)? ") if (player_number == "quit"): print("Thankyou for playing, Goodbye!") exit(0) PLAYER_NUMBER = int(player_number)+1 while (PLAYER_NUMBER < 1 or PLAYER_NUMBER > 5): PLAYER_NUMBER = int(input("Invalid input: ")) #Enter how much money each player will have player_money = input("How much money will each player start out with? ") if (player_money == "quit"): print("Thankyou for playing, Goodbye!") exit(0) player_money = int(player_money) while (player_money < 1 or player_money > 100000000): player_money = int(input("Invalid input, please choose positive number from 1 to 1000000: ")) print("Then let's get started!") #DONE #Player vector player_vector = {} for i in range(0, PLAYER_NUMBER): if (i < PLAYER_NUMBER-1): player_vector[i] = player.Player(player_money, "Player" + str(i), 0) else: player_vector[i] = player.Player(player_money, "Dealer", 0) user_input = "" while (True): # cards.resetHands(player_vector[PLAYER_NUMBER-1]) # cards.resetHands(player_vector[i]) for i in range(0, PLAYER_NUMBER): cards.resetHands(player_vector[i]) # card1 = cards.draw(deck, cards_dealt) # card2 = cards.draw(deck, cards_dealt) # card3 = cards.draw(deck, cards_dealt) # card4 = cards.draw(deck, cards_dealt) all_cards = {} total_card_num = 2*(PLAYER_NUMBER) player_counter = 0 for i in range(0, total_card_num): all_cards[i] = cards.draw(deck, cards_dealt) if (i >= PLAYER_NUMBER): player_vector[player_counter].setHand(all_cards[i-PLAYER_NUMBER], all_cards[i]) player_vector[player_counter].setTotal(all_cards[i-PLAYER_NUMBER].getClassification()+ all_cards[i].getClassification()) player_counter += 1 #PLAYER_NUMBER-1 because we want to loop over every user, not dealer for j in range(0, PLAYER_NUMBER-1): print("\n \n \n \n \n \n \n \n\n \n \n \n \n \n \n \n \n \n \n \n") user_input = input("Ready to play?") if (user_input == "quit" or user_input == "q"): print("Thank you for playing!") exit(0) print("You have $" + str(player_vector[j].getMoney())) amount_bet = int(input("How much are you betting (100, 500, or 1000)?")) while (amount_bet > player_vector[j].getMoney()): amount_bet = int(input("Please enter a valid bet:")) actions.bet(player_vector[j], amount_bet) aces = 0 busted = False hand_index = 2 while (True): for i in range(0, len(player_vector[j].hand)): if (i == 0): print("Hidden: " + player_vector[j].hand[i].getName()) if (player_vector[j].hand[i].getClassification() == 11): aces += 1 else: print("Visible: " + player_vector[j].hand[i].getName()) if (player_vector[j].hand[i].getClassification() == 11): aces += 1 if (len(player_vector[j].hand) == 2 and player_vector[j].getTotal() == 21): print("Blackjack, congradulations!") break; elif (player_vector[j].getTotal() == 21): print("You got 21, congradulations!") break else : print("Your total is now: " + str(player_vector[j].getTotal())) user_input = input("Would you like to hit or stay? ") if (user_input == "quit" or user_input == "q"): print("Thankyou for playing, goodbye!") exit(0) if (user_input == "hit"): player_vector[j].hand[hand_index] = cards.draw(deck, cards_dealt) player_vector[j].adjustTotal(player_vector[j].hand[hand_index].getClassification()) if (player_vector[j].hand[hand_index].getClassification() == 11): aces += 1 hand_index += 1 if (player_vector[j].getTotal() > 21 and aces > 0): cards.aceHighOrLow(player_vector[j]) print("Your total is now: " + str(player_vector[j].getTotal())) if (player_vector[j].getTotal() > 21): print("Oops, busted") for i in range(0, len(player_vector[j].hand)): if (i == 0): print("Hidden: " + player_vector[j].hand[i].getName()) else: print("Visible: " + player_vector[j].hand[i].getName()) busted = True actions.endRound(player_vector[j], amount_bet, busted, False) break if (user_input == "stay"): print("Your total is " + str(player_vector[j].getTotal())) break if (busted): continue print(" \n \n \n \n \n \n \n \n \n \n \n" + player_vector[j+1].getName() + "'s turn!") #Loop to model dealer's move hand_index = 2 while(True): print("\nDealer's cards") print("PLAYER_NUMBER = " + str(PLAYER_NUMBER)) for i in range(0, len(player_vector[PLAYER_NUMBER-1].hand)): if (i == 0): print("Hidden: " + player_vector[PLAYER_NUMBER-1].hand[i].getName()) aces += 1 else: print("Visible: " + player_vector[PLAYER_NUMBER-1].hand[i].getName()) aces += 1 #INCREMENT ACE COUNT PROPERLY if (player_vector[PLAYER_NUMBER-1].getTotal() < 17): player_vector[PLAYER_NUMBER-1].hand[hand_index] = cards.draw(deck, cards_dealt) player_vector[PLAYER_NUMBER-1].adjustTotal(player_vector[PLAYER_NUMBER-1].hand[hand_index].getClassification()) hand_index += 1 print("\nLength of dealer hand = " + str(len(player_vector[PLAYER_NUMBER-1].hand))) print("Hit") for k in range(0, len(player_vector[PLAYER_NUMBER-1].hand)): if (k == 0): print("Hidden: " + player_vector[PLAYER_NUMBER-1].hand[k].getName()) else: print("Visible: " + player_vector[PLAYER_NUMBER-1].hand[k].getName()) print("Dealer total is now: " + str(player_vector[PLAYER_NUMBER-1].getTotal())) continue for i in range(0, PLAYER_NUMBER-1): if (player_vector[PLAYER_NUMBER-1].getTotal() > 21 and aces > 0): cards.aceHighOrLow(player_vector[PLAYER_NUMBER-1]) if (player_vector[PLAYER_NUMBER-1].getTotal() == player_vector[i].getTotal()): print("PUSH!!!") player_vector[i].setMoney(amount_bet, 1) if (player_vector[PLAYER_NUMBER-1].getTotal() > 16 and player_vector[PLAYER_NUMBER-1].getTotal() < 22): print("Dealer total is now: " + str(player_vector[PLAYER_NUMBER-1].getTotal())) if (player_vector[i].getTotal() > player_vector[PLAYER_NUMBER-1].getTotal()): print("You win $" + str(amount_bet) + "!") increment = 2*amount_bet player_vector[i].setMoney(increment, 1) else: print("You lose $" + str(amount_bet)) if (player_vector[PLAYER_NUMBER-1].getTotal() > 21): print("Dealer total is now: " + str(player_vector[PLAYER_NUMBER-1].getTotal())) print("You win $" + str(amount_bet) + "!") amount_bet = 2*amount_bet player_vector[i].setMoney(amount_bet, 1) continue main()
3c7ae17e73043aaf986d163372a113d5ed633eb8
Srini-py/Python
/Daily_Coding_Problem/486_find_celebrity.py
949
4.0625
4
''' At a party, there is a single person who everyone knows, but who does not know anyone in return (the "celebrity"). To help figure out who this is, you have access to an O(1) method called knows(a, b), which returns True if person a knows person b, else False. Given a list of N people and the above operation, find a way to identify the celebrity in O(N) time. ''' matrix = [ [0, 1, 0, 0], [0, 1, 0, 0], [0, 1, 0, 0], [0, 1, 0, 0] ] def knows(a, b): return matrix[a][b] def findcelebrity(matrix, n): a = 0 b = n - 1 while a < b: if knows(a, b): a += 1 else: b -= 1 for i in range(n): if (i != a) and (knows(a, i) or (not knows(i, a))): return -1 return a celeb = findcelebrity(matrix, len(matrix)) if celeb != -1: print("Celebrity ID is", celeb) else: print("There is no celebrity")
a849b4f5a1834eb0245c933a5a55c17130548df8
BiancaPal/PYTHON
/INTRODUCTION TO PYTHON/greet_users.py
827
4.53125
5
# You'll often find it useful to pass a list to a function, whether it's a list of names, # numbers, or more complex objects, such as dictionaries. When you pass a list to a function # the function gets direct access to the contents of the list. Let's use functions to make # working with lists more efficient. # Say you have a list of users and want to print a greeting to each. The following example # sends a list of names to a function called greet_users(), which greets each person in the # list individually: def greet_users(names): """Print a simple greeting to each user in the list""" for name in names: msg = f"Hello, {name.title()}!" print(msg) usernames = ['hannah','ty','margot'] greet_users(usernames) # In the calling we used usernames as the argument, that later on the function loops through
366e230cedf648b32b7653cf9e695eb06d581ba6
PacktPublishing/Python-for-Beginners-Learn-Python-from-Scratch
/52. Mutable vs immutable objects/mutablevsimmutableobjects.py
865
3.8125
4
""" object is a variable with MORE features than just showing value You can invoke a function ON object object can have many different values immutable - unchangable (after sending as argument) mutable - changable immutable object: bool, int, float, tuple, str = - means CHANGING the address. Since now the object points to DIFFENT place METHOD """ x = 4 #y = x #y = 20 #print(id(x)) #listSample2 = listSample1 #listSample1.append(4) def add(x, amount=1): print(id(x)) x = x + amount print(id(x)) #add(x) g = 20 h = 20 listSample1 = [2, 42, 125] print(id(listSample1)) def append_element_to_list(WHATAVER, element): print(id(WHATAVER)) a = [124, 124, 52, 1] # WHATAVER = a print(id(WHATAVER)) WHATAVER.append(4) append_element_to_list(listSample1, 2000) print(listSample1)
1ed286de1e684cdec4e125b981680c59e7605cf5
soniacamacho/Fall-19
/CS 511/jawalkad_classroom_test.py
1,335
3.59375
4
from jawalkad_classroom import Student, Assignment def main(): allen = Student(123, "Allen", "Anderson") becky = Student(456, "Becky", "Beckyson") print(allen.get_full_name()+',', "id:", allen.get_id()) print(becky.get_full_name()+',', "id:", becky.get_id()) a11 = Assignment("Assignment 1", 100) a12 = Assignment("Assignment 1", 100) a21 = Assignment("Assignment 2", 100) a22 = Assignment("Assignment 2", 100) a11.assign_grade(75) a21.assign_grade(85) allen.submit_assignment(a11) allen.submit_assignment(a21) a12.assign_grade(90) a22.assign_grade(100) becky.submit_assignment(a12) becky.submit_assignment(a22) print("Assignment 1 grade for "+allen.get_full_name()+" : "+ str(allen.get_assignment("Assignment 1"))) print("Assignment 1 grade for "+becky.get_full_name()+" : "+ str(becky.get_assignment("Assignment 1"))) beckys_assignments = becky.get_assignments() print("Becky's assignment grades: ") for assignment in beckys_assignments: print(assignment.name, " : ", assignment.grade) print("Average grade for Becky: ", becky.get_average()) becky.remove_assignment("Assignment 2") print("Removed Assignment 2 for Becky") print("Average grade for Becky: ", becky.get_average()) if __name__=="__main__": main()
0f8896f62136e12de13521109e89f8daaebb2032
antohneo/pythonProgramming3rdEdition
/PPCh7PE11.py
446
4.03125
4
# aaa # python3 # Python Programming: An Introduction to Computer Science # Chapter 7 # Programming Excercise 11 def main(): year = int(input("Enter a year: ")) century = year // 100 if year % 4 == 0: if century % 4 == 0: print("{0} is a leap year.".format(year)) else: print("{0} is not a leap year.".format(year)) else: print("{0} is not a leap year.".format(year)) main()
4f79bf248975dd11aa9578ecc87cb56a287c7a99
ArneRobben/DesertIslandDiscs
/code/Scraping.py
6,730
3.625
4
""" import libraries """ from urllib.request import urlopen from bs4 import BeautifulSoup import lxml import requests import re import pandas as pd import time """initialise a session""" # load the landing page landing_page = "https://www.bbc.co.uk/programmes/b006qnmr/episodes/player?page={}" html = requests.get(landing_page.format(1)) soup = BeautifulSoup(html.content, 'html.parser') # now find the number of pages npages = int(soup.find('li', {"class": "pagination__page--last"}).find('a').text) print(f"I found {npages} pages on the website") """ run through the pages and fetch title and url_list """ title_list = [] title_url_list = [] for page in range(1, npages+1): html = requests.get(landing_page.format(page)) soup = BeautifulSoup(html.content, 'html.parser') for title in soup.find_all('h2', class_='programme__titles'): title_list.append(title.text) for href in title: title_url_list.append(href['href']) print("\r processing - ", "{:.2%}".format(page/npages), end='') """ returns a dictionary of the eight discs, book choice, luxury item and favourite """ def unpack_blurb(blurb): return { 'disc one': blurb[re.search("DISC ONE: ", blurb).span(0)[1] : re.search("DISC TWO: ", blurb).span(0)[0]], 'disc two': blurb[re.search("DISC TWO: ", blurb).span(0)[1] : re.search("DISC THREE: ", blurb).span(0)[0]], 'disc three': blurb[re.search("DISC THREE: ", blurb).span(0)[1] : re.search("DISC FOUR: ", blurb).span(0)[0]], 'disc four': blurb[re.search("DISC FOUR: ", blurb).span(0)[1] : re.search("DISC FIVE: ", blurb).span(0)[0]], 'disc five': blurb[re.search("DISC FIVE: ", blurb).span(0)[1] : re.search("DISC SIX: ", blurb).span(0)[0]], 'disc six': blurb[re.search("DISC SIX: ", blurb).span(0)[1] : re.search("DISC SEVEN: ", blurb).span(0)[0]], 'disc seven': blurb[re.search("DISC SEVEN: ", blurb).span(0)[1] : re.search("DISC EIGHT: ", blurb).span(0)[0]], 'disc eight': blurb[re.search("DISC EIGHT: ", blurb).span(0)[1] : re.search("BOOK CHOICE: ", blurb).span(0)[0]], 'book choice': blurb[re.search("BOOK CHOICE: ", blurb).span(0)[1] : re.search("LUXURY ITEM: ", blurb).span(0)[0]], 'luxury item': blurb[re.search("LUXURY ITEM: ", blurb).span(0)[1] : re.search("CASTAWAY'S FAVOURITE: ", blurb).span(0)[0]], 'favourite': blurb[re.search("CASTAWAY'S FAVOURITE: ", blurb).span(0)[1] : re.search("Presenter", blurb).span(0)[0]] } """ run through the different episodes """ DF = pd.DataFrame(columns = ['guest', 'artist', 'track', 'label', 'presenter', 'producer', 'book_choice', 'luxury_item', 'favourite', 'synopsis', 'url']) for ep in range(1, len(title_url_list)+1): html = requests.get(title_url_list[ep-1]) try: soup = BeautifulSoup(html.content, 'html.parser') except ConnectionError: print("I am here") time.sleep(1) soup = BeautifulSoup(html.content, 'html.parser') # get the presenter and producer for entry in soup.find_all('p'): if 'Presenter:' in entry.text: try: # let's try splitting when a colon is used [presenter, producer] = entry.text[11:].split('Producer: ') # except ValueError: # let's try splitting when there is no colon # [presenter, producer] = entry.text[10:].split('Producer ') except: print(f"couldn't split {entry.text} \n") # get the synopsis synopsis = "" for entry in soup.find_all(class_='synopsis-toggle__long'): synopsis += entry.text # get the tracks - if there is a nice 'music played' section if len(soup.find_all(class_='segment segment--music'))>0: # get the book choice, luxury item and favourite for entry in soup.find_all('p'): if 'BOOK CHOICE' in entry.text: [book_choice, luxury_item, favourite] = re.split("BOOK CHOICE:|LUXURY ITEM:|LUXURY:|CASTAWAY'S FAVOURITE:|CASTAWAY'S CHOICE:|FAVOURITE TRACK", entry.text[12:]) for segment in soup.find_all(class_='segment segment--music'): if segment.find(class_='artist') is not None: artist = segment.find(class_='artist').text else: artist = "" if segment.find_all(class_='no-margin') is not None: try: track = segment.find_all(class_='no-margin')[1].find('span').text except IndexError: track = segment.find_all(class_='no-margin')[0].find('span').text except AttributeError: track = segment.find_all(class_='no-margin')[0].find('span').text else: track = "" try: label = segment.find('abbr').text except AttributeError: label = "" # now put everything in a neat DataFrame DF = DF.append({'guest': title_list[ep-1], 'url': title_url_list[ep-1], 'artist': artist, 'track': track, 'label':label, 'presenter':presenter, 'producer':producer, 'book_choice':book_choice, 'luxury_item':luxury_item, 'favourite':favourite, 'synopsis':synopsis}, ignore_index=True) #when we have to grab the tracks from the text else: try: blurb = "" for entry in soup.find_all('p'): blurb += entry.text blurb_scrape = unpack_blurb(blurb) for disc in ['disc one', 'disc two', 'disc three', 'disc four', 'disc five', 'disc six', 'disc seven', 'disc eight']: # now put everything in a neat DataFrame DF = DF.append({'guest': title_list[ep-1], 'url': title_url_list[ep-1], 'disc': blurb_scrape[disc], 'presenter':presenter, 'producer':producer, 'book_choice':blurb_scrape['book choice'], 'luxury_item':blurb_scrape['luxury item'], 'favourite':blurb_scrape['favourite'], 'synopsis':synopsis}, ignore_index=True) except AttributeError: DF = DF.append({'guest': title_list[ep-1], 'url': title_url_list[ep-1]}, ignore_index=True) # print(f"couldn't scrape {title_list[ep-1]}, link is here: {title_url_list[ep-1]}") # print progress print("\r processing - ", "{:.2%}".format(ep/len(title_url_list)))
e44db7e58454d9de0a9cbf27fec6e11f5c56afbe
dphillips97/pract
/general_py_pract_ex/menu.py
3,037
4.625
5
#https://www.reddit.com/r/beginnerprojects/comments/1bytu5/projectmenu_calculator/ '''GOAL Imagine you have started up a small restaurant and are trying to make it easier to take and calculate orders. Since your restaurant only sells 9 different items, you assign each one to a number, as shown below. Chicken Strips - $3.50 French Fries - $2.50 Hamburger - $4.00 Hotdog - $3.50 Large Drink - $1.75 Medium Drink - $1.50 Milk Shake - $2.25 Salad - $3.75 Small Drink - $1.25 To quickly take orders, your program should allow the user to type in a string of numbers and then it should calculate the cost of the order. For example, if one large drink, two small drinks, two hamburgers, one hotdog, and a salad are ordered, the user should type in 5993348, and the program should say that it costs $19.50. Also, make sure that the program loops so the user can take multiple orders without having to restart the program each time. SUBGOALS If you decide to, print out the items and prices every time before the user types in an order. Once the user has entered an order, print out how many of each item have been ordered, as well as the total price. If an item was not ordered at all, then it should not show up.''' menu = { 1: ['Chicken Strips', 3.5], 2: ['French Fries', 2.5], 3: ['Hamburger', 4], 4: ['Hotdog', 3.5], 5: ['Large Drink', 1.75], 6: ['Medium Drink', 1.5], 7: ['Milk Shake', 2.25], 8: ['Salad', 3.75], 9: ['Small Drink', 1.25] } def validator(): # entry starts off as not valid valid = False # while loop to repeat when entry is not valid while valid == False: # print menu with borders print('*' * 20) for key in menu: # print dict key, name, cost (formatted) print('%i. %s - $%.2f' % (key, menu[key][0], menu[key][1])) print('*' * 20) # input as string to avoid immediate error (if declared as int) order_digits = input('Enter your order, \'q\' to quit > ') # break on 'Q' or 'q' (pass to another fnc) # or pass valid quit command if order_digits == 'q' or order_digits.isdigit(): return order_digits # else continue loop else: print('\nPlease enter digits only!\n') def main(order_digits): # for each order generate receipt receipt = [] # set total price to zero total_price = 0 # change order entry to list order_list = list(order_digits) # loop thru order list and compare against menu dict for item in order_list: # get total price and set to float # item is string, must set to int total_price += (menu[int(item)][1]) # add item to receipt (list of items) receipt.append(menu[int(item)][0]) print('\nORDER SUMMARY: ') # find dupes in receipt for item in receipt: count = receipt.count(item) print('%i %s' % (count, item)) # print total price as 2 digit float print('\nTotal is: $%.2f\n' % total_price) def looper(): while True: order = validator() if str(order) == 'q': print('Bye!') break else: main(order) looper()
ced74babd22c59ea6dd25c94c4457cfcce8dde03
trustmub/OBS
/src/controller/customer.py
1,893
3.5625
4
""" controller.customer --------------- A customer controller that provide functionality for the customer creation and amendment my a back office personnel. this controller interacts with the user views.customer module """ import datetime from src import db # from src.models import session from src.models.customer_model import Customer # from src.models.models import Customer class CustomerController: def __init__(self, first_name, last_name, dob, gender, contact_number, email, address, country, new_account, working_bal, account_type, inputter_id): self.first_name = first_name self.last_name = last_name self.dob = dob self.gender = gender self.contact_number = contact_number self.email = email self.address = address self.country = country self.acc_account = new_account self.working_bal = working_bal self.account_type = account_type self.inputter_id = inputter_id def create_customer(self): new_client = Customer(first_name=self.first_name, last_name=self.last_name, dob=self.dob, gender=self.gender, contact_number=self.contact_number, email=self.email, address=self.address, country=self.country, acc_number=self.acc_account, working_bal=self.working_bal, account_type=self.account_type, create_date=datetime.datetime.now(), inputter_id=self.inputter_id) db.session.add(new_client) db.session.commit() def amend_customer(self): pass
91a36da69f6961d31de01501f52e518159a75c1b
siddhantprateek/Python-in-Practice
/Primitive Types/typecoversion.py
220
4.125
4
x = input("x: ") print(type(x)) # y = x + 1 THE PROBLEM IN THIS CODE WAS 'X' WAS A STRING, SO WE CANNOT ADD STRING TO A NUMBER,SO # WE HAVE TO CONVERT X TO AN INTEGER y = int(x) + 1 print(f"x: {x} , y: {y} ")
cec8f60f7c429e9dca44f8e055f137194c9fcbfe
akimi-yano/algorithm-practice
/lc/1687.DeliveringBoxesFromStorageTo.py
4,880
3.9375
4
# 1687. Delivering Boxes from Storage to Ports # Hard # 46 # 4 # Add to List # Share # You have the task of delivering some boxes from storage to their ports using only one ship. However, this ship has a limit on the number of boxes and the total weight that it can carry. # You are given an array boxes, where boxes[i] = [ports​​i​, weighti], and three integers portsCount, maxBoxes, and maxWeight. # ports​​i is the port where you need to deliver the ith box and weightsi is the weight of the ith box. # portsCount is the number of ports. # maxBoxes and maxWeight are the respective box and weight limits of the ship. # The boxes need to be delivered in the order they are given. The ship will follow these steps: # The ship will take some number of boxes from the boxes queue, not violating the maxBoxes and maxWeight constraints. # For each loaded box in order, the ship will make a trip to the port the box needs to be delivered to and deliver it. If the ship is already at the correct port, no trip is needed, and the box can immediately be delivered. # The ship then makes a return trip to storage to take more boxes from the queue. # The ship must end at storage after all the boxes have been delivered. # Return the minimum number of trips the ship needs to make to deliver all boxes to their respective ports. # Example 1: # Input: boxes = [[1,1],[2,1],[1,1]], portsCount = 2, maxBoxes = 3, maxWeight = 3 # Output: 4 # Explanation: The optimal strategy is as follows: # - The ship takes all the boxes in the queue, goes to port 1, then port 2, then port 1 again, then returns to storage. 4 trips. # So the total number of trips is 4. # Note that the first and third boxes cannot be delivered together because the boxes need to be delivered in order (i.e. the second box needs to be delivered at port 2 before the third box). # Example 2: # Input: boxes = [[1,2],[3,3],[3,1],[3,1],[2,4]], portsCount = 3, maxBoxes = 3, maxWeight = 6 # Output: 6 # Explanation: The optimal strategy is as follows: # - The ship takes the first box, goes to port 1, then returns to storage. 2 trips. # - The ship takes the second, third and fourth boxes, goes to port 3, then returns to storage. 2 trips. # - The ship takes the fifth box, goes to port 3, then returns to storage. 2 trips. # So the total number of trips is 2 + 2 + 2 = 6. # Example 3: # Input: boxes = [[1,4],[1,2],[2,1],[2,1],[3,2],[3,4]], portsCount = 3, maxBoxes = 6, maxWeight = 7 # Output: 6 # Explanation: The optimal strategy is as follows: # - The ship takes the first and second boxes, goes to port 1, then returns to storage. 2 trips. # - The ship takes the third and fourth boxes, goes to port 2, then returns to storage. 2 trips. # - The ship takes the fifth and sixth boxes, goes to port 3, then returns to storage. 2 trips. # So the total number of trips is 2 + 2 + 2 = 6. # Example 4: # Input: boxes = [[2,4],[2,5],[3,1],[3,2],[3,7],[3,1],[4,4],[1,3],[5,2]], portsCount = 5, maxBoxes = 5, maxWeight = 7 # Output: 14 # Explanation: The optimal strategy is as follows: # - The ship takes the first box, goes to port 2, then storage. 2 trips. # - The ship takes the second box, goes to port 2, then storage. 2 trips. # - The ship takes the third and fourth boxes, goes to port 3, then storage. 2 trips. # - The ship takes the fifth box, goes to port 3, then storage. 2 trips. # - The ship takes the sixth and seventh boxes, goes to port 3, then port 4, then storage. 3 trips. # - The ship takes the eighth and ninth boxes, goes to port 1, then port 5, then storage. 3 trips. # So the total number of trips is 2 + 2 + 2 + 2 + 3 + 3 = 14. # Constraints: # 1 <= boxes.length <= 105 # 1 <= portsCount, maxBoxes, maxWeight <= 105 # 1 <= ports​​i <= portsCount # 1 <= weightsi <= maxWeight # This solution works : class Solution: def boxDelivering(self, boxes: List[List[int]], portsCount: int, maxBoxes: int, maxWeight: int) -> int: N = len(boxes) dp = [float('inf')] * (N + 1) # dp[idx] means the number of trips to carry boxes up to idx (does not include the box at idx) dp[0] = 0 weight = 0 left = 0 trips = 2 for right in range(N): weight += boxes[right][1] if right > 0 and boxes[right][0] != boxes[right-1][0]: trips += 1 # we need to move left if: # 1. we have more than maxBoxes # 2. we have more than maxWeight # 3. dp[left] == dp[left+1], e.g. we can remove the left box for "free" while right - left >= maxBoxes or weight > maxWeight or (left < right and dp[left] == dp[left+1]): weight -= boxes[left][1] if boxes[left][0] != boxes[left+1][0]: trips -= 1 left += 1 dp[right+1] = dp[left] + trips return dp[-1]
f371461105b0b1bb38f9756589d175e56cbd7f96
StephenRyall/pythonalgorithms
/extraLondFactorials.py
164
3.609375
4
def extraLongFactorials(n): fac = 1 if (int(n) >= 1): for i in range(1, int(n)+1): fac = fac * i print(fac) extraLongFactorials(25)
277c551aca4ee2d3ee0fc6256623f15e522a7286
jiinmoon/Algorithms_Review
/Archives/Leet_Code/Old-Attempts/0148_Sort_List.py
1,341
3.8125
4
""" 148. Sort List Question: Sort a linked list in O(n lg n) using constant space complexity. +++ Solution: We can achieve this sorting in-place via MergeSort algorithm. This is done by first find the mid point to split the linked list into two halves. Then, we recursively sort the list of two halves repeatedly. Then, we merge the two lists starting from single nodes. """ class Solution: def merge(self, list1, list2): dummyHead = curr = ListNode(float('-inf')) while list1 or list2: if list1.val < list2.val: temp = list1 list1 = list1.next else: temp = list2 list2 = list2.next curr.next = temp curr = curr.next curr.next = list1 or list2 return dummyHead.next def findMid(self, head): slow, fast = head, head.next while fast and fast.next: slow = slow.next fast = fast.next.next head2 = slow.next slow.next = None return head2 def sortList(self, head): if not head or not head.next: return head head2 = self.findMid(head) list1 = self.sortList(head) list2 = self.sortList(head2) head = self.merge(list1, list2) return head
77311300092f52bde9efe133f3a8c2379c6c4c3c
kishen19/HSS-Course-Allotment
/code/course.py
1,394
3.65625
4
'''' Course Object ''' class Course: def __init__(self,code: str, name: str, cap: int, lecture_slots: list, tutorial_slots: list): self.code = code # Course code, ex: HS 151, dtype: (string) self.name = name if name else '' # Name of the course, ex: World Civilization, dtype: (string) self.cap = cap # Course cap, ex: 40, dtype: (int) self.students = [] # Roll numbers of the students who will be alloted this course after allocation, ex: [17110090, 17110074, ....], dtype: (list of int) self.lecture_slots = lecture_slots # Lecture slots for this course, ex: ['C1' , 'A'], dtype: (list of strings) self.tutorial_slots = tutorial_slots # Tutorial slots for this course, ex: ['C2', 'B2'], dtype: (list of strings) # Private vars only used during allocation by the main func self.rem = cap # Remaining seats for this course: to keep track during allocation, ex: 31, dtype: (int) self.requests = [] # Roll numbers of the students who filled this course in their preferences, ex: [17110090, 17110074, ....], dtype: (list of int) # Printing a Course Object def __str__(self): return self.code + " " +self.name + "\nNo. of Allocated Students: "+ str(len(self.students)) +"\nAllocated Students: "+" ".join([str(i) for i in self.students])
dd2d9528b3c67f17db915283f036abfb52f8839a
mavrovski/PythonPrograming
/Programming Basics - Python/06Drawing Figures with Loops/10Diamond.py
800
3.953125
4
n = int(input()) leftRightDashes = int((n-1)/2) if n == 1: print("*") else: # upside for row in range(0,int((n-1)/2)): print("-"*leftRightDashes,end='') print("*",end='') middle = int(n - 2 * leftRightDashes - 2) if middle >= 0: print("-" * middle, end='') print("*", end='') print("-" * leftRightDashes) leftRightDashes-=1 print("*"+"-"*(n-2)+"*") leftRightDashes+=1 # downside for downRow in range(0,int((n-1)/2)): print("-"*leftRightDashes,end='') middle = int(n - 2 * leftRightDashes - 2) print("*",end='') if middle >= 0: print("-" * middle, end='') print("*", end='') print("-" * leftRightDashes) leftRightDashes += 1
cdd569e2928c4abb7177bca72878eb8daea269e8
goku1011/66DaysOfData
/dsDay3/intermediateML_categorical_variables.py
3,354
3.59375
4
import pandas as pd from sklearn.model_selection import train_test_split X = pd.read_csv('home-data-for-ml-course/train.csv') X_test = pd.read_csv('home-data-for-ml-course/test.csv') # Remove rows with missing target, separate target from predictors X.dropna(axis=0, subset=['SalePrice'], inplace=True) y = X.SalePrice X.drop(['SalePrice'], axis=1, inplace=True) # To keep things simple, we'll drop columns with missing values cols_with_missing_vals = [col for col in X.columns if X[col].isnull().any()] X.drop(cols_with_missing_vals, axis=1, inplace=True) X_test.drop(cols_with_missing_vals, axis=1, inplace=True) # Break off validation set from training data X_train, X_valid, y_train, y_valid = train_test_split(X, y, train_size=0.8, test_size=0.2, random_state=0) from sklearn.ensemble import RandomForestRegressor from sklearn.metrics import mean_absolute_error # function for comparing different approaches def score_dataset(X_train, X_valid, y_train, y_valid): model = RandomForestRegressor(n_estimators=100, random_state=0) model.fit(X_train, y_train) preds = model.predict(X_valid) return mean_absolute_error(y_valid, preds) ############################## # Approach 1 - Drop columns with categorical data drop_X_train = X_train.select_dtypes(exclude=['object']) drop_X_valid = X_valid.select_dtypes(exclude=['object']) print("MAE from Approach 1 (Drop categorical variables):") print(score_dataset(drop_X_train, drop_X_valid, y_train, y_valid)) # 17952.5914 ############################## # Approach 2 - Label Encoding # All categorical columns object_cols = [col for col in X_train.columns if X_train[col].dtype=='object'] # Columns that can be safely label encoded good_label_cols = [col for col in X_train.columns if set(X_train[col])==set(X_valid[col])] # Problematic columns that will be dropped from the dataset bad_label_cols = list(set(object_cols)-set(good_label_cols)) print('Categorical columns that will be label encoded:', good_label_cols) print('\nCategorical columns that will be dropped from the dataset:', bad_label_cols) from sklearn.preprocessing import LabelEncoder # Drop categorical columns that will not be encoded label_X_train = X_train.drop(bad_label_cols, axis=1) label_X_valid = X_valid.drop(bad_label_cols, axis=1) label_encoder = LabelEncoder() for col in good_label_cols: label_X_train[col] = label_encoder.fit_transform(X_train[col]) label_X_valid[col] = label_encoder.transform(X_valid[col]) print("MAE from Approach 2 (Label Encoding):") print(score_dataset(label_X_train, label_X_valid, y_train, y_valid)) # 17672.8534 ############################## # Approach 3 - One-Hot Encoding from sklearn.preprocessing import OneHotEncoder OH_encoder = OneHotEncoder(handle_unknown='ignore', sparse=False) OH_cols_train = pd.DataFrame(OH_encoder.fit_transform(X_train[object_cols])) OH_cols_valid = pd.DataFrame(OH_encoder.transform(X_valid[object_cols])) OH_cols_train.index = X_train.index OH_cols_valid.index = X_valid.index num_X_train = X_train.drop(object_cols, axis=1) num_X_valid = X_valid.drop(object_cols, axis=1) OH_X_train = pd.concat([num_X_train, OH_cols_train], axis=1) OH_X_valid = pd.concat([num_X_valid, OH_cols_valid], axis=1) print("MAE from Approach 3 (One-Hot Encoding):") print(score_dataset(OH_X_train, OH_X_valid, y_train, y_valid)) # 17508.5926
4c7fc60bd109522a5949d13c688db5776514a3ac
ozkknnt/ML_preprocessing_study
/データクレンジング/defaultdict.py
573
3.65625
4
from collections import defaultdict # 文字列 description description = \ "Artificial intelligence (AI, also machine intelligence, MI) is " + \ "intelligence exhibited by machines, rather than " + \ "humans or other animals (natural intelligence, NI)." # defaultdict を定義して下さい char_freq = defaultdict(int) # 文字の出現回数を記録して下さい for i in description: char_freq[i] += 1 # value の降順にソートし、上位10要素を出力して下さい print(sorted(char_freq.items(),key=lambda x: x[1],reverse = True)[:10])
c958bd658c835edadd29244507f58ee520effec6
alba054/CSUnhas_DataStructure
/HashTable/hashtable.py
1,482
3.578125
4
class HashTable: def __init__(self): self.table = [None] * 10 # put key := string, value := any def put(self, key, value): hash_index = self.hash_func(key) # hash a string if self.table[hash_index] is None: self.table[hash_index] = [] self.table[hash_index].append(tuple([key, value])) # use chaining to handle collision # simple hash function # lazy approach :) def hash_func(self, key): return (len(key) + 3) % 10 def get_value(self, key): hash_index = self.hash_func(key) for k, v in self.table[hash_index]: if key == k: return v return "No key in table" def update_value(self, key, new_value): hash_index = self.hash_func(key) for i in range(len(self.table[hash_index])): if self.table[hash_index][i][0] == key: self.table[hash_index][i] = list(self.table[hash_index][i]) self.table[hash_index][i][1] = new_value self.table[hash_index][i] = tuple(self.table[hash_index][i]) return return "No value to update" def main(): table = HashTable() table.put("kata", 1) table.put("royal", 5) table.put("raft", 4) # print(table.table) print(table.get_value("raft")) table.update_value("raft", 7) print(table.get_value("raft")) if __name__ == "__main__": main()