blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
70cbe1aa492cc0f28430bba876229ee42ab62ec2
sacdallago/dataminer
/conv_net_one_against_all.py
11,730
3.5
4
# coding: utf-8 # In[ ]: ''' A Convolutional Network implementation example using TensorFlow library. This example is using the MNIST database of handwritten digits (http://yann.lecun.com/exdb/mnist/) Author: Aymeric Damien Project: https://github.com/aymericdamien/TensorFlow-Examples/ ''' # In[ ]: import tensorflow as tf from sklearn import cross_validation from sklearn import metrics as mt from sklearn import utils as ut import gc import csv import numpy as np import os.path as path from os import listdir from PIL import Image # In[ ]: def dataSplit(array, size): split = [element['id'] for element in ut.shuffle(array, n_samples=size, random_state=37)] return [element for element in array if element['id'] in split], [element for element in array if element['id'] not in split] def splitPositiveNegative(array, positiveClass): return [element for element in array if positiveClass in element['labels_raw']], [element for element in array if positiveClass not in element['labels_raw']] def proportionalDataSplit(positive, negative, positiveSize, size): positiveSize = np.floor(positiveSize*size).astype(int) negativeSize = (size-positiveSize).astype(int) positiveSplit = [element['id'] for element in ut.shuffle(positive, n_samples=positiveSize, random_state=37)] negativeSplit = [element['id'] for element in ut.shuffle(negative, n_samples=negativeSize, random_state=37)] return [element for element in positive if element['id'] in positiveSplit], [element for element in positive if element['id'] not in positiveSplit], [element for element in negative if element['id'] in negativeSplit], [element for element in negative if element['id'] not in negativeSplit] def dataAndLabels(array, negative = None): if negative is None: return [np.array(Image.open(path.join(imagesDir, element['id']))) for element in array], [element['labels'] for element in array] elif type(negative) is type([]): return [np.array(Image.open(path.join(imagesDir, element['id']))) for element in array] + [np.array(Image.open(path.join(imagesDir, element['id']))) for element in negative], [[0,1]]*len(array) + [[1,0]]*len(negative) else: return # In[ ]: with open('./photo_to_levels.csv') as f: food_to_label = [] for row in csv.DictReader(f, skipinitialspace=True): element = {} for k, v in row.items(): if k == "id": element['id'] = str(v) + ".jpg" elif k == "labels": labels_raw = np.array(str(v).split(' ')) labels = [0] * 9 labels_int = [] try: for lb in labels_raw: labels[int(str(lb))] = 1 labels_int.append(int(lb)) except ValueError: print "Failure with value", lb, "labels lenght", len(labels_raw), "content:", v element['labels'] = labels element['labels_raw'] = labels_int else : print "No idea what you just passed!" if len(element['labels_raw']) is not 0: food_to_label.append(element) else: print "Picture", element['id'], "has no labels and is being ignored!" if len(set([element['id'] for element in food_to_label])) != len(food_to_label): print('something\'s wrong!') # In[ ]: proportions = [] for lb in range(9): l = len([element for element in food_to_label if lb in element['labels_raw']])/float(len(food_to_label)) print "Label", lb, "is present at", int(l*100), "% with respect to all other labels" proportions.append(l) # In[ ]: # Data dir imagesDir = './data/SampleFoodClassifier_Norm_100' # Filter out images which might not be present in the folder but are present in the csv file files = [f for f in listdir(imagesDir) if path.isfile(path.join(imagesDir, f))] food_to_label = [element for element in food_to_label if element['id'] in files] del files[:] gc.collect() print "The new length of the data is", len(food_to_label) # Parameters test_size = 500 learning_rate_start= .001 training_size = 100 training_iters = 100 dropout = 0.75 # Dropout, probability to keep units # Network Parameters # !! Images: 100x100 RGB = 100, 100, 3 w, h, channels = [100, 100, 3] n_classes = 2 print "Width, Height and channels:", w, h, channels, ". Number of classes:", n_classes # tf Graph input x = tf.placeholder(tf.float32, [None, w, h, channels]) y = tf.placeholder(tf.float32, [None, n_classes]) keep_prob = tf.placeholder(tf.float32) #dropout (keep probability) # In[ ]: # Create some wrappers for simplicity def conv2d(x, W, b, strides=1): # Conv2D wrapper, with bias and relu activation x = tf.nn.conv2d(x, W, strides=[1, strides, strides, 1], padding='SAME') x = tf.nn.bias_add(x, b) return tf.nn.relu(x) def maxpool2d(x, k=2): # MaxPool2D wrapper return tf.nn.max_pool(x, ksize=[1, k, k, 1], strides=[1, k, k, 1], padding='SAME') # Create model def conv_net(x, weights, biases, dropout): # Convolution Layer conv1 = conv2d(x, weights['wc1'], biases['bc1']) # Max Pooling (down-sampling) conv1 = maxpool2d(conv1, k=2) # Convolution Layer conv2 = conv2d(conv1, weights['wc2'], biases['bc2']) # Max Pooling (down-sampling) conv2 = maxpool2d(conv2, k=2) print "PLEASE MODIFY WD1 TO", conv2.get_shape().as_list()[1], "*",conv2.get_shape().as_list()[2], "*64" # Fully connected layer # Reshape conv2 output to fit fully connected layer input fc1 = tf.reshape(conv2, [-1, weights['wd1'].get_shape().as_list()[0]]) fc1 = tf.add(tf.matmul(fc1, weights['wd1']), biases['bd1']) fc1 = tf.nn.relu(fc1) # Apply Dropout # fc1 = tf.nn.dropout(fc1, dropout) fc2 = tf.add(tf.matmul(fc1, weights['wd2']), biases['bd2']) fc2 = tf.nn.relu(fc2) # Apply Dropout fc2 = tf.nn.dropout(fc2, dropout) # Output, class prediction out = tf.add(tf.matmul(fc2, weights['out']), biases['out']) return out # In[ ]: # Store layers weight & bias sdev= 0.01 weights = { # 5x5 conv, 1 input, 32 outputs 'wc1': tf.Variable(tf.truncated_normal([5, 5, channels, 32], stddev=sdev)), # 5x5 conv, 32 inputs, 64 outputs 'wc2': tf.Variable(tf.truncated_normal([5, 5, 32, 64], stddev=sdev)), # fully connected, 7*7*64 inputs, 1024 outputs 'wd1': tf.Variable(tf.truncated_normal([25*25*64, 3000], stddev=sdev)), 'wd2': tf.Variable(tf.truncated_normal([3000, 1024], stddev=sdev)), # 1024 inputs, 10 outputs (class prediction) 'out': tf.Variable(tf.truncated_normal([1024, n_classes], stddev=sdev)) } biases = { 'bc1': tf.Variable(tf.truncated_normal([32], stddev=sdev)), 'bc2': tf.Variable(tf.truncated_normal([64], stddev=sdev)), 'bd1': tf.Variable(tf.truncated_normal([3000], stddev=sdev)), 'bd2': tf.Variable(tf.truncated_normal([1024], stddev=sdev)), 'out': tf.Variable(tf.truncated_normal([n_classes], stddev=sdev)) } # Construct model pred = conv_net(x, weights, biases, keep_prob) # Define loss and optimizer cost = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(pred, y)) # optimizer without adapted learning_rate #optimizer = tf.train.AdamOptimizerOptimizer(learning_rate=learning_rate).minimize(cost) #optimizer with adapted learning_rate step = tf.Variable(0, trainable=False) rate = tf.train.exponential_decay(learning_rate_start, step, 1, 0.9999) optimizer = tf.train.AdamOptimizer(rate).minimize(cost, global_step=step) # Evaluate model correct_pred = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1)) accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32)) y_p = tf.argmax(pred, 1) # Gives an array of arrays, where each position represents % of belonging to respective classs. Eg: a[0.34, 0.66] --> class 0 : 34%, class 1: 66% # classes = tf.nn.softmax(pred) classes = tf.nn.softmax(pred) def label_class(x): for i in range(0,len(x)): print i, ":", x[i] # Initializing the variables init = tf.initialize_all_variables() # In[ ]: # save the models saveDir = './tensorflow/one_against_all' saver = tf.train.Saver() # In[ ]: for currentLabel in range(len(proportions)): print "Training model for", currentLabel, "which is represented by", proportions[currentLabel] positive, negative = splitPositiveNegative(food_to_label, currentLabel) # Get some test samples test1, positive, test0, negative = proportionalDataSplit(positive, negative, proportions[currentLabel], test_size) positiveSize = np.floor(proportions[currentLabel]*training_size).astype(int) negativeSize = (training_size-positiveSize).astype(int) # Launch the graph with tf.Session() as sess: sess.run(init) # Keep training until reach max iterations for epoch in range(training_iters): if len(positive) < positiveSize or len(negative) < negativeSize: del ix[:] del iy[:] del batch1[:] del batch0[:] break # Fit training using batch data print "Loading batch...", batch1, positive, batch0, negative = proportionalDataSplit(positive, negative, proportions[currentLabel], training_size) ix, iy = dataAndLabels(batch1, batch0) print "bactch loaded!" print "Running optimizer...", sess.run(optimizer, feed_dict={x: ix, y: iy, keep_prob: 1.}) print "done!" # Compute average loss loss, acc = sess.run([cost, accuracy], feed_dict={x: ix, y: iy, keep_prob: 1.}) # Display logs per epoch step print "Iter " + str(epoch) + ", Minibatch Loss= " + "{:.6f}".format(loss) + ", Training Accuracy= " + "{:.5f}".format(acc) del ix[:] del iy[:] del batch1[:] del batch0[:] print "Optimization Finished!" save_path = saver.save(sess, "/tmp/label-" + str(currentLabel) + ".ckpt") print("Model saved in file: %s" % save_path) runs = 0 acc = 0. y_pred = [] class_pred = [] test = test1 + test0 y_test = [[0,1]]*len(test1) + [[1,0]]*len(test0) for i in range(0, test_size, 30): if i+30 < test_size: x_test, _ = dataAndLabels(test[i:i+30]) val_accuracy, y_pred_i, cls = sess.run([accuracy, y_p, classes], feed_dict={x: x_test, y: y_test[i:i+30], keep_prob: 1.}) else: x_test, _ = dataAndLabels(test[i:]) val_accuracy, y_pred_i, cls = sess.run([accuracy, y_p, classes], feed_dict={x: x_test, y: y_test[i:], keep_prob: 1.}) acc += val_accuracy y_pred.extend(y_pred_i) class_pred.extend(cls) runs += 1 print "Partial testing accuracy:", acc/runs #metrics print "Validation accuracy:", acc/runs y_true = np.argmax(y_test,1) print "Precision for each class:" label_class(mt.precision_score(y_true, y_pred, average=None)) print "Recall for each class:" label_class(mt.recall_score(y_true, y_pred, average=None)) print "F1_score for each class:" label_class(mt.f1_score(y_true, y_pred, average=None)) print "confusion_matrix" print mt.confusion_matrix(y_true, y_pred) fpr, tpr, tresholds = mt.roc_curve(y_true, y_pred) # In[ ]: for i in range(len(y_test)): print "For", i, "as", y_test[i] for j in range(2): print "\t", j, "@", class_pred[i][j]*100 print "\n"
e68b660237b66f9a832bacc13b2c0e0311d24613
link0233/python-dodge-ball-game
/pythonm/wd/ball.py
962
3.59375
4
class ball: def __init__(self,canvas): self.canvas=canvas self.item=canvas.create_oval(0,0,20,20,fill='White') self.kd=[1,1] def loop(self,speed): self.canvas.move(self.item,speed*self.kd[0],speed*self.kd[1]) self.xy=self.canvas.coords(self.item) if self.xy[0]<0 or self.xy[2]>640: self.kd[0]*=-1 if self.xy[1]<0 or self.xy[3]>480: self.kd[1]*=-1 class ball2: def __init__(self,canvas): self.canvas=canvas self.item=canvas.create_oval(0,0,20,20,fill='White') self.kd=[1,1] self.xy=[0,0,0,0] def loop(self,speed): if speed>2: speed-=2 self.canvas.move(self.item,speed*self.kd[0],speed*self.kd[1]) self.xy=self.canvas.coords(self.item) if self.xy[0]<0 or self.xy[2]>640: self.kd[0]*=-1 if self.xy[1]<0 or self.xy[3]>480: self.kd[1]*=-1
10c8d46409b1ac493cc539dd7192745e214f083a
MitchDziak/crash_course.py
/python_work/messing_around.py
462
3.734375
4
# This is my first fun program. print("Welcome to my first program that's supposed to be fun or something!") print("") title = "A NEAT STORY" print("\t\t\t" + title) name = "mitch" age = 23 girlfriend = "SHANNON" print("You wake up, and as usual your first thought is, 'I am " + name.title() + "' and I am " + str(age) + ".") print("\nYour girlfriend " + girlfriend.title() + " asks what's up and you realize you've been asleep for 4 months.")
56176eda107308ea31db050bfa030596f0c14046
balajisaikumar2000/Python-Snippets
/Sets.py
1,397
4.46875
4
#sets are unordered and unindexed and immutable: #every time we run a code the result will be different in output #sets never allow duplicates ,even if we have two same items it will show only one x = {"apple","banana","cherry","cherry"} print(x) print("banana" in x) #add(): y = {"apple","banana","cherry"} y.add("mango") print(y) #update(): z = {"apple","banana","cherry"} z.update(["mango","grapes"]) print(z) #to remove an item in sets we have only two methods: m = {"apple","banana","cherry"} m.remove("apple") print(m) #discard(): n = {"apple","banana","cherry"} n.discard("cherry") print(n) #n.clear() will clear set with remains empty set #del x will delete set permanently #update(): set1= {"a","b","c"} set2 = {1,2,3} set1.update(set2) print(set1) #union(): set3= {"a","b","c","c"} set4 = {1,2,3} set5 = set3.union(set4) print(set5) #intersection(): gives common to each set print(set3 & set5) #or we can use below method set4 = {"a"} print(set3.intersection(set5)) print(set3.intersection(set5,set4)) #if there is no common values we wil get empty set -----(set()) #difference: s1 = {1,2,3} s2 = {2,3,4} s3 = s1.difference(s2) #the result will have elements that are in s1 but not in s2 s4 = s3.difference(s1,s2) print(s3) print(s4) #symmetric_difference: s3 = s2.symmetric_difference(s1) #will give the values other than common values in them print(s3)
3e9428e03d1ed8ea92825f0ebcd3f5679a87cba0
hookeyplayer/exercise.io
/算法/100_same tree.py
859
3.59375
4
# Input: p = [1,2], q = [1,null,2] # Output: false class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def isSameTree(self, p: TreeNode, q: TreeNode) -> bool: if p == q: return True try: l = r = True if p.val == q.val: l = self.isSameTree(p.left, q.left) r = self.isSameTree(p.right, q.right) return (l and r) except: return False return False def isSameTree(self, p: TreeNode, q: TreeNode) -> bool: # 判断是否为空 if not p and not q: return True # 判断根节点 if p and q and p.val == q.val: l = self.isSameTree(p.left, q.left) r = self.isSameTree(p.right, q.right) return (l and r) else: return False
78024de7257eb2c7ab1756a476f251256f45106f
haichao801/learn-python
/7-文件处理/f_read.py
715
3.75
4
""" 语法格式: f = open(file='d:/练习方式.txt', mode='r', encoding='utf-8') data = f.read() f.close * f = open(file='d:/练习方式.txt', mode='r', encoding='utf-8') 表示文件路径 * mode='r'表示只读(可修改为其它) * encoding='utf-8'表示将硬盘上的010101按照utf-8的规则去断句,再将断句后的每一段010101转换成Unicode的010101,Unicode对照表中有010101和字符的对应关系 * f.read()表示读取所有内容,内容是已经转换完毕的字符串 * f.close()表示关闭文件 """ # 文件是以GB2312编码,此时以utf-8编码读取,会报错 f = open(file='联系方式.txt', mode='r', encoding='utf-8') data = f.read() print(data) f.close()
f5d37a7ba9f5aff3f421a4380564843b4727b1a1
CoderMP/PythonPassGen
/PassGen.py
3,661
3.75
4
####### REQUIRED IMPORTS ####### import os import sys import click import random import string from time import sleep ####### FUNCTIONS ###### def displayHeader(): """ () -> () Function that is responsible for printing the application header and menu """ # Clear the console window os.system('cls') # Print the application header & menu print("\033[94m------------------------------\n" + "|| \033[92mPassword Generator \033[94m||\n" + "------------------------------\n\n" + "\033[0mWelcome to Password Generator v1.0\n" + "\033[92mSource Code By: \033[0m\033[1mMark Philips (CoderMP)\n" + "\033[91mLicense: \033[0m\033[1mMIT\n\n" + "\033[0m\033[1m[1] Generate Password(s)\n" + "[2] Exit Program\n") def generator(len, num): """ (int, int) -> list Function that is repsonsible for generating a random alphanumeric password based off the iser request parameters """ # Initialize the list that will hold the generated passwords passList = [] # Initialize a counter variable to assist with generation i = 0 while i < num: # Assemble the password temp = ''.join(random.choices(string.ascii_lowercase + string.digits, k = len)) # Append the temp variable value to the passList passList.append(temp) # Increment the counter i += 1 # Return the password list return passList def passParams(): """ () -> () Function that is responsible for retrieving the desired password generation paramters of the user. """ # Prompt the user for their desired pass length and how many to generate len = click.prompt('How long would you like your password(s) to be? >>', type=int) num = click.prompt('How many password(s) would you like to generate? >>', type=int) print('\n') # Assemble the password list passwordList = generator(len, num) # Print the password list to the console print(*passwordList, sep='\n') def genLogic(): """ () -> () Function that is responsible for executing the application logic based on the user's choice """ # Prompt the user for input op = click.prompt('Enter choice >>', type=int) if (op == 1): print('\n') # Call method that retrieves the password generation parameters passParams() while(True): # Prompt the user as to whether or not they'd like to generate another set choice = click.prompt('\n\nWould you like to generate another set? (y/n) >>', type=str) # Execute accordingly if (choice == 'Y' or choice == 'y'): print('\n') # Call the function that retrieves the password generation parameters passParams() if (choice == 'N' or choice == 'n'): # Notify the user of navigation back to the main menu print('Returning you to the main menu....') sleep(1.3) os.system('cls') break # Display the main menu and prompt the user for input displayHeader() genLogic() if (op == 2): # Notify the user of the termination sequence print('\nTerminating program...') sleep(2) # Terminate sys.exit() else: # Notify the user of their command error and re-prompt them for input print('\033[91mInvalid command, please try again!\033[0m') genLogic() ####### MAIN PROGRAM ####### if __name__ == '__main__': displayHeader() genLogic()
e292710bb2c757b52dfd939390e70bf9832fdab6
notaidea/python
/adv/zhuangshiqi5.py
904
3.625
4
# -*- coding: utf-8 -*- """ 装饰器用在类方法上(非静态) 内部的function,第一个形参对应类方法的self 装饰器用在类静态方法上 不能和非静态方法共用装饰器(形参个数不一样) @staticmethod要写在最上面 """ def check(func): #第一个形参对应类方法的self def _check(obj): print("checking......") func(obj) return _check def checkstatic(func): #第一个形参对应类方法的self def _check(): print("checking......") func() return _check class Test(): def __init__(self, name): self.name = name @check def say(self): print(self.name) #@staticmethod要写在最上面 @staticmethod @checkstatic def info(): print("info") obj = Test("peter") obj.say() Test.info()
bb4244d08950407ac0e9312e2addf354e39e5e2f
PaulGuo5/Leetcode-notes
/notes/0866/0866.py
609
3.609375
4
class Solution: def primePalindrome(self, N: int) -> int: def reverse(n): res = 0 while n > 0: res = res*10 + n%10 n = n//10 return res def isprime(n): for i in range(2, int(n**.5)+1): if n%i == 0: return False return True if N == 1: return 2 while True: if N == reverse(N) and isprime(N): return N N += 1 if 10**7 < N < 10**8: N = 10**8
24a36d9a5f8747064a4dfe6b6bd1ff72d16a03a0
StevenSigil/Conways-Game-of-Life
/game/life_logic.py
4,243
3.703125
4
import numpy as np def random_position(arr): # Random position to place active cell relative to board dimensions rows = arr.shape[0] cols = arr.shape[1] random_row = np.random.randint(0, rows) random_col = np.random.randint(0, cols) return random_row, random_col def setup_random(arr): """Defining the amount of random positions.""" count = 0 while count < round(arr.size * .3): # Adjusting the .3 will give different results. r_pos = random_position(arr) arr[r_pos] = 1 count += 1 return def cell_check(arr): """For each tick of the clock, retrieve the alive positions (before determining if they are to stay alive).""" alive_positions = [] dead_positions = [] for row in range(0, arr.shape[0]): for col in range(0, arr.shape[1]): value = arr[row, col] if value == 1: alive_positions.append((row, col)) else: dead_positions.append((row, col)) return alive_positions, dead_positions def find_neighbors(position): """Coordinates of the 8 neighboring cells relative to the cell being checked. tl = top-left, tt = top-top, etc...""" col_pos = position[1] row_pos = position[0] tl = int(row_pos - 1), int(col_pos - 1) tt = int(row_pos - 1), int(col_pos) tr = int(row_pos - 1), int(col_pos + 1) lt = int(row_pos), int(col_pos - 1) rt = int(row_pos), int(col_pos + 1) bl = int(row_pos + 1), int(col_pos - 1) bb = int(row_pos + 1), int(col_pos) br = int(row_pos + 1), int(col_pos + 1) return [tl, tt, tr, lt, rt, bl, bb, br] def check_neighbors(arr, cell): """For each cell on the board, returns the count of their alive neighbors""" alive_neighbor_count = 0 neighbor_positions = find_neighbors(cell) # Checks neighboring positions to determine if the position is a position or the edge of the board. valid_positions = [i for i in neighbor_positions if arr.shape[0] - 1 >= i[0] >= 0 and arr.shape[1] - 1 >= i[1] >= 0] for neighbor in valid_positions: if arr[neighbor] == 1: alive_neighbor_count += 1 return alive_neighbor_count def alive_rules(arr, row, column): """Rule 1 Cell stays alive if 2 or 3 neighbors are alive. """ n_count = check_neighbors(arr, (row, column)) if n_count != 2 and n_count != 3: change_to_dead = row, column return "D", change_to_dead else: keep_alive = row, column return "A", keep_alive def dead_rules(arr, row, column): """Rule 2 A dead cell with three live neighbors is made alive. """ n_count = check_neighbors(arr, (row, column)) if n_count == 3: change_to_alive = row, column return "A", change_to_alive else: stay_dead = row, column return "D", stay_dead def cell_killer(arr, cell): arr[cell[0], cell[1]] = 0 def cell_defibrillator(arr, cell): arr[cell[0], cell[1]] = 1 def update_grid(arr): """Runs each tick of the clock. Takes the cells current position and value and changes the value depending on the outcome of the rules. """ alive_cells, dead_cells = cell_check(arr) # Holding lists for current gen cells after checking them against rules. gen2_dead_cells = [] gen2_alive_cells = [] for cell in alive_cells: # Send alive cells through 'alive rules' -> append results to list -> Do NOT have npArray change yet char, position = alive_rules(arr, cell[0], cell[1]) if char == "D": gen2_dead_cells.append(position) elif char == "A": gen2_alive_cells.append(position) for cell in dead_cells: # Send dead cells through 'dead rules' -> append results to list -> Do NOT change array yet char, position = dead_rules(arr, cell[0], cell[1]) if char == "A": gen2_alive_cells.append(position) elif char == "D": gen2_dead_cells.append(position) # Now the cells are identified, change (or not) their value accordingly. for cell in gen2_dead_cells: cell_killer(arr, cell) for cell in gen2_alive_cells: cell_defibrillator(arr, cell) return arr
56d76f7d8ea08912ed786310fc16598fbf90c27b
heiligbasil/Sprint-Challenge--Data-Structures-Python
/names/binary_search_tree.py
2,019
4.03125
4
class BinarySearchTree: """Binary Search Tree, is a node-based binary tree data structure which has the following properties: The left subtree of a node contains only nodes with keys lesser than the node’s key. The right subtree of a node contains only nodes with keys greater than the node’s key. The left and right subtree each must also be a binary search tree. There must be no duplicate nodes """ def __init__(self, value): self.value = value self.left = None self.right = None def insert(self, value): """Insert the given value into the tree. Insert adds the input value to the binary search tree, adhering to the rules of the ordering of elements in a binary search tree""" if value < self.value: if self.left: self.left.insert(value) else: self.left = BinarySearchTree(value) if value >= self.value: if self.right: self.right.insert(value) else: self.right = BinarySearchTree(value) def contains(self, target): """This searches the binary search tree for the input value, returning a boolean indicating whether the value exists in the tree or not""" if self.value == target: return True if self.value > target: if self.left: return self.left.contains(target) else: return False if self.value <= target: if self.right: return self.right.contains(target) else: return False def get_max(self): """This returns the maximum value in the binary search tree""" if self.right is None: # No more nodes to the right; found the largest value return self.value else: # Keep traversing the nodes to the right in search of the final one return self.right.get_max()
977c7c3732c5f5dcf4e6c7105dec21836fc71cc1
caiknife/test-python-project
/src/PythonCookbook/Chapter19/ex19-04/ex.py
463
3.625
4
#!/usr/bin/python # coding: UTF-8 """ Created on 2012-11-25 在多重赋值中拆解部分项 @author: CaiKnife """ def peel(iterable, arg_cnt=1): """获得一个可迭代对象的前arg_cnt项,然后用一个迭代器表示余下的部分""" iterator = iter(iterable) for num in xrange(arg_cnt): yield iterator.next() yield iterator if __name__ == '__main__': t5 = range(1, 6) a, b, c = peel(t5, 2) print a, b, list(c)
3444f30670edd189748841ad556b9aafb4c8cfd1
curtislb/ProjectEuler
/py/problem_067.py
1,147
3.71875
4
#!/usr/bin/env python3 """problem_067.py Problem 67: Maximum path sum II By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23. 3 7 4 2 4 6 8 5 9 3 That is, 3 + 7 + 4 + 9 = 23. Find the maximum total from top to bottom of the triangle contained in the file FILE_NAME. NOTE: This is a much more difficult version of Problem 18. It is not possible to try every route to solve this problem, as there are 2^99 altogether! If you could check one trillion (10^12) routes every second it would take over twenty billion years to check them all. There is an efficient algorithm to solve it. """ __author__ = 'Curtis Belmonte' import common.fileio as fio import problem_018 as p018 # PARAMETERS ################################################################## FILE_NAME = '../input/067.txt' # default: '../input/067.txt' # SOLUTION #################################################################### def solve() -> int: return p018.max_triangle_path(list(fio.ints_from_file(FILE_NAME))) if __name__ == '__main__': print(solve())
85e4159fe6900ef200e6154846a9cb934826f304
Nithy-Sree/Crazy-Python-
/simple urlChecker.py
1,166
3.984375
4
# pip install validators # pip install tkinter # import the neccessary packages import tkinter as tk import validators from tkinter import messagebox # create a GUI window root = tk.Tk() # setting the title for the window root.title("URL Validator") # setting the size of the window to display root.geometry("250x100") def checkUrl(): # to get the entered data in the Entry field urlEntry = f'{baseString.get()}' # print(url) if len(urlEntry) == 0: messagebox.showerror("Error!", "Enter a valid string") elif validators.url(urlEntry): messagebox.showinfo("Success", "URL you entered is Valid") else: messagebox.showwarning("Invalid", "URL is not Valid") # displaying text in the window label = tk.Label(root, text = "Enter URL to check (with http or https)") label.pack() # to hold a string value baseString = tk.StringVar() # getting input from the user using Entry entry = tk.Entry(root, textvariable=baseString) entry.pack() # checking the entered string is valid url or not validateButton = tk.Button(text="Check", command = checkUrl) validateButton.pack() # start the GUI Window root.mainloop()
81beeefbe30be803983cd0610509cb0f40bbf860
SimonPavlin68/python
/pygame/circle.py
739
3.578125
4
import pygame, math, sys from pygame.locals import * BLACK = (0,0,0) RED = (255,0,0) WHITE = (255,255,255) WIDTH = 640 HEIGHT = 480 RADIUS = 10 screen = pygame.display.set_mode((WIDTH, HEIGHT)) screen.fill(WHITE) x = 320 y = 240 xd = 1; yd = -1; pygame.draw.circle(screen, RED, (x,y), RADIUS) pygame.display.update() clock = pygame.time.Clock() while True: clock.tick(100) x += xd y += yd screen.fill(WHITE) pygame.draw.circle(screen, RED, (x, y), 10) pygame.display.update() if (y <= RADIUS/2) or (y >= HEIGHT-RADIUS/2): yd *= -1 if (x <= RADIUS/2) or (x >= WIDTH-RADIUS/2): xd *= -1 for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit()
58c9f98ce62da07e187ea70818cdfd3ab54056f7
hira66it/pyProject
/Algorithm/3_find_missingNumber.py
239
3.71875
4
def missingNumber(arr): tmp_1=0 tmp_2=0 length = len(arr) print(length) for i in range(length): tmp_1 += arr[i] tmp_2 += i tmp_2 += (length) return tmp_2 - tmp_1 print(missingNumber([0,1,2,3,5]))
a9548f3ba1052f073a456cea261be80b7f1d8089
dyollluap/August5
/primenumber1000.py
333
3.765625
4
# -*- coding: utf-8 -*- """ Paul Lloyd - August 2014 This is a script to find prime numbers under 1000. """ minIdx =1; maxIdx =1001; for i in range(minIdx,maxIdx): isPrime = True; for j in range(2,i): if (i % j == 0): isPrime = False; break if (isPrime == True): print i
4ae4595fe4e3d92e783bd8424a99e611d845df42
Vakonda-River/Lesson4
/lesson4_1.py
601
3.546875
4
import less4myfunc name = input('Укажите имя и фамилию сотрудника: ') hour = float(input('Введите выработку в часах: ')) rate = float(input('Введите размер почасовой ставки: ')) prize = float(input('Если предусмотрено, введите размер премии: ')) w = round(less4myfunc.wage(hour,rate),2) w_p = w + prize print(name,', основная заработная плата, начислено:',w,'руб. Премия:',prize,'руб. Итого к выплате:', w_p,'руб. ')
121740a86e8ae4526e584863cd3a6c3df44b2a6a
BengiY/Management-of-a-communications-company-python
/venv/Line.py
1,084
3.5
4
# Line Management class class Line(): def __init__(sel,CustomerCode,RouteCode,LineFone): self.__CustomerCode=CustomerCode self.__RouteCode=RouteCode self.__LineFone=LineFone #proprty @property def LineCode(self): return self.__LineCode @LineCode.setter def LineCode(self, value): self.__LineCode=value @property def CustomerCode(self): return self.__CustomerCode @CustomerCode.setter def CustomerCode(self, value): self.__CustomerCode=value @property def RouteCode(self): return self.__RouteCode @RouteCode.setter def RouteCode(self, value): self.__RouteCode = value @property def LineFone(self): return self.__LineFone @LineFone.setter def LineFone(self, value): self.__LineFone = value #class function def __str__(self): return "CustomerCode: " + str(self.CustomerCode) + " RouteCode: " + str( self.RouteCode) + " Phone: " + self.LineFone
9273587b9f3d7fc9a3639056132c93cc0e40cdce
fossabot/textlytics
/textlytics/sentiment/negation_handling.py
1,865
3.734375
4
# coding: utf-8 import re as _re _full_negation = "not, no, none, never, nothing, nobody, nowhere, neither, nor" _quasi_negation = "hardly, scarcely" _abs_negation = "not at all, by no means, in no way, nothing short of" _negation = _full_negation + ", " + _quasi_negation + ", " + _abs_negation _negation_regexp = "(?i)(" + (")|(".join(_negation.split(", "))) + ")" _quasi_negatives = "not every, not all, not much, not many, not always, not never" _quasi_negatives = "(?i)(" + (")|(".join(_quasi_negatives.split(", "))) + ")" _interpunction = ", . ;".split(" ") # TODO move it to preprocessing def _filter_empty(x): """x is an iterable (e.g. list) function assumes that each element in the iterable is a string and is passes only non-empty strings """ new = [] for i in x: if i and i != "not": new.append(i) return new def handle_negation(sentence): """ s is a sentence written in english This function tries to add "not_" prefix to all of the words, that are negated in that sentence """ parsed = _re.sub(_quasi_negatives, "", sentence) # remove parsed = _re.sub(_negation_regexp, "not", parsed) # assume all negation words mean the same as not parsed = _re.sub("(?i)(\w+)n't", "\\1 not", parsed) # change n't to not parsed = _re.sub("([.,;:])", " \\1", parsed) # add additional space to enable later split tokens = _re.split("[ ]", parsed) # print tokens flag = False for i in range(len(tokens)): if flag: if tokens[i] in _interpunction: flag = False else: tokens[i] = "not_" + tokens[i] else: if _re.match(_negation_regexp, tokens[i]): flag = True tokens = _filter_empty(tokens) return " ".join(tokens)
86c9da450c6beb05fcf713cbdbe2a31d7fd396c4
surenderpal/Durga
/Exception Handling/multiple_except.py
541
3.875
4
# try: # x=int(input('Enter first value:')) # y=int(input('Enter second value:')) # print('The result: ',x/y) # except ZeroDivisionError: # print("Can't Divide with zero") # except ValueError: # print('Please provide only int values only') # try: # print(10/0) # except ZeroDivisionError: # print('ZeroDivisionError') # except ArithmeticError: # print('ArithmeticError') try: print(10/0) except ArithmeticError: print('ArithmeticError') except ZeroDivisionError: print('ZeroDivisionError')
225fe19b785ddc3108a6e37b47ff4cb8fed9ebb1
mashagua/hackercode
/hackercode30/Day_25.py
295
3.9375
4
import math def check_prime(num): if num == 1: return "Not prime" sq = int(math.sqrt(num)) for x in range(2, sq+1): if num % x == 0: return "Not prime" return "Prime" T=int(input()) for i in range(T): num=int(input()) print(check_prime(num))
7d190d11468bd05e997f6789c14ada6e57e42585
miguelabreuss/scripts_python
/CursoEmVideoPython/desafio55.py
447
3.5625
4
peso = 0 maior = 0 menor = 9999 pes_maior = 0 pes_menor = 0 for i in range(0, 5): peso = int(input('Digite o peso [kg] da {}ª pessoa: '.format(i+1))) if peso > maior: maior = peso pes_maior = i if peso < menor: menor = peso pes_menor = i print('O maior peso lido foi {} kg, da {}ª pessoa'.format(maior, pes_maior + 1)) print('O menor peso lido foi {} kg, da {}ª pessoa'.format(menor, pes_menor + 1))
827ced0d9a3018519f2cf4179e1cb4409f42c61d
Aminaba123/LeetCode
/227 Basic Calculator II.py
2,582
4.1875
4
""" Implement a basic calculator to evaluate a simple expression string. The expression string contains only non-negative integers, +, -, *, / operators and empty spaces . The integer division should truncate toward zero. You may assume that the given expression is always valid. Some examples: "3+2*2" = 7 " 3/2 " = 1 " 3+5 / 2 " = 5 Note: Do not use the eval built-in library function. """ __author__ = 'Daniel' class Solution: def calculate(self, s): """ :type s: str :rtype: int """ lst = self.to_list(s) post = self.infix2postfix(lst) return self.eval_postfix(post) def to_list(self, s): i = 0 ret = [] while i < len(s): if s[i] == " ": i += 1 elif s[i] in ("(", ")", "+", "-", "*", "/"): ret.append(s[i]) i += 1 else: b = i while i < len(s) and s[i].isdigit(): i += 1 ret.append(s[b:i]) return ret def infix2postfix(self, lst): stk = [] # store operators in strictly increasing precedence ret = [] for elt in lst: if elt.isdigit(): ret.append(elt) elif elt == "(": stk.append(elt) elif elt == ")": while stk[-1] != "(": ret.append(stk.pop()) stk.pop() else: # generalized to include * and / while stk and self.precendece(elt) <= self.precendece(stk[-1]): ret.append(stk.pop()) stk.append(elt) while stk: ret.append(stk.pop()) return ret def precendece(self, op): if op in ("(", ")"): return 0 if op in ("+", "-"): return 1 if op in ("*", "/"): return 2 return 3 def eval_postfix(self, post): stk = [] for elt in post: if elt in ("+", "-", "*", "/"): b = int(stk.pop()) a = int(stk.pop()) if elt == "+": stk.append(a+b) elif elt == "-": stk.append(a-b) elif elt == "*": stk.append(a*b) else: stk.append(a/b) else: stk.append(elt) assert len(stk) == 1 return int(stk[-1]) if __name__ == "__main__": assert Solution().calculate("3+2*2") == 7
7210d7f1c3f90fcceb987790f8d585c6e1dcdf16
akassian/Python-DS-Practice
/09_is_palindrome/is_palindrome.py
833
4.21875
4
def is_palindrome(phrase): """Is phrase a palindrome? Return True/False if phrase is a palindrome (same read backwards and forwards). >>> is_palindrome('tacocat') True >>> is_palindrome('noon') True >>> is_palindrome('robert') False Should ignore capitalization/spaces when deciding: >>> is_palindrome('taco cat') True >>> is_palindrome('Noon') True """ return phrase.replace(" ", "").lower() \ == reverse_string(phrase.replace(" ", "").lower()) def reverse_string(phrase): """Reverse string, >>> reverse_string('awesome') 'emosewa' >>> reverse_string('sauce') 'ecuas' """ reversed = "" for char in phrase: reversed = char + reversed return reversed
406db45850da08ce4a08b0d966883dce55f03e2b
Akhilnazim/Problems
/leetcode/string.py
99
3.75
4
s=input("enter the value") # b=ord(s) # print(b) for i in s: a= ord(i)+2 print(str(a))
f5c85218a843f2131b62b683867a444d695263b2
Jung-Woo-sik/mailprograming_problem
/before_2021/Q28.py
364
3.765625
4
class LinkedList: def __init__(self, data, next=None): self.data = data self.next = next def solution(head): start = end = head while start: end = start total = 0 skip = False while end: total += end.data if total == 0: start = end skip = True break end = end.next if not skip: print(start.data) start = start.next
a35ea4e9cf26d265e8e8cc508b514cc0bae85010
kishoreKumar01/Project_1
/TWITTER Sentiment_Analysis/main.py
1,927
3.546875
4
import string from collections import Counter import matplotlib.pyplot as plt from nltk.tokenize import word_tokenize from nltk.corpus import stopwords import GetOldTweets3 as got def get_tweets(): Tweet_Criteria = got.manager.TweetCriteria().setQuerySearch('CoronaOutbreak').setMaxTweets(500) \ .setSince("2020-03-20") \ .setUntil("2020-04-25") tweets = got.manager.TweetManager.getTweets(Tweet_Criteria) tweet_txt = [[tweet.text] for tweet in tweets] return tweet_txt text = get_tweets() print(text) length = len(text) #reading the twitter text as a string twitter_txt = "" for i in range(0,length): twitter_txt += text[i][0] + " " #print(twitter_txt) lower_txt = "" #with open('read.txt',encoding='utf-8') as text: for word in twitter_txt: # converting all text to the lower case for analysis word = word.lower() lower_txt += word #removing all the special characters that are not useful for our analysis clear_txt = lower_txt.translate(str.maketrans('','',string.punctuation)) text_lst = word_tokenize(clear_txt,'English') #removing the unnecessary words form the file final_lst = [] for words in text_lst: if words not in stopwords.words("English") and words.isalpha() is True: final_lst.append(words) #print(final_lst) #getting the emotion of each words form the emotion.txt emotion_lst = [] with open('emotion.txt', 'r') as file: for line in file: line = line.replace(",","").replace("'","").replace("\n","").strip() words,emotion_words = line.split(':') if words in final_lst: emotion_lst.append(emotion_words) #print(emotion_lst) count = (Counter(emotion_lst)) x,y = count.keys(),count.values() plot = plt.bar(x,y) plt.savefig('sentiment_Analysis') plt.title('sentiment_Analysis') plt.xlabel("Emotions in the content") plt.ylabel("Rate of Emotions") plt.show()
a65db3659b938f74f2ec6b3f20a847b641304fa6
zhaobf1990/MyPhpDemo
/first/com/zhaobf/test15.py
173
3.609375
4
def fun1(n): if n == 1: print("你选择了1") elif n == 2: print("你选择了2") elif n == 3: print("你选择了3") fun1(1) fun1(2)
f632e80951c04fae3d12bb4e773c790e6c01dc2d
2019-b-gr2-fundamentos/fund-Santamaria-Herrera-Lizbeth-Ultimo
/Examen/Borrar-Actualizar-Crear.py
2,880
4.21875
4
print("Con este programa se podra crear, actualizar y borrar nombres de dinosaurios") DINOSAURIOS = ["Brachiosaurus", "Diplodocus", "Stegosaurus", "Triceratops", "Protoceratops","Patagotitan", "Apatosaurus","Camarasurus"] import random def main(): dinosaurios() def dinosaurios(): print (" ",DINOSAURIOS) print ("Selecciona una opcion:\n1.Observar el arreglo de dinosaurios \n2.Añadir o cambiar \n3:Eliminar\n4:Observar un dinosaurio en especifico\n5:Salir") print("Ingresa el numero de la opcion que deseas que se ejecute") opcion = int(input()) if opcion == 1: print("El arreglo de dinosaurios es: ", DINOSAURIOS) print("1:menú principal\n2:salir") op = int(input()) if op == 1: main() elif op ==2 : print("Adios") else: print("opcion no valida") elif opcion == 2: print("Ingrese el nombre del dinosaurio que desea añadir") agregar = str(input()) DINOSAURIOS.append(agregar) print("Ël arreglo con un dinisaurio agregado es: ", DINOSAURIOS) print("1:menú principal\n2:salir") op = int(input()) if op == 1: main() elif op == 2: print("Adios") else: print("opcion no valida") elif opcion == 3: print ("El arreglo es : ", DINOSAURIOS) print("Ingrese el numero de la posicion del Dinosaurio que desea borrar/eliminar") indice = int(input()) if 0 <= indice <= len(DINOSAURIOS)-1 : p = DINOSAURIOS.pop(indice) print("El arreglo con el nombre del dinosaurio eliminado es: ", DINOSAURIOS) print("El dinosaurio eliminsado es: ", p ) print("1:menú principal\n2:salir") op = int(input()) if op == 1: main() elif op == 2: print("Adios") else: print("opcion no valida") else: print("No es una posicion del arreglo") elif opcion == 4: print("Ingrese la posicion del nombre del dinosaurio que desea observar") dino = int(input()) if 0 <= dino <= len(DINOSAURIOS)-1 : dinop = DINOSAURIOS[dino] print("El dinosaurio que seleccionó es: ", dinop) print("Desea actualizar su eleccion, escriba :\n1:si\n2:salir\n3menú principal") sf = int(input()) if sf == 1: aleatorio = random.choice(DINOSAURIOS) print(aleatorio) elif sf == 2: print("Adios") elif sf == 3: main() else: print("Opcion no valida") else: print("No es una posicion del arreglo") elif opcion == 5: print ("Adios") else: print("Opción no vallida") main()
1ce8a38810e2bcb958f79e71aaa570ce62f28260
SaItFish/PySundries
/algorithm_questions/LeetCode/剑指Offer/55-1二叉树的深度.py
953
3.734375
4
# !/usr/bin/env python3 # -*- coding: utf-8 -*- # @author: SaltFish # @file: 55-1二叉树的深度.py # @date: 2020/07/23 """ 输入一棵二叉树的根节点,求该树的深度。从根节点到叶节点依次经过的节点(含根、叶节点)形成树的一条路径,最长路径的长度为树的深度。 例如: 给定二叉树 [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 返回它的最大深度 3 。 """ # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def maxDepth(self, root: TreeNode) -> int: self.res = 0 def dfs(node: TreeNode, depth: int): if not node: return self.res = max(depth, self.res) dfs(node.left, depth + 1) dfs(node.right, depth + 1) dfs(root, 1) return self.res
280dbe664cbe6a89dde47dd7a850b26a448e2f59
ckimmons/code2040Assessment
/ReverseAString.py
472
3.9375
4
# Stage 2. # Reverses a string, posts the result. from ApiRequestHandler import RecieveProblem, ValidateProblem REQUEST_URL = 'http://challenge.code2040.org/api/reverse' VALIDATE_URL = 'http://challenge.code2040.org/api/reverse/validate' # Uses the slicing operator to return the reversed string. def ReverseAString(string): return string[::-1] string = ReceiveProblem(REQUEST_URL) reverse = ReverseAString(string) ValidateProblem(VALIDATE_URL, 'string', reverse)
5ae73e1b62af982d36d0664776865bd680d571fa
vaibhavyesalwad/Basic-Python-and-Data-Structure
/Python Data Structure/Dictionary/11_NestedDictfromList.py
460
4.40625
4
"""Program to convert a list into a nested dictionary of keys""" numbers = [1, 2, 3, 4, 5] for num in numbers: dict1 = dict.fromkeys([num]) # creating dictionary in each iteration if num == 1: my_dictionary = dict1 # parent dictionary if num > 1: dict2[num-1] = dict1 # assigning new dictionary crated as value for dictionary in last iteration dict2 = dict1 print(my_dictionary)
a99f0f49ec1455b3e25748b64a001d0557147770
TesioMatias/othello-reinforcement-learning
/othello_solutions.py
2,200
3.515625
4
from urllib.request import urlopen # Python 3 import os import numpy as np def download_value_func(link, filename): response = urlopen(link) file_size = response.length CHUNK = 16 * 1024 downloaded = 0 print('Donwloading: ', link) print('Saving it as: ', filename) with open(filename, 'wb') as f: while True: read_chunk = response.read(CHUNK) if not read_chunk: break downloaded = downloaded + len(read_chunk) print('\r','Progress: %'+str(int(100*downloaded/file_size + 0.5)), end='') f.write(read_chunk) print() def get_solution(name): """ WIN_LOOSE: The reward is 1 for winning, -1 for loosing, 0 for tie MAXIMIZE_MARGIN: The reward is different between the number winner pieces vs number of looser pieces at the end of the game MINIMIZE_PIECES: The reward is (16 - number of pieces in the board) for the winner MINIMIZE_STEPS: The reward is (N - number of steps) for the winner. Where N should be bigger than the maximim possible number of steps """ solutions = { 'WIN_LOOSE': {'value_func': {'filename': 'V_WIN_LOOSE.npy', 'url': 'https://github.com/jganzabal/othello-reinforcement-learning/blob/master/V_WIN_LOOSE.npy?raw=true'}}, 'MAXIMIZE_MARGIN': {'value_func': {'filename': 'V_MAXIMIZE_MARGIN.npy', 'url': 'https://github.com/jganzabal/othello-reinforcement-learning/blob/master/V_MAXIMIZE_MARGIN.npy?raw=true'}}, 'MINIMIZE_PIECES': {'value_func': {'filename': 'V_MINIMIZE_PIECES.npy', 'url': 'https://github.com/jganzabal/othello-reinforcement-learning/blob/master/V_MINIMIZE_PIECES.npy?raw=true'}}, 'MINIMIZE_STEPS': {'value_func': {'filename': 'V_MINIMIZE_STEPS.npy', 'url': 'https://github.com/jganzabal/othello-reinforcement-learning/blob/master/V_MINIMIZE_STEPS.npy?raw=true'}} } val_func = solutions[name]['value_func'] if os.path.isfile(val_func['filename']): print('Already downloaded, remove it if you want to download it again.') else: download_value_func(val_func['url'], val_func['filename']) return np.load(val_func['filename'], allow_pickle=True).item()
3a4050db7e4cf187f1fad1072b4cfe49b9505eb0
Alan6584/PythonLearn
/demos/D019_thread.py
653
3.984375
4
#! /usr/bin/python # -*- coding:UTF-8 -*- import threading import time class MyThread(threading.Thread): '自定义线程' def __init__(self, threadID, count): threading.Thread.__init__(self) self.threadID = threadID self.count = count def run(self): print "MyThread:%d -->run start......count:%d" % (self.threadID, self.count) self.__loop(self.count) print "MyThread:%d -->run end......" % (self.threadID) def __loop(self, count): while (count > 0): time.sleep(1) #睡眠1秒 print "MyThread:%d -->loop()......count:%d" % (self.threadID, count) count -= 1 t1 = MyThread(1, 5) t2 = MyThread(2, 6) t1.start() t2.start()
ae5db1f411e0d8d9215fb28791011fc60bbb9b31
Walker-TW/Python_Projects
/fizzbuzz_python/fizzbuzz.py
519
3.953125
4
def better_fizzbuzz (x): for x in range(x): output = "" if ( x % 3 == 0): output += "Fizz" if ( x % 5 == 0): output += "Buzz" if output == "": print ( x ) else: print ( output ) # OR def simple_fizzbuzz(x): if x % 3 == 0: print ("Fizz") elif x % 5 == 0: print ("Buzz") elif (x % 3 == 0) & (x % 5 == 0): print ("Fizzbuzz") else : print (x) for x in range(101): simple_fizzbuzz(x) # OR i = 0 while i < 100: i += 1 simple_fizzbuzz(i)
1c171d37832d685379130b36b83db0f3c9469af3
liruileay/data_structure_in_python
/data_structure_python/question/chapter3_binary_tree/question20.py
3,151
3.515625
4
""" Tarjan算法与并查集解决二叉树节点间最近公共祖先的批量查询问题 题目: """ from development.chapter10.ChainHashMap import ChainHashMap from development.chapter7.FavoritesList import FavoritesList as LinkedList class Node: def __init__(self, value): self.left = None self.right = None self.value = value class Query: def __init__(self, o1, o2): self.o1 = o1 self.o2 = o2 # 要求如果二叉树的节点个数为N,查询语句的条数为M,整个处理过程的时间复杂度要求达到O(N+M) class DisjointSets: def __init__(self): self.father_map = ChainHashMap() self.rank_map = ChainHashMap() def make_set(self, node): self.father_map.clear() self.rank_map.clear() self.pre_order_make(node) def pre_order_make(self, head): if head is None: return self.father_map[head] = head self.rank_map[head] = 0 self.pre_order_make(head.left) self.pre_order_make(head.right) def find_father(self, n): father = self.father_map.get(n) if father is not n: father = self.find_father(father) self.father_map[n] = father return father def union(self, a, b): if a is None or b is None: return a_father = self.find_father(a) b_father = self.find_father(b) if a_father is not b_father: a_frank = self.rank_map.get(a_father) b_frank = self.rank_map.get(b_father) if a_frank < b_frank: self.father_map[a_father] = b_father elif a_frank > b_frank: self.father_map[b_father] = a_father else: self.father_map[b_father] = a_father self.rank_map[a_father] = a_frank + 1 class Tarjan(object): def __init__(self): self.query_map = ChainHashMap() self.index_map = ChainHashMap() self.ancestor_map = ChainHashMap() self.sets = DisjointSets() def query(self, head, ques): ans = [None] * len(ques) self.set_queries(ques, ans) self.sets.make_set(head) self.set_answers(head, ans) return ans def set_queries(self, ques, ans): for i in range(len(ans)): o1 = ques[i].o1 o2 = ques[i].o2 if o1 is o2 or o1 is None or o2 is None: ans[i] = o1 if o1 is not None else o2 else: if not self.query_map.__contains__(o1): self.query_map[o1] = LinkedList() self.index_map[o1] = LinkedList() if not self.query_map.__contains__(o2): self.query_map[o2] = LinkedList() self.index_map[o2] = LinkedList() self.query_map.get(o1).access(o2) self.index_map.get(o1).access(i) self.query_map.get(o2).access(o1) self.index_map.get(o2).access(i) def set_answers(self, head, ans): if head is None: return self.set_answers(head.left, ans) self.sets.union(head.left, head) self.ancestor_map[self.sets.find_father(head)] = head self.set_answers(head.right, ans) self.sets.union(head.right, head) self.ancestor_map[self.sets.find_father(head)] = head nList = self.query_map.get(head) iList = self.index_map.get(head) while nList is not None and not nList.is_empty(): node = nList.pop() index = iList.pop() node_father = self.sets.find_father(node) if self.ancestor_map.__contains__(node): ans[index] = self.ancestor_map.get(node_father)
a3938c06c8f4a8e282e6739bcd914e6c3bdae488
Elain26/elains_leetcode_practice
/8Check If N and Its Double Exist.py
313
3.609375
4
arr=[10,2,5,3] def doubleornot(arr): n=len(arr) #暴力穷举对比任意两个数是否有两倍关系,注意两数不能同为0 for i in range(n): for j in range(n): if arr[i]*2==arr[j] and i!=j: return True return False print(doubleornot(arr))
e3ba323f94745f35e6e5b4890e9049b851a5d856
p83218882/270201032
/lab4/example1.py
180
3.546875
4
if 0 <= a < 10: print(a) elif a == 10: print(1) elif 10 < a <= 99 : print((a % 10) + ((a - (a % 10)) / 10)) elif a >= 100: print((a % 10) + ((a - a % 10) / 10) % 10)
8b9dad1d0e76314bbc07118194630d3bc4f7b7fb
andrezzadede/Curso-de-Python-POO
/interfaceclassabstrata.py
404
3.640625
4
# Classe abstrata ou interface #Uma classe abstrata nãoo pode ser diretamente instanciada, ela serve apenas para que outras classes possam ter ela como base from abc import ABCMeta, abstractmethod class MinhaClasseAbstrata(metaclass=ABCMeta): @abstractmethod def fazer_algo(self): pass @abstractmethod def fazer_algo_novamente(self, o_que_fazer): pass
0c864d46d32d37d371fa0685ced591190e30411f
RebeccaML/Practice
/Python/Challenges/fizzbuzz.py
455
4.1875
4
# Fizzbuzz challenge # For all numbers from 1 to 100, if number is a multiple of 3 print Fizz # if a multiple of 5 print Buzz, if a multiple of both print Fizzbuzz # Otherwise print the number def fizzbuzz(): for i in range(1, 101): if i % 3 == 0 and i % 5 == 0: print("Fizzbuzz!") elif i % 3 == 0: print("Fizz") elif i % 5 == 0: print("Buzz") else: print(i) fizzbuzz()
b7a1f9b331f27df994bc721003cdb236fde991b8
prashanthr11/Leetcode
/practice/Backtracking/N-Queens.py
2,698
3.5625
4
class Solution: def solveNQueens(self, n): # Time: O(N!) where n is the size of the chess board. # Space: O(N ** 2) Keeping track of all possitions in N * N board. def solve(board, a): if a >= len(board): # Base case: When all Queens are placed. nonlocal ret tmp = [''.join(i) for i in board] ret.append(tmp) return False # Backtracking for i in range(n): if can_place(board, a, i): # Checking if Queen can be placed at board[a][i] board[a][i] = 'Q' if solve(board, a + 1): # Recursive call for placing next Queen return True board[a][i] = '.' # Remove Queen at board[a][i] (BackTracking) return False # Returns False when Queen cannot be placed in a single row. def can_place(board, a, b): ln = len(board) if 'Q' in board[a]: # Checking in a Row return False for k in range(ln): # Checking in Column b if board[k][b] == 'Q': return False x, y = a, b i, j = a, b # Checking for a Queen in Left Upper Diagonal while i >= 0 and j >= 0: if board[i][j] == 'Q': return False i -= 1 j -= 1 # Checking for a Queen in Left Bottom Diagonal while y >= 0 and x < ln: if board[x][y] == 'Q': return False x += 1 y -= 1 x, y = a, b i, j = a, b # Checking for a Queen in Right Bottom Diagonal while i < ln and j < ln: if board[i][j] == 'Q': return False i += 1 j += 1 # Checking for a Queen in Right Upper Diagonal while x >= 0 and y < ln: if board[x][y] == 'Q': return False x -= 1 y += 1 return True board = [['.'] * n for i in range(n)] ret = list() solve(board, 0) return ret
349edb0cc4d510c37a3cd91559f91448228a67ef
ishitadate/nsfPython
/Week 2/w2_homework_solutions.py
591
3.703125
4
# Week 2 Solutions # 1. // is integer division. It takes the floor of a number. # 2. % is a modulus. It finds the remainder of the division between numbers. # 3. Apples is not updated in memory. It should read: apples = 6 apples -= 3 # 4. Ilikecookies # 5. Yes. You can't subtract from a string, this is a syntax error. # 6. != # 7. Sample code. Keep in mind there are multiple ways to write this solution. number = 5 userInput = int(input("Pick a number ")) if userInput < number: print("guess higher") elif userInput > number: print("guess lower") else: print("good job")
170ba0f1681910726fe92a96e02d523ddc0af520
Anuar7/TSIS5
/7.py
177
3.5625
4
def file(f): arr = [] with open(f) as a: for line in a: arr.append(line) print(arr) file('test.txt')
6afb96f2a75a2c5f883cbd971c464095780c888f
Antechamber/sandbox
/sumTo100.py
1,086
4.125
4
# this module searches for combinations of '+', '-' and '', placed between the numbers 1-9 in order and finds # expressions which evaluate to exactly 100 from itertools import product numbers = ['1', '2', '3', '4', '5', '6', '7', '8', '9'] arr = ['', '-', '+'] operators_combos = product(arr, repeat=8) # evaluate expression and check whether it sums to 100 def test_equation(eq: str) -> bool: value = eval(eq) if value == 100: return True else: return False # alternate operators and numbers to create every possible combination combined = [] try: for item in operators_combos: combined.append([item for sublist in zip(numbers, next(operators_combos)) for item in sublist]) except StopIteration: # end of generator operator_combos reached pass # collapse lists into string expressions combined_strings = [] for item in combined: item.append('9') combined_strings.append(''.join(item)) # test each string expression and print passing expressions equals_100 = filter(test_equation, combined_strings) print(list(equals_100))
1702050be4acd0aabae929727fb48bdd68e83655
ioef/PPE-100
/Level1/q9.py
233
4.25
4
#!/usr/bin/env python ''' Define a function that can convert a integer into a string and print it in console. Hints: Use str() to convert a number to string. ''' number = 3245 def int2str(num): print(str(num)) int2str(number)
8e82b70ac64be6ccadf6ed5064d712506f922607
dwagon/pydominion
/dominion/cards/Card_Huntingparty.py
2,676
3.75
4
#!/usr/bin/env python import unittest from dominion import Game, Card, Piles import dominion.Card as Card ############################################################################### class Card_Huntingparty(Card.Card): def __init__(self): Card.Card.__init__(self) self.cardtype = Card.CardType.ACTION self.base = Card.CardExpansion.CORNUCOPIA self.desc = """+1 Card +1 Action. Reveal your hand. Reveal cards from your deck until you reveal a card that isn't a duplicate of one in your hand. Put it into your hand and discard the rest.""" self.name = "Hunting Party" self.cards = 1 self.actions = 1 self.cost = 5 def special(self, game, player): discards = [] for card in player.piles[Piles.HAND]: player.reveal_card(card) while True: card = player.next_card() player.reveal_card(card) if not card: player.output("No more cards") break if player.piles[Piles.HAND][card.name]: player.output(f"Discarding {card.name}") discards.append(card) continue player.output(f"Picked up a {card.name}") player.add_card(card, Piles.HAND) break for card in discards: player.discard_card(card) ############################################################################### class Test_Huntingparty(unittest.TestCase): def setUp(self): self.g = Game.TestGame(numplayers=1, initcards=["Hunting Party"]) self.g.start_game() self.plr = self.g.player_list(0) self.card = self.g["Hunting Party"].remove() self.plr.piles[Piles.HAND].set("Silver", "Gold") def test_playcard(self): """Play a hunting party""" self.plr.piles[Piles.DECK].set("Copper", "Province", "Silver", "Gold", "Duchy") self.plr.piles[Piles.HAND].set("Gold", "Silver") self.plr.add_card(self.card, Piles.HAND) self.plr.play_card(self.card) self.assertEqual(self.plr.actions.get(), 1) self.assertIn("Duchy", self.plr.piles[Piles.HAND]) self.assertIn("Province", self.plr.piles[Piles.HAND]) self.assertIn("Silver", self.plr.piles[Piles.DISCARD]) self.assertIn("Gold", self.plr.piles[Piles.DISCARD]) # Original Hand of 2 + 1 card and 1 non-dupl picked up self.assertEqual(self.plr.piles[Piles.HAND].size(), 4) ############################################################################### if __name__ == "__main__": # pragma: no cover unittest.main() # EOF
0ccfb9a5ea6bd60956afcd3876e61dececbfcdc4
Matthew-Lin-Duke/Class_02072020
/dictionary.py
1,374
3.78125
4
def create_dictionary(): new_dictionary = {"day": "between sunrise and sunset", "food": "something to eat", "night": "when the moon is out", "star": "Blinking lights in the night sky"} return new_dictionary def create_patient(): new_patient = { "last name": "Liu", "age": 234, "married": False, "test result": [23,34,54,654]} return new_patient def save_Json(patient): import json filename = "patient_data.txt" out_file = open(filename, 'w') #w stands for write json.dump(patient, out_file) out_file.close() return def read_dictionary(my_dict): my_key = "food" y = my_dict[my_key] #print(y) print("The definition of {} is {}".format(my_key, y)) return def add_dictionary(my_dict): my_dict["lunch"] = "meal at noon" my_dict["star"] = "other planet and fixed stars in space" return my_dict if __name__ == "__main__": y = create_patient() save_Json(y) """x = create_dictionary() y = create_patient() print(y) a = y.get("test result") b = y["test result"][2] print(a) print(b) #read_dictionary(x) #print(x) #x = add_dictionary(x) #print(x) #z = x.get("food") #print(z) #print(x) #print(type(x)) """
8b473ccb6315120ca87783d87e0ebfda07f42030
wwtang/code02
/wordcount3.py
2,308
4.1875
4
""" The problem in you code: 1, you read the whole file one time, that will be slow for the large file 2, you have another method to sort the dict by its values 3, you do not have the clear train of thought Here is the train of thought(algorithm) first, do the base, derive a dict from the file secondly, define the two functions, so in you future program, remember how to get the dict from the file """ import sys import operator # derive the sorted word_count_dict from the file def word_count_dict(filename): try: input_file = open(filename,"r") except IOError: print "could not open the file" sys.exit() word_count = {} for line in input_file: words = line.split() # Special check for the fisrt word in the file for word in words: word = word.lower() if not word in word_count: word_count[word] = 1 else: word_count[word] +=1 input_file.close() return word_count # Print the word_count _dict XXXXXReturn the sorted dict def print_count(filename): word_dict = word_count_dict(filename) words = sorted(word_dict.keys()) # create an index of dict, but the dict not sorted, so loop as the index and print corresponding values for item in words: print item, word_dict[item] # used for sorted by dict values def get_value(tuples): return tuples[1] def top_count(filename): word_dict = word_count_dict(filename) #word_dict.item() concert the dict into a list of tuple # sorted_word = sorted(word_dict.item(), key= get_value, reverse=True) # for word in sroted_word[:20]: # print word, sorted_word[word] sorted_word = sorted(word_dict.iteritems(), key=operator.itemgetter(1), reverse=True) for item in sorted_word: print item[0], item[1] def main(): if len(sys.argv) != 3: print "usage: python wordcount.py {--count|--topcount} \"filename\" " sys.exit(1) option = sys.argv[1] filename = sys.argv[2] if option == "--count": print_count(filename) elif option == "--topcount": top_count(filename) else: print "unkonwn " + option sys.exit(1) if __name__ == "__main__": main()
1f5c2478f011d39acca7096c40ae962b089258b5
WilliamO-creator/Digital_Solutions
/Chapter 3/Exercises_4.py
395
3.703125
4
num1 = input("enter number 1 to 10") if num1 == ("1") : print("I") if num1 == ("2") : print("II") if num1 == ("3") : print("III") if num1 == ("4") : print("IV") if num1 == ("5") : print("V") if num1 == ("6") : print("VI") if num1 == ("7") : print("VII") if num1 == ("8") : print("VIII") if num1 == ("9") : print("IX") if num1 == ("10") : print("X")
9652da3a491426d6ade172c8da875fdc3b854503
sccdcwc/Newcode
/14.py
1,740
3.515625
4
''' 请实现一种数据结构SetOfStacks,由多个栈组成,其中每个栈的大小为size,当前一个栈填满时,新建一个栈。该数据结构应支持与普通栈相同的push和pop操作。 给定一个操作序列int[][2] ope(C++为vector<vector<int>>),每个操作的第一个数代表操作类型, 若为1,则为push操作,后一个数为应push的数字;若为2,则为pop操作,后一个数无意义。 请返回一个int[][](C++为vector<vector<int>>),为完成所有操作后的SetOfStacks,顺序应为从下到上, 默认初始的SetOfStacks为空。保证数据合法。 ''' # -*- coding:utf-8 -*- class SetOfStacks: def setOfStacks(self, ope, size): # write code here list=[] stack=[] l=0 for i in ope: if i[0]==1: if l<size-1: list.append(i[1]) l+=1 else: list.append(i[1]) stack.append(list) list=[] l=0 if i[0]==2: if l !=0: list.pop() l-=1 elif l == 0: list=stack.pop() list.pop() l=size-1 if len(list)!=0: stack.append(list) return stack size=2 ope=[[1,97868],[1,69995],[1,28525],[1,72341],[1,86916],[1,5966],[2,58473],[2,93399],[1,84955],[1,16420],[1,96091],[1,45179],[1,59472],[1,49594],[1,67060],[1,25466],[1,50357],[1,83509],[1,39489],[2,51884],[1,34140],[1,8981],[1,50722],[1,65104],[1,61130],[1,92187],[2,2191],[1,2908],[1,63673],[2,92805],[1,29442]] s=SetOfStacks(); print(s.setOfStacks(ope,size))
624c1ba2d6971e2ea8e2f5c197eacb6f4468bae9
neelakantankk/AoC_2019
/Problem_03/main.py
3,033
3.953125
4
from collections import namedtuple Point = namedtuple('Point',['x','y']) class Path: def __init__(self): self.path = [Point(0,0)] def __repr__(self): return ', '.join([str(point) for point in self.path]) def go_right(self,steps): current_point = self.path[-1] for step in range(1,steps+1): new_point = Point(current_point.x + step,current_point.y) self.path.append(new_point) def go_left(self, steps): current_point = self.path[-1] for step in range(1,steps+1): new_point = Point(current_point.x - step, current_point.y) self.path.append(new_point) def go_up(self, steps): current_point = self.path[-1] for step in range(1, steps+1): new_point = Point(current_point.x, current_point.y + step) self.path.append(new_point) def go_down(self, steps): current_point = self.path[-1] for step in range(1, steps+1): new_point = Point(current_point.x, current_point.y - step) self.path.append(new_point) def intersection_points(self, other_path): self_set = set(self.path[1:]) other_set = set(other_path.path[1:]) return self_set & other_set def create_path(self, listing): for instruction in listing: direction = instruction[0] steps = int(instruction[1:]) if direction == "R": self.go_right(steps) elif direction == "L": self.go_left(steps) elif direction == "U": self.go_up(steps) elif direction == "D": self.go_down(steps) def calculate_distance(point): return int(abs(point.x) + abs(point.y)) def calculate_timing(point, wire_one, wire_two): return (wire_one.path.index(point) + wire_two.path.index(point)) def main(): path_listing = [] with open('input.txt','r') as fInput: for line in fInput.readlines(): path_listing.append(line.strip().split(',')) wire_one = Path() wire_two = Path() wire_one.create_path(path_listing[0]) wire_two.create_path(path_listing[1]) intersections = wire_one.intersection_points(wire_two) print(intersections) intersections = list(intersections) minimum_distance = calculate_distance(intersections[0]) for intersection in intersections[1:]: distance = calculate_distance(intersection) if distance < minimum_distance: print(intersection) minimum_distance = distance print(f"Least distance: {minimum_distance}") minimum_timing = calculate_timing(intersections[0], wire_one, wire_two) for intersection in intersections[1:]: timing = calculate_timing(intersection, wire_one, wire_two) if timing < minimum_timing: print(intersection) minimum_timing = timing print(f"Least time: {minimum_timing}") if __name__ == '__main__': main()
33af13dbdeb2321144dab3c7863e20ed5cc87f8c
akadir/CodingInterviewSolutions
/Matrix Spiral/MatrixSpiral.py
1,783
3.515625
4
import unittest def first_solution(number): result = [] for i in range(0, number): result.append([None] * number) counter = 1 start_row = 0 end_row = number - 1 start_column = 0 end_column = number - 1 while start_column <= end_column and start_row <= end_row: i = start_column while start_column <= i <= end_column: result[start_row][i] = counter counter += 1 i += 1 start_row += 1 i = start_row while start_row <= i <= end_row: result[i][end_column] = counter counter += 1 i += 1 end_column -= 1 i = end_column while end_column >= i >= start_column: result[end_row][i] = counter counter += 1 i -= 1 end_row -= 1 i = end_row while end_row >= i >= start_row: result[i][start_column] = counter counter += 1 i -= 1 start_column += 1 return result class MatrixSpiralTest(unittest.TestCase): def test_first_solution(self): m = first_solution(2) self.assertEqual(2, len(m)) self.assertEqual([1, 2], m[0]) self.assertEqual([4, 3], m[1]) m = first_solution(3) self.assertEqual(3, len(m)) self.assertEqual([1, 2, 3], m[0]) self.assertEqual([8, 9, 4], m[1]) self.assertEqual([7, 6, 5], m[2]) m = first_solution(4) self.assertEqual(4, len(m)) self.assertEqual([1, 2, 3, 4], m[0]) self.assertEqual([12, 13, 14, 5], m[1]) self.assertEqual([11, 16, 15, 6], m[2]) self.assertEqual([10, 9, 8, 7], m[3])
69d013e50fd7991b9a69f2efcddb57ed85cfed40
RakeshSuvvari/Joy-of-computing-using-Python
/speech-text.py
598
3.59375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Feb 27 11:12:16 2021 @author: rakesh """ import speech_recognition as sr AUDIO_FILE = ("sample2.wav") # use audio file as source r = sr.Recognizer() # initialize the recognizer with sr.AudioFile(AUDIO_FILE) as source: audio = r.record(source) #reads the audio file try: print("audio file contains "+r.recognize_google(audio)) except sr.UnkownValueError: print("Google Speech Recognition could not understand the audio") except sr.RequestError: print("couldn't get the result from Google Speech Recognition")
7fde89a195460769eb57aaf12566ed983edfbe45
santos816/curso_python_2020
/exec03.py
498
4.09375
4
valor_1 = int(input("Forneça o valor 1:\n")) valor_2 = int(input("Forneça o valor 2:\n")) soma = valor_1 + valor_2 print(f'Soma: {soma}') subtracao = valor_1 - valor_2 print(f'Subtração: {subtracao}') divisao = valor_1 / valor_2 print(f'Divisão: {divisao}') divisao_inteiro = valor_1 // valor_2 print(f'Divisão inteira: {divisao_inteiro}') multiplicacao = valor_1 * valor_2 print(f'Multiplicação: {multiplicacao}') resto = valor_1 % valor_2 print(f'Resto: {resto}')
0a3950b13fcb35fe6471279ea0dbad3433668a86
salvadorhmutec/python_curse
/session01/011_concatenation_format.py
164
3.8125
4
#variables, formato y operacioens foo=10 bar=12 print ("{}+{}={:.2f}".format(foo,bar,foo+bar)) print ("{foo}+{bar}={res:.2f}".format(foo=foo,bar=2,res=foo+bar))
03a16a337524cfb8ea3827994b6342935171a7d6
Sofista23/Aula1_Python
/Aulas/Exercícios-Mundo3/Aula018/Ex088.py
395
3.6875
4
from random import randint from time import sleep cont=0 lista=[] jogos=[] quant=int(input("Quantiade de vezes de palpites:")) tot=0 while tot<=quant: while True: num=randint(1,60) if num not in lista: lista.append(num) cont+=1 if cont>=6: break lista.sort() jogos.append(lista[:]) lista.clear() tot+=1 print(jogos)
53a6ce49a45b4a2ee1569ad82dd194eee137c1fe
lqa9970/J.A.R.V.I.S
/Understanding.py
202
3.796875
4
you = "hello" if you == "": jarvis = "I can't hear you" elif you == "hello": jarvis = "Hello QA" elif you == "date": jarvis = "Saturday" else: jarvis = "I'm good, thanks" print(jarvis)
c78e80626a76212673e0504a27a275663e5c35bb
superniaoren/fresh-fish
/python_tricks/functions/test_function_return.py
743
3.921875
4
# programmers should know the ins and outs of the language they're working with # after all, code is communication # today's topic: implicit return statement def pretend(value): if value: return value else: return None def pretend_none(value): """ bare return, implies `return None` """ if value: return value else: return def pretend_default(value): """ missing return statement, implies `return None` """ if value: return value #return if __name__ == '__main__': print(type(pretend(0))) print(type(pretend_none(0))) print(type(pretend_default(0))) print('-' * 40) print(pretend(0)) print(pretend_none(0)) print(pretend_default(0))
d7475b96024b7a05d49674d826789af2da9d8f6e
MijaToka/Random3_1415
/Tarea 2 Transformadores de Binario-Decimal/decimalABinario.py
567
3.75
4
# -*- coding: utf-8 -*- """ Created on Fri Oct 2 13:29:26 2020 @author: Admin """ def decimalABinario(n10,n2= ''): """Traduce una representacion decimal de un valor a su representacion binaria.""" if n10 == '0' and n2 == '': return '0' elif n10 == '0' or n10 == '': return '' else: if int(n10) % 2 == 1: n2 = n2 + '1' return decimalABinario( str((int(n10)//2)),n2 ) + '1' elif int(n10) % 2 == 0: n2 = n2 + '0' return decimalABinario( str((int(n10)//2)),n2 ) + '0' print(decimalABinario(input()), end='')
2f69b8cbce4604f02b90bd9fa0c591c619f7db7c
Dan-Vizor/SmallProjects
/python/incCode/.goutputstream-AZB37Y
2,352
3.984375
4
#!/usr/bin/python3 ################################################## def encrypt(): key = int(input("enter key: ")) data = raw_input("enter text: ") loop = int(input("enter loop (min 1): ")) for x in range(0,loop): if x > 0: out = encryptword(olOut, key) olOut = out else: out = encryptword(data, key) olOut = out print("") print (olOut) return olOut def encryptword(word, key): encrypted="" for c in word: x = ord(c) dec = encryptLetter(c, key); encrypted += dec return encrypted def encryptLetter(letter, key): x = ord(letter) if letter == " ": enc = ord(" ") else: enc = x + key if enc > ord("z"): enc = enc - 26 return chr(enc) ################################################## def decrypt(data): key = int(input("enter key: ")) loop = int(input("enter loop (min 1): ")) for x in range(0,loop): if x > 0: out = decryptWord(olOut, key) olOut = out else: out = decryptWord(data, key) olOut = out print("") print (out) def decryptLetter(letter, key): x = ord(letter) enc = x - key if enc < ord("a"): enc = enc + 26 return chr(enc) def decryptWord(word, key): decrypted="" for c in word: if c == " ": return decrypted x = ord(c) dec = decryptLetter(c, key); decrypted += dec return decrypted ################################################## tqxxa iadxp def scan_dict(word): doc = open("words.txt","r") for line in doc: if word == line.strip(): return word else: print("can't find match") return 404 ################################################## print("") while True: print ("\n1 - in-code") print ("2 - de-code") print ("3 - force de-code") print ("5 - scan dict") print ("5 - end") mode = int(input("pick mode: ")) end ="" print ("") if mode == 1: encrypt() if mode == 2: data = raw_input("enter code: ") decrypt(data) if mode == 3: enter = raw_input("enter code: ") loop = int(input("enter loop (min 1): ")) for key in range(0,25): end = decryptWord(enter, key) print(" sirching with new key ") scan_dict(word) if mode == 5: break if mode == 4: word = raw_input("enter word: ") out = scan_dict(word) if out == 404: print("do you want to add " + word + "to the dictonary y/n") a = raw_input(": ") if a == "y": doc = open("words2.txt","a") doc.write("\n" + word + "\n")
ddceece488cdbf8134db701ff95a96b897a67975
araujomarianna/codingbat-solutions
/warmup_1/sleep_in.py
396
3.671875
4
def sleep_in(weekday, vacation): """ This function verifies if you can or cannot sleep taking into account weekday and vacation values. :param weekday: Any bool value :type weekday: bool :param vacation: Any bool value :type vacation: bool :return: It returns True if weekday is False or vacation is True :rtype: bool """ return not weekday or vacation
2b29d733701024692d259066f9be8ecd50998fb2
kennethokwu/Leetcode-Blind-75
/PythonSolutions/InsertIntervals.py
471
3.703125
4
from typing import List class Solution: def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]: intervals.append(newInterval) intervals = sorted(intervals, key = lambda x: x[0]) ans = [intervals[0]] for interval in intervals: if interval[0]>ans[-1][1]: ans.append(interval) elif interval[1]>ans[-1][1]: ans[-1][1]=interval[1] return ans
b120badc64c9522a7c5dc281ef41310e7860ee41
rayhanzfr/latihan_github
/lat4-Loop_Statements/lat4-5.py
415
3.71875
4
x=str(input("masukan sebuah kalimat: ")) panjang=len(x) while 0<=len(x)<=50 or len(x)>50: if 0<len(x)<=50: y=x.replace(" ","") print("*"+str.upper(y)+"*") break elif len(x)==0: print("Masukkan sebuah inputan") x=str(input("masukan sebuah kalimat: ")) else: print("Melebihi batas(50 karakter) ") x=str(input("masukan sebuah kalimat: "))
fb3ce2c07e04110b1c43ce429f47243178798a81
artie63/SMU_Homwwork-
/PythonAPI homework/weatherhomework
4,606
3.953125
4
#!/usr/bin/env python # coding: utf-8 # # WeatherPy # ---- # # #### Note # * Instructions have been included for each segment. You do not have to follow them exactly, but they are included to help you think through the steps. # In[19]: # Dependencies and Setup import matplotlib.pyplot as plt import pandas as pd import numpy as np import requests import time from scipy.stats import linregress # Import API key from api_keys import weather_api_key # Incorporated citipy to determine city based on latitude and longitude from citipy import citipy # Output File (CSV) output_data_file = "cities.csv" # Range of latitudes and longitudes lat_range = (-90, 90) lng_range = (-180, 180) # ## Generate Cities List # In[20]: # List for holding lat_lngs and cities lat_lngs = [] cities = [] # Create a set of random lat and lng combinations lats = np.random.uniform(lat_range[0], lat_range[1], size=1500) lngs = np.random.uniform(lng_range[0], lng_range[1], size=1500) lat_lngs = zip(lats, lngs) # Identify nearest city for each lat, lng combination for lat_lng in lat_lngs: city = citipy.nearest_city(lat_lng[0], lat_lng[1]).city_name # If the city is unique, then add it to a our cities list if city not in cities: cities.append(city) # Print the city count to confirm sufficient count len(cities) # ### Perform API Calls # * Perform a weather check on each city using a series of successive API calls. # * Include a print log of each city as it'sbeing processed (with the city number and city name). # # In[21]: firstCity = cities[5] firstCity # In[22]: units = "imperial" url = f"http://api.openweathermap.org/data/2.5/weather?q={firstCity}&appid={weather_api_key}&units={units}" url # In[23]: response = requests.get(url).json() pprint(response) # In[24]: response["clouds"]["all"] # In[5]: # In[26]: for city in cities: url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={weather_api_key}&units={units}" try: response = requests.get(url).json() code = response["cod"] if code == 200: citiesFound.append(city) lats.append(response["coord"]["lat"]) longs.append(response["coord"]["lon"]) temps.append(response["main"]["temp"]) humids.append(response["main"]["humidity"]) pressures.append(response["main"]["pressure"]) winds.append(response["wind"]["speed"]) clouds.append(response["clouds"]["all"]) if counter % 50 == 0: print(counter) except Exception as e: print(e) counter += 1 time.sleep(1) # In[27]: counter # ### Convert Raw Data to DataFrame # * Export the city data into a .csv. # * Display the DataFrame # ## Inspect the data and remove the cities where the humidity > 100%. # ---- # Skip this step if there are no cities that have humidity > 100%. # In[6]: # In[7]: # Get the indices of cities that have humidity over 100%. # In[8]: # Make a new DataFrame equal to the city data to drop all humidity outliers by index. # Passing "inplace=False" will make a copy of the city_data DataFrame, which we call "clean_city_data". # In[9]: # Extract relevant fields from the data frame # Export the City_Data into a csv # ## Plotting the Data # * Use proper labeling of the plots using plot titles (including date of analysis) and axes labels. # * Save the plotted figures as .pngs. # ## Latitude vs. Temperature Plot # In[10]: # ## Latitude vs. Humidity Plot # In[11]: # ## Latitude vs. Cloudiness Plot # In[12]: # ## Latitude vs. Wind Speed Plot # In[13]: # ## Linear Regression # In[14]: # OPTIONAL: Create a function to create Linear Regression plots # In[15]: # Create Northern and Southern Hemisphere DataFrames # #### Northern Hemisphere - Max Temp vs. Latitude Linear Regression # In[16]: # #### Southern Hemisphere - Max Temp vs. Latitude Linear Regression # In[17]: # #### Northern Hemisphere - Humidity (%) vs. Latitude Linear Regression # In[18]: # #### Southern Hemisphere - Humidity (%) vs. Latitude Linear Regression # In[19]: # #### Northern Hemisphere - Cloudiness (%) vs. Latitude Linear Regression # In[20]: # #### Southern Hemisphere - Cloudiness (%) vs. Latitude Linear Regression # In[21]: # #### Northern Hemisphere - Wind Speed (mph) vs. Latitude Linear Regression # In[22]: # #### Southern Hemisphere - Wind Speed (mph) vs. Latitude Linear Regression # In[23]: # In[ ]:
9bbc430428dbed0e737c0616f7edf3e939e088e6
denismoroz/ds-and-alg-p2
/problem_5.py
3,954
4.28125
4
#!/usr/bin/env python # coding: utf-8 # # Building a Trie in Python # # Before we start let us reiterate the key components of a Trie or Prefix Tree. A trie is a tree-like data structure that stores a dynamic set of strings. Tries are commonly used to facilitate operations like predictive text or autocomplete features on mobile phones or web search. # # Before we move into the autocomplete function we need to create a working trie for storing strings. We will create two classes: # * A `Trie` class that contains the root node (empty string) # * A `TrieNode` class that exposes the general functionality of the Trie, like inserting a word or finding the node which represents a prefix. # # Give it a try by implementing the `TrieNode` and `Trie` classes below! # In[1]: import collections # Represents a single node in the Trie class TrieNode: def __init__(self): self.children = collections.defaultdict(TrieNode) self.is_word = False def insert(self, char): return self.children[char] # The Trie itself containing the root node and insert/find functions class Trie: def __init__(self): self.root = TrieNode() def insert(self, word): current_node = self.root for char in word: current_node = current_node.insert(char) current_node.is_word = True def find(self, prefix): # Find the Trie node that represents this prefix if not isinstance(prefix, str): raise ValueError("Please, provide string as input parameter") current_node = self.root for char in prefix: if char not in current_node.children: return None current_node = current_node.children[char] return current_node # # Finding Suffixes # # Now that we have a functioning Trie, we need to add the ability to list suffixes to implement our autocomplete # feature. To do that, we need to implement a new function on the `TrieNode` object that will return all complete word # suffixes that exist below it in the trie. For example, if our Trie contains the words # `["fun", "function", "factory"]` and we ask for suffixes from the `f` node, we would expect to receive # `["un", "unction", "actory"]` back from `node.suffixes()`. # # Using the code you wrote for the `TrieNode` above, try to add the suffixes function below. # (Hint: recurse down the trie, collecting suffixes as you go.) # In[5]: class TrieNode: def __init__(self): self.children = collections.defaultdict(TrieNode) self.is_word = False def insert(self, char): return self.children[char] def suffixes(self, suffix=''): ## Recursive function that collects the suffix for ## all complete words below this point result = [] if self.is_word and suffix: result.append(suffix) for char, node in self.children.items(): result += node.suffixes(suffix+char) return result # # Testing it all out # # Run the following code to add some words to your trie and then use the interactive search box to see what your code returns. # In[6]: MyTrie = Trie() wordList = [ "ant", "anthology", "antagonist", "antonym", "fun", "function", "factory", "trie", "trigger", "trigonometry", "tripod" ] for word in wordList: MyTrie.insert(word) def testFunction(prefix, expectation): prefixNode = MyTrie.find(prefix) result = prefixNode.suffixes() if prefixNode else [] if expectation == result: print('Pass') else: print('Fail') testFunction('a', ['nt', "nthology", "ntagonist", "ntonym"]) # Pass testFunction('fun', ["ction"]) # Pass testFunction('trip', ["od"])# Pass #Edge cases testFunction('', wordList) # Pass testFunction('z', []) # Pass try: testFunction(None, []) except ValueError as e: print(e)
9f183efe234d243fcae07959919ff78dd70f653b
nikolaCh6/nikolaCh6
/kurs/python/trojkat.py
1,082
3.734375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # # trojkat.py import math def prostokatny(a, b, c): trojkat = False if a**2 + b**2 == c**2 or a**2 + c**2 == b**2 or c**2 + b**2 == a**2: trojkat = True if trojkat: print('Trójkąt będzie prostokątny :D') else: print('Trójkąt nie będzie prostokątny :/') def pole(a, b, c): l = (a + b + c)/2 p = math.sqrt(l * (l - a) * (l - b) * (l - c)) print('Pole wynosi: {:.4f}'.format(p)) def trojkat(a, b, c): trojkat = False if a + b > c and a + c > b and b + c > a: trojkat = True if trojkat: print('Gratuluję, zbudujesz trójkąt :)') prostokatny(a, b, c) pole(a, b, c) else: print('Idioto, spróbuj ponownie :P') def main(args): a, b, c = eval(input("Podaj dane oddzielone przecinkami: ")) print('Podano boki: {}, {}, {}'.format(a, b, c)) trojkat(a, b, c) return 0 if __name__ == '__main__': import sys sys.exit(main(sys.argv))
ccff04e26f54c2d02d1e79406183782ee2e736d6
kirtivr/leetcode
/281.py
1,053
3.765625
4
class ZigzagIterator(object): def __init__(self, v1, v2): """ Initialize your data structure here. :type v1: List[int] :type v2: List[int] """ self.totalSize = len(v1) + len(v2) self.index = 0 self.data = [] smaller = min(len(v1),len(v2)) for i in range(smaller): self.data.append(v1[i]) self.data.append(v2[i]) if len(v1) > len (v2): self.data.extend(v1[smaller:]) else: self.data.extend(v2[smaller:]) def next(self): """ :rtype: int """ val = self.data[self.index] self.index = self.index + 1 return val def hasNext(self): """ :rtype: bool """ if self.index < self.totalSize: return True else: return False # Your ZigzagIterator object will be instantiated and called as such: # i, v = ZigzagIterator(v1, v2), [] # while i.hasNext(): v.append(i.next())
9b66fdb9e5f811e837d88de60b2262d6c095aae1
jcschefer/sudoku
/sudoku.py
12,515
3.5625
4
# Jack Schefer, pd. 6 # import heapq from time import time from copy import deepcopy # def blankBoard(): board = {} for i in range(9): for j in range(9): board[ (i,j) ] = '.' return board # #print(board) # ALL_COORDINATES = [] for i in range(9): for j in range(9): ALL_COORDINATES.append( (i,j) ) # def makeBoard(string): b = blankBoard() for i in range(9): for k in range(9): sub = string[9*i+k] b[(i,k)] = sub return b # # # def printBoard(b): for r in range(9): s = '' for c in range(9): s += b[ (r,c) ] #s += str(r) + str(c) s += ' ' print(s) # #printBoard(board) # # def printBoard2(b): for r in range(9): s = '' for c in range(9): n,s,v = board[(r,c)] s += v #s += str(r) + str(c) s += ' ' print(s) # # # # def findNeighbors(board, row, col): #returns a list of tuples, the r,c of each neighbor nbrs = set() for i in range(9): if i != row: nbrs.add((i,col)) if i != col: nbrs.add((row, i)) # rowQuad = row // 3 colQuad = col // 3 for i in range(3): for j in range(3): nR = i+rowQuad*3 nC = j+colQuad*3 if nR != row and nC != col and (nR,nC) not in nbrs: nbrs.add( (nR,nC) ) # return nbrs # # # # # ''' --- CHECKS FOR CORRECT NEIGHBROS --- for r in range(9): for c in range(9): b = blankBoard() b[ (r,c) ] = '*' printBoard(b) nbrs = findNeighbors(b, r, c) for n in nbrs: ro,co = n b[(ro,co)] = 'X' printBoard(b) #print(nbrs) #print('\n') ''' # # # # # #''' --- CHECKS TO PRINT OUT PUZZLE CORRECTLY s = list(open('sudoku128.txt')) lines = [] for l in s: lines.append(l.rstrip()) # def isCorrect(board): rowsCorrect = True colsCorrect = True quadsCorrect = True # for i in range(9): rows = set() cols = set() for j in range(9): val = board[ (i, j) ] if val in rows or val == '.': return False rows.add(val) val = board[ (j,i) ] if val in cols: return False cols.add(val) # for i in range(3): for j in range(3): tQuad = set() for k in range(3): for m in range(3): val = board[ (3*i+k,3*j+m) ] if val in tQuad: return False tQuad.add(val) # # # # # return True # # # ''' --CHECKS IF THE isCorrect() is correct-- print(lines[0]) board = makeBoard(lines[0]) printBoard(board) print(isCorrect(board)) board[(0,0)] = '4' printBoard(board) print(isCorrect(board)) ''' # # # # # # def isWrong(board): rowsCorrect = True colsCorrect = True quadsCorrect = True # for i in range(9): rows = set() cols = set() for j in range(9): val = board[ (i, j) ] if val in rows and val != '.': return True rows.add(val) val = board[ (j,i) ] if val in cols and val != '.': return True cols.add(val) # for i in range(3): for j in range(3): tQuad = set() for k in range(3): for m in range(3): val = board[ (3*i+k,3*j+m) ] if val in tQuad and val != '.': return True tQuad.add(val) # # # # # return False # # # ''' --CHECKS IF THE isWrong() is correct-- print(lines[0]) board = makeBoard(lines[0]) printBoard(board) print(isWrong(board)) board[(0,0)] = '7' printBoard(board) print(isWrong(board)) ''' # # # # ~~EASY ONES~~ def recursiveSolve(b,p): #return a tuple of the form (boolean, board) if isCorrect(b): return (True,b) if isWrong(b): return (False,b) # #printBoard(b) #print() # pair = (8,8) for r in range(9): for c in range(9): if b[r,c] == '.': pair = (r,c) nB = b nB[pair]=n nP = makePossibilities(b) ans,bo = recursiveSolve(b,nP) if ans: return (True,bo) # print('returned by default') return (False,b) # # # # # # def pqHelper(b,pq): if isCorrect(b): return (True, b) if isWrong(b): return (False,b) # numPoss,coordinates,possibilities = heapq.heappop(pq) while b[coordinates] != '.': numPoss,coordinates,possibilities = heapq.heappop(pq) newBoard = {} #newPQ = [] #if numPoss ==0: #print(numPoss,'\t',coordinates,'\t',possibilities) cR,cC = coordinates nbrs = findNeighbors(b,cR,cC) for n in possibilities: newBoard = b newBoard[coordinates] = n newPQ = [] for i in pq: nPoss,tC,poss = i if tC in nbrs and n in poss: poss.remove(n) nPoss -= 1 heapq.heappush(newPQ, ( nPoss,tC,poss ) ) ans,bo = pqHelper(newBoard,newPQ) if ans: return (True,bo) return (False,b) # # def dictHelper(b,d): #THIS WORKS if isCorrect(b): return (True,b) if isWrong(b): return (False,b) # minC = (-1,-1) minNum = 10 minSet = set() for c in ALL_COORDINATES: if b[c] == '.': tNum,tSet = d[c] if tNum < minNum: minC = c minNum = tNum minSet = tSet # # # # if minNum == 10: print("minNum stil 10") # minCR,minCC = minC finalSet = minSet #print('begain: ',minSet,'\nCoordinates: ',minC) #if len(finalSet)>1: print('HAD TO GUESS') for eachPossibility in finalSet: newD = deepcopy(d) newB = deepcopy(b) #newD=d #newB=b #replace your dictionary with a one dimension list where the index is just 9*r+c... #newD = d[:] #newB =b[:] newB[minC] = eachPossibility for eachNeighbor in findNeighbors(newB,minCR,minCC): thNum,thSet = newD[eachNeighbor] if eachNeighbor != minC and eachPossibility in thSet: newSet = thSet newSet.remove(eachPossibility) thNum -= 1 newD[eachNeighbor] = (thNum,newSet) # # # ans,bo = dictHelper(newB,newD) if ans: #print('GUESSED RIGHT') return (True,bo) #print('GUESSED WRONG') #print('end: ',minSet) # # return (False,b) # # def dictHelper2(b,p,nums): #SUPAH FAST if isCorrect(b): return (True,b) if isWrong(b): return (False,b) # minC = (-1,-1) minNum = 10 minSet = set() for c in ALL_COORDINATES: #print(b[c]) #if p[c]: return(False,b) if b[c] == '.' and nums[c] < minNum: minC = c minNum = nums[c] minSet = p[c] # # # # if minNum == 10: print("minNum stil 10") # minCR,minCC = minC for eachPossibility in minSet.copy(): rmList=[] b[minC]=eachPossibility for eachNeighbor in findNeighbors(b,minCR,minCC): if eachNeighbor != minC and eachPossibility in p[eachNeighbor]: rmList.append(eachNeighbor) newSet = p[eachNeighbor] newSet.remove(eachPossibility) p[eachNeighbor]=newSet newN = nums[eachNeighbor] newN-= 1 nums[eachNeighbor]=newN # # # ans,bo = dictHelper2(b,p,nums) if ans:return (True,bo) # guess=b[minC] b[minC]='.' for changed in rmList: nSet=p[changed] nSet.add(guess) p[changed]=nSet nN=nums[changed] nN+=1 nums[changed]=nN # # return (False,b) # # # def dictHelper3(b,p,nums): #THIS DOESN'T WORK if isCorrect(b): return (True,b) if isWrong(b): return (False,b) # minC = (-1,-1) minNum = 10 minSet = set() for c in ALL_COORDINATES: #print(b[c]) #if p[c]: return(False,b) if b[c] == '.' and nums[c] < minNum: minC = c minNum = nums[c] minSet = p[c] # # # # if minNum == 10: print("minNum stil 10") # minCR,minCC = minC for eachPossibility in minSet.copy(): rmList=[] oldP=p b[minC]=eachPossibility for eachNeighbor in findNeighbors(b,minCR,minCC): if eachNeighbor != minC and eachPossibility in p[eachNeighbor]: rmList.append(eachNeighbor) newN = nums[eachNeighbor] newN-= 1 nums[eachNeighbor]=newN # # p=makePossibilities3(b) # ans,bo = dictHelper2(b,p,nums) if ans:return (True,bo) # guess=b[minC] b[minC]='.' for changed in rmList: nN=nums[changed] nN+=1 nums[changed]=nN p=oldP # # return (False,b) # # # # # # def priorityQueueAttempt(b,p): pq = [] # priority queue of tuples with following structure: ( number of possibilites, coordinates ,set of possibilities) for pCoord in b.keys(): pTuple = ( len(p[pCoord]),pCoord,p[pCoord]) heapq.heappush(pq,pTuple) return pqHelper(b,pq) # # def dictionaryAttempt(b,p): d = {} # dictionary with key of (r,c) and value of tuple (number of possiblities, set of possibilities) for c in b.keys(): d[c] = (len(p[c]), p[c]) return dictHelper(b,d) # # # def dictionaryAttempt2(b,p): newB=b # dict of value SUPAH FAST #nbrs={} nums={} for c in b.keys(): #nbrs[c]=p[c] nums[c]=len(p[c]) #print(nbrs) return dictHelper2(newB,p,nums) # # def dictionaryAttempt3(b,p): newB=b # dict of value SUPAH FAST #nbrs={} nums={} for c in b.keys(): #nbrs[c]=p[c] nums[c]=len(p[c]) #print(nbrs) return dictHelper2(newB,p,nums) # # # # # def makePossibilities(board): neighbors ={} for r in range(9): for c in range(9): toAdd = set() allTheNeighbors = findNeighbors(board,r,c) #set containing all tuple coordinates of nbrs neighborValues = set() for i in allTheNeighbors: #print('Value of ',i,': ',board[i]) if board[i] is not '.':neighborValues.add(board[i]) #print(neighborValues) for j in range(1,10): #print(j, '/t',neighborValues) if str(j) not in neighborValues: toAdd.add(str(j)) # #if 0 in toAdd: toAdd.remove(0) neighbors[ (r,c) ] = toAdd # # return neighbors # # def makePossibilities3(board): neighbors ={} for r in range(9): for c in range(9): toAdd = set() allTheNeighbors = findNeighbors(board,r,c) #set containing all tuple coordinates of nbrs neighborValues = set() for i in allTheNeighbors: if board[i] is not '.':neighborValues.add(board[i]) for j in range(1,10): if str(j) not in neighborValues: toAdd.add(str(j)) # neighbors[ (r,c) ] = toAdd # # #ADD STUFF/MAKE MORE EFFICIENT #for r in range(9): # # # return neighbors # # # # # # # # # # # # # # # # ''' i = 72 for i in range(10) print(lines[i]) b = makeBoard(lines[i]) printBoard(b) p = makePossibilities(b) #print(p[(8,3)]) ans,bo = dictionaryAttempt(b,p) print('\nResults: ',ans) printBoard(bo) ''' # # #''' out = open('sudokuOutput.txt','w') ls = [] #tuples of form ( time, number , originalboard, finished board ) ''' for i in range(18): print('---------- #',i+1,' ----------') b = makeBoard(lines[i]) print(lines[i]) printBoard(b) p = makePossibilities(b) #print(p[(0,0)]) s = time() ans,board = dictionaryAttempt2(b,p) e = time() #while not ans: ans,board = priorityQueueAttempt(b,p) print('\nResults: ',ans) printBoard(board) heapq.heappush(ls, ((e-s)**-1,i+1,b,board) ) print('Time: ',e-s) print() print() # print('\n\n\n~~~~~~~~~~ RESULTS ~~~~~~~~~~') for i in range(3): t,n,orig,fin = heapq.heappop(ls) s=str( n) + ': ' +str(t**-1) print(s) out.write(s+'\n') printBoard(orig) print() printBoard(fin) print() print() # ''' START = time() for i in range(128): b = makeBoard(lines[i]) p = makePossibilities(b) s = time() ans,bo= dictionaryAttempt2(b,p) e = time() heapq.heappush(ls,((e-s)**-1,i+1,b,bo )) print(str(i+1),': ',ans,'\t\t','Time: ',str(e-s),'\t\tTotal: ',e-START) print('\n\n\n~~~~~~~~~~ RESULTS ~~~~~~~~~~') for i in range(3): t,n,orig,fin = heapq.heappop(ls) s=str( n) + ': ' +str(t**-1) print(s) out.write(s+'\n') # out.close() #''' # # # # ~~NOTES~~ # > Base Case 1: found solution. (return stuff, something good) # > Base Case 2: determined that we guessed wrong (return false, etc) # - if the most constrained slot has zero options # > Recursive Case: pick an empty slot, loop over possibilites, try each one and recur down that side tree. # - return each recursive call using OR # > If none work, return false. # # # #I CAN COPY AND PASTE # # # End of File
3d09932eefc806c63a2d152c58f10945abbef70c
gracomot/Basic-Python-For-College-Students
/ProgrammingExercises/Lesson 4/question3.py
376
4.5
4
# Question 3 (Draw a Triangle) # Write a program that draws a triangle. Your program should ask for the height # of the triangle and it should display a triangle with the specified height. # Get the height of triangle as input height = int(input("Enter the height of the triangle: ")) for i in range(1, height+1): for j in range(i): print("*",end='') print()
4381abb8aac66cdf3760fc0ea0ccb73581222972
daviddwlee84/LeetCode
/Python3/Array/ReconstructItinerary/DFS332.py
963
3.65625
4
from typing import List from collections import defaultdict class Solution: def findItinerary(self, tickets: List[List[str]]) -> List[str]: """ https://leetcode.com/problems/reconstruct-itinerary/discuss/709877/Python3-DFS-Solution https://leetcode.com/problems/reconstruct-itinerary/discuss/710861/Python-Simple-Greedy-DFS-explained-(BEATS-97) """ tickets = sorted(tickets, key=lambda x: x[1], reverse=True) edges = defaultdict(list) for start, to in tickets: edges[start].append(to) route = [] def dfs(airport: str): while edges[airport]: dfs(edges[airport].pop()) route.append(airport) dfs("JFK") return route[::-1] # Runtime: 80 ms, faster than 81.65% of Python3 online submissions for Reconstruct Itinerary. # Memory Usage: 14.1 MB, less than 67.37% of Python3 online submissions for Reconstruct Itinerary.
c660d1b2086414a3afb54a563c487b9579e542e0
mingeun128/algorithm
/LeetCode/Valid Sudoku Solution.py
1,362
3.546875
4
class Solution: def isValidSudoku(self, board: List[List[str]]) -> bool: checkValid = [False] * 10 for i in range(9): for j in range(9): if board[i][j] != ".": if checkValid[int(board[i][j])] == True: return False else: checkValid[int(board[i][j])] = True for k in range(len(checkValid)): checkValid[k] = False for i in range(9): for j in range(9): if board[j][i] != ".": if checkValid[int(board[j][i])] == True: return False else: checkValid[int(board[j][i])] = True for k in range(len(checkValid)): checkValid[k] = False for n in [0,3,6]: for i in range(9): if i % 3 == 0: for k in range(len(checkValid)): checkValid[k] = False for j in range(n,n+3): if board[i][j] != ".": if checkValid[int(board[i][j])] == True: return False else: checkValid[int(board[i][j])] = True return True
870eb4065cdcc78427c434c86e3d137dbbb6755d
junekim00/ITP115
/Assignments/ITP115_A6_Kim_June/ITP115_A6_Kim_June.py
7,001
4.09375
4
# June Kim # ITP115, Fall 2019 # Assignment 6 # junek@usc.edu # This program allows for airplane seat reservation, displays seat arrangement, and prints boarding passes. def main(): # setting initial empty seats seating = ["", "", "", "", "", "", "", "", "", ""] totalSeats = 10 filled = 0 firstClassSeats = 4 filledFirstClass = 0 economySeats = 6 filledEconomy = 0 menuChoice = 0 keepGoing = True while keepGoing == True: # menu print("1: Assign Seat.\n2: Print Seat Map.\n3: Print Boarding pass.\n-1: Quit.") menuChoice = input(">") if menuChoice != "1" and menuChoice != "2" and menuChoice != "3" and menuChoice != "-1": print("Invalid choice.") menuChoice = input(">") # assign seat if menuChoice == "1": if filled != totalSeats: print("Input full name:") name = input(">").title() # extra credit economy vs first class print("Type 1 for First Class or Type 2 for Economy.") seatType = input(">") keepSeatGoing = True if seatType != "1" and seatType != "2": print("Invalid choice.") while keepSeatGoing == True: # first class if seatType == "1": if firstClassSeats == filledFirstClass: print("First class is full. Would you like to book economy? (Y/N)") bookOther = input(">").lower() if bookOther != "y" and bookOther != "n": "Invalid choice." keepSeatGoing = False if bookOther == "y": seatType = "2" if bookOther == "n": print("Next flight leaves in 3 hours.") keepSeatGoing = False if firstClassSeats != filledFirstClass: print("Please choose a seat (1-4):") seatChoice = int(input(">")) seatChoiceIndex = seatChoice - 1 if seating[seatChoiceIndex] != "": print("This seat is already taken. Please choose again.") keepSeatGoing = False else: del seating[seatChoiceIndex] seating.insert(seatChoiceIndex, name) filled = filled + 1 filledFirstClass = filledFirstClass + 1 keepSeatGoing = False # economy if seatType == "2": if economySeats == filledEconomy: print("Economy is full. Would you like to book first class? (Y/N)") bookOther = input(">").lower() if bookOther != "y" and bookOther != "n": "Invalid choice." keepSeatGoing = False if bookOther == "y": seatType = "1" if bookOther == "n": print("Next flight leaves in 3 hours.") keepSeatGoing = False if economySeats != filledEconomy: print("Please choose a seat (5-10):") seatChoice = int(input(">")) seatChoiceIndex = seatChoice - 1 if seating[seatChoiceIndex] != "": print("This seat is already taken. Please choose again.") keepSeatGoing = False else: del seating[seatChoiceIndex] seating.insert(seatChoiceIndex, name) filled = filled + 1 filledEconomy = filledEconomy + 1 keepSeatGoing = False if filled == totalSeats: print("Next flight leaves in 3 hours.") # print seat map if menuChoice == "2": for i in range(len(seating)): # first class if i < 4: if seating[i] != "": print("First Class Seat #" + str(i+1) + ": " + seating[i]) if seating[i] == "": print("First Class Seat #" + str(i+1) + ": Empty") # economy if i >= 4: if seating[i] != "": print("Economy Seat #" + str(i+1) + ": " + seating[i]) if seating[i] == "": print("Economy Seat #" + str(i+1) + ": Empty") # print boarding pass if menuChoice == "3": print("Type 1 to search boarding pass by seat number.\n" + "Type 2 to search boarding pass by name.") search = input(">") if search != "1" and search != "2": print("Invalid choice") # search by seat number if search == "1": print("What is your seat number?") numbSearch = input(">") if numbSearch.isdigit() == False or int(numbSearch) > 10: print("Invalid choice.") else: seatChoiceIndex = int(numbSearch) - 1 print("======= BOARDING PASS =======\n" + "Seat #: " + numbSearch + "\nPassenger Name: " + seating[seatChoiceIndex] + "\n=============================") # search by name if search == "2": print("What is your name?") searchName = input(">").title() fakeSeatNumb = 11 for j in range(len(seating)): if seating[j] == searchName: fakeSeatNumb = j + 1 if fakeSeatNumb > 10: print("Name not found.") else: print("======= BOARDING PASS =======\n" + "Seat #: " + str(fakeSeatNumb) + "\nPassenger Name: " + searchName + "\n=============================") # quit if menuChoice == "-1": keepGoing = False else: print("Have a nice day!") main()
96988cac8c8e2cf8dd2bb33c9ab0f251a4f92554
ahmadabudames/Train-data-structure
/data_structure/preorderTraversal.py
608
3.625
4
class TreeNode(object): def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def preorderTraversal( root): if root is None: return [] global ans ans = [] def preorder (root): global ans ans.append(root.val) if root.left : preorder(root.left) if root.right: preorder(root.right) preorder(root) return ans tree=TreeNode(1) tree.left=TreeNode(5) tree.right=TreeNode(2) print(preorderTraversal(tree))
2a0ce67ed6914dfa1c41ae7646bcdd8cb5ec0325
technicaltitch/pipelines
/functions/dataframe.py
1,670
4.125
4
import pandas as pd def merge_dataframes(df_merge_list, how='inner', on=None): """ Merge a list (or dict) of dataframes using a shared column or the index """ try: # df_merge_list is a dict df_merge_list = df_merge_list.values() except AttributeError: # df_merge_list is already a list pass result = list(df_merge_list).pop(0) for df in df_merge_list: if on: result = result.merge(df, how=how, on=on) else: result = result.merge(df, how=how, left_index=True, right_index=True) return result def pivot_dataframe(df, index_name, column_name): """ Pivots a dataframe such that you have a single row for each unique ID. index_name should correspond to the unique id column_name should correspond to the primary question which the subsequent questions/columns are based on. The new column names correspond to the primary question ID, the value of the primary question, and the subsequent question. Example: q103_2_q104 --- this corresponds to values for q104 when q103 has the value of 2 """ # Pivot dataframe result = df.pivot(index=index_name, columns=column_name) # Pivot moves index_name to an index... reset to a column result.reset_index(inplace=True) # Pivot creates multi-index columns if more than two columns (excluding # index) exist. Collapse multi-index column names c_names = result.columns.tolist() c_names = [c_names[0][0]] + [column_name + "_" + str(c[1]) + "_" + str(c[0]) for c in c_names[1:]] c_index = pd.Index(c_names) result.columns = c_index return result
deb094506bd1b121466383b03a85eca5f452aba9
BibiAyesha/Python
/UnHash.py
178
3.8125
4
def unHash(num): res="" letters= "acdegilmnoprstuw" num = int(num) while num >7: res = letters[int(num%37)] + res num = num/37 return res[1:]
11216033586c87d383e50492a27a71bf255d8fb6
ndminh4497/python
/Exercises 21.py
254
4.15625
4
def check_number(n): # n = int(input("Please enter an integer number:\n")) if (n % 2 == 0): return str(n) +" Is an even number" else: return str(n) +" Is an odd number" n = int(input("Please enter an integer number:\n")) print(check_number(n))
280194e23a3e3123254f558a5c663e78c21def17
mattkuo/gtfs-tools
/scripts/peuker.py
2,505
3.734375
4
import sys import math class Point(): """Represents a point on a map""" def __init__(self, shape_id, lat, long, point_num, traveled): self.lat = lat self.long = long self.shape_id = shape_id self.point_num = point_num self.traveled = traveled def __str__(self): return "shape_id: %s, Lat: %s, Long: %s, point_num: %s" % (self.shape_id,self.lat, self.long, self.point_num) def peuker(points, epsilon): first_point = points[0] last_point = points[-1] if len(points) <= 2: return points index = -1 distance = 0 for i, point in enumerate(points): current_dist = find_perp_dist(point, first_point, last_point); if current_dist > distance: distance = current_dist index = i if distance > epsilon: line1 = points[:index + 1] line2 = points[index:] call1 = peuker(line1, epsilon)[:-1] call2 = peuker(line2, epsilon) call1.extend(call2) return call1 else: return [first_point, last_point] def find_perp_dist(p, p1, p2): if p1.long == p2.long: result = abs(p.long - p1.long) else: slope = (p2.lat - p1.lat) / (p2.long - p1.long) intercept = p1.lat - (slope * p1.long) result = abs(slope * p.long - p.lat + intercept) / math.sqrt(abs(slope) ** 2 + 1) return result if __name__ == '__main__': if len(sys.argv) != 3: print "Usage: %s %s %s" % (sys.argv[0], "GTFS_TEXT", "NEW_TEXT") sys.exit(-1) file = open(sys.argv[1]) new_file = open(sys.argv[2], "w") points = [] current_shape_id = 0 header = file.readline() new_file.write(header) for i, line in enumerate(file): data = line.split(",") if i == 0: current_shape_id = data[0] if data[0] != current_shape_id: result = peuker(points, 0.00005) for point in result: new_file.write("%s, %s, %s, %s, %s\n" % (point.shape_id, point.lat, point.long, point.point_num, point.traveled)) current_shape_id = data[0] points = [] point = Point(data[0],float(data[1]), float(data[2]), data[3], float(data[4])) points.append(point) result = peuker(points, 0.00005) for point in result: new_file.write("%s, %s, %s, %s, %s\n" % (point.shape_id, point.lat, point.long, point.point_num, point.traveled)) file.close() new_file.close()
80f59bb4c4cb3f6956ea6986ecc710d4ff30987c
scyser/my_works
/Geodesy/pgz.py
577
3.9375
4
import math X1 = float(input("Введите X1: ")) Y1 = float(input("Введите Y1: ")) print("Введение дирекционного угла") grad = float(input("Введите градусы: ")) minut = float(input("Введите минуты: ")) sec = float(input("Введите секунды: ")) print(" ") d = float(input("Введите расстояние до точки 2: ")) alpha = math.radians(grad+minut/60+sec/3600) X2 = X1 + d*math.cos(alpha) Y2 = Y1 + d*math.sin(alpha) print(" ") print("X2 = : " + str(X2)) print("Y2 = : " + str(Y2))
908fd9e7fd4c6087092ccf1454c76fee351dd6c8
zasdaym/daily-coding-problem
/problem-062/solution.py
967
3.921875
4
from typing import List def count_ways(row: int, col: int) -> int: """ 1. Create 2d table to as "cache" table. table[i][j] contains number of ways to reach this coordinate from top-left. 2. All cells in first row and first column have only one way to reach them. 3. Any other columns possible ways is sum of ways to reach column on the left and ways to reach cell on the top of them. 4. Build this table in bottom up manner. """ if row == 1 or col == 1: return 1 ways_by_coordinate = [[0] * col] * row for i in range(row): ways_by_coordinate[i][0] = 1 for i in range(col): ways_by_coordinate[0][i] = 1 for i in range(1, row): for j in range(1, col): ways_by_coordinate[i][j] = ways_by_coordinate[i][j-1] + ways_by_coordinate[i-1][j] return ways_by_coordinate[row-1][col-1] assert count_ways(2, 2) == 2 assert count_ways(2, 3) == 3 assert count_ways(5, 5) == 70
78a6ac5c6ada68978155541f529d55032758961c
chris-mlvz/Python-for-Everybody
/12-Networked programs/using_urllib.py
750
3.625
4
# * Using a urllib in Python # import urllib.request # import urllib.parse # import urllib.error # fhand = urllib.request.urlopen('http://data.pr4e.org/romeo.txt') # for line in fhand: # print(line.decode().strip()) # * Like a file... # import urllib.request # import urllib.parse # import urllib.error # fhand = urllib.request.urlopen('http://data.pr4e.org/romeo.txt') # counts = dict() # for line in fhand: # words = line.decode().split() # for word in words: # counts[word] = counts.get(word, 0) + 1 # print(counts) # * Reading Web Pages import urllib.request import urllib.parse import urllib.error fhand = urllib.request.urlopen('http://www.dr-chuck.com/page1.htm') for line in fhand: print(line.decode().strip())
08e43464c83418749a11ce7c71ecd79af23f2c71
Archit9394/BOOTCAMP_Python_Functions
/task12.py
194
3.84375
4
# 12. Write a function to compute 5/0 and use try/except to catch the exceptions def divide(): return 5/0 try: divide() except ZeroDivisionError: print ("The denominator is zero")
f930e3eebd9d520fd8ffe9e1ce76b1458f8f0a2d
alizkzm/BioinformaticsPractice
/Bio4_2.py
4,042
3.5
4
import math class Tree(object): def __init__(self,N=-1,bidirectional = True): self.nodes = list(range(N)) # {node : age} self.edges = {} self.bidirectional = bidirectional self.N = N self.weight = {} def half_unlink(self, a, b): links = [(e, w) for (e, w) in self.edges[a] if e != b] if len(links) < len(self.edges[a]): self.edges[a] = links else: print('Could not unlink {0} from {1}'.format(a, b)) self.print() def get_nodes(self): for node in self.nodes: yield(node) def unlink(self, i, k): try: self.half_unlink(i, k) if self.bidirectional: self.half_unlink(k, i) except KeyError: print('Could not unlink {0} from {1}'.format(i, k)) self.print() def half_link(self,a,b,weight=1): if a not in self.nodes: self.nodes.append(a) if a in self.edges: self.edges[a] = [(b0,w0) for (b0,w0) in self.edges[a] if b0!=b] + [(b,weight)] else: self.edges[a] = [(b,weight)] def link(self,StartNode,StopNode,weight=1): self.half_link(StartNode,StopNode,weight) if self.bidirectional: self.half_link(StopNode,StartNode,weight) def next_node(self): return len(self.nodes) def traverse(self, i, k, path=[], weights=[]): if not i in self.edges: return (False, []) if len(path) == 0: path = [i] weights = [0] for j, w in self.edges[i]: if j in path: continue path1 = path + [j] weights1 = weights + [w] if j == k: return (True, list(zip(path1, weights1))) else: found_k, test = self.traverse(j, k, path1, weights1) if found_k: return (found_k, test) return (False, []) def UPGMA(D,n): def closest_clusters(): ii = -1 jj = -1 best_distance = float('inf') for i in range(len(D)): for j in range(i): if i in Clusters and j in Clusters and D[i][j] < best_distance: ii = i jj = j best_distance = D[i][j] return (ii, jj, best_distance) T = Tree(n) Clusters = {} Age = {} for i in range(n): Clusters[i] =[i] for node in T.get_nodes(): Age[node] = 0 while len(Clusters) > 1 : def d(i, j): return sum([D[cl_i][cl_j] for cl_i in Clusters[i] for cl_j in Clusters[j]]) / ( len(Clusters[i]) * len(Clusters[j])) \ if i in Clusters and j in Clusters \ else float('nan') finded_i,finded_j,dist_ij = closest_clusters() node=T.next_node() T.link(node,finded_i) T.link(node,finded_j) Clusters[node] = Clusters[finded_j]+Clusters[finded_i] Age[node] = D[finded_i][finded_j]/2 del Clusters[finded_i] del Clusters[finded_j] row = [d(i,node) for i in range(len(D))] + [0.0] for k in range(len(D)): D[k].append(row[k]) D.append(row) for node in T.nodes: T.edges[node] = [(e, abs(Age[node] - Age[e])) for e, W in T.edges[node]] return T def main(): n = 4 D = """0 20 17 11 20 0 20 13 17 20 0 10 11 13 10 0 """ SplitedD = D.split("\n") NumericalD = [[0]*n for i in range(n)] for i in range(n): NumericalD[i] = list(map(int,SplitedD[i].split())) myTree = UPGMA(NumericalD,n) for node in myTree.nodes: if node in myTree.edges: for edge in myTree.edges[node]: end,weight=edge print ('{0}->{1}:{2:{prec}f}'.format(node,end,weight,prec='.3')) main()
f5774ea2fdc3048eea43e9822b4169290c28640f
lcnodc/codes
/09-revisao/practice_python/hangman.py
2,935
4.46875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Exercise 32: Hangman This exercise is Part 3 of 3 of the Hangman exercise series. The other exercises are: Part 1 and Part 2. You can start your Python journey anywhere, but to finish this exercise you will have to have finished Parts 1 and 2 or use the solutions (Part 1 and Part 2). In this exercise, we will finish building Hangman. In the game of Hangman, the player only has 6 incorrect guesses (head, body, 2 legs, and 2 arms) before they lose the game. In Part 1, we loaded a random word list and picked a word from it. In Part 2, we wrote the logic for guessing the letter and displaying that information to the user. In this exercise, we have to put it all together and add logic for handling guesses. Copy your code from Parts 1 and 2 into a new file as a starting point. Now add the following features: Only let the user guess 6 times, and tell the user how many guesses they have left. Keep track of the letters the user guessed. If the user guesses a letter they already guessed, don’t penalize them - let them guess again. Optional additions: When the player wins or loses, let them start a new game. Rather than telling the user "You have 4 incorrect guesses left", display some picture art for the Hangman. This is challenging - do the other parts of the exercise first! Your solution will be a lot cleaner if you make use of functions to help you! """ import random def read_from_file(filename): with open(filename, "r") as a_file: text = a_file.readlines() return text def choose_a_word(a_list): return random.choice(a_list).strip() def get_hint(secret_word, letters): hint = [] for letter_secret in secret_word: if letter_secret in letters: hint.append(letter_secret) else: hint.append("_") return " ".join(hint) def check_game(secret_word, letters): fail = 0 for index, letter in enumerate(letters): if letter in secret_word: secret_word = secret_word.replace(letter, "") elif letter in letters[:index]: letters.remove(letter) print("Letter already informed, please again...") else: fail += 1 if not secret_word: return False, True elif fail == 6: return True, False else: print( "You have %i incorrect guesses left" % (6 - fail)) return False, False if __name__ == "__main__": letters = [] loose = False secret_word = choose_a_word(read_from_file("sowpods.txt")) win = False print("Welcome to Hangman!") while not loose and not win: print("\n" + get_hint(secret_word, letters)) letters.append(input("\nType a letter: ")) print(get_hint(secret_word, letters)) loose, win = check_game(secret_word[:], letters) print("%s" % "You win!" if win else "You loose")
0a1c886ea2e08e76800a990a6834761f2bfc3e0b
18sby/python-study
/vippypython/chap8/demo8.py
519
3.875
4
# 集合的数学操作 s1 = { 10, 20, 30, 40 } s2 = { 20, 30, 40, 50, 60 } # 交集操作 intersection = &,不更改原集合 print(s1.intersection(s2)) print(s1 & s2) # 并集操作 union = | ,不更改原集合 print(s1.union(s2)) print(s1 | s2) # 差集操作 s1.difference(s2) 在 s1 中除去 s1 和 s2 的并集 print(s1.difference(s2)) print(s1 - s2) print(s2.difference(s1)) print(s2 - s1) # 对称差集 两个集合的并集 - 两个集合的交集 print(s1.symmetric_difference(s2)) print(s1 ^ s2)
970146e52061c35f09465a60c060f156c9417d71
laukikpanse/Python-Practice-Examples
/Practice3.py
234
4.3125
4
'''Write a Python program which accepts the radius of a circle from the user and compute the area''' radius = int(input("Please enter the radius of the Circle: ")) print("The area of this circle is: {0}".format(3.14 * (radius**2)))
34ed72c6902bd461f26f20ea10aac276bec3a750
fsym-fs/Python_AID
/month01/simple_mall/my_shopping.py
5,237
3.734375
4
# 简单商城 class Merchants_Views: pass class Merchants_Controllers: pass class Shopping_Models: def __init__(self, name, price, number, id): self.name = name self.price = price self.number = number self.id = id class Shopping_cart_Models: def __init__(self, id, number): self.number = number self.id = id class User_Shopping_Views: def __init__(self): self.__controls = User_Shopping_Controllers() def main(self): while True: self.__show_home_page() if self.__user_input() == 0: break def __show_home_page(self): print(""" 欢迎光临-浮生@商城 ************************* * 1 键 展示所有商品 * * 2 键 进入购物车 * * 3 键 退出程序 * ************************* """) def __user_input(self): item = input("请输入您向进入的功能:") if item == "1": self.__show_all() self.__show_buy() self.__input_buy() elif item == "2": self.__show_cart() if self.__controls.total_price == 0: pass else: self.__controls.paying() elif item == "3": print("欢迎下次光临,浮生@商城随时为您服务! ^_^") return 0 else: print("很抱歉,您的输入错误,请重新输入!") def __show_all(self): self.__controls.show_all_goods() def __show_buy(self): print(""" 欢迎光临-浮生@商城 ************************* * 1 键 购买商品 * * 2 键 进入购物车 * * 3 键 返回上一层 * ************************* """) def __input_buy(self): item = input("请输入您向进入的功能:") if item == "1": self.__add_shoppings() elif item == "2": self.__show_cart() if self.__controls.total_price == 0: pass else: self.__controls.paying() elif item == "3": print("正在返回上一层,请您稍等片刻.... ^_^") return 0 else: print("很抱歉,您的输入错误,请重新输入!") def __add_shoppings(self): while True: cid = int(input("请输入商品编号:")) if self.__controls.find_goods(cid) == 1: break else: print("该商品不存在") count = int(input("请输入购买数量:")) if self.__controls.merge_goods(cid, count) == 1: print("添加到购物车.") else: print("库存不足,很抱歉!") def __show_cart(self): self.__controls.show_shopping_cart() class User_Shopping_Controllers: shopping_mall = [ Shopping_Models("屠龙刀", 10000, 55, 101), Shopping_Models("倚天剑", 10000, 45, 102), Shopping_Models("九阴白骨爪", 8000, 65, 103), Shopping_Models("九阳神功", 9000, 95, 104), Shopping_Models("降龙十八掌", 8000, 35, 105), Shopping_Models("乾坤大挪移", 10000, 25, 106), ] def __init__(self): self.cart = [] self.total_price = 0 def show_all_goods(self): for good in User_Shopping_Controllers.shopping_mall: print("编号:%d,名称:%s,单价:%d,库存:%d." % (good.id, good.name, good.price, good.number)) def find_goods(self, cid): for good in User_Shopping_Controllers.shopping_mall: if good.id == cid: return 1 return 0 def merge_goods(self, cid, count): for good in User_Shopping_Controllers.shopping_mall: if good.id == cid and good.number >= count: for shop in self.cart: if cid == shop.id: shop.number += count good.number -= count return 1 good.number -= count self.cart.append(Shopping_cart_Models(cid, count)) return 1 else: return 0 def show_shopping_cart(self): for item in self.cart: for good in User_Shopping_Controllers.shopping_mall: if good.id == item.id: print("商品编号:%d,商品:%s,单价:%d,数量:%d." % (good.id, good.name, good.price, item.number)) self.total_price += good.price * item.number # 结算购物车 def paying(self): while True: qian = float(input("总价%d元,请输入金额:" % self.total_price)) if qian >= self.total_price: print("购买成功,找回:%d元." % (qian - self.total_price)) self.cart.clear() self.total_price = 0 break else: print("金额不足.") shopping = User_Shopping_Views() shopping.main()
bc8a0652480153aba374378e646fe4bf9aa56885
EdikCarlos/Exercicios_Python_intermediario
/ex_Matriz2.0.py
701
3.6875
4
matriz = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] par = 0 soma = 0 maior = 0 for l in range(0,3): for c in range(0,3): matriz[l][c] = int(input(f'Digite o valor na posição [{l}, {c}]: ')) if matriz[l][c] % 2 == 0: par += matriz[l][c] if c == 2: soma += matriz[l][c] if l == 1: if matriz[l][c] > maior: maior = matriz[l][c] print('-='*35) for l in range(0,3): for c in range(0,3): print(f'[{matriz[l][c]:^5}]', end='') print() print('-='*35) print(f'A soma de todos os números pares é {par}.') print(f'A soma dos elementos da 3ª coluna é {soma}.') print(f'O maior número da 2ª linha é {maior}.')
5fbf448dda046aaba7d3a52b1b011e96604b3bf1
forest-float/python
/03/线程.py
2,577
3.75
4
# -*- coding: utf-8 -*- # @Author: wlp # @Date: 2020-04-08 14:12:15 # @Last Modified by: forest-float # @Last Modified time: 2020-04-08 15:01:04 import _thread import time def thread_function(threadName, delay): n = 5 while n > 0: time.sleep(delay) n -= 1 print(time.ctime(time.time()), threadName) try: _thread.start_new_thread(thread_function, ('thread1', 2)) _thread.start_new_thread(thread_function, ('thread2', 4)) except: print("error ,can't create thread") import threading exitFlag = 0 class myThread(threading.Thread): def __init__(self, threadID, name, counter): threading.Thread.__init__(self) self.threadID = threadID self.name = name self.counter = counter def run(self): print("开始线程:" + self.name) print(self.name, self.counter) time.sleep(5) print("退出线程:" + self.name) def print_time(threadName, delay, counter): while counter: if exitFlag: threadName.exit() time.sleep(delay) print ("%s: %s" % (threadName, time.ctime(time.time()))) counter -= 1 #创建新线程 thread1 = myThread(1, "thread-1", 1) thread2 = myThread(2, "thread-2", 2) #开启进程 thread1.start() thread2.start() thread1.join() thread2.join() from time import sleep from threading import Thread, Lock #用于线程间的同步,相当于互斥锁,防止多个线程同时访问一块地址,造成数据错误 class Account(object): def __init__(self): self._balance = 0 self._lock = Lock()#将这个变量设置为锁属性,等待获取锁acquire()和release()函数去加锁和解锁 def deposit(self, money): # 先获取锁才能执行后续的代码 self._lock.acquire() try: new_balance = self._balance + money sleep(0.01) self._balance = new_balance finally: # 在finally中执行释放锁的操作保证正常异常锁都能释放 self._lock.release() @property def balance(self): return self._balance class AddMoneyThread(Thread): def __init__(self, account, money): super().__init__() self._account = account self._money = money def run(self): self._account.deposit(self._money) def main(): account = Account() threads = [] for _ in range(100): t = AddMoneyThread(account, 1) threads.append(t) t.start() for t in threads: t.join() print('账户余额为: ¥%d元' % account.balance) if __name__ == '__main__': main()
ea48bc97395027293178fe58071b453441240bd1
NiltonGMJunior/hackerrank-python
/text_wrap.py
626
3.859375
4
import textwrap # My solution without textwrap (works fine) # def wrap(string, max_width): # lines = [] # total_length = 0 # for i in range(len(string) // max_width): # lines.append(string[i * max_width : (i + 1) * max_width]) # total_length += max_width # if total_length != max_width: # lines.append(string[max_width * (len(string) // max_width) : ]) # return "\n".join(lines) def wrap(string, max_width): return textwrap.fill(string, max_width) if __name__ == '__main__': string, max_width = input(), int(input()) result = wrap(string, max_width) print(result)
4c7626742b0773a9f838d90a6cd3a6cc3eb3f8a5
nirupamaBenis/FAIRnessOmicsRepositories
/apiSearch.py
15,937
3.609375
4
## Import packages required for the search import dill import math import numpy import re import pandas ## Function to parse json or xml files from the API responses def getParsedOutput(apiLink, respType): import requests import json resp = requests.get(apiLink) searchResult = resp.text if respType == 'json': # Parse the json text to a dictionary object parsedJson = json.loads(searchResult) return(parsedJson) if respType == 'xml': import xmltodict parsedXml = xmltodict.parse(searchResult) return(parsedXml) else: print("Only works with JSON and XML formats for now") ######################## Get API results ######################## # In this section we # - search the APIs of the chosen repositories with particular search terms, with or without filters, # - count the number of results and # - save the information to be reviewed for relevance to the initial search ###### Array express ###### # Free text search arrayexpressLinkAll = 'https://www.ebi.ac.uk/arrayexpress/json/v3/experiments?keywords=huntington+blood+human' arrayexpressJsonAll = getParsedOutput(apiLink=arrayexpressLinkAll, respType='json') arrayexpressCountAll = arrayexpressJsonAll['experiments']['total'] # 8 results # Search with filters, free text for terms without filters arrayexpressLinkFilt = 'https://www.ebi.ac.uk/arrayexpress/json/v3/experiments?keywords=huntington+blood&species=%22homo%20sapiens%22' arrayexpressJsonFilt = getParsedOutput(apiLink=arrayexpressLinkFilt, respType='json') arrayexpressCountFilt = arrayexpressJsonFilt['experiments']['total'] # 8 results # Experiment details to review # Relevant details are in 'accession', 'name', 'organism', 'description' and 'samplecharacteristic' for i in range(arrayexpressCountAll): aeExptId = arrayexpressJsonAll['experiments']['experiment'][i]['accession'] aeExptName = arrayexpressJsonAll['experiments']['experiment'][i]['name'] aeExptOrganism = arrayexpressJsonAll['experiments']['experiment'][i]['organism'][0] aeExptDescription = arrayexpressJsonAll['experiments']['experiment'][i]['description'][0]['text'] if i == 0: aeDF = pandas.DataFrame({'Repo':'ArrayExpress','Id':aeExptId, 'Name':aeExptName, 'Organism':aeExptOrganism, 'Description':aeExptDescription}, index=[0]) else: aeDF = aeDF.append({'Repo':'ArrayExpress','Id':aeExptId, 'Name':aeExptName, 'Organism':aeExptOrganism, 'Description':aeExptDescription}, ignore_index=True) aeDF.to_csv('arrayExpressAllTerms.csv', index=False) # Take in information from 'samplecharacteristic' manually because each experiment has different values in this location categoryValuesDisease = arrayexpressJsonAll['experiments']['experiment'][1]['samplecharacteristic'][4]['value'] # 4 disease, 9 organism part ###### DbGaP ###### # Uses the Entrez API to serve information like most NCBI resources # Free text search gapSearchLinkAll = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=gap&term=Huntington+blood+human' gapSearchResultAll = getParsedOutput(gapSearchLinkAll, 'xml') gapSearchCountAll = gapSearchResultAll['eSearchResult']['Count'] # 21 results # Search with filters, free text for terms without filters gapSearchLinkFilt = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=gap&term=Huntington[disease]+blood+human' gapSearchResultFilt = getParsedOutput(gapSearchLinkFilt, 'xml') gapSearchCountFilt = gapSearchResultFilt['eSearchResult']['Count'] # 1 results # The Entrez API retrieves the ids of datasets that match the search and a separate query must be made to get # experimental details of those ids # Get all ids that matched the search gapSearchAllIdsLink = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=gap&retmax=' + gapSearchCountAll + '&term=Huntington+blood+human' gapSearchAllIdsResult = getParsedOutput(gapSearchAllIdsLink, 'xml') # Make a loop here with a retmax of 50 ids per query gapSraIds = gapSearchAllIdsResult['eSearchResult']['IdList']['Id'] gapNumSplits = math.ceil(len(gapSraIds) / 50) gapSraSplitIds = numpy.array_split(gapSraIds, gapNumSplits) gapSraSummary = [] for i in range(gapNumSplits): tmpIds = gapSraSplitIds[i] tmpGapSummaryLink = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?db=sra&id=' + ','.join(tmpIds) tmpGapSummaryResult = getParsedOutput(tmpGapSummaryLink, 'xml') for j in range(len(gapSraSplitIds[i])): gapSraSummary.append(tmpGapSummaryResult['eSummaryResult']['DocSum'][j]['Item'][0]['#text']) # Experiment details to review # The XML output from the Entrez API is not parsable so here we use regex to retrieve the relevant details for review for i in range(len(gapSraSummary)): status = re.sub('^.* status="(.*)".*$', '\\1', gapSraSummary[i]) if status != 'withdrawn': gapExptId = re.sub('^.*\\<Study acc="(.*)" name="[A-Z][a-z].*$', '\\1', gapSraSummary[i]) gapExptName = re.sub('^.*\\<Study acc="(.*)" name="(.*)"\\/\\>\\<Organism taxid.*$', '\\2', gapSraSummary[i]) gapExptOrganism = re.sub('^.*ScientificName="(.*)"\\/\\>\\<Sample.*$', '\\1', gapSraSummary[i]) gapExptDescription = "NA" else: gapExptId = gapExptName = gapExptOrganism = gapExptDescription = "NA" if i == 0: gapDF = pandas.DataFrame({'Repo':'DbGaP-SRA','Id':gapExptId, 'Name':gapExptName, 'Organism':gapExptOrganism, 'Description':gapExptDescription}, index=[0]) else: gapDF = gapDF.append({'Repo': 'DbGaP-SRA', 'Id': gapExptId, 'Name': gapExptName, 'Organism': gapExptOrganism, 'Description': gapExptDescription}, ignore_index=True) gapDF.to_csv('dbGaPSRAAllTerms.csv', index=False) ###### ENA ###### # Free text search enaLinkAll = 'https://www.ebi.ac.uk/ena/browser/api/xml/textsearch?domain=sra-study&query=huntington+blood+human' enaSearchResultAll = getParsedOutput(enaLinkAll, 'xml') enaSearchCountAll = len(enaSearchResultAll['STUDY_SET']['STUDY']) # 0 results # No filters available ###### GEO ###### # Uses the Entrez API to serve information like most NCBI resources # Free text search geoSearchLinkAll = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=gds&term=huntington+blood+human' geoSearchResultAll = getParsedOutput(apiLink=geoSearchLinkAll, respType='xml') geoSearchCountAll = geoSearchResultAll['eSearchResult']['Count'] # 31 results # Search with filters, free text for terms without filters geoSearchLinkFilt = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=gds&term=huntington+blood+AND+human[orgn]' geoSearchResultFilt = getParsedOutput(apiLink=geoSearchLinkFilt, respType='xml') geoSearchCountFilt = geoSearchResultFilt['eSearchResult']['Count'] # 29 results # The Entrez API retrieves the ids of datasets that match the search and a separate query must be made to get experimental details of those ids # Get all ids that matched the search geoSearchAllIdsLink = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=gds&retmax=' + geoSearchCountAll + '&term=huntington+blood+human' geoSearchAllIdsResult = getParsedOutput(geoSearchAllIdsLink, 'xml') # Make a loop here with say 50 ids per query geoIds = geoSearchAllIdsResult['eSearchResult']['IdList']['Id'] geoNumSplits = math.ceil(len(geoIds) / 50) geoSplitIds = numpy.array_split(geoIds, geoNumSplits) geoSummaryList = [] for i in range(geoNumSplits): tmpIds = geoSplitIds[i] tmpGeoSummaryLink = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?db=gds&id=' + ','.join(tmpIds) tmpGeoSummaryResult = getParsedOutput(tmpGeoSummaryLink, 'xml') geoSummaryList.append(tmpGeoSummaryResult['eSummaryResult']['DocSum']) geoSummary = [y for x in geoSummaryList for y in x] # Experiment details to review # The XML output from the Entrez API is not parsable so here we use regex to retrieve the relevant details for review for i in range(len(geoSummary)): geoExptId = geoSummary[i]['Id'] geoExptName = geoSummary[i]['Item'][2]['#text'] geoExptOrganism = geoSummary[i]['Item'][6]['#text'] geoExptDescription = geoSummary[i]['Item'][3]['#text'] if i == 0: geoDF = pandas.DataFrame({'Repo':'GEO','Id':geoExptId, 'Name':geoExptName, 'Organism':geoExptOrganism, 'Description':geoExptDescription}, index=[0]) else: geoDF = geoDF.append({'Repo':'GEO', 'Id':geoExptId, 'Name':geoExptName, 'Organism':geoExptOrganism, 'Description':geoExptDescription}, ignore_index=True) geoDF.to_csv('geoAllTerms.csv', index=False) ###### Metabolomics Workbench ###### # Free text search in title metabWBSearchTitleLink = 'https://www.metabolomicsworkbench.org/rest/study/study_title/huntington/summary' metabWBSearchTitleResult = getParsedOutput(metabWBSearchTitleLink, 'json') # 1 result ###### OmicsDI ###### # Free text search omicsdiLinkAll = 'https://www.omicsdi.org:443/ws/dataset/search?query=huntington+blood+human&start=0&size=10&faceCount=0' omicsdiSearchResultAll = getParsedOutput(apiLink=omicsdiLinkAll, respType='json') omicsdiCountAll = omicsdiSearchResultAll["count"] # 146 results # Search with filters, free text for terms without filters omicsdiLinkAllProper = "https://www.omicsdi.org/ws/dataset/search?query=disease:%22huntington%22%20AND%20TAXONOMY:%229606%22%20AND%20tissue:%22Blood%22" omicsdiSearchResultAllProper = getParsedOutput(apiLink=omicsdiLinkAllProper, respType='json') omicsdiCountAllProper = omicsdiSearchResultAllProper["count"] # 0 results # The API limits the number of search results that can be retrieved but gives an indication of the total number of results # Here we take the total number of results and split the list into about 100 ids and get information on them iteratively searchNum = omicsdiCountAll searchStart = 0 searchSize = 100 searchDone = True omicsdiAllDatasetsAll = [] while searchDone: tmpOmicsdiLink = 'https://www.omicsdi.org:443/ws/dataset/search?query=huntington+blood+human&start=' + str(searchStart) + '&size=' + str(searchSize) +'&faceCount=0' tmpOmicsdiSearchResult = getParsedOutput(apiLink=tmpOmicsdiLink, respType='json') for i in range(len(tmpOmicsdiSearchResult['datasets'])): omicsdiAllDatasetsAll.append(tmpOmicsdiSearchResult['datasets'][i]) if searchStart + searchSize > searchNum: searchDone = False else: searchStart = searchStart + searchSize # Experiment details to review for i in range(len(omicsdiAllDatasetsAll)): omicsdiExptId = omicsdiAllDatasetsAll[i]['id'] omicsdiExptName = omicsdiAllDatasetsAll[i]['title'] if len(omicsdiAllDatasetsAll[i]['organisms']) != 0: omicsdiExptOrganism = omicsdiAllDatasetsAll[i]['organisms'][0]['name'] omicsdiExptDescription = omicsdiAllDatasetsAll[i]['description'] if i == 0: omicsdiDF = pandas.DataFrame({'Repo':'OmicsDI','Id':omicsdiExptId, 'Name':omicsdiExptName, 'Organism':omicsdiExptOrganism, 'Description':omicsdiExptDescription}, index=[0]) else: omicsdiDF = omicsdiDF.append({'Repo':'OmicsDI', 'Id':omicsdiExptId, 'Name':omicsdiExptName, 'Organism':omicsdiExptOrganism, 'Description':omicsdiExptDescription}, ignore_index=True) omicsdiDF.to_csv('omicsdiAllTerms.csv', index=False) ## PRIDE # Free text search # The PRIDE API shows 1000 results per page and the number of results exceeded 1000 so to find out how many results # there were we query the system interatively until the number of results is less than 1000 which we presume is # the end of the list # Final number 5246 prideSearchResultAll = [] for i in range(100): prideLinkAll = 'https://www.ebi.ac.uk:443/pride/ws/archive/project/list?query=huntington+blood+human&show=1000&page=' + str(i) + '&order=desc' tmpPrideSearchResultAll = getParsedOutput(apiLink=prideLinkAll, respType='json') prideSearchCountAll = len(tmpPrideSearchResultAll['list']) prideSearchResultAll.append(tmpPrideSearchResultAll['list']) print(prideSearchCountAll) if prideSearchCountAll == 1000: continue else: break prideSearchResultAll = [y for x in prideSearchResultAll for y in x] # Since the number of results is not expected to be over 5k for a rare disease we suspect that the search engine is # performing an 'OR' search instead of 'AND" with the search terms # Separate the three queries and do an AND operation # Disease prideLinkDisease = 'https://www.ebi.ac.uk:443/pride/ws/archive/project/list?query=huntington&show=100&page=0&order=desc' prideSearchResultDisease = getParsedOutput(apiLink=prideLinkDisease, respType='json') # 19 results # only 19 so no need for loop # Tissue prideLinkTissue = 'https://www.ebi.ac.uk:443/pride/ws/archive/project/list?query=blood&show=1000&page=0&order=desc' prideSearchResultTissue = getParsedOutput(apiLink=prideLinkTissue, respType='json') # exactly 1000 so expanding the query with a for loop prideSearchResultAllTissue = [] for i in range(100): prideLinkAllTissue = 'https://www.ebi.ac.uk:443/pride/ws/archive/project/list?query=blood&show=1000&page=' + str(i) + '&order=desc' tmpPrideSearchResultAllTissue = getParsedOutput(apiLink=prideLinkAllTissue, respType='json') prideSearchCountAllTissue = len(tmpPrideSearchResultAllTissue['list']) prideSearchResultAllTissue.append(tmpPrideSearchResultAllTissue['list']) print(prideSearchCountAllTissue) if prideSearchCountAllTissue == 1000: continue else: break prideSearchResultAllTissue = [y for x in prideSearchResultAllTissue for y in x] # 1001 results # Species prideLinkSpecies = 'https://www.ebi.ac.uk:443/pride/ws/archive/project/list?query=human&show=100&page=0&order=desc' # We assume that it is going to be a lot of results because we are searching for human data prideSearchResultAllSpecies = [] for i in range(100): prideLinkAllSpecies = 'https://www.ebi.ac.uk:443/pride/ws/archive/project/list?query=human&show=1000&page=' + str(i) + '&order=desc' tmpPrideSearchResultAllSpecies = getParsedOutput(apiLink=prideLinkAllSpecies, respType='json') prideSearchCountAllSpecies = len(tmpPrideSearchResultAllSpecies['list']) prideSearchResultAllSpecies.append(tmpPrideSearchResultAllSpecies['list']) print(prideSearchCountAllSpecies) if prideSearchCountAllSpecies == 1000: continue else: break prideSearchResultAllSpecies = [y for x in prideSearchResultAllSpecies for y in x] # 5019 results # Do an intersection of all the ids separateSearchDiseaseIds = [] separateSearchTissueIds = [] separateSearchSpeciesIds = [] for i in range(len(prideSearchResultDisease['list'])): separateSearchDiseaseIds.append(prideSearchResultDisease['list'][i]['accession']) for i in range(len(prideSearchResultAllTissue)): separateSearchTissueIds.append(prideSearchResultAllTissue[i]['accession']) for i in range(len(prideSearchResultAllSpecies)): separateSearchSpeciesIds.append(prideSearchResultAllSpecies[i]['accession']) unqSeparateSearchAllIds = list(set(separateSearchDiseaseIds) & set(separateSearchSpeciesIds)) # 0 results in intersection # Search with filters prideLinkAllProper = 'https://www.ebi.ac.uk:443/pride/ws/archive/project/list?show=10&page=0&order=desc&speciesFilter=9606%20&tissueFilter=blood&diseaseFilter=huntington' prideSearchResultAllProper = getParsedOutput(apiLink=prideLinkAllProper, respType='json') prideSearchCountAllProper = len(prideSearchResultAllProper['list']) # 0 results # Save all the API results sessionDumpFilename = 'globalsaveAllAPIsAllTerms.pkl' dill.dump_session(sessionDumpFilename) ###### LOAD THE PREVIOUSLY SAVED VARIABLES ###### import dill dill.load_session('globalsaveAllAPIsAllTerms.pkl')
62c0978cec5f9d589fe7ce3c9378824e98ada987
rueuntal/AdventofCode2020
/scripts/day3.py
1,274
4.1875
4
def data_parser(): """ Parse out data in ../data/day3.txt Returns: list: list of str where each string shows open space and trees in one row. """ file_path = '../data/day3.txt' with open(file_path, 'r') as stream: raw = stream.readlines() out = [x.strip() for x in raw] return out def count_trees(right, down): """ Count the number of trees that will be bumped into by right and down. Args: right (int): position to move to the right in each round down (int): position to move to the bottom in each round Returns: int: number of trees encountered """ dat = data_parser() row, pos = 0, 0 row_len = len(dat[0]) tree_count = 0 while row < len(dat) - down: row += down pos = (pos + right) % row_len if dat[row][pos] == '#': tree_count += 1 return tree_count def count_trees_multiple(): """ Apply the previous function with different options and obtain the product of the counts. """ ans = 1 for right, down in [[1, 1], [3, 1], [5, 1], [7, 1], [1, 2]]: ans *= count_trees(right, down) print(ans) return if __name__ == '__main__': print(count_trees(3, 1)) count_trees_multiple()
a7b1ecdfa56e96e9c93097f685486f134e685bb3
zzsyjl/crack_the_coding_interview
/chap03栈和队列/01三合一.py
1,800
3.84375
4
import unittest """ 用一个数组实现3个栈 思路: 一个线性的数组, 是怎么实现这个的呢? 可以加一个计数器, 每个栈都有计数. 就弄三个平行的吧. 我们可以增加一下难度, 把3换成n, 那么这样就需要不固定数量的函数了. """ class ManyStacksInOne: def __init__(self, n) -> None: self.n = n self.array = [] self.len_max = 0 self.lens = [0] * n def push(self, i, num): len_i = self.lens[i] if len_i == self.len_max: self.array.extend([None]*self.n) self.len_max += 1 self.array[len_i * self.n + i] = num self.lens[i] += 1 def pop(self, i): len_i = self.lens[i] if len_i == self.len_max and sum(self.lens >= len_i) > 1: result = self.array[self.n * (len_i-1) + i] del self.array[-self.n:] return result else: result = self.array[self.n * (len_i-1) + i] self.array[self.n * (len_i-1) + i] = None return result # class Test(unittest.TestCase): # test_cases = [ # ] # test_funcs = [ # # is_permutation # ] # def test_method(self): # assert self.test_cases != [] # assert self.test_funcs != [] # for arguments, result in self.test_cases: # for test_func in self.test_funcs: # self.assertEqual(test_func(*arguments), result) if __name__ == "__main__": # unittest.main() a = ManyStacksInOne(3) a.push(0, 0) assert a.array == [0, None, None] a.push(0, 1) assert a.array == [0, None, None, 1, None, None] assert a.pop(1) == None, a.array == [0, None, None, 1, None, None] a.push(2, 33) assert a.array == [0, None, 33, 1, None, None]
fbe33798e2bf01ba4c38621cb4b91f61cc0a69ad
duynhatldn/pythonCode
/venv/lib/python2.7/code/python/BigSorting/BigSorting.py
329
4.03125
4
import os import sys def bigSorting(unsorted): return sorted(unsorted) if __name__ == '__main__': n = int(raw_input()) unsorted = [] for _ in xrange(n): unsorted_item = raw_input() unsorted.append(long(unsorted_item)) result = bigSorting(unsorted) for x in result: print(x)
d34ad946c62da37ce38b4555205a4c9c2ee21650
silvioedu/TechSeries-Daily-Interview
/day15/Solution.py
1,091
3.671875
4
def arraySquare(nums): square = [] [square.append(pow(i, 2)) for i in sorted(nums)] return square def findPythagoreanTriplets(nums): n = arraySquare(nums) # print(nums) for a in (range(len(n) - 2)): # print("a -> ", nums[a]) for b in (range(a + 1, len(n) - 1)): # print(" b -> ", nums[b]) for c in (range(b + 1, len(n))): # print(" c -> ", nums[c]) # print('{} == {} + {} --> {}'.format(n[a], n[b], n[c], n[a] == n[b] + n[c])) # print('{} == {} + {} --> {}'.format(n[b], n[a], n[c], n[b] == n[a] + n[c])) # print('{} == {} + {} --> {}'.format(n[c], n[a], n[b], n[c] == n[a] + n[b])) if n[a] == n[b] + n[c] or \ n[b] == n[a] + n[c] or \ n[c] == n[a] + n[b]: return True return False if __name__ == '__main__': print(findPythagoreanTriplets([3, 12, 5, 13])) # True print(findPythagoreanTriplets([10, 4, 6, 12, 5])) # False
a49ab6ceec93af3f922e82b77b12aedece2491ea
ntuckertriplet/Advent-Of-Code-2019
/day1/day1.py
476
4.03125
4
def calculate(mass): return mass // 3 - 2 def recurse(int_input): final = int_input // 3 - 2 if final <= 0: return 0 return final + recurse(final) final_answer_part_1 = 0 final_answer_part_2 = 0 with open("data.txt", "r") as file: data = file.readlines() for line in data: final_answer_part_1 += calculate(int(line)) final_answer_part_2 += recurse(int(line)) print(final_answer_part_1) print(final_answer_part_2)
51298ab6d1e8f086179776b20cd4d528f60c8855
ahmedfahmyaee/Cyber-Security
/Ciphers/demonstration.py
3,275
4.1875
4
import math from matplotlib import pyplot from string import ascii_lowercase from collections import Counter """ This is a module to demonstrate how the Caesar Cipher works and how it can be broken using frequency analysis In addition this module contains a function which plots 2 graphs to illustrate how frequency analysis can be used to break the Caesar Cipher """ ALPHABET = ascii_lowercase ALPHABET_SIZE = len(ALPHABET) LETTER_FREQUENCY = {'e': 12.7, 't': 9.06, 'a': 8.17, 'o': 7.51, 'i': 6.97, 'n': 6.75, 's': 6.33, 'h': 6.09, 'r': 5.99, 'd': 4.25, 'l': 4.03, 'c': 2.78, 'u': 2.76, 'm': 2.41, 'w': 2.36, 'f': 2.23, 'g': 2.02, 'y': 1.97, 'p': 1.93, 'b': 1.29, 'v': 0.98, 'k': 0.77, 'j': 0.15, 'x': 0.15, 'q': 0.10, 'z': 0.07} GRAPH_STYLE = 'fivethirtyeight' LETTERS_X = list(ascii_lowercase) def cipher(text: str, key: int, decrypt: bool) -> str: """ Using the schema A-> 0, B-> 1, C-> 2 ... Z -> 25 We can decipher the letter x being given the key k using the formula: D(x) = (x - k) mod 26 Similarly we can encrypt the letter x given the key k using the formula: E(x) = (x + k) mod 26 :param text: text to be encrypted/decrypted :param key: the key to be used :param decrypt: a boolean value indicating weather to encrypt or decrypt :return: the cipher text """ output = '' for char in text: # If the character is not in the english alphabet don't change it. if char not in ALPHABET: output += char continue index = ALPHABET.index(char.lower()) if decrypt: new_char = ALPHABET[(index - key) % ALPHABET_SIZE] else: new_char = ALPHABET[(index + key) % ALPHABET_SIZE] # Setting the right case for the letter and adding it to the output output += new_char.upper() if char.isupper() else new_char return output def illustrate(plain_text: str, cipher_text: str): def construct_y_axis(text: str) -> list[float]: counter = Counter(text) return [counter.get(letter, 0) * 100 / len(text) for letter in ALPHABET] pyplot.style.use(GRAPH_STYLE) fig, axs = pyplot.subplots(2) fig.suptitle('Letter Frequency Before And After Encryption (Before on the top)') for axis in axs: axis.set_xlabel('Letters') axis.set_ylabel('Percentage %') axs[0].bar(LETTERS_X, construct_y_axis(plain_text)) axs[1].bar(LETTERS_X, construct_y_axis(cipher_text)) pyplot.show() def difference(text: str) -> float: counter = Counter(text) return sum([abs(counter.get(letter, 0) * 100 / len(text) - LETTER_FREQUENCY[letter]) for letter in ALPHABET]) / ALPHABET_SIZE def break_cipher(cipher_text: str) -> int: lowest_difference = math.inf encryption_key = 0 for key in range(1, ALPHABET_SIZE): current_plain_text = cipher(cipher_text, key, True) current_difference = difference(current_plain_text) if current_difference < lowest_difference: lowest_difference = current_difference encryption_key = key return encryption_key
262b70798ea2fc9e060604ba6f8313402783a0ec
rndviktor2devman/11_duplicates
/duplicates.py
2,001
3.71875
4
import os import sys import shutil def are_files_duplicates(file_path1, file_path2): if os.path.basename(file_path1) == os.path.basename(file_path2): if os.path.getsize(file_path1) == os.path.getsize(file_path2): return True return False def are_folders_duplicates(folder_path1, folder_path2): if folder_path1.startswith(folder_path2) or folder_path2.startswith(folder_path1): return False if os.path.basename(folder_path1) == os.path.basename(folder_path2): if not os.listdir(folder_path1) and not os.listdir(folder_path2): return True return False def get_folders(path): folders_paths = [] for root, dirs, files in os.walk(path): for name in dirs: folders_paths.append(os.path.join(root, name)) return folders_paths def get_files(path): files_paths = [] for root, dirs, files in os.walk(path): for name in files: files_paths.append(os.path.join(root, name)) return files_paths def notify_deletion(path_list, item_name): for path in path_list: print("removing {} {}".format(item_name, path)) def get_duplicates(paths_list, check_function): file_number = 1 deletion_list = set() for filepath in paths_list[:-1]: for filepath2 in paths_list[file_number:]: if check_function(filepath, filepath2): deletion_list.add(filepath2) file_number += 1 return deletion_list if __name__ == '__main__': if len(sys.argv) > 1: rootdir = sys.argv[1] else: rootdir = os.getcwd() files = get_files(rootdir) duplicate_files = get_duplicates(files, are_files_duplicates) notify_deletion(duplicate_files, "file") list(map(os.remove, duplicate_files)) folders = get_folders(rootdir) duplicate_folders = get_duplicates(folders, are_folders_duplicates) notify_deletion(duplicate_folders, "directory") list(map(shutil.rmtree, duplicate_folders))
ad351ca484312ebb24ecc713e6509d76cbc42a92
bopopescu/Glowing-Grass
/NicksGardens/venv/Pseudocode.py
420
3.765625
4
import datetime customer_details_csv = open('contact_details.csv', 'r').read() day = int(input("Input day: ")) month = int(input("Input month: ")) year = int(input("Input year: ")) date = str(datetime.date(year,month,day)) print(date) if date in customer_details_csv: print("Date used") else: print("Date not used") #'%B' used to refer to month name e.g. December #'%m' used to refer to month number e.g. 12
a0eb02a5455ec95869bc79c5ccce98167d027b88
sf19pb1-petercooper/graph_paper
/graph_paper_1.py
753
3.875
4
import sys rows = int(input("How many rows of boxes? ")) columns = int(input("How many columns of boxes? ")) row_spaces = int(input("How many rows of spaces in each box? ")) column_spaces = int(input("How many columns of spaces in each box (e.g., 3)? ")) for i in range(rows): for i in range(columns): print("+",end="") for i in range(column_spaces): print("-",end="") print("+") for spaces in range(row_spaces): for _ in range(columns): print("|",end="") for space in range(column_spaces): print(" ",end="") print("|") for i in range(columns): print("+",end="") for i in range(column_spaces): print("-",end="") print("+") #+ and - are characters sys.exit(0)