blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
5e4ebbcc9a0da90a2d5be7a5e2ab181d22598512
jingzli/study
/python/googlePythonClass/D1_file.py
1,238
3.625
4
import sys import os def Cat(filename): # read the file line by line, use less RAM than read in whole file f = open(filename, 'rU') for line in f: # print line # line string include new line at the end print line, # ',' at the end, prohibits the new line at the end f.close() # close file def Cat2(filename): # read the file as a list, need 20G RAM to store, if the file is 20G big f = open(filename, 'rU') lines = f.readlines() print lines f.close def Cat3(filename): try: f = open(filename, 'rU') text = f.read() print '--------', filename print text f.close except IOError: #print error if fails print 'IO Error', filename # open a file for writing, this will zero out the file #to do def print_line_to_file(filename, lines): f = open(filename, 'w') f.writelines(lines) f.close def print_text_to_file(filename, text): f = open(filename, 'w') f.write(text) f.close # find files in dir with ending def files_in_dir (dir = './', ending= '.txt'): for file in os.listdir(dir): if file.endswith(ending): print file def main(): args = sys.argv[1:] for arg in args: Cat3(arg) if __name__ == '__main__': main()
d132b39aab49dbd3ed14ef9eefa8eec92ba63f72
SimonLundell/Udacity
/Intro to Self-Driving Cars/Introduction/2_car_turning.py
504
3.6875
4
# CODE CELL # # This is the code you should edit and run to control the car. from Car import Car import time # TODO: Make changes to the steering and gas values and see how they affect the car's motion def circle(car): car.steer(4.5) car.gas(0.50) car = Car() circle(car) # Observations: Increasing the gas requires a decrease in steer for the car to stay on the circle. Seems to be a relation of roughly 10. Once car stabilizes it is maintaining same circle assuming speed is constant.
4a5a794c8e9604f09e64d570eefa26173085a45c
ap1729/ML_Project1
/implementations.py
19,821
3.8125
4
# -*- coding: utf-8 -*- """some helper functions for project 1.""" import csv import numpy as np def standardize(x): """ Standardize the original data set with standard deviation. Arguments: x (array to be standardized) """ std_x = np.std(x) if std_x == 0: std_x = 1 mean_x = np.mean(x) x = x - mean_x x[np.where(x==0)[0]]=1e-5 x = x / std_x return x def quart_standardize(x): """ Standardize the original data set with quantiles Arguments: x (array to be standardized) """ q1 = np.percentile(x,15) q3 = np.percentile(x,85) iqr = q3-q1 if iqr == 0: iqr = 1 median = np.median(x) x = x-median x[np.where(x==0)[0]]=1e-5 x = x/iqr return x def scaled_standardize(x): """ Standardize the original data set with max values Arguments: x (array to be standardized) """ min_x = np.min(x) max_x = np.max(x) range_x = max_x-min_x if range_x == 0: range_x = 1 x = x - min_x x[np.where(x==0)[0]]=1e-5 x = x/range_x return x def standardize_data(input_data, mode = 0): """ Standardize the original data with respect to the mode chose Arguments: input_data (array to be standardized) mode = 0, 1, 2 (0: standard deviation 1: quantile standardization 2: scaled standardization) """ #Standardize all the remaining columns for i in range(0,len(input_data[0])): if mode == 0: input_data[:,i] = standardize(input_data[:,i]) elif mode == 1: input_data[:,i] = quart_standardize(input_data[:,i]) elif mode == 2: input_data[:,i] = scaled_standardize(input_data[:,i]) else: input_data[:,i] = standardize(input_data[:,i]) #input_data_tx = np.c_[np.ones(len(input_data)), input_data] #Adding column of ones to make it tX return input_data def clean_columns_rows(x, y, percentage_lign, percentage_col, flags): """ Deletes columns and rows if number of -999. values is higher than a certain percentage of number of columns or rows Arguments: x (array to be cleaned) y (prediction to be cleaned [to respect the size of matrices]) percentage_lign (value between 0 and 1, multiplies the number of ligns for comparison) percentage_col (value between 0 and 1, multiplies the number of columns for comparison) flags (function flags for feature expansion) """ nb_col = len(x[0]) nb_lign = len(x) col_to_del = [] lign_to_del = [] x_cop = x y_cop = y for col in range(0,nb_col): unique, counts = np.unique(x_cop[:,col], return_counts = True) if flags[0] == True and counts[np.where(unique == 0.)[0]] > 0.8*nb_lign: col_to_del.append(col) if counts[np.where(unique == -999.)[0]] > percentage_lign*nb_lign: col_to_del.append(col) x_cop = np.delete(x_cop, col_to_del, 1) for lign in range(0,nb_lign): unique, counts = np.unique(x[lign,:], return_counts = True) if counts[np.where(unique == -999.)[0]] >= percentage_col*nb_lign: lign_to_del.append(lign) x_cop = np.delete(x_cop, lign_to_del, 0) y_cop = np.delete(y_cop, lign_to_del, 0) return x_cop, y_cop, col_to_del def var_clean_columns(x, var_threshold): """ Deletes columns based on variance threshold, deletes columns with variance under var_threshold Arguments: x (array to be cleaned) var_threshold (threshold of variance) """ nb_col = len(x[0]) col_to_del = [] x_cop = x for col in range(0,nb_col): var = np.var(x_cop[:,col]) if var <= var_threshold: col_to_del.append(col) x_cop = np.delete(x_cop, col_to_del, 1) return x_cop def clean_undef_columns(x,undef_val): nb_col = len(x[0]) col_to_del = [] x_cop = x for col in range(0,nb_col): val = x_cop[1,col] if val == undef_val: col_to_del.append(col) x_cop = np.delete(x_cop, col_to_del, 1) return x_cop def load_csv_data(data_path, sub_sample=False): """Loads data and returns y (class labels), tX (features) and ids (event ids)""" y = np.genfromtxt(data_path, delimiter=",", skip_header=1, dtype=str, usecols=1) x = np.genfromtxt(data_path, delimiter=",", skip_header=1) ids = x[:, 0].astype(np.int) input_data = x[:,2:] # convert class labels from strings to binary (-1,1) yb = np.ones(len(y)) yb[np.where(y=='b')] = -1 # sub-sample if sub_sample: yb = yb[::50] input_data = input_data[::50] ids = ids[::50] return yb, input_data, ids def predict_labels(weights, data): """Generates class predictions given weights, and a test data matrix""" y_pred = np.dot(data, weights) y_pred[np.where(y_pred <= 0)] = -1 y_pred[np.where(y_pred > 0)] = 1 return y_pred def predict_labels_new(weights, data,degree,flags, col_to_del): """Generates class predictions given weights, and a test data matrix""" #After Splitting into 4 parts, we need to recombine them here y_pred=np.zeros(data.shape[0]) data23=[row[22] for row in data[0:100]] #23rd column which is JET_PRI_NUM and has exactly 4 distinct values values=(list(set(data23))) #get all 4 unique values , and these have been verified to correspond to our original ordering first_col = np.array(data[:,0]) first_col[first_col == -999.] = 0 first_col[first_col == 0.] = np.median(first_col) data[:,0] = first_col for i in range(0,4): #extracting the indices of column 22 curr_indices=np.where(data==values[i])[0] data_cop = data[curr_indices] data_cop = np.delete(data_cop, col_to_del[i], 1) X_test = standardize_data(data_cop, mode = 1) data_cop[data_cop == 0.]=1e-3 tX_pred=feature_expand(data_cop,degree,flags[i]) #Feature Expand and delete 23rd column y_pred[curr_indices]= np.dot(tX_pred,weights[i]) y_pred[np.where(y_pred <= 0)] = -1 y_pred[np.where(y_pred > 0)] = 1 return y_pred def create_csv_submission(ids, y_pred, name): """ Creates an output file in .csv format for submission to Kaggle or AIcrowd Arguments: ids (event ids associated with each prediction) y_pred (predicted class labels) name (string name of .csv output file to be created) """ with open(name, 'w') as csvfile: fieldnames = ['Id', 'Prediction'] writer = csv.DictWriter(csvfile, delimiter=",", fieldnames=fieldnames) writer.writeheader() for r1, r2 in zip(ids, y_pred): writer.writerow({'Id':int(r1),'Prediction':int(r2)}) def build_model_data(height, weight): """Form (y,tX) to get regression data in matrix form.""" y = weight x = height num_samples = len(y) tx = np.c_[np.ones(num_samples), x] return y, tx def batch_iter(y, tx, batch_size, num_batches=1, shuffle=True): """ Generate a minibatch iterator for a dataset. Takes as input two iterables (here the output desired values 'y' and the input data 'tx') Outputs an iterator which gives mini-batches of `batch_size` matching elements from `y` and `tx`. Data can be randomly shuffled to avoid ordering in the original data messing with the randomness of the minibatches. Example of use : for minibatch_y, minibatch_tx in batch_iter(y, tx, 32): <DO-SOMETHING> """ data_size = len(y) if shuffle: shuffle_indices = np.random.permutation(np.arange(data_size)) shuffled_y = y[shuffle_indices] shuffled_tx = tx[shuffle_indices] else: shuffled_y = y shuffled_tx = tx for batch_num in range(num_batches): start_index = batch_num * batch_size end_index = min((batch_num + 1) * batch_size, data_size) if start_index != end_index: yield shuffled_y[start_index:end_index], shuffled_tx[start_index:end_index] def build_poly(x, degree): """polynomial basis functions for input data x, for j=0 up to j=degree.""" # this function returns the matrix formed # by applying the polynomial basis to the input data if degree==0: return np.ones(len(x)) tx = np.c_[np.ones(len(x)), x] for j in range(2,degree+1): tx = np.c_[tx,x**j ] return tx def split_data(x, y, ratio, seed=1): """ split the dataset based on the split ratio. If ratio is 0.8 you will have 80% of your data set dedicated to training and the rest dedicated to testing """ # set seed and shuffle both x and y with the same seed np.random.seed(seed) np.random.shuffle(x) np.random.seed(seed) np.random.shuffle(y) train_rows = int(ratio * len(x)) test_rows = len(x) - train_rows x_train=x[0:train_rows] y_train=y[0:train_rows] x_test=x[train_rows:] y_test=y[train_rows:] return x_train, x_test, y_train, y_test def cross_validation(weights,tX_cross,y_cross): """Calculate the cross validation""" y_pred_cross = np.dot(tX_cross, weights) y_pred_cross[np.where(y_pred_cross <= 0)] = -1 y_pred_cross[np.where(y_pred_cross > 0)] = 1 #calculate fraction which is correct with the known data return (np.count_nonzero(y_pred_cross == y_cross))/len(y_cross) def cross_validation_new(weights,tX_cross,y_cross,values): """Calculate the cross validation for the 4 way split""" y_pred_cross = np.dot(tX_cross, weights[0]) for i in range(1,4): curr_indices=np.where(tX_cross==values[i])[0] y_pred_cross[curr_indices]= np.dot(tX_cross[curr_indices],weights[i]) y_pred_cross[np.where(y_pred_cross <= 0)] = -1 y_pred_cross[np.where(y_pred_cross > 0)] = 1 #calculate fraction which is correct with the known data return (np.count_nonzero(y_pred_cross == y_cross))/len(y_cross) def feature_expand(x,degree,flags=[True,True,True]): """Form (tx) to get feature expanded data in matrix form.""" tx = np.c_[np.ones(len(x)), x] # Adding column of ones for j in range(2,degree+1): tx = np.c_[tx, x**j ] tx = np.c_[tx, np.sqrt(np.abs(x)) ] if flags[0]==True: tx=np.c_[tx,np.log(np.abs(x))] if flags[1]==True: tx=np.c_[tx,np.sin(x)] if flags[2]==True : tx = np.c_[tx,np.cos(x)] return tx """ ************************************************************************************************ ************************************************************************************************ ************************************************************************************************ ************************************************************************************************ ************************************************************************************************ """ """Function which implement various machine learning algorithms for project 1.""" def compute_loss(y, tx, w): """Calculate the loss""" e = y-(tx@w) N = y.size L = np.sum(np.square(e))/(2*N) return L #************************************************** GRADIENT DESCENT ************************************************************* def compute_gradient(y, tx, w): """Compute the gradient.""" e = y-(tx@w) N = len(e) return -tx.T@e/N def gradient_descent(y, tx, initial_w, max_iters, gamma): """Gradient descent algorithm.""" # Define parameters to store w and loss ws = [initial_w] losses = [] w = initial_w for n_iter in range(max_iters): #compute gradient and loss grad=compute_gradient(y,tx,w) loss =compute_loss(y,tx,w) #Update step w = w-gamma*grad # store w and loss ws.append(w) losses.append(loss) print("Gradient Descent({bi}/{ti}): loss={l}".format(bi=n_iter, ti=max_iters - 1, l=loss)) return losses, ws #****************************************************************************************************************************************** #************************************************** STOCHASTIC GRADIENT DESCENT ************************************************************* def compute_stoch_gradient(y, tx, w): """Compute a stochastic gradient from just few examples n and their corresponding y_n labels.""" e= y- np.dot(tx,w) return (-1.0/len(y))*np.dot( np.transpose(tx),e) def stochastic_gradient_descent(y, tx, initial_w, batch_size, max_iters, gamma): """Stochastic gradient descent algorithm.""" # Define parameters to store w and loss ws = [initial_w] losses = [] w = initial_w n_iter=0 for minibatch_y, minibatch_tx in batch_iter(y, tx, batch_size, max_iters): n_iter+=1 #compute gradient and loss grad=compute_gradient(minibatch_y,minibatch_tx,w) loss =compute_loss(minibatch_y,minibatch_tx,w) w = w-gamma*grad # store w and loss ws.append(w) losses.append(loss) print("Stochastic Gradient Descent({bi}/{ti}): loss={l}".format(bi=n_iter, ti=max_iters - 1, l=loss)) return losses, ws #****************************************************************************************************************************************** #************************************************** LEAST SQUARES ************************************************************* def least_squares(y, tx): """calculate the least squares solution.""" a = tx.T@tx b = tx.T@y wts = np.linalg.solve(a,b) mse = compute_loss(y, tx, wts) return mse, wts # returns mse, and optimal weights #****************************************************************************************************************************************** #************************************************** RIDGE REGRESSION ************************************************************* def ridge_regression(y, tx, lambda_): """Ridge regression Algorithm""" a = 2 * tx.shape[0] * lambda_ * np.identity(tx.shape[1]) + tx.T.dot(tx) b = tx.T.dot(y) wts = np.linalg.solve(a, b) mse = compute_loss(y, tx, wts) + lambda_* np.dot(wts, wts) return mse, wts # returns mse, and optimal weights #****************************************************************************************************************************************** #************************************************** LOGISTIC REGRESSION ************************************************************* def sigmoid(t): """apply the sigmoid function on t.""" return 1/(1+np.exp(-t)) def calculate_logistic_loss(y, tx, w): """compute the loss: negative log likelihood.""" return -np.sum( y*np.log(sigmoid(tx@w)) + (1-y)*np.log(1-sigmoid(tx@w)) ) def calculate_logistic_gradient(y, tx, w): """compute the gradient of loss.""" return tx.T@(sigmoid(tx@w)-y) def logistic_gradient_descent(y, tx, initial_w, max_iters, gamma): """compute the logistic gradient descent""" # init parameters threshold = 1e-8 ws = [initial_w] losses = [] w=initial_w for iter in range(max_iters): # get loss and update w loss= calculate_logistic_loss(y, tx, w) grad= calculate_logistic_gradient(y, tx, w) w = w-gamma*grad ws.append(w) # log info if iter % 10 == 0: print("Current iteration={i}, loss={l}".format(i=iter, l=loss)) # converge criterion losses.append(loss) if len(losses) > 1 and np.abs(losses[-1] - losses[-2]) < threshold: break return losses, ws #********************************************************************************************************************************************** #************************************************** REGULARIZED LOGISTIC REGRESSION ************************************************************* def reg_logistic_gradient_descent(y, tx, initial_w, max_iters, gamma, lambda_): """ Computes the regularized logistic gradient descent """ # init parameters threshold = 1e-8 ws = [initial_w] losses = [] w=initial_w for iter in range(max_iters): # get loss and update w loss= calculate_logistic_loss(y, tx, w) + lambda_* (np.sum( np.dot(w.T, w))) grad= calculate_logistic_gradient(y, tx, w) + 2*lambda_*w w = w-gamma*grad ws.append(w) # log info if iter % 10 == 0: print("Current iteration={i}, loss={l}".format(i=iter, l=loss)) # converge criterion losses.append(loss) if len(losses) > 1 and np.abs(losses[-1] - losses[-2]) < threshold: break return losses, ws #******************************************************************************************************************************************************* #************************************************** NEWTON'S METHOD LOGISTIC REGRESSION ************************************************************* def calculate_hessian(y, tx, w): """return the Hessian of the loss function.""" S=np.identity(len(y)) for i in range(0,len(y)): S[i,i] = (sigmoid(tx@w)*(1-sigmoid(tx@w)))[i,0] hess = tx.T @ S @ tx return hess def newt_logistic_gradient_descent(y, tx, initial_w, max_iters, gamma): """ Computes the Newton Logistic Gradient Descent """ # init parameters threshold = 1e-8 ws = [initial_w] losses = [] w=initial_w for iter in range(max_iters): # get loss and update w loss= calculate_logistic_loss(y, tx, w) grad= calculate_logistic_gradient(y, tx, w) hess= calculate_hessian(y, tx, w) w= w- gamma* ( np.linalg.solve(hess, np.identity(len(w)) ) ) @grad ws.append(w) losses.append(loss) # log info print("Current iteration={i}, loss={l}".format(i=iter, l=loss)) # converge criterion losses.append(loss) if len(losses) > 1 and np.abs(losses[-1] - losses[-2]) < threshold: break return losses, ws def newt_stochastic_gradient_descent(y, tx, initial_w, max_iters, gamma, batch_size): # init parameters threshold = 1e-8 ws = [initial_w] losses = [] w=initial_w n_iter=0 for baty, batx in batch_iter(y, tx, batch_size,max_iters): loss= calculate_logistic_loss(baty, batx, w) grad= calculate_logistic_gradient(baty, batx, w) hess= calculate_hessian(baty, batx, w) w= w- gamma* ( np.linalg.solve(hess, np.identity(len(w)) ) ) @grad ws.append(w) losses.append(loss) # log info print("Current iteration={i}, loss={l}".format(i=n_iter, l=loss)) n_iter+=1 # converge criterion if len(losses) > 1 and np.abs(losses[-1] - losses[-2]) < threshold: break return losses, ws #*******************************************************************************************************************************************************
198403d68bf29faddf7d4098ac93c6f97bcc8ac7
friessm/math-puzzles
/p0006.py
872
4.09375
4
""" Solution to Project Euler problem 6 https://projecteuler.net/problem=6 """ def sum_of_squares(number): """ Cubic function. 1**2 + 2**2 + ... + n**2 can be expressed as a cubic function. a*n**3 + b*n**2 + c*n + d where d = 0 because 0, for n = 0. Solve 3 unknowns and voila 1/3*n*3 + 1/2*n**2 + 1/6*n. """ return int(1/3*number**3 + 1/2*number**2 + 1/6*number) def square_of_sums(number): """ Square a triangular number. 1,3,6,10,15,... is a triangular sequence and can therefor be solved with the simple formulae: n(n+1)/2 https://www.mathsisfun.com/algebra/triangular-numbers.html """ return int((number*(number+1)/2)**2) def sum_square_difference(number): return int(square_of_sums(number) - sum_of_squares(number)) if __name__ == '__main__': print(sum_square_difference(100))
51bcee4b0342d18462144f80e360f2082c6a1bf0
mithun2k5/Python-Code
/Python-Projects/Flatten Nested List Iterator.txt
304
3.8125
4
#Flatten Nested List Iterator: lst = [[1,2],2,[1,1]] new_lst = [] for i in range(len(lst)): if type(lst[i]) == list: temp = lst[i] for j in range(len(temp)): new_lst.append(temp[j]) else: new_lst.append(lst[i]) new_lst Output: [1, 2, 2, 1, 1]
bdfd26506d21d238f55e5679e34930c852a99c86
MariusDL/Python-Steganography
/steganography.py
2,182
3.921875
4
from PIL import Image import stepic import easygui import base64 # show options to the user print("Choose an option:\n1. Encode text in image\n2. Extract text from image\n") # loop until the user enters a correct choice choice = "" while(not(choice == "1" or choice == "2")): choice = input("Enter your choice: ") # function to encrypt the text with a key so it is not encoded in the image in plain form def encodeText(key, clear): enc = [] for i in range(len(clear)): key_c = key[i % len(key)] enc_c = chr((ord(clear[i]) + ord(key_c)) % 256) enc.append(enc_c) return base64.urlsafe_b64encode("".join(enc).encode()).decode() # function to decrypt the text extracted from the image def decodeText(key, enc): dec = [] enc = base64.urlsafe_b64decode(enc).decode() for i in range(len(enc)): key_c = key[i % len(key)] dec_c = chr((256 + ord(enc[i]) - ord(key_c)) % 256) dec.append(dec_c) return "".join(dec) # function to encode the text in the image def encode(): # opens a window so the user selects a file img = Image.open(easygui.fileopenbox()) # the text that will be encrypted text = input("Enter the text you want to hide inside the image: ") # loops until the user enters a password to encrypt the text key = "" while(len(key)==0): key = input("Enter the password to encrypt the text: ") # encrypt the text with the password textToHide = encodeText(key, text) # encode the text in the image img2 = stepic.encode(img, textToHide.encode('ascii')) # save the image img2.save('encoded.png', 'PNG') # function to extract the text from the image def decode(): # opens a window so the user selects a file img = Image.open(easygui.fileopenbox()) # extract the text from the image data = stepic.decode(img) # loops until the user enters a password to decrypt the text key = "" while(len(key)==0): key = input("Enter the password to decode the text: ") # decrypt the extracted text decodedData = decodeText(key, str(data)) # print the text print("Decoded data: " + decodedData) if(choice == "1"): encode() elif(choice == "2"): decode()
c40f2d082ce47b2047bc9cdaff881a76e27397fb
franciszxlin/Practice-Problems
/count_and_say.py
1,282
4.125
4
# -*- coding: utf-8 -*- """ Created on Fri May 22 23:52:06 2020 @author: Francis Lin """ """ The count-and-say sequence is the sequence of integers with the first five terms as following: 1. 1 2. 11 3. 21 4. 1211 5. 111221 6. 312211 1 is read off as "one 1" or 11. 11 is read off as "two 1s" or 21. 21 is read off as "one 2, then one 1" or 1211. Given an integer n where 1 ≤ n ≤ 30, generate the nth term of the count-and-say sequence. You can do so recursively, in other words from the previous member read off the digits, counting the number of digits in groups of the same digit. Note: Each term of the sequence of integers will be represented as a string. """ def count_and_say(n): string = '1' for i in range(n - 1): cnt = 0 new_string = [] prev_c = None for c in string: if prev_c is not None and prev_c != c: new_string.append(str(cnt)+prev_c) cnt = 0 cnt += 1 prev_c = c new_string.append(str(cnt)+c) string = ''.join(new_string) return string def main(): term = 6 ans = count_and_say(term) # Expect to see 312211 print('Output : {}'.format(ans)) if __name__ == '__main__': main()
70be452441f85c74ed4205e63086486e0b85909b
Sale3054/SwiftRepo3308
/docs/movie_data.py
1,081
3.875
4
#!/usr/bin/python3 from urllib.request import urlopen import json from random import shuffle def api(title): """ The function takes a tile pull info via api then return a json data of the ginve movie """ title = title.replace(" ", "+") response = urlopen("http://www.omdbapi.com/?apikey=cc47980e&t={}".format(title)).read().decode('utf8') data = json.loads(response) return data def picktitle(genre, n): """ The function reads the file and get the list of titles Then, it returns the randomly picked n titles """ movie_titles = [] file_name = "{}.txt".format(genre) with open(file_name, 'r') as f: for title in f: movie_titles.append(title.strip()) shuffle(movie_titles) # make sure n is less than the number of titles in the file if n > len(movie_titles): n = len(movie_titles) return movie_titles[:n] def main(): num_movie = 5 genre = "comedy" movie_titles = picktitle(genre, num_movie) for title in movie_titles: print("title: {}".format(title)) print(api(title)) print() if __name__ == '__main__': main()
9a3071b077f666ffde246e0f72e0cb0b88c450bf
gar-kai/com404
/Notes/bot.py
1,220
3.921875
4
== If the values of two operands are equal, then the condition becomes true. (a == b) is not true. != If values of two operands are not equal, then condition becomes true. (a != b) is true. <> If values of two operands are not equal, then condition becomes true. (a <> b) is true. This is similar to != operator. > If the value of left operand is greater than the value of right operand, then condition becomes true. (a > b) is not true. < If the value of left operand is less than the value of right operand, then condition becomes true. (a < b) is true. >= If the value of left operand is greater than or equal to the value of right operand, then condition becomes true. (a >= b) is not true. <= If the value of left operand is less than or equal to the value of right operand, then condition becomes true. (a <= b) is true and Returns True if both statements are true x < 5 and x < 10 or Returns True if one of the statements is true x < 5 or x < 4 not Reverse the result, returns False if the result is true not(x < 5 and x < 10) % Modulus Divides left hand operand by right hand operand and returns remainder b % a = 0 ** Exponent Performs exponential (power) calculation on operators a**b =10 to the power 20
4e560b35fb492beb9aa7e358abfc6ebe8e717196
ay701/Coding_Challenges
/number/findMaxAfterMin.py
475
3.640625
4
# [10,1,15,2,3,5,1,3] def find_max_after_min(l): if len(l) <= 1: return None prev = l[0] min_ = prev max_ = None for cur in l[1:]: if prev < min_: min_ = prev max_ = cur if cur > prev else None elif cur == min_: if max_ is None or cur > max_: max_ = cur prev = cur return max_ print find_max_after_min([10, 1, 15, 2, 3, 5, 1, 3, 10, 1, 16, 2, 3, 5, 1, 3])
87e166b85733264dcab02b51435b2cced4764008
pretolindao/prova-douglas
/10 LISTA.py
171
3.59375
4
list = [] for i in range(10): word=input(f"ESCREVE QUALQUER COISA) {i+1} de 10)\n") list.append( word + '\n') text = open("list.text", "w+") text.writelines(list)
dd37ae44ec9541992069adec175f379bf1e84740
daniel-reich/turbo-robot
/fNQEi9Y2adsERgn98_16.py
1,586
4.21875
4
""" Write a function that takes the coordinates of three points in the form of a 2d array and returns the perimeter of the triangle. The given points are the vertices of a triangle on a two-dimensional plane. ### Examples perimeter( [ [15, 7], [5, 22], [11, 1] ] ) ➞ 47.08 perimeter( [ [0, 0], [0, 1], [1, 0] ] ) ➞ 3.42 perimeter( [ [-10, -10], [10, 10 ], [-10, 10] ] ) ➞ 68.28 ### Notes * The given points always create a triangle. * The numbers in the argument array can be positive or negative. * Output should have 2 decimal places * This challenge is easier than it looks. """ def perimeter(lst): # Working Out Length of Side 1 Side_01_H = abs(lst[0][0] - lst[1][0]) Side_01_V = abs(lst[0][1] - lst[1][1]) A_Squared = Side_01_H ** 2 B_Squared = Side_01_V ** 2 C_Squared = A_Squared + B_Squared TSL1_Length = C_Squared ** 0.5 # Working Out Length of Side 2 Side_02_H = abs(lst[1][0] - lst[2][0]) Side_02_V = abs(lst[1][1] - lst[2][1]) A_Squared = Side_02_H ** 2 B_Squared = Side_02_V ** 2 C_Squared = A_Squared + B_Squared TSL2_Length = C_Squared ** 0.5 # Working Out Length of Side 3 Side_03_H = abs(lst[2][0] - lst[0][0]) Side_03_V = abs(lst[2][1] - lst[0][1]) A_Squared = Side_03_H ** 2 B_Squared = Side_03_V ** 2 C_Squared = A_Squared + B_Squared TSL3_Length = C_Squared ** 0.5 # Working Out Perimeter of Triangle Perimeter = TSL1_Length + TSL2_Length + TSL3_Length # Rounding and Giving Answer Answer = round(Perimeter,2) return Answer
39296d73450775bf150d55f89f1884705cb676bb
ch3n-github/Leetcode
/_20_isValid.py
263
3.671875
4
class Solution: def isValid(self, s: str) -> bool: valdic=['{}','()','[]'] s0='' for i in s: s0+=i if s0[-2:]in valdic: s0=s0[:-2] if s0=='':return True else:return False
d6a40e0f05b1040bfea89d08d869a124cd863bdc
pinological/pythonClass4th
/pythonlist1/qn8.py
202
4.1875
4
import array number = input("Enter the number :") temp = number[::-1] if(number == temp): print("The number "+number+" is a palindrome") else: print("The number "+number+" is not a palindrome")
3fe0f513c8b7a35f2f232bc6114d6a47fee13644
rjcrter11/leetChallenges
/arrays/matrix_elements_sum.py
776
3.984375
4
''' Given matrix, a rectangular matrix of integers, where each value represents the cost of the room, your task is to return the total sum of all rooms that are suitable for the CodeBots (ie: add up all the values that don't appear below a 0). Example -For matrix = [[0, 1, 1, 2], [0, 5, 0, 0], [2, 0, 3, 3]] the output should be matrixElementsSum(matrix) = 9. ''' input = [[0, 1, 1, 2], [0, 5, 0, 0], [2, 0, 3, 3]] def matrixElementsSum(matrix): row = len(matrix) col = len(matrix[0]) total = 0 for j in range(col): for i in range(row): if matrix[i][j] != 0: total += matrix[i][j] else: break return total print(matrixElementsSum(input))
d18c10b9adc6cceb4091e3f99ba7c0e584f2bdb8
Srihitha2782/BestEnlist
/task21.py
747
3.859375
4
#1Q def listofTuples(11, 12): return list(map(lambda x, y:(x,y), 11, 12)) list1 = [1,2,3] list2 = ['a', 'b', 'c'] print(listofTuples(list1, list2)) def merge(list1, list2): merged_list = list(zip(list1, list2)) return merged_list list1 = [1,2,3] list2 = ['a', 'b', 'c'] print(merge(list1, list2)) #2Q list1 = [1,2,3,4,5,6,7,8] list2 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] result =tuple(zip(list1,list2)) print(result) #3Q list1=[23,45,26,35,35,55,44] list2=sorted(list1) print(list2) #4Q def filtereven(nums): if nums%2 !=0: return True else: return False numbers =[23,11,25,53,44,56,35,56,48,38,68] result=filter(filtereven,numbers) for i in result: print(i)
89a92dc31166267184d089faa36c0f9699de175b
IlyaMosiychuk/python_language
/students/km63/Mosijchuk_Illya/homework_7.py
5,678
3.6875
4
#task1----------------------------------------------- """ Найдите индексы первого вхождения максимального элемента. Выведите два числа: номер строки и номер столбца, в которых стоит наибольший элемент в двумерном массиве. Если таких элементов несколько, то выводится тот, у которого меньше номер строки, а если номера строк равны то тот, у которого меньше номер столбца. Программа получает на вход размеры массива n и m, затем n строк по m чисел в каждой. """ row = input().split(' ') n = int(row[0]); m = int(row[1]) line = [input() for i in range(n)] mas = (' '.join(line)).split() mas = [int(i) for i in mas] print(((mas.index(max(mas))) // m), (mas.index(max(mas))) // n) #---------------------------------------------------- #task2----------------------------------------------- """ Дано нечетное число n. Создайте двумерный массив из n×n элементов, заполнив его символами "." (каждый элемент массива является строкой из одного символа). Затем заполните символами "*" среднюю строку массива, средний столбец массива, главную диагональ и побочную диагональ. В результате единицы в массиве должны образовывать изображение звездочки. Выведите полученный массив на экран, разделяя элементы массива пробелами. """ size = int(input()) TwoDArray = [['.'] * size for i in range(size)] for i in range(size): TwoDArray[i][i] = '*' TwoDArray[size // 2][i] = '*' TwoDArray[i][size // 2] = '*' TwoDArray[i][size - i - 1] = '*' for row in TwoDArray: print(' '.join(row)) #---------------------------------------------------- #task3----------------------------------------------- """ Даны два числа n и m. Создайте двумерный массив размером n×m и заполните его символами "." и "*" в шахматном порядке. В левом верхнем углу должна стоять точка. """ size = input().split() a=int(size[0]) b=int(size[1]) matrix = ['.'] * a for i in range(a): matrix[i] = ['.'] * b for i in range(a): for j in range(b): if (i+j)%2 == 1: matrix[i][j] = '*' for i in range(a): for j in range(b): print(matrix[i][j], end=' ') print() #---------------------------------------------------- #task4----------------------------------------------- """ Дано число n. Создайте массив размером n×n и заполните его по следующему правилу. На главной диагонали должны быть записаны числа 0. На двух диагоналях, прилегающих к главной, числа 1. На следующих двух диагоналях числа 2, и т.д. """ n = int(input()) matrix = [[abs(i - j) for j in range(n)] for i in range(n)] for row in matrix: print(' '.join([str(i) for i in row])) #---------------------------------------------------- #task5----------------------------------------------- """ Дано число n. Создайте массив размером n×n и заполните его по следующему правилу: Числа на диагонали, идущей из правого верхнего в левый нижний угол равны 1. Числа, стоящие выше этой диагонали, равны 0. Числа, стоящие ниже этой диагонали, равны 2. Полученный массив выведите на экран. Числа в строке разделяйте одним пробелом. """ size = int(input()) matrix = [0] * size for i in range(size): matrix[i] = [0] * (size-i-1) + [1] + [2] * i for i in range(size): for j in range(size): print(matrix[i][j], end=' ') print() #---------------------------------------------------- #task6----------------------------------------------- """ Дан двумерный массив и два числа: i и j. Поменяйте в массиве столбцы с номерами i и j и выведите результат. Программа получает на вход размеры массива n и m, затем элементы массива, затем числа i и j. Решение оформите в виде функции swap_columns(a, i, j). """ def swap_columns(matrix, i, j): for z in range (a): buf=matrix[z][i] matrix[z][i]=matrix[z][j] matrix[z][j]=buf return size = input().split() a = int(size[0]) b = int(size[1]) matrix = [] for k in range(a): row = input().split() for k in range(len(row)): row[k] = int(row[k]) matrix.append(row) size = input().split() i = int(size[0]) j = int(size[1]) swap_columns(matrix, i, j) for i in range(a): for j in range(b): print(matrix[i][j], end=' ') print() #----------------------------------------------------
e209c8ebcc4a19c0b93982b9497175b6ef587624
candytale55/Bitwise_Operations_Py_2
/11_The_Man_Behind_the_Bit_Mask.py
936
4.53125
5
""" A bit mask is just a variable that aids you with bitwise operations. A bit mask can help you turn specific bits on, turn others off, or just collect data from an integer about which bits are on or off. """ # we want to see if the third bit from the right is on: num = 0b1100 mask = 0b0100 desired = num & mask if desired > 0: print "Bit was on" """ we create a mask with the third bit on. Then, we use a bitwise-AND operation to see if the third bit from the right of num is on. If desired is greater than zero, then the third bit of num must have been one. """ # function _check_bit4_ takes one argument _input_, an integer. It should check to see if the fourth bit from the right is on. def check_bit4(input): mask = 0b1000 checked = input & mask if checked > 1: return "on" else: return "off" print check_bit4(0b1) # ==> "off" print check_bit4(0b11011) # ==> "on" print check_bit4(0b1010) # ==> "on"
6891eaaaa7e7136afd12bc737ef3ac5f4e71255c
GitDruidHub/lessons-1
/lesson-06/classwork-01.py
305
3.53125
4
dict_eng_to_rus = { "apple": "яблоко", "house": "дом" } dict_rus_to_eng = { value: key for key, value in dict_eng_to_rus.items() } def from_eng_to_rus(eng): rus = dict_eng_to_rus[eng] return rus def from_rus_to_eng(rus): eng = dict_rus_to_eng[rus] return eng
004f2809837913d7b1cfb949743bd4ce3edde9c0
suchak1/leetcode
/e/univalued-bst.py
544
3.84375
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def unival(self, root, val): if not root: return True else: return root.val == val and self.unival(root.left, val) and self.unival(root.right, val) def isUnivalTree(self, root: TreeNode) -> bool: if not root: return True return self.unival(root, root.val) #36ms, 91.69%
18be90e99417955daeebd2b304f8790b754a2792
evicente71/evicente_pyton
/cadenas.py
1,005
4.28125
4
# Ejemplo de cadenas s1 = "Parte 1" s2 = "Parte 2" print(s1 + " " + s2) #Parte 1 Parte 2 s = "curso de Python" print(type(s)) #Formateo de cadenas x = 5 s = "El número es: " + str(x) print(s) s = "Los números son %d y %d." % (5, 10) print(s) #uso de format cadenas s = "Los números son {} y {}".format(5, 10) print(s) s = "Los números son {a} y {b}".format(a=5, b=10) print(s) #cadenas literales o f-strings, permite incrustar expresiones dentro de cadenas. a = 5; b = 10 s = f"Los números son {a} y {b}" print(s) #Se puede multiplicar un string por un int. Su resultado es replicarlo tantas veces como el valor del entero. s = "Hola " print(s*3) #Hola Hola Hola #Podemos ver si una cadena esta contenida en otra con in. print("mola" in "Python mola") #Con chr() and ord() podemos convertir entre carácter y su valor numérico que lo representa y viceversa. El segundo sólo función con caracteres, es decir, un string con un solo elemento. print(chr(8364)) #€ print(ord("€")) #110
95808b861c32248f3557a3957e39cbe06211f87b
Yifei-Deng/myPython-foundational-level-practice-code
/Woniu ATM version3.0.py
3,691
3.5625
4
''' WoniuATM a. 在前面项目的基础上进一步改进,要求使用一个二位列表来保存用户名和密码 b. 添加如下操作主菜单,用户选择对应的菜单选项进行操作,每次操作完成后继续进入主菜单,用户输入3之后可以结束并退出应用 *****************Welcome to Woniu ATM***************** ******Please Choose One of The Following Options****** **************1.Sign Up 2.Log In 3.Exit*************** ''' users = [ ['Rey','5P1Wsl'], ['Rose','pPofPI'], ['Finn','FL4J4L'] ] def get_menu(): menu = ''' *****************Welcome to Woniu ATM***************** ******Please Choose One of The Following Options****** **************1.Sign Up 2.Log In 3.Exit*************** ''' while True: print(menu) op = input('Please enter your option: ') if op == '1': reg() elif op == '2': login() elif op == '3': print('Thanks for using Woniu ATM, see you next time...') break else: print('Invalid input, please try again!') def reg(): print("Welcome to Woniu ATM, sign up now!") while True: return_flag = True user = input('Please enter the username for your new account: ') for record in users: if record[0] == user: print('The username has already been taken, try another!') return_flag = False break if return_flag: break while True: pw = input('Please enter the password for your new account: ') if len(pw) < 6: print("Your password can't be less then 6 characters long, try another!") else: users.append([user,pw]) print('Thanks for signing up with Woniu ATM. Redirecting to the Start menu... ') return def login(): return_flag = False while True: user = input('Please enter your username: ') pw = input('Please enter your password: ') for record in users: if record[0] == user and record[1] == pw: print('Hello {}!'.format(user)) return_flag = True break if return_flag: break else: print('The username or password you entered is incorrect, please try again!') if __name__ == '__main__': get_menu() ''' Example Outputs: *****************Welcome to Woniu ATM***************** ******Please Choose One of The Following Options****** **************1.Sign Up 2.Log In 3.Exit*************** Please enter your option: 1 Welcome to Woniu ATM, sign up now! Please enter the username for your new account: Rey The username has already been taken, try another! Please enter the username for your new account: Poe Please enter the password for your new account: 123 Your password can't be less then 6 characters long, try another! Please enter the password for your new account: 123456 Thanks for signing up with Woniu ATM. Redirecting to the Start menu... *****************Welcome to Woniu ATM***************** ******Please Choose One of The Following Options****** **************1.Sign Up 2.Log In 3.Exit*************** Please enter your option: 2 Please enter your username: Poe Please enter your password: 123456 Hello Poe! *****************Welcome to Woniu ATM***************** ******Please Choose One of The Following Options****** **************1.Sign Up 2.Log In 3.Exit*************** Please enter your option: 3 Thanks for using Woniu ATM, see you next time... '''
46c3d5a31541a82d027ae7a16075716ba603494b
jewells07/Python
/divisible7&5.py
174
3.796875
4
#Find numbers which are divisible by 7 and multiple of 5 between a range n1=[] for x in range(1,200): if(x%7==0) and (x%5==0): n1.append(str(x)) print(",".join(n1))
06fa4009cec4a6db92cce8ae8e8a9bcd24bb5bbe
george39/hackpython
/entrada.py
176
4.15625
4
#!/usr/bin/env python #_*_ coding: utf8 _*_ nombre = input("digite su nombre") edad = int(input("digite la edad")) print('tu nombre es: ' + nombre) print('tu edad es ', edad)
c61eb10372fca1bc295758c20137fd53eaffe7f6
northcott-j/film-revenue-model
/src/data_collection/QueueConsumer.py
1,225
4.0625
4
""" Abstract class to handle taking an item, doing something, and adding it to an output Queue """ from abc import ABCMeta, abstractmethod from threading import Thread class QueueConsumer: __metaclass__ = ABCMeta def __init__(self, ins, outs): self.input_q = ins self.output_q = outs self.thread = None def start(self): """ Starts a thread using the consume method and passes in and out queue :mutate thread: Starts and adds a thread :return: Nothing """ self.thread = Thread(target=self.consume_loop, args=()) self.thread.daemon = True self.thread.start() def consume_loop(self): """ While True to keep consuming items :return: Nothing """ while True: try: self.consume() except: print "SOMETHING ABSOLUTELY HORRID HAPPENED BUT I'M GONNA KEEP ON TRUCKING!!!!" @abstractmethod def consume(self): """ method to consume an item from the input and add it to the output :param input_q: queue of input items :param output_q: queue of output items :return: Nothing """
e9e91310537c8efb5f082271da1653d76b94e62b
gurbuxanink/Python-Companion-to-ISLR
/code/chap2/incomeEdPlot.py
1,137
4.15625
4
import pandas as pd import matplotlib.pyplot as plt import numpy as np income_ed = pd.read_csv('data/Income1.csv', index_col=0) # The book does not provide the true function of Income versus Education # This function is similar to the plot shown in the book def edIncome(ed, a, b, c, d): return d + c * np.exp(a * ed + b) / (1 + np.exp(a * ed + b)) income_true = np.vectorize(edIncome)(income_ed['Education'], 0.6, -9.6, 60, 20) ed_exog = np.linspace(income_ed['Education'].min(), income_ed['Education'].max()) fig = plt.figure() ax1 = fig.add_subplot(121) income_ed.plot(x='Education', y='Income', kind='scatter', legend=False, ax=ax1, c='r', alpha=0.7) ax1.set_xlabel('Years of Education') ax2 = fig.add_subplot(122) income_ed.plot(x='Education', y='Income', kind='scatter', legend=False, ax=ax2, c='r', alpha=0.7) ax2.set_ylabel('') ax2.set_xlabel('Years of Education') ax2.plot(ed_exog, np.vectorize(edIncome)(ed_exog, 0.6, -9.6, 60, 20), 'b-') ax2.vlines(income_ed['Education'], income_true, income_ed['Income'], colors='b', alpha=0.7) fig.tight_layout()
854eb1c70addcefc8ce71c70e91795aef40d8fcc
TeoMoisi/LFTC
/Scanner/Scanner.py
3,986
3.53125
4
from LanguageSpecification import operators, lexic, separators, codificationTable import re class Scanner: def __init__(self, pif, symbolTable, fileManipulator): self.pif = pif self.symbolTable = symbolTable self.fileManipulator = fileManipulator def stringWithoutQuotes(self, line, index): if index == 0: return False return line[index - 1] == '\\' def lookUp(self, char): for operator in operators: if char in operator: return True return False def isIdentifier(self, token): return re.match(r'^(?=.{1,8}$)_{0,1}[a-zA-Z]+\d*$', token) def isConstant(self, token): return re.match(r'^(true|false|\d{1}|[+-]{1}[1-9]{1}|[1-9]{1}\d*|[+-]{1}[1-9]{1}\d*|''[a-zA-Z0-9]{1}''|"[a-zA-z0-9 ]*")$', token) def detectStringToken(self, line, index): quotesNumber = 0 token = '' while index < len(line) and quotesNumber < 2: if line[index] == '"' and not self.stringWithoutQuotes(line, index): quotesNumber += 1 token += line[index] index += 1 return token, index def detectOperatorToken(self, line, index): token = '' while index < len(line) and self.lookUp(line[index]): token += line[index] index += 1 if token == '-' and self.isConstant(line[index]): token += line[index] index += 1 return token, index def ifValidLenght(self, token): if token and len(token) <= 8: return True return False def detectToken(self, line): token = '' index = 0 tokens = [] while index < len(line): if line[index] == '"': if token: tokens.append(token) token, index = self.detectStringToken(line, index) tokens.append(token) token = '' elif line[index] in separators: if token: tokens.append(token) token, index = line[index], index + 1 tokens.append(token) token = '' elif self.lookUp(line[index]): if token: tokens.append(token) token, index = self.detectOperatorToken(line, index) tokens.append(token) token = '' else: token += line[index] index += 1 if token: tokens.append(token) return tokens def scan(self, filename): errors = [] with open(filename, 'r') as file: lineNumber = 0 for line in file: lineNumber += 1 for token in self.detectToken(line[0:-1]): if token in lexic: self.pif.add(codificationTable[token], -1) elif self.isIdentifier(token): id = self.symbolTable.add(token) self.pif.add(codificationTable['identifier'], id) elif self.isConstant(token): id = self.symbolTable.add(token) self.pif.add(codificationTable['constant'], id) else: errors.append('This ' + token + 'does not exists.') if len(errors) == 0: print("There are no errors!\n") else: print("ERRORS: \n") print(errors) print("Codification table: \n", codificationTable) print('Program Internal Form: \n', self.pif) self.fileManipulator.writePifToFile(self.pif) result = [] for p in self.pif.getPIF(): result.append(str(p[0])) print("PIF", result) print('Symbol Table: \n', self.symbolTable) self.fileManipulator.writeSymbolTableToFile(self.symbolTable)
e5e189f6821e116aea1ee15a89c144a6a0ba9344
Winnie1003/python
/dongChui.py
476
3.828125
4
#coding=utf-8 import random #1.获取用户输入 player = int(input("please input a number:0:剪刀,1:石头,2:布...")) #2.获取电脑输入 computer = random.randint(0,2) #3.将玩家的输入和电脑的输入作比较 #玩家盈 if (player == 0 and computer == 1) or (player == 1 and computer == 2) or (player == 2 and computer == 0): print("Congradulation!You win!") #平局 elif player == computer: print("WIN-WIN!") #玩家输 else: print("Sorry!You failed!")
f55a862e6e398f8c8696bffc2777db3bc1cfc6a6
Indiana3/python_exercises
/wb_chapter5/exercise113.py
439
4.28125
4
## # Read a collection of words and display each word only once # # Start with an empty list words = [] # Read a word from user and add it to the list till a blank line is entered word = input("Please, enter a word: ") while word != "": words.append(word) word = input("Please, enter another word: ") # Display each word in the list just once for i in range(len(words)): if words[i] not in words[:i]: print(words[i])
2430a171a815debe7d24712c04dad8db852c1d15
TMcMac/holbertonschool-higher_level_programming
/0x03-python-data_structures/10-divisible_by_2.py
265
3.9375
4
#!/usr/bin/python3 def divisible_by_2(my_list=[]): if len(my_list) == 0: return None results = [] for num in my_list: if num % 2 == 0: results.append(True) else: results.append(False) return results
26f4ab2068f8db50d1c58577de51b5d2f943acc0
keerow/python-Q2
/Ex3 - Sequences & Lists/firstlastnameSearch.py
655
4.03125
4
#Prend en entrée le nom des étudiants et renvoie une liste d'étudiants n'ayant pas été cités firstname = ['Anne', 'Bastien', 'Cécile', 'Didier', 'Bastien','Cécile'] lastname = ['Smal','Bodart','Pirotte','Valentin','Boldart','Poireau'] search = [] #Simulation d'un DO WHILE sur python inputname = input("Nom de l'élève (Entrez Q pour terminer): ") while inputname != 'Q' : search.append(inputname) inputname = input("Nom de l'élève (Entrez Q pour terminer): ") for i,j in zip (firstname,lastname) : #Affiche la liste d'étudiants qui n'ont pas été cités if search.count(i) <= 0 : print(i,j,"n'a pas été cité(e)")
51a3929965fa81e23638ca2907e017e0ee4e3d38
mitchellflax/lps_grading
/ps6/jorge.py
977
3.953125
4
class Player(object): def __init__(self, name, age, goals): self.name = name self.age = age self.goals = goals def getStats(self): summary = "The players name is " + self.name + "." + "\n" summary = summary + "The players age is " + str(self.age) + "." + "\n" summary = summary + "The players final goals are " + str(self.goals) + "." return summary players = [] # x.getStats() keepRunning = True while keepRunning: print("(0) To add a player:") print("(1) To see the players stats:") print("(2) To exit and delete information:") y = raw_input() if y == "0": print("What is the name of the player?") playerName = raw_input() print("What is the age of the player?") playerAge = raw_input() print("How many goals did this player get?") playerGoals = raw_input() myPlayer = Player(playerName, playerAge, playerGoals) players.append(myPlayer) elif y == "1": for p in players: print(p.getStats()) elif y == "2": keepRunning = False
940b5d0055ee9eb938abd40e1c7d624c1d95ddc8
jashby360/Python-Playground
/PythonEx/ch2.26.py
379
3.84375
4
import turtle c = int(input("Enter the radius: ")) turtle.down() turtle.circle(c) turtle.penup() turtle.setposition(-(c * 2), 0) turtle.pendown() turtle.circle(c) turtle.penup() turtle.setposition(0, -(c * 2)) turtle.pendown() turtle.circle(c) turtle.penup() turtle.setposition(-(c * 2), -(c * 2)) turtle.pendown() turtle.circle(c) turtle.mainloop()
9036b8bbac167a941a4ed09195cd32ef2730d805
pvanh80/intro-to-programming
/round01/study_benefits.py
437
3.875
4
amount_study_benefit = float(input('Enter the amount of the study benefits: ')) index_raise = 0.0117 after_raise = amount_study_benefit*index_raise+amount_study_benefit print ('If the index raise is 1.17 percent, the study benefit,' '\n' 'after a raise, would be', after_raise, 'euros') print ('and if there was another index raise, the study' '\n' 'benefits would be as much as', after_raise*index_raise + after_raise, 'euros')
db8402bb7f364388c40a6628a38fa268bd3bd05d
CalicheCas/IS211_Assignment6
/conversions_refactored.py
2,256
3.75
4
def convertThat(self, fromUnit, toUnit, value): # Distance Conversions while fromUnit.lower() == 'miles': if toUnit.lower() == 'meters': return round(value * 1609.344, 2) elif toUnit.lower() == 'yards': return round(value * 1760, 2) elif toUnit.lower() == 'miles': return value else: raise Exception('ConversionNotPossibleException') while fromUnit.lower() == 'yards': if toUnit.lower() == 'meters': return round(value / 0.9144, 2) elif toUnit.lower() == 'miles': return round(value / 1760, 2) elif toUnit.lower() == 'yards': return value else: raise Exception('ConversionNotPossibleException') while fromUnit.lower() == 'meters': if toUnit.lower() == 'miles': return round(value / 1609.344, 2) elif toUnit.lower() == 'yards': return round(value * 1.094, 2) elif toUnit.lower() == 'meters': return value else: raise Exception('ConversionNotPossibleException') # Temperature Conversions while fromUnit.lower() == 'kelvin': if toUnit.lower() == 'celsius': return round(value - 273.15, 2) elif toUnit.lower() == 'fahrenheit': return round((value - 273.15) * (9/5) + 32, 2) elif toUnit.lower() == 'kelvin': return value else: raise Exception('ConversionNotPossibleException') while fromUnit.lower() == 'celsius': if toUnit.lower() == 'kelvin': return round(value + 273.15, 2) elif toUnit.lower() == 'fahrenheit': return round((value * 9/5) + 32, 2) elif toUnit.lower() == 'celsius': return value else: raise Exception('ConversionNotPossibleException') while fromUnit.lower() == 'fahrenheit': if toUnit.lower() == 'kelvin': return round((value + 459.67) * (5/9), 2) elif toUnit.lower() == 'celsius': return round((value - 32) / 1.8, 2) elif toUnit.lower() == 'fahrenheit': return value else: raise Exception('ConversionNotPossibleException')
4d14544d41079e18bba67fad0f72063784f69931
Zoom30/a115_repo
/challenge.py
294
3.859375
4
def tuple_added(nums, target): if type(nums) != list: raise TypeError("You are expected to insert a list") else: for i in range(0, len(nums)): for j in range(i + 1, len(nums)): if nums[i] + nums[j] == target: return i, j
2016bd3ee79cbee4d4c565cd92d62fc4be2acd17
standardgalactic/bond
/pybond/tutorials/heat_watcher/heat_watcher.py
3,650
3.5625
4
# # A simple demonstration of using Bond for spying and mocking # an application for monitoring temperature and sending alerts # # See a full explanation of this example at # http://necula01.github.io/bond/example_heat.html # # rst_Start import time import re import urllib, urllib2 from bond import bond class HeatWatcher: """ Monitor temperature rise over time. See description in the Bond documentation. """ def __init__(self): self.last_temp = None # The last temp measurement self.last_time = None # The time when we took the last measurement self.last_alert_state = 'Ok' # Ok, Warning, Critical self.last_alert_time = float('-inf') # Time when we sent the last alert def monitor_loop(self, exit_time=None): """ Monitor the temperature and send alerts :param exit_time: the time when to exit the monitor loop. """ while True: temp = self.get_temperature() now = self.get_current_time() if exit_time is not None and now >= exit_time: return if self.last_temp is None: # First reading self.last_temp = temp self.last_time = now interval = 60 else: change_rate = (temp-self.last_temp) / (now-self.last_time) * 60 if change_rate < 1: interval = 60 alert_state = 'Ok' elif change_rate < 2: interval = 10 alert_state = 'Warning' else: interval = 10 alert_state = 'Critical' self.last_temp = temp self.last_time = now if (alert_state != self.last_alert_state or (alert_state != 'Ok' and now >= 600 + self.last_alert_time)): # Send an alert self.send_alert("{}: Temperature is rising at {:.1f} deg/min" .format(alert_state, change_rate)) self.last_alert_time = now self.last_alert_state = alert_state self.sleep(interval) # Spy this function, want to spy the result @bond.spy_point(spy_result=True, mock_only=True) def get_temperature(self): """ Read the temperature from a sensor """ resp_code, temp_data = \ self.make_request('http://system.server.com/temperature') assert resp_code == 200, 'Error while retrieving temperature!' match = re.search('<temperature>([0-9.]+)</temperature>', temp_data) assert match is not None, \ 'Error while parsing temperature from: {}'.format(temp_data) return float(match.group(1)) @bond.spy_point(mock_only=True) def get_current_time(self): """ Read the current time """ return time.time() @bond.spy_point() def sleep(self, seconds): """ Sleep a few seconds """ time.sleep(seconds) @bond.spy_point() def send_alert(self, message): """ Send an alert """ self.make_request('http://backend.server.com/messages', {'message': message}) @bond.spy_point(require_agent_result=True) def make_request(self, url, data=None): """ HTTP request (GET, or POST if the data is provided) """ resp = urllib2.urlopen(url, urllib.urlencode(data)) return (resp.getcode(), resp.read())
e8f4b54c644f0380cb3fcc83696147f948aac196
GangaJathin/Ganga-Jathin
/NEXUS.py
6,872
4
4
def title(): print("THE.......") print("MYSTERY.....") print("press p to play, q to exit....") print("P.S......press enter to advance to next message") title() print("you are in a cold dark room with an old man with a scar on his eye beside you") print("All you remember is that few minutes ago u were happy ") print("playing with your friends and then suddenly......") print(" THRASH:!!! hey you what's your name kiddo!") print("Enter Your Name") name = input("") print("ok" + name + "listen you wanna know why you are here??") print("y(yes)/n(no)") ch=input() if ch=="y": print("THEN ! do what i say i will tell you everything after you help me") input() print("......oh no....") input() print("he is coming shoot him with the gun behind you!!!!") else: print("what an idiotic question i asked......") input() print("help me you dont have any other choice or else you will die ......") input() print("He is coming shoot him with the gun behind you!!!!!") print("s(shoot)/d(not shoot)") ch=input() if ch=="s": print("hey kid nice shot dude! well we got the keys there lets get out") input() print(" well you dont know but you just became the underwold biggest mafia don") input() print("can't believe it! welcome to mafiaworld your majesty") else: print("the intruder takes a gun and kills u") input() print("GAME OVER GAME OVER GAME OVER GAME OVER") input() title() print("CHAPTER TWO........") input() print("so u wanna know your parents flashback huh?") print("y(yes)/n(no)") ch=input() if ch=="y": print("your father was mafia king of the golden mafia era") input() print("after his death you are the next mafia king") input() print("you will take the responsibility, won't you?") input() print("a] 'of course i want to become a king why not for mafias'") print("b] 'what is my dad that scary, no i will call police to take care of the rest'") print("c] 'nah, not interested in these stuffs...booring ....lame....'") print("a/b/c") ch=input() if ch=="a": print("i know his blood runs through your veins well then i shall be your minister") print("as a first step kill this innocent young man will you") print("k(kill)/n(no kill)") ch=input() if ch=="k": print("Very well, this world shall be ours!") else: print("what a innocent kid you are i need to mend your ways first") elif ch=="b": print("HOW THE HELL CAN YOU BE SO ARROGANT TO YOUR DAD OUR KING I NEED TO KILL YOU HERE NOW") input() print("takes the gun and kills you") input() print("GAME OVER GAME OVER GAME OVER") else: print("impossible his blood should run through your veins") input() print("well as a witness of the truth i must kill you now am sorry") input() print("takes the gun annd kills you") input() print("GAME OVER GAME OVER GAME OVER") else: print("you must know your parents flashback and then decide your fate ok dude!") input() print("your father was mafia king of the golden mafia era") input() print("after his death you are the next mafia king") input() print("you will take the responsibility, won't you?") input() print("a] 'of course i want to become a king why not for mafias'") print("b] 'what is my dad that scary, no i will call police to take care of the rest'") print("c] 'nah, not interested in these stuffs...booring ....lame....'") print("a/b/c") ch=input() if ch=="a": print("i know his blood runs through your veins well then i shall be your minister") print("as a first step kill this innocent young man will you") print("k(kill)/n(no kill)") ch=input() if ch=="k": print("Very well, this world shall be ours!") else: print("what a innocent kid you are i need to mend your ways first") elif ch=="b": print("HOW THE HELL CAN YOU BE SO ARROGANT TO YOUR DAD OUR KING I NEED TO KILL YOU HERE NOW") input() print("takes the gun and kills you") input() print("GAME OVER GAME OVER GAME OVER") else: print("impossible his blood should run through your veins") input() print("well as a witness of the truth i must kill you now am sorry") input() print("takes the gun annd kills you") input() print("GAME OVER GAME OVER GAME OVER") input() print("thanks for playing this game its name is MAFIUS") title() print("CHAPTER TWO........") input() print("so u wanna know your parents flashback huh?") print("y(yes)/n(no)") ch=input() if ch=="y": print("your father was mafia king of the golden mafia era") input() print("after his death you are the next mafia king") input() print("you will take the responsibility, won't you?") input() print("a] 'of course i want to become a king why not for mafias'") print("b] 'what is my dad that scary, no i will call police to take care of the rest'") print("c] 'nah, not interested in these stuffs...booring ....lame....'") print("a/b/c") ch=input() if ch=="a": print("i know his blood runs through your veins well then i shall be your minister") print("as a first step kill this innocent young man will you") print("k(kill)/n(no kill)") ch=input() if ch=="k": print("Very well, this world shall be ours!") else: print("what a innocent kid you are i need to mend your ways first") elif ch=="b": print("HOW THE HELL CAN YOU BE SO ARROGANT TO YOUR DAD OUR KING I NEED TO KILL YOU HERE NOW") input() print("takes the gun and kills you") input() print("GAME OVER GAME OVER GAME OVER") else: print("impossible his blood should run through your veins") input() print("well as a witness of the truth i must kill you now am sorry") input() print("takes the gun annd kills you") input() print("GAME OVER GAME OVER GAME OVER")
98993ed9b9b69074dc3624a14646e117b5d74f40
aquatiger/LaunchCode
/word count.py
1,841
3.890625
4
# Write a program called alice_words.py # that creates a text file named alice_words.txt # containing an alphabetical listing of all the words and # the number of times each wrod occurs import string file_name = 'oxford.txt' wordset = {} with open(file_name, 'r') as f: for line in f: word_list = line.split(' ') print(word_list) for word in line: cleanWord = word.strip() print(cleanWord) sentence2 = word_list.lower() print(sentence2) for word in word_list: word_list[word] = word_list[word].strip(string.punctuation) print(word_list) if word_list[i] in wordset: wordset[word_list[i]] += 1 else: wordset[word_list[i]] = 1 print(wordset) f.close() ##print(string.punctuation) ##def alice_words(file): ## words = {} ## with open(file, "r") as infile: ## for line in infile: ## lines = line.strip(string.punctuation) ## print(line) ## print(lines) ## splitted = lines.split() ## print(splitted) ## ## # maybe look at the exercises at Code Guild ## for word in line: ## if word in words: ## words[word] += 1 ## else: ## words[word] = 1 ## print(words) ## infile.close() ## ##alice_words("C:/Users/Roger/Documents/Roger/Python/statistics notebook.txt") ## ##def counter(text): ## alphabet = {} ## for achar in text: ## if achar in alphabet: ## alphabet[achar] += 1 ## else: ## alphabet[achar] = 1 ## items = alphabet.items() ## print(items) ## ## keys = alphabet.keys() ## print(keys) ## for char in sorted(keys): ## print(char, "\t", alphabet[char]) ## ##counter(sentence)
bcca74def9958fb37810d2894143e0ceb85e0321
benquick123/code-profiling
/code/batch-2/vse-naloge-brez-testov/DN12-M-001.py
1,788
3.5
4
from collections import * def preberi(ime_datoteke): file = open(ime_datoteke) dictionary = defaultdict(list) line_counter = 1 for line in file: line = line.replace("\n", "") clean_line = map(int, line.split(" ")) dictionary[line_counter] += clean_line line_counter += 1 for key, value in dictionary.items(): for a in value: if value[0] > a: value.insert(0, value.pop()) file.close() return(dictionary) def mozna_pot(pot, zemljevid): a = None exits = [] for key, value in zemljevid.items(): if len(value) == 1: exits.append(key) for (x, y) in zip(pot, pot[1::]): for b in exits: if pot[0] in exits and pot[-1] in exits: if b not in pot[1::]: if y in zemljevid[x]: a = True if y not in zemljevid[x]: return False elif b in pot[1:-1]: return False elif pot[0] not in exits or pot[-1] not in exits: return False return a def hamiltonova(pot, zemljevid): a = None exits = [] roundabout = [] checked = [] for key, value in zemljevid.items(): if len(value) == 1: exits.append(key) else: roundabout.append(key) for c in pot: for b in roundabout: if b not in pot: return False if c in checked: return False if c not in zemljevid.keys(): return False if c in zemljevid.keys(): a = mozna_pot(pot, zemljevid) checked.append(c) return a
44f10e8de70cb01b12913be72836374e53b2e2cc
lilharry/rc-data
/utils/hours.py
13,747
3.859375
4
import sqlite3 import os import csv import random def addKcidsToDb(): #connect to db db = sqlite3.connect("data/database.db") c = db.cursor() #open csvs f1314 = open("data/csv/hours_kc-13-14.csv") f1415 = open("data/csv/hours_kc-14-15.csv") f1516 = open("data/csv/hours_kc-15-16.csv") f1617 = open("data/csv/hours_kc-16-17.csv") #id correspondence #YY - YY f s j S #13 - 14 3 2 1 9 #14 - 15 4 3 2 1 #15 - 16 5 4 3 2 #16 - 17 1 5 4 3 #arrays h1314 = [] h1415 = [] h1516 = [] h1617 = [] reader = list(csv.reader(f1314)) #stuff to generate random number for id l = range(len(reader)) random.shuffle(l) i = 0 for row in reader: try: student = row[0] if student[0:1] == "9": grade = 4 elif student[0:1] == "1": grade = 3 elif student[0:1] == "2": grade = 2 elif student[0:1] == "3": grade = 1 student = int(student) #check if its an int, if not, go to except block student = l[i] hours = int(round(float(row[1]))) if hours < 0: hours = 0 h1314.append([student,hours,grade]) except ValueError: pass i+=1 reader = list(csv.reader(f1415)) #stuff to generate random number for id l = range(len(reader)) random.shuffle(l) i = 0 for row in reader: try: student = row[0] if student[0:1] == "1": grade = 4 elif student[0:1] == "2": grade = 3 elif student[0:1] == "3": grade = 2 elif student[0:1] == "4": grade = 1 student = int(student) student = l[i] hours = int(round(float(row[1]))) if hours < 0: hours = 0 h1415.append([student,hours,grade]) except ValueError: pass i+=1 reader = list(csv.reader(f1516)) #stuff to generate random number for id l = range(len(reader)) random.shuffle(l) i = 0 for row in reader: try: student = row[0] if student[0:1] == "2": grade = 4 elif student[0:1] == "3": grade = 3 elif student[0:1] == "4": grade = 2 elif student[0:1] == "5": grade = 1 student = int(student) student = l[i] hours = int(round(float(row[1]))) if hours < 0: hours = 0 h1516.append([student,hours,grade]) except ValueError: pass i+=1 reader = list(csv.reader(f1617)) #stuff to generate random number for id l = range(len(reader)) random.shuffle(l) i = 0 for row in reader: try: student = row[0] if student[0:1] == "3": grade = 4 elif student[0:1] == "4": grade = 3 elif student[0:1] == "5": grade = 2 elif student[0:1] == "1": grade = 1 student = int(student) student = l[i] hours = int(round(float(row[1]))) if hours < 0: hours = 0 h1617.append([student,hours,grade]) except ValueError: pass i+=1 for student in h1314: c.execute("INSERT INTO kcids1314 VALUES (?,?,?)",(student[0],student[1],student[2])) for student in h1415: c.execute("INSERT INTO kcids1415 VALUES (?,?,?)",(student[0],student[1],student[2])) for student in h1516: c.execute("INSERT INTO kcids1516 VALUES (?,?,?)",(student[0],student[1],student[2])) for student in h1617: c.execute("INSERT INTO kcids1617 VALUES (?,?,?)",(student[0],student[1],student[2])) f1314.close() f1415.close() f1516.close() f1617.close() db.commit() db.close() def addRcidsToDb(): #connect to db db = sqlite3.connect("data/database.db") c = db.cursor() #open csvs f1314 = open("data/csv/hours_src-13-14.csv") f1415 = open("data/csv/hours_src-14-15.csv") f1516 = open("data/csv/hours_src-15-16.csv") f1617 = open("data/csv/hours_src-16-17.csv") #id correspondence #YY - YY f s j S #13 - 14 3 2 1 9 #14 - 15 4 3 2 1 #15 - 16 5 4 3 2 #16 - 17 1 5 4 3 #arrays h1314 = [] h1415 = [] h1516 = [] h1617 = [] reader = list(csv.reader(f1314)) #stuff to generate random number for id l = range(len(reader)) random.shuffle(l) i = 0 for row in reader: try: student = row[0] if student[0:1] == "9": grade = 4 elif student[0:1] == "1": grade = 3 elif student[0:1] == "2": grade = 2 elif student[0:1] == "3": grade = 1 student = int(student) #check if its an int, if not, go to except block student = l[i] hours = int(round(float(row[1]))) if hours < 0: hours = 0 h1314.append([student,hours,grade]) except ValueError: pass i+=1 reader = list(csv.reader(f1415)) #stuff to generate random number for id l = range(len(reader)) random.shuffle(l) i = 0 for row in reader: try: student = row[0] if student[0:1] == "1": grade = 4 elif student[0:1] == "2": grade = 3 elif student[0:1] == "3": grade = 2 elif student[0:1] == "4": grade = 1 student = int(student) student = l[i] hours = int(round(float(row[1]))) if hours < 0: hours = 0 h1415.append([student,hours,grade]) except ValueError: pass i+=1 reader = list(csv.reader(f1516)) #stuff to generate random number for id l = range(len(reader)) random.shuffle(l) i = 0 for row in reader: try: student = row[0] if student[0:1] == "2": grade = 4 elif student[0:1] == "3": grade = 3 elif student[0:1] == "4": grade = 2 elif student[0:1] == "5": grade = 1 student = int(student) student = l[i] hours = int(round(float(row[1]))) if hours < 0: hours = 0 h1516.append([student,hours,grade]) except ValueError: pass i+=1 reader = list(csv.reader(f1617)) #stuff to generate random number for id l = range(len(reader)) random.shuffle(l) i = 0 for row in reader: try: student = row[0] if student[0:1] == "3": grade = 4 elif student[0:1] == "4": grade = 3 elif student[0:1] == "5": grade = 2 elif student[0:1] == "1": grade = 1 student = int(student) student = l[i] hours = int(round(float(row[1]))) if hours < 0: hours = 0 h1617.append([student,hours,grade]) except ValueError: pass i+=1 for student in h1314: c.execute("INSERT INTO rcids1314 VALUES (?,?,?)",(student[0],student[1],student[2])) for student in h1415: c.execute("INSERT INTO rcids1415 VALUES (?,?,?)",(student[0],student[1],student[2])) for student in h1516: c.execute("INSERT INTO rcids1516 VALUES (?,?,?)",(student[0],student[1],student[2])) for student in h1617: c.execute("INSERT INTO rcids1617 VALUES (?,?,?)",(student[0],student[1],student[2])) f1314.close() f1415.close() f1516.close() f1617.close() db.commit() db.close() def getRandomRc(): db = sqlite3.connect("data/database.db") c = db.cursor() query = "SELECT * FROM rcids1314,rcids1415,rcids1516,rcids1617 WHERE rcids1314.id = rcids1415.id AND rcids1415.id = rcids1516.id AND rcids1516.id = rcids1617.id" info = list(c.execute(query)) random.shuffle(info) info = info[0] db.close() return {"id": info[0], "hours": [info[1],info[4],info[7],info[10]] } def getRandomKc(): db = sqlite3.connect("data/database.db") c = db.cursor() query = "SELECT * FROM kcids1314,kcids1415,kcids1516,kcids1617 WHERE kcids1314.id = kcids1415.id AND kcids1415.id = kcids1516.id AND kcids1516.id = kcids1617.id" info = list(c.execute(query)) random.shuffle(info) info = info[0] db.close() return {"id": info[0], "hours": [info[1],info[4],info[7],info[10]] } def getTotalRcHours(): db = sqlite3.connect("data/database.db") c = db.cursor() #hrs = [f,s,j,S] h1314 = [0,0,0,0] h1415 = [0,0,0,0] h1516 = [0,0,0,0] h1617 = [0,0,0,0] info = c.execute("SELECT hours,grade from rcids1314") for x in info: grade = x[1] if grade == 1: h1314[0] += x[0] elif grade == 2: h1314[1] += x[0] elif grade == 3: h1314[2] += x[0] elif grade == 4: h1314[3] += x[0] info = c.execute("SELECT hours,grade from rcids1415") for x in info: grade = x[1] if grade == 1: h1415[0] += x[0] elif grade == 2: h1415[1] += x[0] elif grade == 3: h1415[2] += x[0] elif grade == 4: h1415[3] += x[0] info = c.execute("SELECT hours,grade from rcids1516") for x in info: grade = x[1] if grade == 1: h1516[0] += x[0] elif grade == 2: h1516[1] += x[0] elif grade == 3: h1516[2] += x[0] elif grade == 4: h1516[3] += x[0] info = c.execute("SELECT hours,grade from rcids1617") for x in info: grade = x[1] if grade == 1: h1617[0] += x[0] elif grade == 2: h1617[1] += x[0] elif grade == 3: h1617[2] += x[0] elif grade == 4: h1617[3] += x[0] db.close() return {"2014":h1314, "2015":h1415, "2016":h1516, "2017":h1617} def getTotalKcHours(): db = sqlite3.connect("data/database.db") c = db.cursor() #hrs = [f,s,j,S] h1314 = [0,0,0,0] h1415 = [0,0,0,0] h1516 = [0,0,0,0] h1617 = [0,0,0,0] info = c.execute("SELECT hours,grade from kcids1314") for x in info: grade = x[1] if grade == 1: h1314[0] += x[0] elif grade == 2: h1314[1] += x[0] elif grade == 3: h1314[2] += x[0] elif grade == 4: h1314[3] += x[0] info = c.execute("SELECT hours,grade from kcids1415") for x in info: grade = x[1] if grade == 1: h1415[0] += x[0] elif grade == 2: h1415[1] += x[0] elif grade == 3: h1415[2] += x[0] elif grade == 4: h1415[3] += x[0] info = c.execute("SELECT hours,grade from kcids1516") for x in info: grade = x[1] if grade == 1: h1516[0] += x[0] elif grade == 2: h1516[1] += x[0] elif grade == 3: h1516[2] += x[0] elif grade == 4: h1516[3] += x[0] info = c.execute("SELECT hours,grade from kcids1617") for x in info: grade = x[1] if grade == 1: h1617[0] += x[0] elif grade == 2: h1617[1] += x[0] elif grade == 3: h1617[2] += x[0] elif grade == 4: h1617[3] += x[0] db.close() return {"2014":h1314, "2015":h1415, "2016":h1516, "2017":h1617} def getTotalVolunteers(): db = sqlite3.connect("data/database.db") c = db.cursor() for x in c.execute("SELECT COUNT(*) FROM rcids1314"): rc2014 = x[0] for x in c.execute("SELECT COUNT(*) FROM rcids1415"): rc2015 = x[0] for x in c.execute("SELECT COUNT(*) FROM rcids1516"): rc2016 = x[0] for x in c.execute("SELECT COUNT(*) FROM rcids1617"): rc2017 = x[0] for x in c.execute("SELECT COUNT(*) FROM kcids1314"): kc2014 = x[0] for x in c.execute("SELECT COUNT(*) FROM kcids1415"): kc2015 = x[0] for x in c.execute("SELECT COUNT(*) FROM kcids1516"): kc2016 = x[0] for x in c.execute("SELECT COUNT(*) FROM kcids1617"): kc2017 = x[0] db.close() return {"rc2014":rc2014, "rc2015":rc2015, "rc2016":rc2016, "rc2017":rc2017, "kc2014":kc2014, "kc2015":kc2015, "kc2016":kc2016, "kc2017":kc2017} if __name__ == "__main__": ''' db = sqlite3.connect("data/database.db") c = db.cursor() query = "SELECT * FROM rcids1314,rcids1415,rcids1516,rcids1617 WHERE rcids1314.id = rcids1415.id AND rcids1415.id = rcids1516.id AND rcids1516.id = rcids1617.id" info = list(c.execute(query)) random.shuffle(info) print info[0] ''' print getTotalVolunteers()
404f9d0498bf7bf466ac1333152ffc988061dbe6
shafirpl/InterView_Prep
/Basics/Colt_Data_structure/DynamicPrograming/fibonaci.py
793
4.1875
4
def fibonaci_recursive(n): if n == 1: return 1 if n == 2: return 1 return (fibonaci_recursive(n-1)+ fibonaci_recursive(n-2)) def fibonaci_memo(n, memo = {}): if memo.get(n) is not None: return memo[n] if n <= 2: return 1 memo[n] = fibonaci_memo(n-1, memo) + fibonaci_memo(n-2, memo) return (fibonaci_memo(n-1, memo) + fibonaci_memo(n-2, memo)) def fibonaci_tabulation(n): if( n<= 2 ): return 1 memo = {} memo[0] = 0 memo[1] = 1 memo [2] = 1 i = 3 while i <= n: memo[i] = memo[i-1] + memo[i-2] i += 1 return memo[n] # print(fibonaci_memo(100)) # print(fibonaci_memo(100)) print(fibonaci_tabulation(100)- fibonaci_memo(100)) # print(fibonaci_recursive(100))
41056ebd735b836a3b3cc2a3ce38bfc485ef9fcd
pqnguyen/CompetitiveProgramming
/platforms/interviewbit/MaxDepthofBinaryTree.py
455
3.703125
4
# Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param A : root node of tree # @return an integer def maxDepth(self, A): return self.maxDepthHelper(A) def maxDepthHelper(self, node): if not node: return 0 return max(self.maxDepthHelper(node.left), self.maxDepthHelper(node.right)) + 1
bcaf58fbba375c2fbc89e55a4115b25f1a7d588d
vasujain/Pythonify
/lib108.py
231
3.65625
4
#!/usr/bin/env python """Produces a christmas tree pattern of stars.""" ch = "*" bl = " " for i in range(10): print bl*(9-i), print ch*(2*i -1), print bl*(9-1) #9 bl 1 star 9 bl #8 bl 3 star 8 bl #7 bl 5 star 7 bl
986af6784b1e35b488c1e9273e87c4566755cb03
platinum2015/python2015
/cas/python_module/v07_braking_distance.py
343
3.890625
4
def get_braking_distance(v0): ''' Calculates braking distance [m] with mu = 0.3 and v0 [km/h] ''' mu = 0.3 #Coefficient of friction g = 9.81 # gravitational acceleration return 0.5*v0**2 / (mu*g) velocity = 100 #km/h print "The braking distance for v0=",velocity,"is",get_braking_distance(velocity),"m"
7ffdf8aa753b4eb6eb2ae72a04aaa3d22f073f9f
syurskyi/Python_Topics
/021_module_collection/counter/_exercises/templates/counter_005_Updating from another Iterable or Counter_template.py
1,135
4.3125
4
# f.. c... _______ d..d.., C.. # # # Updating from another Iterable or Counter # # Lastly let's see how we can update a Counter object using another Counter object. # # When both objects have the same key, we have a choice - do we add the count of one to the count of the other, # # or do we subtract them? # # We can do either, by using the update (additive) or subtract methods. # # c1 _ C.. a_1 b_2 c_3 # c2 _ C.. b_1 c_2 d_3 # c1.up.. c2 # print(c1) # # Counter({'c': 5, 'b': 3, 'd': 3, 'a': 1}) # # # On the other hand we can subtract instead of add counters: # # c1 _ C.. a_1 b_2 c_3 # c2 _ C.. b_1 c_2 d_3 # c1.su.. c2 # print(c1) # # Counter({'a': 1, 'b': 1, 'c': 1, 'd': -3}) # # # Notice the key d - since Counters default missing keys to 0, when d: 3 in c2 was subtracted from c1, # # the counter for d was defaulted to 0. # # Just as the constructor for a Counter can take different arguments, so too can the update and subtract methods. # # c1 _ C.. 'aabbccddee' # print(c1) # c1.up.. 'abcdef' # print(c1) # # Counter({'a': 2, 'b': 2, 'c': 2, 'd': 2, 'e': 2}) # # Counter({'a': 3, 'b': 3, 'c': 3, 'd': 3, 'e': 3, 'f': 1})
16c1d2822646823aa5f5f0c5567ab17db67d62cf
andystanier/andystanier.github.io
/projects/Yahtzee/yahtzee.py
4,146
4.0625
4
#!/usr/bin/python ############################################################## ## ## Yahtzee.py ## Andy Stanier ## 29-30 August 2016 ## ## The purpose is to simulate throwing a Yahtzee ## (Five of a kind with 5 dice) and counting how ## many goes it takes before it occurs. ## ## The process is repeated many times and the average ## number taken. ## ############################################################## import math import random import sys ## ## Simulates 5 dice being rolled, places the result of each die in a list ## Tests if 5 of dice are the same value ## class fiveDice(): # for holding the 5 dice values _numList = [] def __init__(self): self.roll5dice() # get number list # returns numList def getNumList(self): return self._numList # gets the value at a given index # returns the value # parameter index, the index whose value is required def getIndexOfNumList(self, index): return self._numList[index] # generates a random num from 1 to 6 # returns a number 1 - 6 inclusive def randomNum(self): return random.randint(1,6) # generates 5 random numbers and stores them in a list def roll5dice(self): if len(self._numList) == 5: del self._numList[:] for num in range(5): self._numList.append(self.randomNum()) # tests if two of the dice are equal in value # parameter first, the first number to check against # parameter second, the second number to check # returns True or False def equal2Nums(self, first, second): firstNum = self.getIndexOfNumList(first-1) secondNum = self.getIndexOfNumList(second-1) if firstNum == secondNum: return True else: return False # Tests if all 5 dice are equal (Yahtzee) # returns True or False def yahtzee(self): if self.equal2Nums(1,2) and self.equal2Nums(1,3) and self.equal2Nums(1,4) and self.equal2Nums(1,5): return True else: return False # Rolls the dice the number of times provided # parameter times, number of times to roll the dice # returns the number of rolls to get a Yahtzee def rollDiceXTimes(times): count = 0 x = 0 while x < times: roll = fiveDice() if not(roll.yahtzee()): count += 1 else: #print(roll.getNumList()) count += 1 break x += 1 return count # Main method # takes two arguments, the upperlimit of rolls and the number of repeats # suggested values are 10000 and 150 def main(argv): wrongArgs = "Takes one argument, number of repeats: suggested 150" if len(sys.argv) <= 2: numberOfRepeats = 150 print(wrongArgs) print("Running with %s repeats" % (str(numberOfRepeats))) sys.argv = [sys.argv[0], str(numberOfRepeats)] print("\r") if len(sys.argv) > 2: print(wrongArgs) sys.exit() # roll the dice no more than this upperlimit = 10000 # number of times this is repeated ##times = 150 times = int(sys.argv[1]) # the list to hold the data attempts = [] print("Rolling 5 dice...when I get a Yahtzee I will stop") print("Repeating "+str(times)+" times...") print("\r") # range is the number of times the iterations are run for t in range(times): roll = rollDiceXTimes(upperlimit) if roll == upperlimit: print("Took more than %d attempts" % (upperlimit)) else: attempts.append(roll) minNum = min(attempts) maxNum = max(attempts) aveNum = sum(attempts)/len(attempts) ## output #print(attempts) print("The lowest number of rolls it took me was "+str(minNum)) print("The most was "+str(maxNum)+" rolls") print("On average it took me %.1f rolls" % (aveNum)) print("\r") print("Probability says I should get a Yahtzee every 1296 rolls") print("I was out by %.1f rolls" % math.fabs(aveNum-1296)) if __name__ == "__main__": main(sys.argv[1:])
462d132fc58a8f29bc642d2b55d56714831bb30e
upon120/pythonAlgorithm
/code/第一章/1-6(p24).py
350
4.0625
4
num1 = int(input("Enter the dividend:")) num2 = int(input("Enter the divider:")) if num2 != 0: #如果输入的除数不是0 result = num1/num2 if result == int(num1/num2): #如果result的值与两数相除取整后的值相等 print(int(result),"integer") else: print(result,"decimal") else: print("The divider can’t be 0.Error.")
0b130db7ae27c0a89c40d7b9e680d0bb5a302cd8
menglf1203/python
/课堂/list.py
2,885
3.90625
4
# /usr/bin/env python # -*- coding:utf-8 -*- #列表list # a=[1,'dfgh',3,4,5] # print(a[1]) #支持索引 # print(a[:]) #中括号里加:是显示全部的 # print(a[-2]) #也支持反索引 # print(a[2:9]) #支持切片 # print(a[:2]) # a=[123,'sad',213,['fgh','ytr',87],5,56] # #列表中有:数字,字符串,列表,元组等 # print(a[1][0]) #支持嵌套索引 # print(a[1][2]) #前提是提取的元素是支持索引(也就是字符串) # print(a[1][-1]) #字符串中的元素使用和字符串索引一样 # print(a[3][0][0]) #也可以多层数据嵌套 # print(a[3][0]) #多层数据 #列表中的内置函数 # a=[12,'asdf',34] # b=a[1].upper() #根据数据类型可以这样写 # print(b) # # a=[12,'asdf',34,['uyt',2,5]] # b=[87,'iuyt','jhg'] # a[3].append([87,2,1]) #将括号中的元素添加到表中,注意:只能添加1个 # print(a) #默认添加到最后 # a.append(b) #也可以定义一个列表、字符串等添加进去 # print(a) # a=[12,'asdf',34,['uyt',2,5]] # a.insert(1,'abc') #第一个参数是下标位置,第二个参数是添加的元素 # a.insert(0,[12,4,5]) #添加元素可以是列表、字符串、数字等 # print(a) # a=[12,'asdf',34,['uyt',2,5]] # #a.remove(12) #只能删除某个元素,括号里直接写元素 # a.pop(1) #删除下标位置删除的,括号里写下标号 # print(a) # a=[12,'asdf',34,['uyt',2,5]] # b=a.index(12) #获取某元素的下标值(如果有重复的,只会显示第一个的下标值) # print(b) # print(a[-1].index(2)) #也可以直接写在print括号中 # a='kju1h,ygt' # b=len(a) # print(b) # # a=[12,34,'asdf',34,[34,34,34]] # b=a.count(34) #统计某元素在列表中的个数 # c=len(a) #统计某数据类型有多少个元素 # #len不能统计整数、浮点数 # print(b) # print(a[4].count(34)) # print(c) # d='kjuytrertyui' # print(len(d)) # a=[12,34,'asdf',34,[34,34,34]] # a.reverse() #反转列表 # print(a) # a=['asd','Zsdf','sdfg','qwert'] # a.sort() #排序,默认是升序 # print(a) #字符串是根据首字母在ASCII中的顺序排序,先大写后小写 # b=[123,4,56,87,9] # b.sort() #数字排序,正序排列 # print(b) # b.sort(reverse=True) #先排序在反转 # print(b) #倒序显示 # import copy # i=[12,4321,24] # a=[i,1234,56543] # b=a.copy() #复制列表 浅复制 # # a.clear() #清空 # # print(a) # # print(b) # a.append(100) # a[0].append(100) # d=copy.deepcopy(a) # print(d) # print(a) # a=[1234,56543] # b=[12,4321,24] # a.extend(b) #将b的元素更新到a列表中 # # b.extend(a) # print(a) # print(b) # b={12,453,45} # a={213,'ds','afsd'} # # print(a|b) # print(a&b) # print(a-b) # a=[123,234,7,56,7,87645,324] # b=set(a) # c=list(b) # c.sort() # print(c) # c.sort(reverse=True) # print(c)
153b9506f70150871f135fb9cc002e757a5ba8db
Aeres-u99/tsurusetto
/tsurusetto.py
646
4.5
4
#!/bin/env python3 # 2 Enter space betweeen similar functions/conversives of each other # 4 Enter space betweeen 2 different functions # A comment line to specify what it does. def character_to_ascii(character_series): '''Converts a characterstring to ascii numbers''' ascii_series = [" ".join(str(ord(characters)) for characters in character_series)][0] return ascii_series def ascii_to_character(ascii_series): character_series = "".join([" ".join(str(chr(int(characters)))) for characters in ascii_series.split(' ')]) return character_series test = ascii_to_character(character_to_ascii("hello world")) print(test)
dd1417c7ca8a59ab9434afe61b0c9f6409c7d6e4
tnakaicode/jburkardt-python
/polpak/omega.py
6,345
4.03125
4
#! /usr/bin/env python # def omega(n): # *****************************************************************************80 # # OMEGA returns OMEGA(N), the number of distinct prime divisors of N. # # First values: # # N OMEGA(N) # # 1 1 # 2 1 # 3 1 # 4 1 # 5 1 # 6 2 # 7 1 # 8 1 # 9 1 # 10 2 # 11 1 # 12 2 # 13 1 # 14 2 # 15 2 # 16 1 # 17 1 # 18 2 # 19 1 # 20 2 # # Formula: # # If N = 1, then # # OMEGA(N) = 1 # # else if the prime factorization of N is # # N = P1^E1 * P2^E2 * ... * PM^EM, # # then # # OMEGA(N) = M # # Licensing: # # This code is distributed under the GNU LGPL license. # # Modified: # # 24 February 2015 # # Author: # # John Burkardt # # Parameters: # # Input, integer N, the value to be analyzed. N must be 1 or # greater. # # Output, integer VALUE, the value of OMEGA(N). But if N is 0 or # less, NDIV is returned as 0, a nonsense value. If there is # not enough room for factoring, NDIV is returned as -1. # from i4_factor import i4_factor if (n <= 0): value = 0 return value if (n == 1): value = 1 return value # # Factor N. # nfactor, factor, power, nleft = i4_factor(n) if (nleft != 1): print('') print('OMEGA - Fatal error!') print(' Not enough factorization space.') value = nfactor return value def omega_test(): # *****************************************************************************80 # # OMEGA_TEST tests OMEGA. # # Licensing: # # This code is distributed under the GNU LGPL license. # # Modified: # # 24 February 2015 # # Author: # # John Burkardt # import platform from omega_values import omega_values print('') print('OMEGA_TEST') print(' Python version: %s' % (platform.python_version())) print(' OMEGA counts the distinct prime divisors of an integer N.') print('') print(' N Exact OMEGA(N)') n_data = 0 while (True): n_data, n, c1 = omega_values(n_data) if (n_data == 0): break c2 = omega(n) print(' %8d %12d %12d' % (n, c1, c2)) # # Terminate. # print('') print('OMEGA_TEST') print(' Normal end of execution.') return def omega_values(n_data): # *****************************************************************************80 # # OMEGA_VALUES returns some values of the OMEGA function. # # Discussion: # # In Mathematica, the function can be evaluated by # # Length [ FactorInteger [ n ] ] # # First values: # # N OMEGA(N) # # 1 0 # 2 1 # 3 1 # 4 1 # 5 1 # 6 2 # 7 1 # 8 1 # 9 1 # 10 2 # 11 1 # 12 2 # 13 1 # 14 2 # 15 2 # 16 1 # 17 1 # 18 2 # 19 1 # 20 2 # # Formula: # # If N = 1, then # # OMEGA(N) = 0 # # else if the prime factorization of N is # # N = P1^E1 * P2^E2 * \ * PM^EM, # # then # # OMEGA(N) = M # # Licensing: # # This code is distributed under the GNU LGPL license. # # Modified: # # 20 February 2015 # # Author: # # John Burkardt # # Reference: # # Milton Abramowitz and Irene Stegun, # Handbook of Mathematical Functions, # US Department of Commerce, 1964. # # Stephen Wolfram, # The Mathematica Book, # Fourth Edition, # Wolfram Media / Cambridge University Press, 1999. # # Parameters: # # Input/output, integer N_DATA. The user sets N_DATA to 0 before the # first call. On each call, the routine increments N_DATA by 1, and # returns the corresponding data; when there is no more data, the # output value of N_DATA will be 0 again. # # Output, integer N, the argument of the OMEGA function. # # Output, integer C, the value of the OMEGA function. # import numpy as np n_max = 23 c_vec = np.array(( 0, 1, 1, 1, 1, 2, 1, 1, 1, 2, 3, 1, 4, 4, 3, 1, 5, 2, 2, 1, 6, 7, 8)) n_vec = np.array(( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 30, 101, 210, 1320, 1764, 2003, 2310, 2827, 8717, 12553, 30030, 510510, 9699690)) if (n_data < 0): n_data = 0 if (n_max <= n_data): n_data = 0 n = 0 c = 0 else: n = n_vec[n_data] c = c_vec[n_data] n_data = n_data + 1 return n_data, n, c def omega_values_test(): # *****************************************************************************80 # # OMEGA_VALUES_TEST demonstrates the use of OMEGA_VALUES. # # Licensing: # # This code is distributed under the GNU LGPL license. # # Modified: # # 20 February 2015 # # Author: # # John Burkardt # import platform print('') print('OMEGA_VALUES_TEST:') print(' Python version: %s' % (platform.python_version())) print(' OMEGA_VALUES stores values of the OMEGA function.') print('') print(' N OMEGA(N)') print('') n_data = 0 while (True): n_data, n, c = omega_values(n_data) if (n_data == 0): break print(' %12d %12d' % (n, c)) # # Terminate. # print('') print('OMEGA_VALUES_TEST:') print(' Normal end of execution.') return if (__name__ == '__main__'): from timestamp import timestamp timestamp() omega_test() timestamp()
e20fabfeb57512caa024f152e85c902d51d91ceb
komalahire/Test-questioin
/prime.py
202
4.125
4
user_input = input("enter your number") i = 2 while i < (user_input): if user_input % i == 0: print ("not prime number") break i = i + 1 else: print ("prime number")
eb05fed186593ad09d834d19d4af40fe957eb506
DenisPower1/NOS
/tests/teste.py
134
3.828125
4
while True: n=0 n=input("Informe o número a ser multiplicado ") for x in [1,2,3,4,5,6,7,8,9,10,11,12] : print(n,"X",x,"=",n*x)
c5d3b8afbe27965f5d360b7536128d07fb0202d9
cnyy7/LeetCode_EY
/leetcode-algorithms/242. Valid Anagram/242.valid-anagram.py
1,318
3.984375
4
# # @lc app=leetcode id=242 lang=python3 # # [242] Valid Anagram # # https://leetcode.com/problems/valid-anagram/description/ # # algorithms # Easy (52.42%) # Likes: 747 # Dislikes: 111 # Total Accepted: 356.2K # Total Submissions: 676.9K # Testcase Example: '"anagram"\n"nagaram"' # # Given two strings s and t , write a function to determine if t is an anagram # of s. # # Example 1: # # # Input: s = "anagram", t = "nagaram" # Output: true # # # Example 2: # # # Input: s = "rat", t = "car" # Output: false # # # Note: # You may assume the string contains only lowercase alphabets. # # Follow up: # What if the inputs contain unicode characters? How would you adapt your # solution to such case? # # class Solution: def isAnagram(self, s: str, t: str) -> bool: # solution 1 # if len(s)!=len(t): # return False # map=[0]*26 # for i in range(len(s)): # map[ord(s[i]) - ord('a')]+=1 # map[ord(t[i]) - ord('a')]-=1 # for c in map: # if c: # return False # return True # # solution 2 # return sorted(s)==sorted(t) # # solution 3 return collections.Counter(s) == collections.Counter(t)
3bb0dd7e18654592917a9d5b37db4042eabdf32f
milw0rmch/SPSE
/Module2/inputParser.py
545
3.9375
4
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Sun Feb 5 11:39:00 2017 @author: root """ def input_Parser(portRange): plist = portRange.split("-") # print plist[0] # print plist[1] portList = range(int(plist[0]),int(plist[1])+1) return portList # print portList[2] #for i in portList: # print str(i) ## print "-" ##print portRange[1] def print_Parser(): plist = input_Parser("51-60") for i in plist: print(i) print_Parser()
fc29352ab6004121baad2b6d3f44092fce02b6e0
nweston/sort-visualizations
/sort.py
4,695
3.734375
4
import hypothesis.strategies as st def selection_sort(data): """Sort contents of data in place. This is a generator which yields each algorithm step (comparison or swap), allow for visualization or instrumentation. The caller is responsible for performing swaps. """ for dest in range(len(data) - 1): yield 'label', 'Find Smallest' smallest_i = dest yield 'focus', dest for i in range(dest + 1, len(data)): yield 'cmp', smallest_i, i if data[i] < data[smallest_i]: smallest_i = i yield 'focus', i yield 'label', 'Move to Front' yield 'swap', dest, smallest_i def merge(data, left, mid, right): # Copy each sub-list, reverse them so we can pop from the end, and # merge back into the main list. This isn't terribly efficient but # it's convenient. yield 'merge', (left, mid), (mid, right) sub_left = data[left:mid] sub_right = data[mid:right] for i in range(left, right): if not sub_right or (sub_left and sub_left[0] < sub_right[0]): yield 'set', i, sub_left[0] del sub_left[0] else: yield 'set', i, sub_right[0] del sub_right[0] assert len(sub_left) == 0 assert len(sub_right) == 0 def merge_sort(data, left=None, right=None): """Merge sort in place. Like selection_sort, this is a generator.""" if left is None: left = 0 if right is None: right = len(data) if right <= left + 1: return mid = (left + right) // 2 yield 'subdivide', left, mid yield from merge_sort(data, left, mid) yield 'subdivide', mid + 1, right yield from merge_sort(data, mid, right) yield from merge(data, left, mid, right) def quicksort(data, left=None, right=None): """Quick sort in place. Like selection_sort, this is a generator.""" if left is None: left = 0 if right is None: right = len(data) - 1 if right <= left: return mid = None def partition(data, left, right): pi = (left + right) // 2 pivot = data[pi] yield 'label', 'Partition, pivot=%s' % pivot i = left j = right while True: yield 'focus', pi while True: yield 'cmp', i, pi if i == pi or data[i] > pivot: yield 'focus', i, pi break i += 1 while True: yield 'cmp', j, pi if j == pi or data[j] < pivot: yield 'focus', i, j break j -= 1 nonlocal mid if i >= j: mid = j return elif data[i] == pivot and data[j] == pivot: mid = i return yield 'swap', i, j if i == pi: pi = j elif j == pi: pi = i yield from partition(data, left, right) assert(mid is not None) yield 'label', 'Sort Left Side' yield 'subdivide', left, mid + 1 yield from quicksort(data, left, mid) yield 'label', 'Sort Right Side' yield 'subdivide', mid + 1, right + 1 yield from quicksort(data, mid + 1, right) yield 'subdivide', left, right + 1 yield 'label', 'Sorted from %d to %d' % (left, right) def perform_effect(effect, data): """Apply an effect to a list, modifying the data argument.""" kind = effect[0] if kind == 'swap': a, b = effect[1:] data[a], data[b] = data[b], data[a] if kind == 'set': a, b = effect[1:] data[a] = b def run(sort, data, callback=None): """Run a sorting algorithm, passing all effects to optional callback.""" for effect in sort(data): if callback: callback(*effect) perform_effect(effect, data) def print_effects(sort, data): """Run a sorting algorithm, printing all steps.""" run(sort, data, lambda *e: print(*e)) def count_steps(sort, data): """Run a sorting algorithm, returning the number of effects performed.""" def inc_count(effect, *args): nonlocal count if effect in ['cmp', 'swap', 'set']: count = count + 1 count = 0 run(sort, data, inc_count) return count def random_list(length, max_value=None): return st.lists(st.integers(min_value=1, max_value=max_value), min_size=length, max_size=length).example() if __name__ == '__main__': lst = [-2, -2] mysort = quicksort print_effects(mysort, lst) print(lst) print(count_steps(mysort, lst), 'steps')
620a60aa84f44480ccc5843d259509d0304b5c0c
oyxhm/Leetcode
/Leetcode-Python/FlattenBinaryTreeToLinkedList.py
1,051
4.25
4
""" Given a binary tree, flatten it to a linked list in-place. For example, Given 1 / \ 2 5 / \ \ 3 4 6 The flattened tree should look like: 1 \ 2 \ 3 \ 4 \ 5 \ 6 """ from TreeNode import TreeNode class Solution: def __init__(self): self.__pre = None # @param {TreeNode} root # @return {void} Do not return anything, modify root in-place instead. def flatten(self, root): if not root: return temp = root.right if self.__pre: self.__pre.left, self.__pre.right = None, root self.__pre = root self.flatten(root.left) self.flatten(temp) if __name__ == '__main__': n1 = TreeNode(1) n2 = TreeNode(2) n3 = TreeNode(3) n4 = TreeNode(4) n5 = TreeNode(5) n6 = TreeNode(6) n1.left = n2 # n1.right = n5 n2.left = n3 # n2.right = n4 # n5.right = n6 head = Solution().flatten(n1)
3bcad3924bf0c413103c9d522a16f052937969be
runalb/Python-Problem-Statement
/PS-1/ps04.py
270
4.375
4
# PS-04 WAP to accept radius of circle and calculate area and circumference of circle r = float(input("Enter radius of circle: ")) #Aera of circle area = 3.14 * r * r #Circumference of circle circum = 2 * 3.14 * r print("Area:",area) print("Circumference:",circum)
e34370dea04d81a7746edda98242fab660f8d81e
joonkyu4220/LeetCode
/Remove Nth Node From End of List.py
1,528
3.65625
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution(object): def removeNthFromEnd(self, head, n): """ :type head: ListNode :type n: int :rtype: ListNode """ head = ListNode(None, head) cur = head mem = list() idx = 0 for i in range(n): mem.append(cur) cur = cur.next while (cur.next): mem[idx] = cur cur = cur.next idx = (idx + 1) % n mem[idx].next = mem[idx].next.next return head.next # cur = head # sz = 1 # while (cur.next): # cur = cur.next # sz += 1 # cur = head # if sz == n: # return head.next # for i in range(sz): # if i == sz-n-1: # cur.next = cur.next.next # return head # else: # cur = cur.next # cur = head # sz = 1 # while(cur.next): # cur = cur.next # sz += 1 # head = ListNode(None, head) # cur = head # for i in range(sz): # if i == sz - n: # cur.next = cur.next.next # return head.next # else: # cur = cur.next
8ab1b9300d8fa05c260086882736e11037756f97
eshaanmandal/morse_shu
/morshu.py
4,677
3.6875
4
class Morse: '''the default dictionary used for encoding and decoding ''' morse_codes = { 't':'-', 'e':'.', 'm':'--', 'n':'-.', 'a':'.-', 'i':'..', 'o':'---', 'g':'--.', 'k':'-.-', 'd':'-..', 'w':'.--', 'r':'.-.', 'u':'..-', 's':'...', '?':'----', '.':'---.', 'q':'--.-', 'z':'--..', 'y':'-.--', 'c':'-.-.', 'x':'-..-', 'b':'-...', 'j':'.---', 'p':'.--.', 'l':'.-..', '-':'..--', 'f':'..-.', 'v':'...-', 'h':'....', '0':'-----', '9':'----.', '8':'---..', '7':'--...', '6':'-....', '1':'.----', '2':'..---', '3':'...--', '4':'....-', '5':'.....' } error_message = '' error_code = 0 def __init__(self, char_separator=' ', space_separator=' ', dictionary=None): ''' The default constructor accepts the character to use to differentiate between characters and words, default values are single space and double space, the dictionary used for encoding/decoding ''' if len(char_separator) > len(space_separator): self.error_code = -1 self.error_message = '''The length of space separator is less than character separator, it may lead to additional problems when decoding''' self.char_separator = char_separator self.space_separator = space_separator if dictionary is None: self.dictionary = Morse.morse_codes else: self.dictionary = dictionary def convert_to_morse(self, string): ''' Method converts normal text to morse code ''' if self.error_code == -1: return char_count = 0 # Counts the number of character iterated by the for loop string = string + ' ' # adds a space after the last character else it doesn't get encoded to morse isfirstchar = True # flag for checking if the the character is the first character of a word coded_char ='' # stores the encoded character self.coded_string='' # the final encoded string that would be returned l_string = string.lower() # converts the text into lower case for char in l_string: if char in self.dictionary.keys(): char_count += 1 if char_count == 1: if isfirstchar: coded_char += self.dictionary[char] isfirstchar = False else: coded_char += self.char_separator coded_char +=self.dictionary[char] elif char_count == 2: self.coded_string += coded_char self.coded_string += self.char_separator self.coded_string += self.dictionary[char] char_count = 0 coded_char = '' else: isfirstchar = True coded_char += self.space_separator self.coded_string += coded_char char_count = 0 coded_char = '' return self.coded_string def convert_to_normal_text(self, string): ''' Converts the morse code to normal text''' if self.error_code == -1: return string = string + ' ' # a space is needed after the last char else the method fails at last char # /t is of len 1 which causes certain problems: this conditional is for dealing with that if '\t' in self.space_separator: space_num = len(self.space_separator) + 1 else: space_num = len(self.space_separator) # cleaning the code from all the separators after this the code only contains spaces between the characters self.clean_code = '' for char in string: if char not in self.dictionary.keys() and char == '\t': self.clean_code += ' ' elif char not in self.dictionary.keys() and char != '\t': self.clean_code += ' ' else: self.clean_code += char self.normal_text, citext = '','' spaces = 0 # counts the number of spaces # conversion begins for c in self.clean_code: if c != ' ': spaces = 0 citext += c else: spaces += 1 if spaces == space_num: self.normal_text += ' ' elif spaces == 1: self.normal_text += list(self.dictionary.keys())[list(self.dictionary.values()).index(citext)] citext = '' return self.normal_text
a099f9a99aa4b730d4843044b06272759b21b997
akimitsu1025/kadai-04
/for_study.py
8,043
3.953125
4
import pandas as pd ### 商品クラス class Item: def __init__(self,item_code,item_name,price): self.item_code=item_code self.item_name=item_name self.price=price def get_price(self): return self.price ### オーダークラス class Order: def __init__(self,item_master): self.item_order_list=[] self.item_count_list=[] self.item_master=item_master def add_item_order(self, input_code, input_count): # 引数を(self, item_code, item_count)から(self, input_code, input_count)に。 self.item_order_list.append(input_code, input_count) # 引数を(item_code, item_count)から(input_code, input_count) def view_item_list(self): for item in self.item_order_list: print("商品コード:{}".format(item)) #1 オーダー登録した商品の一覧(商品名、価格)を表示できるようにしてください def print_list(self): for xxx in self.item_order_list: for yyy in self.item_master: if yyy.item_code == xxx: print(yyy.item_name, yyy.price) break #2 オーダーをコンソール(ターミナル)から登録できるようにしてください。登録時は商品コードをキーとする def registration(self): input_code = input('購入したい商品のコードを入力してください。(001 or 002 or 003 or 004 or 005):') if input_code in ["001", "002", "003", "004", "005"]: print('{}が登録されました。'.format(input_code)) #4 オーダー登録時に個数も登録できるようにしてください input_count = input('個数を入力してください。:') print('{}個購入します。'.format(input_count)) else: print('正しいコード(001 or 002 or 003 or 004 or 005)を入力してください。') #5 オーダー登録した商品の一覧(商品名、価格)を表示し、かつ合計金額、個数を表示できるようにしてください #3 商品マスタをCSVから登録できるようにしてください def master_registration(): df = pd.read_csv('./master.csv') x = list(df["商品コード"]) y = list(df["商品名"]) z = list(df["価格"]) item_master = [] for xx, yy, zz in zip(x, y, z): item_master.append(Item(xx, yy, zz)) return item_master ### メイン処理 def main(): # main関数の定義。インデントされていないので、これはOrderクラスのメソッドではない? # マスタ登録 # item_master=[] # 変数item_masterに空の空のリストを用意。何のために?これがインスタンス化? # item_master.append(Item("001","りんご",100)) # 31行目で定義したitem_masterにItemクラスを追加。引数は3つ。どういう意味? # item_master.append(Item("002","なし",120)) # 31行目で定義したitem_masterにItemクラスを追加。引数は3つ。どういう意味? # item_master.append(Item("003","みかん",150)) # 31行目で定義したitem_masterにItemクラスを追加。引数は3つ。どういう意味? item_master = master_registration() # オーダー登録 order=Order(item_master) # インスタンス化。変数orderにOrderクラスを代入。引数の扱いがよくわからない。 # order.add_item_order("001") # 37行目で定義した変数orderに17行目で定義したadd_item_orderメソッドを追加。引数は1つ?引数の扱いがよくわからない。 # order.add_item_order("002") # 37行目で定義した変数orderに17行目で定義したadd_item_orderメソッドを追加。引数は1つ?引数の扱いがよくわからない。 # order.add_item_order("003") # 37行目で定義した変数orderに17行目で定義したadd_item_orderメソッドを追加。引数は1つ?引数の扱いがよくわからない。 # オーダー表示 order.view_item_list() # 37行目で定義した変数orderに20行目で定義したview_item_listメソッドを追加。引数はなくていいのか? order.registration() order.print_list() #order.add_item_order(input_code, input_count) if __name__ == "__main__": # pyファイルとして実行されているかを確認する定型文。 main() ''' ① まずやることの確認 1 UTF-8 with BOM 2 venvの設定 3 gitignoreの設定 4 pip3 installでライブラリをインストール(課題4ではpandasだけ?) ② venvはフォルダごとで反映されるのか?  ファイルごとに作成、有効化する必要はない?  python3 -m venv venv  . venv/bin/activate ③ 「pip3 install〜」はファイルごとにする必要がある? ④ gitignoreの追加方法。 コマンドパレットでgitignoreを追加したが、ファイルが何も書かれていない。 参考サイト:https://opcdiary.net/gitignore-extension-for-visual-studio-code/ ⑤ メソッドにつく引数の使い方がわからない。 例)def __init__(self,item_code,item_name,price)   def __init__(self,item_master)   def add_item_order(self,item_code)   def view_item_list(self) 。。。 コンストラクタ__init__の引数と自作関数の引数、それぞれ役割が違うのか? selfの使い方がよくわからない。 コンストラクタでよくみられる表記。 def __init__(self, 第2引数): self.第2引数 = 第2引数 。。。 例)3〜6行目。 def __init__(self, item_code, item_name,price): self.item_code = item_code self.item_name = item_name self.price = price   ←「self.price」と「price」の違いは? ★ selfのみの場合は?  def view_item_list(self): ★ __init__以外のメソッドにつく引数は?  def add_item_order(self,item_code): その後、「self.item_code = item_code」とはなっていない。 〜課題1:オーダー登録した商品の一覧(商品名、価格)を表示できるようにしてください〜 【わからないこと】 ・オーダー登録した商品とは?mainの中のマスタ登録のことか?.appendで追加されているりんご、なし、みかんのこと? ・コードを書く場所は?回答ではmain()の処理の前に記述されている。 ・コードの表記は?回答を見ても理解できなかった。。 【やったこと:できなかった】 ・一覧表示のためにメソッドを作成。 ・self.item_masterの引数は3つずつなので、for文の中に3つの変数を用意して繰り返し処理。 def print_list(self): for x, y, z in self.item_master: print(x, y, z) これでxに商品コードが、yに商品名が、zに価格が代入されるのでは。。? その後の呼び出しは「order.print_list()」としたが、エラーになる。 〜課題2:オーダーをコンソール(ターミナル)から登録できるようにしてください 登録時は商品コードをキーとする〜 【わからないこと】 ・コードを書く場所 ・コードの表記 ・作成した関数と別の関数(もしくはクラス)との連携。 【やったこと】 ・メソッドを作成 ・inputを使う def registration(self): input_code = input('商品コードを入力してください。(001 or 002 or 003):') if input_code == 001, 002, 003: print('{}が登録されました。'.format(input_code)) else: print('正しいコード(001 or 002 or 003)を入力してください。') 〜課題3:商品マスタをCSVから登録できるようにしてください〜 【やろうとしていること】 Pandasを使って、read_csv。 ★ def main()のインデント。 →この関数はどのクラスにも属していないということ? '''
f74ce7c37ba366e011194db3eae095451e8f6278
c2eien/python
/hardway/ex13.py
524
4.1875
4
from sys import argv # argv is a MODULE that allows you to pass variables through the command line # so you run this file from the command line like this: "python ex13.py 1st 2nd 3rd" # where 1st 2nd 3rd are the variables after the script name print(argv) script, first, second, third = argv # this unpacks/maps the given arguments to respective variables print ("The script is called:", script) print("Your first variavle is:", first) print("Your second variable is:", second) print("Your third variable is:", third)
ca21032f32fd02073167d1e781539137012f8ecb
janissuonpera/school_work
/Python/round1/checkers.py
372
3.65625
4
r = int(input()) c = int(input()) h = int(input()) w = int(input()) for z in range(1, r+1): for x in range(1, h+1): for c in range(1, c+1): for v in range(1, w+1): if(z%2 != 0): if(c%2 != 0): print(" ", end="") else: print("#", end="") else: if(c%2 == 0): print(" ", end="") else: print("#", end="") print()
576cc092ec8a0d19d7e27bc917202efd95810dcf
HusanYariyev/Python_darslari
/57-masala.py
265
3.671875
4
ism = input("Ismingizni kiriting ") son = int(input("Necha martta takrorlasin ")) def takror(ism): if ism[len(ism)-1] != " " : ism = ism + " " else: ism = ism return lambda n : n * ism x = takror(ism) print(x(son))
b9d0113abc4f9ca6ca4e62aeb38d03fdbc61d5f5
amithimself/rbac
/rbac_app/models/resources.py
824
3.515625
4
class Resources: def __init__(self): self.resourcesList = {} def add_resource(self, resources_name, required_persmission): """Add a resource in the system :param name: name of resource and permission associated for the resource """ self.resourcesList[resources_name] = required_persmission def remove_resource(self, resource_name): """Remove a resource :param name: name of resource """ self.resourcesList.pop(resource_name) def display_resources(self): """display all resources available in the system """ for i in range(len(self.resourcesList.keys())): print(f'Press {i}. {(list(self.resourcesList.keys()))[i]}') def __repr__(self): return '<Resources %s>' % self.resourcesList
3f6cfdbc4eaa1f85fbeac72e60dce722773ce0a9
antho1810/CursoPython
/Tareas/ActividadFor.py
175
3.671875
4
def main(): V1 = int(input("Ingrese el primer valor: ")) V2 = int(input("Ingrese el segundo valor: ")) for i in range(V1, V2): if i % 2 != 0: print(i) main()
67c5028a12b5d04e84b2360091d3628624bfb06f
santoshtbhosale/Python-String
/Python_Interview_program.py
3,267
4.125
4
""" Write a program to demonstrate different number data types in Python. a = 34 b = 34.7 c = 3 + 4j print(type(a)) print(type(b)) print(type(c)) ______________________________________________________________________________________ Write a program to create, concatenate and print a string and accessing sub-string from a given string. s1 = input("Enter the String1:") s2 = input("Enter the String2:") print("First String:",s1) print("First String:",s2) s = s1 + s2 print("Concatenate of Two String:",s) print("Sub-String from the given string is:",s[1:5]) ______________________________________________________________________________________ Write a python script to print the current date in the following format “Sun May 29 02:26:23 IST 2017” import time d = time.localtime() print(time.strftime("%a %b %d %H:%M:%S %Z %Y",d)) ____________________________________________________________________________________ Write Star Patteren n = 5 for i in range(n): for j in range(i): print('*',end=" ") print() for i in range(n,0,-1): for j in range(i): print('*',end=" ") print() ______________________________________________________________________________________ Write a Python script that prints prime numbers less than 20. for num in range(1,21): if num > 1: for i in range(2,num): if num % i == 0: break else: print(num) _______________________________________________________________________________________ Write a python program to find factorial of a number using Recursion. def factorial(n): if n == 0: result = 1 else: result = n*factorial(n-1) return result num = int(input("Enter the Number:")) print(factorial(num)) ___________________________________________________________________________________ Write a program that accepts the lengths of three sides of a triangle as inputs. The program output should indicate whether or not the triangle is a right triangle (Recall from the Pythagorean Theorem that in a right triangle, the square of one side equals the sum of the squares of the other two sides). base = float(input("Enter the Base:")) per = float(input("Enter the Per:")) hypo = float(input("Enter the hypo:")) if hypo ** 2 == base ** 2 + per ** 2: print("The Traingle is Right Traingle") else: print("The Traingle is not Right Traingle") ____________________________________________________________________________________________________ Write a Python class to implement pow (x, n) def pow(x, y): if y == 0: return 1 elif (int(y%2) == 0): return pow(x, int(y/2)) * pow(x, int(y/2)) else: return (x * pow(x, int(y/2)) * pow(x, int(y/2))) x = 3 y = 2 print(pow(x, y)) __________________________________________________________________ Write a Python class to reverse a string word by word. class Reverse(): def reverse_word(self,s): return ''.join(reversed(s.split())) print(Reverse().reverse_word('Welcome to python')) __________________________________________________________________ Python Program for Find remainder of array multiplication divided by n """
ea447e7bda484358b280cea02f588fd17b9df919
Sattik-Tarafder/PYHTON
/noob_kuhu.py
451
4.28125
4
# Program to sort alphabetically the words form a string provided by the user # Define sentence word = "Hello this Is an Example With cased letters" # Split string by space, then sort the splitted string, and then put the string back together word = ' '.join( sorted( word.split() ) ) # word.split() - Splits string by space # sorted() - Sorts array of string # ' '.join() - Joins the string array together with a space print(word)
b4d80daa0ad92a2456dd871443eb482a643698a9
letsudo/learn_python
/09_python_loop_statements.py
2,094
4
4
# coding=utf-8 # 循环类型 描述 # while 循环 在给定的判断条件为 true 时执行循环体,否则退出循环体。 # for 循环 重复执行语句 # 嵌套循环 你可以在while循环体中嵌套for循环 # break 语句 在语句块执行过程中终止循环,并且跳出整个循环 # continue 语句 在语句块执行过程中终止当前循环,跳出该次循环,执行下一次循环。 # pass 语句 pass是空语句,是为了保持程序结构的完整性。 count = 0 while (count < 9): print 'The count is:', count count = count + 1 print "Good bye!" print ('\n') # continue 和 break 用法 i = 1 while i < 10: i += 1 if i % 2 > 0: # 非双数时跳过输出 continue print i # 输出双数2、4、6、8、10 i = 1 while 1: # 循环条件为1必定成立 print i # 输出1~10 i += 1 if i > 10: # 当i大于10时跳出循环 break # var = 1 # while var == 1: # 该条件永远为true,循环将无限执行下去 # num = raw_input("Enter a number :") # print "You entered: ", num # # print "Good bye!" # # print ('\n') # count = 0 # while count < 5: # print count, " is less than 5" # count = count + 1 # else: # print count, " is not less than 5" # # # # flag = 1 # # while (flag): print 'Given flag is really true!' # print "Good bye!" for letter in 'Python': # 第一个实例 print '当前字母 :', letter fruits = ['banana', 'apple', 'mango'] for fruit in fruits: # 第二个实例 print '当前水果 :', fruit print "Good bye!" fruits = ['banana', 'apple', 'mango'] for index in range(len(fruits)): print '当前水果 :', fruits[index] print "Good bye!" for num in range(10,20): # 迭代 10 到 20 之间的数字 for i in range(2,num): # 根据因子迭代 if num%i == 0: # 确定第一个因子 j=num/i # 计算第二个因子 print '%d 等于 %d * %d' % (num,i,j) break # 跳出当前循环 else: # 循环的 else 部分 print num, '是一个质数'
3b6c491307c8238f836eb109e14ada90ef1655ad
mryanivtal/dual_svm_project
/src/svm/helpers/data_helpers.py
3,031
3.5625
4
import pandas as pd import numpy as np def convert_class_to_int(df: pd.DataFrame, target_column: str, DEBUG=False) -> dict: """Converts DataFrame Target object column from string to integer in {-1, 1}, updates the dataframe in-place. Gets: df - dataframe target_column - Target column name returns a dictionary of target values: {int value: string} """ int_str_class_dict = {} str_int_class_dict = {} for col in df.columns: if df[col].dtype == object: if col == target_column: if df[col].dtype == object and len(pd.unique(df[col])) == 2: col_str_value_list = df[col].unique() col_int_value_list = np.array([-1, 1]) else: print('[convert_class_to_int] ERROR - Target column does not fix, convertion failed!') return None else: col_str_value_list = df[col].unique() col_int_value_list = np.arange(len(col_str_value_list)) int_str_class_dict[col] = dict(zip(col_int_value_list, col_str_value_list)) str_int_class_dict[col] = dict(zip(col_str_value_list, col_int_value_list)) df[col] = df[col].apply(lambda str: str_int_class_dict[col].get(str)) df[col] = df[col].astype('int32') if DEBUG: print(f'[convert_class_to_int] Info: Column {col} converted, Target = {col == target_column}') return int_str_class_dict def assess_accuracy(predictions: np.array, y: np.array): results = np.zeros(8) # Col 0 - class, columns: 1 - total, 2 - successes, 3- false negatives, # 4 - false positives, 5 - %success, 6- % false neg, 7 - % false pos for i in range(len(y)): results[0] = 1 results[1] += 1 if predictions[i] == y[i]: results[2] += 1 else: if y[i] == 1: results[4] += 1 else: results[3] += 1 results[5] = 100 * results[2] / results[1] results[6] = 100 * results[3] / results[1] results[7] = 100 * results[4] / results[1] results_df = pd.DataFrame([results], columns=['Class', 'Total', 'Successes', 'False neg.', 'False pos.', '% Success', '% False neg', '% False pos']) return results_df def normalize(X: np.array, DEBUG=False) -> np.array: if DEBUG: print('[data_helpers.normalize()]: entering method') X = X.astype('float32') for i in range(X.shape[1]): if DEBUG: print(f'[data_helpers.normalize()]: Before: Column {i} range: [{X[:, i].min()}, {X[:, i].max()}]') if X[:, i].max() - X[:, i].min() != 0: X[:, i] = (X[:, i] - X[:, i].min()) / (X[:, i].max() - X[:, i].min()) else: X[:, i] = 0 if DEBUG: print(f'[data_helpers.normalize()]: After: Column {i} range: [{X[:, i].min()}, {X[:, i].max()}]') return X
3f69d04480d7db06f88251162f4f5f32ad86b752
alixhami/palindrome_check_python
/palindrome_check.py
191
3.796875
4
# A function to check if the input string is a palindrome. # Return True if the string is a palindrome, otherwise return False. def palindrome_check(my_phrase): raise NotImplementedError
94353813b9f04451ec8b7489d4deda5710dfcaeb
Neminem1203/Puzzles
/DailyCodingProblem/30-rainWall.py
2,061
4.03125
4
''' You are given an array of non-negative integers that represents a two-dimensional elevation map where each element is unit-width wall and the integer is the height. Suppose it will rain and all spots between two walls get filled up. Compute how many units of water remain trapped on the map in O(N) time and O(1) space. For example, given the input [2, 1, 2], we can hold 1 unit of water in the middle. Given the input [3, 0, 1, 3, 0, 5], we can hold 3 units in the first index, 2 in the second, and 3 in the fourth index (we cannot hold 5 since it would run off to the left), so we can trap 8 units of water. ''' import random def rainWall(walls): def calculateRain(highest, ind1, ind2, step=1): secondHighest = 0 secondHighestInd = 0 sumOfWalls = 0 sumOfRain = 0 for ind in range(ind1, ind2, step): sumOfWalls += walls[ind] if(walls[ind] > secondHighest): sumOfRain += (secondHighest*(abs(ind-secondHighestInd))) secondHighest = walls[ind] secondHighestInd = ind sumOfRain += (secondHighest * (abs(ind2 - secondHighestInd))) # return (secondHighest*(abs(ind2-ind1))-sumOfWalls) return sumOfRain - sumOfWalls highest = walls[0] ind = 0 for i in range(len(walls)): if walls[i] > highest: highest = walls[i] ind = i rain = 0 rain += calculateRain(highest,0, ind) rain += calculateRain(highest,len(walls)-1, ind, -1) # print(rain) return(rain) # sampleWall = [3, 0, 1, 3, 0, 5] # print(sampleWall,"\n",rainWall(sampleWall)) # bigWall = [2,5,3,6,9,5,3,9,1,5,6,4] # print(bigWall,"\n",rainWall(bigWall)) for i in range(0, 3): randomWall = [random.randint(0,15) for x in range(random.randint(5,15))] print(randomWall,"\n",rainWall(randomWall)) ''' .....X .....X XOOXOX XOOXOX XOXXOX 301305 SUM = 8 ....XOOX.... ....XOOX.... ....XOOX.... ...XXOOXOOX. .XOXXXOXOXX. .XOXXXOXOXXX .XXXXXXXXXXX XXXXXXXXXXXX XXXXXXXXXXXX 253695391564 SUM = 18 '''
4d17776eb2dd0857e8b30a7267d9cd943f819365
mehdirezaie/f2py
/ex2/hw_python.py
330
3.5
4
#!/usr/bin/python """ Pure Python module to do matrix multiplication (c) Mehdi Rezaie """ import math, sys,numpy def mul(x,y): t = numpy.shape(x) z = numpy.zeros((t[0],t[0])) for i in range(t[0]): for j in range(t[0]): for k in range(t[0]): z[i][j] += x[i][k]*y[k][j] return z
ab5e25eb1fb40bfd794ebff06b3fb86f8da83113
HagenGaryP/lpthw
/ex14.py
998
4.3125
4
# Exercise 14: Prompting and Passing # In this exercise we'll use input slightly different by having it print # a simple > prompt. This is similar to games like Zork or Adventure. from sys import argv script, user_name = argv # command line arg - "python ex14.py Name" prompt = '> ' print(f"Hi {user_name}, I'm the {script} script.") print("I'd like to ask you a few questions.") print(f"Do you like me, {user_name}?") likes = input(prompt) print(f"Where do you live, {user_name}?") lives = input(prompt) print("What kind of computer do you have?") computer = input(prompt) print(f""" Alright, so you said {likes} about liking me. You live in {lives}. Not sure where that is. And you have a {computer} computer. Niiiiice. """) # We make a variable, prompt, that is set to the prompt we want, and give # that to input instead of typing it over and over. # Now if we want to make the prompt something else, we just change it in # this one spot and rerun the script. Very handy.
f114fd5b958f06c7642c914113b7de5b22f6634f
Lisolo/ACM
/leap_year.py
369
3.546875
4
# coding=utf-8 import datetime year = '2014' def isLeapYear(y): y = int(y) if (y % 4 == 0 and y % 100 != 0) or (y % 400 == 0): print 366 else: print 365 def isLeapYear2(y): y = int(y) y1 = datetime.datetime(y, 1, 1) y2 = datetime.datetime(y+1, 1, 1) print str(y2 - y1).split(' ')[0] isLeapYear(year) isLeapYear2(year)
67cfc04ef7569fed8c48d5a04ad7d443fb15bf16
kylegarrettwilson/Python-Madlib
/Intro to Python/main.py
1,728
4.09375
4
print "Hello World" # one line comments ''' this is multiple lines (doc strings) ''' first_name = "Kermit" last_name = "The Frog" response = raw_input("Enter your name ") print "Hello there, ", response #expressions birth_year = 1989 current_year = 2016 age = current_year - birth_year print "You are " + str(age) + " years old" # int(var) #conditions budget = 200 if budget > 100: brand = "nike" print "yay! by the " + brand else: print "save your money" budget = 80 if budget > 100: brand = "nike" print "yay! by the " + brand elif budget > 70: print "buy some knock offs" else: print "save your money" # can also do pass to continue # array characters = ["mark", "ted", "ned"] characters.append("kyle") print characters[0] movie = dict() #creates this dictionary movies = {"star wars":"darth vader", "star trek":"ted"} # key first print movies["star wars"] # this will print darth vader #loops (while and for) #while not used as often #will loop any number of times i = 0 while i<9: print "the count is", i i = i+1 # will loop a specific amount of times for i in range(0,10): print "the count is", i i = i+1 # great for going through arrays rappers = ["MGK", "Biggie", "tupac"] for r in rappers: print "Here is a rapper" # functions def = definitions def calcArea(h, w): area = h * w return area #call it (invoke) a = calcArea(20, 40) print str(a) + "sqft" weight = 200 height = 45 message = ''' Your height is {height} and your weight is {weight} ''' message = message.format(**locals()) print message
5e44053edbc76774efae6a7736c6fbefa2fa1779
kedgarnguyen298/nguyenquockhanh-fundamental-c4e24
/session2/homework/serious_ex2.py
121
4.15625
4
n = int(input("Enter a number: ")) fac = 1 for i in range(1, n+1): fac *= i print("Factorial of", n, "is: ", fac)
1b3f99fcae5d9049d6323706819d4ef2a356e90d
CelesteRCodes/whiteboardingpractice
/sum-counts/count.py
1,231
4.46875
4
"""Count words in a sentence, and print in ascending order. For example:: >>> word_count("berry cherry cherry cherry berry apple") apple: 1 berry: 2 cherry: 3 If there is a tie for a count, make sure the words are printed in ascending order within the tie:: >>> word_count("hey hi hello") hello: 1 hey: 1 hi: 1 Capitalized words are considered distinct:: >>> word_count("hi Hi hi") Hi: 1 hi: 2 """ def word_count(phrase): """Count words in a sentence, and print in ascending order.""" # want to split phrase into list of separate strings # then loop over list of strings, counting the number of times each word was seen # can then place them in a dicitonary, key = word, value = number of times it's in phrase # want to return that dictionary sep_phrase = phrase.split(" ") word_count = 0 for words in sep_phrase: if words == words: word_count += 1 word_list = [] word_list.append(words) word_dict = dict(word_list, word_count) print(word_dict) if __name__ == '__main__': import doctest if doctest.testmod().failed == 0: print("\n*** ALL TESTS PASSED; NICE JOB! ***\n")
598dea25a327a5b4388d395da60f1d72ff764862
mwarne97/Meme_Generator
/src/QuoteEngine/models.py
633
3.609375
4
"""QuoteModel defines the structure of a meme's quote.""" class QuoteModel: """A quote model. A quote model comprises a body of text and an author, both of which are required. """ def __init__(self, body: str, author: str): """Create a new 'QuoteModel'.""" self.body = body self.author = author def __str__(self): """Return 'str(self)'.""" return self.body + " - " + self.author def __repr__(self): """Return 'repr(self)', a computer-readable string representation of this object.""" return f"QuoteModel(body={self.body!r}, author={self.author})"
88b75bed128ab946873296ab7fe9894729f8b96c
jocelinoFG017/IntroducaoAoPython
/01-Cursos/GeekUniversity/Seção04-Váriaveis_e_tipos_de_dados/Exs_22_ao_53/S04_Ex26.py
295
3.625
4
""" Leia um valor de área em metros quadrados m² e apresente-o em hectares. A fórmula de conversão é: H = M * 0.0001, sendo M a área em m² e H a área em hectares. """ area = float(input("Valor da área (M²): ")) convert = area * 0.0001 print("Em Hectares fica: {:.4f}".format(convert))
e1d7e436ff1ad01ff4490dc2de4a61b2a3e739c1
shlesh/Python
/car_game.py
959
4.125
4
print('''Welcome to the Car Game Start Stop Quit''') var = input("what would you like to do? ").upper() status = False while len(var) >= 0: if var == "START": if status == False: status = True print("Car has started") status = True var = input("What would you like to do? ").upper() else: print("The car is already running") var = input("What would you like to do? ").upper() elif var == "STOP": if status == True: print("Car has stopped") var = input("What would you like to do? ").upper() status = False else: print("The car hasn't even started") var = input("What would you like to do? ").upper() elif var == "QUIT": print("You just quit...") break else: print("I dont understand this") var = input("what would you like to do? ").upper()
2a2c92eac65a47807f7d9e8441ce6c879d48d828
eriksnc/CYPErikNC
/libro/Problemas_resueltos/capitulo2/problema2_1.py
91
3.515625
4
n=int(input("Dame un valor:")) if (n>0): t=n/4+40 print("La temperatura es de,",t)
934ca2bca3540fca06c3c3f363fb6281253a7199
harryhk/ProgrammingCompetition
/rpi_UPE/PC2012-spring2/prac/years.py
565
3.609375
4
#!/usr/bin/env python from __future__ import print_function import sys , pdb def travel(l,time): diff = [ y-x for (x, y) in zip( l, l[1:] )] diff.sort() jump = len(diff) for i in diff: time = time -i if time <= 0: if time == 0 : jump=jump-1 break else: jump = jump -1 return jump fin = open(sys.argv[1]) nloop = int( fin.readline().strip() ) for i in range(nloop) : (t, time) = [ int(j) for j in fin.readline().strip().split() ] l=[ int (j) for j in fin.readline().strip().split() ] print( travel(l, time) +1 )
69e582f8cab2743ea65e3b89bc795fd719a11a53
awzsse/Keep_Learning_ML
/PythonDataStructure/DataStructure/single_cycle_link_list.py
5,562
3.90625
4
# 首先定义一个节点类 class Node(object): def __init__(self, elem): self.elem = elem self.next = None class SingleLinkList(object): # 单向循环链表 # 定义构造函数,默认参数node为None,即一个Node类的对象 def __init__(self,node=None): # 设置私有属性,头节点先指向None self.__head = node # 如果不是空链表,让第一个节点的next指向自己 if node: node.next = node # 判断链表是否为空的方法 def is_empty(self): # 如果头指向的node为空那么就是空的 return self.__head == None # 返回长度 def length(self): # 遍历整个链表 # 创建一个cur游标,用来移动遍历节点 # 先将cur跟头节点指向同一个node if self.is_empty(): return 0 cur = self.__head # 由于条件变了,count从1开始 count = 1 # 判断,当cur指向的节点不是头节点指向的节点 while cur != self.__head: # count用来计算节点个数 count += 1 # cur指向的是节点对象,所以可以用next这个构造函数方法 cur = cur.next return count # 遍历整个链表 def travel(self): # 跟算长度一样,也是遍历 if self.is_empty(): return cur = self.__head while cur.next != self.__head: print(cur.elem, end = " ") cur = cur.next # 退出循环,cur指向尾节点,但是尾节点的元素没打印 print(cur.elem) # 头部添加元素 # 这里要注意顺序问题 # 如果先把head指向新添加节点,再把新添加节点的next指向原始第一个节点,那么会导致原来的节点丢失 # 应先让新节点的next指向原始第一个节点,再把head指向新节点 def add(self, item): # 先创建节点对象 node = Node(item) if self.is_empty(): self.__head node.next = node else: # 现在需要遍历,遍历到最后一个节点,再把最后一个节点指向第一个节点 cur = self.__head # 循环结束条件是,找到最后一个节点 while cur.next != self.__head: cur = cur.next node.next = self.__head self.__head = node cur.next = self.__head # 在尾部添加元素 def append(self, item): # 这里的item是具体的数据,不是节点。因此要构造节点 node = Node(item) # 如果是空,跟add一样,加上,同时指向自身 if self.is_empty(): self.__head node.next = node else: cur = self.__head # 判断指针有没有指向最后一个元素 while cur.next != self.__head: cur = cur.next # 添加 node.next = self.__head cur.next = node # 在指定位置添加 # 中间插入跟单链表一样 def insert(self, pos, item): # 这里要在指定位置插入,游标如果是cur当前游标,则无法操作前一个node,因此需要用到pre # 加入的放入与add一样,即先将需要插入的node.next指向前一个node原本指向的下一个节点 # 再将前一个节点的next指向该节点。这是为了保证原有链表的结构不受影响 # 注意偶!!!一定要记住,python等号值得是,右边这个变量指向的值给pre if pos <= 0: # 如果输入的pos小于等于零,认作头插法 self.add(item) elif pos > (self.length()-1): self.append(item) else: pre = self.__head count = 0 while count < (pos-1): pre = pre.next count += 1 # 当循环退出后,pre指向pos-1的位置 node = Node(item) node.next = pre.next pre.next = node # 删除节点 # 这个更简单,只要将cur前一个的node的next指向cur后一个node即可 # 这时候利用两个游标便于理解 def remove(self, item): # 一上来就是个空的 if self.is_empty(): return # 一开始pre就比cur早一个位置 cur = self.__head pre = None while cur != None: if cur.elem == item: # 这一步就把item对应的node删除了,前后node直接链接 # 同时这里还要判断是不是头节点 if cur == self.__head: # 头结点,最复杂 # 找尾节点 rear = self.__head while rear.next != self.__head: reat = rear.next # 现在可以删除cur节点那个元素删除 self.__head = cur.next # 再把尾部节点指向头结点现在指向的那个 rear.next = self.__head # self.__head = cur.next else: # 中间节点 pre.next = cur.next # 这里要return了,不然下面的if还会继续判断 return # 先移动pre到cur,在移动cur到下一个 else: pre = cur cur = cur.next # 退出循环,cur指向尾节点,但是没判断。 if cur.elem == item: # 如果只有一个节点,就是你要删除的 if cur == self.__head: self.__head == None else: pre.next = cur.next # 判断节点是否存在 def search(self, item): # 利用游标一个一个找 if self.is_empty(): return False cur = self.__head while cur.next != self.__head: if cur.elem == item: return True else: cur = cur.next # 退出循环的时候,仍然需要判断一次,因为用的是cur.next # 万一这个元素在最后一个,那么就没有判断到这个元素了 if cur.elem == item: return True return Flase if __name__ == "__main__": ll = SingleLinkList() print(ll.is_empty()) print(ll.length()) ll.append(1) print(ll.is_empty()) print(ll.length()) ll.append(2) ll.append(3) ll.append(4) ll.append(5) ll.append(6) ll.add(1234) ll.insert(-1, 9) ll.insert(2, 100) ll.insert(10, 200) ll.append(100) ll.remove(100) ll.travel()
6aa189c5418517066d8a22ebb13047bc6b9e7cc3
asihacker/python3_bookmark
/python笔记/aaa基础内置/python内置模块/signal信号模块/timeout-decorator模块实现超时机制.py
725
3.640625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2021/6/15 20:09 # @Author : AsiHacker # @File : timeout-decorator模块实现超时机制.py # @Software: PyCharm # @notice : True masters always have the heart of an apprentice. import time import traceback import stopit # https://www.cnblogs.com/haoxr/p/8757985.html 函数超时机制的几种实现方法 @stopit.threading_timeoutable() def infinite_loop(): # As its name says... try: print("Start") for i in range(1, 10): print("%d seconds have passed" % i) time.sleep(1) except Exception as e: print(e) traceback.print_exc() if __name__ == '__main__': infinite_loop(timeout=1)
5daea9573ee2764a78cd8cf6074fc4428ac64621
zTaverna/Logica-de-Programacao
/Unidade 01/Aula 04 ex 04.py
439
4.15625
4
print("Digite os lados de um triângulo:") a=float(input("Lado 1: ")) b=float(input("Lado 2: ")) c=float(input("Lado 3: ")) if a<(b+c) and b<(a+c) and c<(a+b): if a==b and b==c: print("O triângulo é equilátero!") else: if a==b or a==c or b==c: print("O triângulo é isósceles!") else: print("O triângulo é escaleno!") else: print("Não é um triângulo!")
50103f6538f1b1ac23c34d3ccad29d72336d4677
rsaravia/PythonBairesDevBootcamp
/Level2/ejercicio1.py
408
4.09375
4
# 1. Write a Python program to scan a specified directory and identify the sub directories and files. import os #get all the elements of current working directory l = os.listdir(os.getcwd()) print("elementos en ",os.getcwd(),": ", l) for elemento in l: if os.path.isfile(os.path.join(os.getcwd(),elemento)): print(elemento, "is a file") else: print(elemento, "is a directory")
aecce113728843f51a52f13535c79f4951a68eee
BrennoBernardoDeAraujo/ALGORITMOS-2019.2
/A2.Q4.py
526
4.0625
4
n1 = float(input("digite um numero: ")) n2 = float(input("digite outro numero: ")) n3 = float(input("digite mais outro numero: ")) if n1 <= n2 and n2 <= n3: print(n3,n2,n1) if n2 < n1: aux = n1 n1 = n2 n3 = aux if n3 < n2: aux = n3 n3 = n2 n2 = aux if n3 < n2: aux = n3 n3 = n2 n2 = aux if n2 < n1: aux = n1 n1 = n2 n2 = aux print("O maior número é:",n3) print("O menor numro é:",n1)
fe49c869128cf2d704aa1cc08c17c28170181e03
S-Vel/day-4-
/Question 03.py
81
3.515625
4
a=50 b=50.74 print("Int to float a: ",float(a)) print("Float to int b: ",int(b))
fe51bbf21a1cb9188e4cbc6a147bfe4d2dd3fecf
emildoychinov/Talus
/loader/maths.py
3,298
3.90625
4
import re class grammarError(Exception) : pass #the tokenizer for the parser class Tokenizer: def __init__(self, expr): #we split the expression into different tokens with a regular expression self.tokens = re.findall(r'[\d\.]+|[+-\/*\(\)\^]', expr) #if lettets (a-Z) are in the expression it is invalid, so we raise an exception if re.match(r'[a-zA-z]', expr): raise grammarError ('Invalid expression') self.ix = 0 #getting the next token def getNext(self) : if self.ix < len(self.tokens): op = self.tokens[self.ix] self.ix+=1 return op return None #peeking the next token def peekNext(self) : if self.ix < len(self.tokens): return self.tokens[self.ix] return None class parser: def __init__(self, expr): self.expr = expr #we tokenize the expression self.tokenizer = Tokenizer(self.expr) #a function that will be used to check if a certain token is a number def isNumber(self, token): try : float(token) return True except ValueError: return False def term (self): #we get the result from factoring op1 = float(self.factor()) #while the next token is + or - while self.tokenizer.peekNext() in ('+', '-'): #we get the operation by going onto the next token opr = self.tokenizer.getNext() #we get the result from factoring op2 = float(self.factor()) #we return the result between the two operands if opr == '+' : op1+=op2 else : op1-=op2 return op1 def factor (self): #we get the result from powering op1 = float(self.power()) while self.tokenizer.peekNext() in ('*', '/'): opr = self.tokenizer.getNext() #we get the result from powering op2 = float(self.power()) #we return the result between the two operands if opr == '*' : op1*=op2 else :op1/=op2 return op1 def power (self): #we get the result from the expression in brackets, if there is one op1 = float(self.value()) while self.tokenizer.peekNext() == '^' : opr = self.tokenizer.getNext() op2 = float(self.value()) #we return the result between the two operands op1 = op1**op2 return op1 def value(self): #we get the next token token = self.tokenizer.getNext() #if it is a bracket if token == '(': #we call for the highest layer of the recursion - the one where we are adding the numbers, until we eventually come back here token = self.term() #if the next token is not a closing bracket, the expression is not valid, so we raise an exception if self.tokenizer.getNext() != ')': raise grammarError('The expression is invalid') #if the token is not a number and it was not an opening bracket, then we return 0 as an operand to be used if not self.isNumber(token): self.tokenizer.ix-=1 token = 0 return token
161b04446c18397bec71c78b670e0c20d79bf37d
XMK233/Leetcode-Journey
/py/231.py
822
3.609375
4
class Solution: def isPowerOfTwo(self, n: int) -> bool: ## 大佬的思路:n和n-1按位与,得0,则为幂。 ## 要注意,边界条件如果是0,1之类,属于特殊情况,需要另行对待。 if n == 0: return False if n == 1: return True return (n & (n - 1) == 0) ## 我的思路:反正就是1打头后面皆是0的数字就对了。 ## 那就酱紫:这个数右移一位,再左移一位,如果跟原来有出入,就包含不止一个1,那就肯定不是2的幂 ## 这个会超时 # n1 = n # while n1 != 1: # tmp = n1>>1<<1 # if tmp != n1: # return False # n1 = n1 >> 1 # return True s = Solution() print(s.isPowerOfTwo(4))
203cb1e2b2dfb59ada4faac11d2d30e63466df2f
a307/Pong-Game
/Pong_Game.py
4,351
3.96875
4
# simple pong game # 2020-08-16 Sean B # name of file ---> Pong_Game.py import turtle # creating window for GUI wn = turtle.Screen() # window title, colour, and demenions wn.title("Pong by Sean") wn.bgcolor("black") wn.setup(width=800, height=600) # updates window faster wn.tracer(0) # Score score_a = 0 score_b = 0 # ------------------------------------------------------------------------- # Paddle A # creating paddle as a turtle object (turtle is the gui import) paddle_a = turtle.Turtle() # speed of animation required by turtle module paddle_a.speed(0) paddle_a.shape("square") paddle_a.color("white") paddle_a.shapesize(stretch_wid=5, stretch_len=1) paddle_a.penup() paddle_a.goto(-350, 0) # Paddle B # creating paddle as a turtle object (turtle is the gui import) paddle_b = turtle.Turtle() # speed of animation required by turtle module paddle_b.speed(0) paddle_b.shape("square") paddle_b.color("white") paddle_b.shapesize(stretch_wid=5, stretch_len=1) paddle_b.penup() paddle_b.goto(350, 0) # Ball # creating paddle as a turtle object (turtle is the gui import) ball = turtle.Turtle() # speed of animation required by turtle module ball.speed(0) ball.shape("square") ball.color("white") ball.penup() ball.goto(0, 0) # adding movement to ball (d stands for delta) ball.dx = .15 ball.dy = .15 # Pen (score board) pen = turtle.Turtle() pen.speed(0) pen.color("white") pen.penup() pen.hideturtle() pen.goto(-200, 260) pen.write("Player A: 0 Player B: 0", font=("Courier", 24, "normal")) # ------------------------------------------------------------------------- # Paddle a movement funtions def paddle_a_up(): # ycor reutrns the y cordinate # when this funtion is called paddle a moves up 20 pixles y = paddle_a.ycor() y += 20 paddle_a.sety(y) def paddle_a_down(): y = paddle_a.ycor() y -= 20 paddle_a.sety(y) # Paddle b movement funtions def paddle_b_up(): # ycor reutrns the y cordinate # when this funtion is called paddle b moves up 20 pixles y = paddle_b.ycor() y += 20 paddle_b.sety(y) def paddle_b_down(): y = paddle_b.ycor() y -= 20 paddle_b.sety(y) # ------------------------------------------------------------------------- # keyboard binding wn.listen() # calling paddle_a_up function when w key is pressed wn.onkeypress(paddle_a_up, "w") wn.onkeypress(paddle_a_down, "s") # calling paddle b movement functions wn.onkeypress(paddle_b_up, "Up") wn.onkeypress(paddle_b_down, "Down") # ------------------------------------------------------------------------- # Main game loop while True: # wn.update will update the screen everytime it loops wn.update() # Move the ball ball.setx(ball.xcor() + ball.dx) ball.sety(ball.ycor() + ball.dy) # Border checking for paddles if (paddle_a.ycor() > 245): paddle_a.sety(245) if (paddle_a.ycor() < -245): paddle_a.sety(-245) if (paddle_b.ycor() > 245): paddle_b.sety(245) if (paddle_b.ycor() < -245): paddle_b.sety(-245) # Border checking for ball if ball.ycor() > 290: # this will bounce ball off of top of window by reversing directoin of it ball.sety(290) ball.dy *= -1 if ball.ycor() < -290: ball.sety(-290) ball.dy *= -1 if ball.xcor() > 390: ball.goto(0, 0) ball.dx = -.15 score_a += 1 pen.clear() pen.write("Player A: {} Player B: {}".format(score_a, score_b), font=("Courier", 24, "normal")) if ball.xcor() < -390: ball.goto(0, 0) ball.dx = .15 score_b += 1 pen.clear() pen.write("Player A: {} Player B: {}".format(score_a, score_b), font=("Courier", 24, "normal")) # Ball collision with paddles if (ball.xcor() > 340 and ball.xcor() < 350) and ( ball.ycor() < paddle_b.ycor() + 40 and ball.ycor() > paddle_b.ycor() - 40): ball.setx(340) ball.dx *= -1.2 if (ball.xcor() < -340 and ball.xcor() > -350) and ( ball.ycor() < paddle_a.ycor() + 40 and ball.ycor() > paddle_a.ycor() - 40): ball.setx(-340) ball.dx *= -1.2
7f4fbe710728db649fbc3164cd7658d6bc984e94
suchi-dev/python-practice
/data_structures.py
548
3.609375
4
our_list = [ 27, 46, -1, 17, 99] print(our_list) print(type(our_list)) jackson = ["A", "B", "C", 1,2,3, "Do", "Rey", "Mi", True, False] print(jackson[4]) print(jackson[7]) print(jackson[-2]) x = jackson[6] print(x) print(jackson[0:3]) my_list=[1,2, [3,4,5],6,7, 8] print(my_list[2]) print(my_list[2][0]) print(my_list[2][1]) print(my_list[2][1:]) print(my_list[2][0::2]) our_table = [[1,2,3],[ 4,5,6], [7,8,9]] print(our_table[0]) print(our_table[1]) print(our_table[0][1]) print(our_table[1][2]) print(our_table[2][1]) print(our_table[1][1:])
bbac63f6f91fae88d6e43656ec0f3a51af8d1f89
jimbrunop/brunoperotti
/Exercicios-Python/DecisaoExercicio26.py
2,175
3.734375
4
# Um posto está vendendo combustíveis com a seguinte tabela de descontos: # # Álcool: # até 20 litros, desconto de 3% por litro # acima de 20 litros, desconto de 5% por litro # Gasolina: # até 20 litros, desconto de 4% por litro # acima de 20 litros, desconto de 6% por litro Escreva um algoritmo que leia o número de litros vendidos, o tipo de combustível (codificado da seguinte forma: A-álcool, G-gasolina), calcule e imprima o valor a ser pago pelo cliente sabendo-se que o preço do litro da gasolina é R$ 2,50 o preço do litro do álcool é R$ 1,90. litros_vendidos = float(input("Informe quantos litros foram inseridos: ")) tipo_combustivel = input("Informe o tipo de combustivel, g - gasolina ou a - alcool") preco_litro_gasolina = 2.50 preco_litro_alcool = 1.90 def calcula_valor_abastecimento (litros_vendidos, tipo_combustivel, preco_litro_gasolina, preco_litro_alcool): if tipo_combustivel == 'g' or tipo_combustivel == 'G': valor_abastecido = (litros_vendidos * preco_litro_gasolina) if litros_vendidos <= 20.00: valor_com_desconto = valor_abastecido - (valor_abastecido * 4) / 100 print( "Foram abastecidos: " + str(litros_vendidos) + "com valor de R$: " + str(valor_abastecido) + "Aplicando deesconto: R$" + str(valor_com_desconto)) else: print( "Foram abastecidos: " + str(litros_vendidos) + "com valor de R$: " + str(valor_abastecido)) elif tipo_combustivel == 'a' or tipo_combustivel == 'A': valor_abastecido = (litros_vendidos * preco_litro_alcool) if litros_vendidos <= 20.00: valor_com_desconto = valor_abastecido - (valor_abastecido * 3)/100 print("Foram abastecidos: " + str(litros_vendidos) + "com valor de: R$ " + str(valor_abastecido) + "Aplicando deesconto: R$" + str(valor_com_desconto)) else: print("Foram abastecidos: " + str(litros_vendidos) + "com valor de: R$" + str(valor_abastecido)) else: print("Tipo combustivel inválido") calcula_valor_abastecimento (litros_vendidos, tipo_combustivel, preco_litro_gasolina, preco_litro_alcool)
1d93b7a51dc4979a8de22e1ad02c5a886bf77d98
jegiraldp/python
/calculadora/inicio.py
1,532
3.765625
4
from suma import suma from resta import resta from producto import producto from division import division import sys class inicio: def inicio(): inicio.menu() def menu(): print("\n-----------------------") print("Calculator T2000\n") print("1. Sumar") print("2. Restar") print("3. Multiplicar") print("4. Dividir") print("5. Salir\n") opcion = input("Digite la opción -> ") opcion= int(opcion) inicio.proceder(opcion) def proceder(opcion): if opcion==5: print("\nGracias por utilizar nuestro servicios") sys.exit(0) else: numeroUno = input("Digite número 1 -> ") numeroDos = input("Digite número 2 -> ") numeroUno = int(numeroUno) numeroDos = int(numeroDos) if opcion==1: print ("Resultado "+ str(suma.calcular(numeroUno,numeroDos))) if opcion==2: print ("Resultado "+ str(resta.calcular(numeroUno,numeroDos))) if opcion==3: print ("Resultado "+ str(producto.calcular(numeroUno,numeroDos))) if opcion==4: if numeroDos==0: print("\nNo se puede dividir por cero !!!") pass else: print ("Resultado "+ str(division.calcular(numeroUno,numeroDos))) inicio.menu() inicio.inicio()
eb0c5d436ca162983688852debbb31b9e63db828
JulianKemmerer/Drexel-CS260
/PA2/group4-assignment2/tries.py
1,266
4.21875
4
#!/usr/bin/env python from array import * from list_array import * def makeTrie(): allWords = [] f = open("AliceInWonderland.txt","r"); lines = f.readlines(); for i in lines: thisline = i.split(" "); for j in thisline: if j!="": allWords.append(j.strip()) x=ListArray() for word in allWords: for letter in word: if (word!=""): x.insert(letter,x.end()) x.insert("$",x.end()) count=0 counter=0 while(x.retrieve(counter)!=None): if x.retrieve(counter)=="$": count=count+1 counter=counter+1 return count print "The purpose of this program is to create a trie of all the words appearing in AliceInWonderland.txt, and to find the size of that trie." print "The program does this by creating an array list containing all the words that are in Alice in Wonderland." print "It then iterates through each word, and adds the corresponding letters in order to the list_array implementation. The letters following each letter are stored in a list. At the end of each word, a '$' character is added to indicate the end of a unique word. The method then counts the number of occurences of the '$' character, and returns that number as the size of the trie." print "The size of the trie of AliceInWonderland.txt is:",makeTrie(),"."
9224e40d1f4b6309099dcdb1d214b0947f3e83c5
kumaranshu8092/Python_tut
/Day-3/treasure_island.py
1,248
4.5
4
#day-3 project print("Welcome to treasure Island \nYour mission is to cross through the door alive") direction=input("You are at cross road.Where you want to go? Type 'left' or 'right'\n") if(direction=='left' or direction=='Left'): print("You come to a lake.\nThere is an island in the middle of the lake.") boat_wait=input("Type 'wait' to wait for a boat.Type 'Swim' to swim across.\n") if (boat_wait=='wait' or boat_wait=='Wait'): print("You arrived at the island unharmed.\nThere is a houses with 3 doors.") doors=input("One red,one yellow and one blue.Which gate you want to enter\n") if(doors == 'yellow' or doors == 'Yellow'): print("You entered the house and won the game") elif (doors == 'blue' or doors == 'Blue' or doors == 'red' or doors == 'red'): print("wrong gate.Game over") else: print("Invalid input") elif(boat_wait=='swim' or boat_wait=='Swim'): print("There was crocodile in the water,you died, Game Over") else: print("Invalid input") elif(direction=='right' or direction=='Right'): print("meet with an accident and died,Game Over") else: print("Invalid output")
d61ca312823933744e122218ded8d5ef056ccaf6
Mondiegus/Python_learning
/Basics/euclidean_distance2.py
833
3.84375
4
from math import sqrt def euclidean_distance(A, B): """ >>> A = (0,1,0,1) >>> B = (1,1,0,0) >>> euclidean_distance(A, B) 1.4142135623730951 >>> euclidean_distance((0,0,0), (0,0,0)) 0.0 >>> euclidean_distance((0,0,0), (1,1,1)) 1.7320508075688772 >>> euclidean_distance((0,1,0,1), (1,1,0,0)) 1.4142135623730951 >>> euclidean_distance((0,0,1,0,1), (1,1,0,0,1)) 1.7320508075688772 >>> euclidean_distance((0,0,1,0,1), (1,1)) Traceback (most recent call last): ... ValueError: Points must be in the same dimensions """ count = 0 if len(A) != len(B): raise ValueError('Points must be in the same dimensions') else: for n1, n2 in zip(A, B): count += (n2-n1)**2 return sqrt(count)
f13f8e376f008d27bb4233044864b8632423ace3
gabriellaec/desoft-analise-exercicios
/backup/user_348/ch40_2020_06_21_22_25_41_499277.py
385
3.78125
4
#Com for def soma_valores (valores): s = 0 for i in range(len(valores)): s = s + valores[i] return s #Com while def soma_valores (valores): # Determina uma variável com o valor inicial da soma s = 0 i = 0 while i< len(valores): # Atualiza o valor da soma para cada elemento da lista s = s + valores[i] i= i +1 return s
10f2ad8bc33b8d4dd3907927e7910cddae826c95
riley-csp-2019-20/1-2-3-apple-avalanche-pickles9
/123adamschmok.py
4,522
3.578125
4
# a123_apple_1.py import turtle as trtl import random apple_image = "apple.gif" # Store the file name of your shape wn = trtl.Screen() wn.addshape(apple_image) # Make the screen aware of the new file wn.setup(width=1.0, height=1.0) wn.bgpic("tree.gif") #apple = trtl.Turtle() #drawer = trtl.Turtle() number_of_apples = 5 current_letters = [] apple_list = [] letter_list = ["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"] letter = "" random.shuffle(letter_list) ground = -150 xcor_offset = -5 ycor_offset = -25 #apple.speed(3) #apple.pu() #drawer.pu() #drawer.ht() #drawer.goto(0,100) # given a turtle, set that turtle to be shaped by the image file def draw_apple(active_apple): global current_letters if (len(letter_list) != 0): active_apple.shape(apple_image) active_apple.goto(random.randint(-200, 200),random.randint(0, 100)) active_apple.st() letter = letter_list.pop() draw_letter(letter, active_apple) current_letters.append(letter) wn.update() def apple_fall(letter): wn.tracer(True) index = current_letters.index(letter) current_letters.pop(index) active_apple = apple_list.pop(index) active_apple.clear() active_apple.goto(active_apple.xcor(), ground) active_apple.ht() wn.tracer(False) draw_apple(active_apple) apple_list.append(active_apple) def draw_letter(letter, active_apple): wn.tracer(False) active_apple.color("white") old_pos = active_apple.position() active_apple.setpos(active_apple.xcor() + xcor_offset, active_apple.ycor() + ycor_offset) active_apple.write(letter, font=("arial", 30, "bold")) active_apple.setpos(old_pos) for i in range(number_of_apples): active_apple = trtl.Turtle(shape = apple_image) active_apple.pu() draw_apple(active_apple) apple_list.append(active_apple) #draw_apple(apple) def test_a (): if ("a" in current_letters): apple_fall("a") def test_b (): if ("b" in current_letters): apple_fall("b") def test_c (): if ("c" in current_letters): apple_fall("c") def test_d (): if ("d" in current_letters): apple_fall("d") def test_e (): if ("e" in current_letters): apple_fall("e") def test_f (): if ("f" in current_letters): apple_fall("f") def test_g (): if ("g" in current_letters): apple_fall("g") def test_h (): if ("h" in current_letters): apple_fall("h") def test_i (): if ("i" in current_letters): apple_fall("i") def test_j (): if ("j" in current_letters): apple_fall("j") def test_k (): if ("k" in current_letters): apple_fall("k") def test_l (): if ("l" in current_letters): apple_fall("l") def test_m (): if ("m" in current_letters): apple_fall("m") def test_n (): if ("n" in current_letters): apple_fall("n") def test_o (): if ("o" in current_letters): apple_fall("o") def test_p (): if ("p" in current_letters): apple_fall("p") def test_q (): if ("q" in current_letters): apple_fall("q") def test_r (): if ("r" in current_letters): apple_fall("r") def test_s (): if ("s" in current_letters): apple_fall("s") def test_t (): if ("t" in current_letters): apple_fall("t") def test_u (): if ("u" in current_letters): apple_fall("u") def test_v (): if ("v" in current_letters): apple_fall("v") def test_w (): if ("w" in current_letters): apple_fall("w") def test_x (): if ("x" in current_letters): apple_fall("x") def test_y (): if ("y" in current_letters): apple_fall("y") def test_z (): if ("z" in current_letters): apple_fall("z") wn.onkeypress(test_a, "a") wn.onkeypress(test_b, "b") wn.onkeypress(test_c, "c") wn.onkeypress(test_d, "d") wn.onkeypress(test_e, "e") wn.onkeypress(test_f, "f") wn.onkeypress(test_g, "g") wn.onkeypress(test_h, "h") wn.onkeypress(test_i, "i") wn.onkeypress(test_j, "j") wn.onkeypress(test_k, "k") wn.onkeypress(test_l, "l") wn.onkeypress(test_m, "m") wn.onkeypress(test_n, "n") wn.onkeypress(test_o, "o") wn.onkeypress(test_p, "p") wn.onkeypress(test_q, "q") wn.onkeypress(test_r, "r") wn.onkeypress(test_s, "s") wn.onkeypress(test_t, "t") wn.onkeypress(test_u, "u") wn.onkeypress(test_v, "v") wn.onkeypress(test_w, "w") wn.onkeypress(test_x, "x") wn.onkeypress(test_y, "y") wn.onkeypress(test_z, "z") wn.listen() trtl.mainloop()