blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
b02c3710c778ed71534721cea03c11db41f6072c
kivy/kivy
/examples/widgets/recycleview/rv_animate_items.py
3,628
3.984375
4
'''How to use Animation with RecycleView items? In case you really want to use the Animation class with RecycleView, you'll likely encounter an issue, as widgets are moved around, they are used to represent different items, so an animation on a specific item is going to affect others, and this will lead to really confusing results. This example works around that by creating a "proxy" widget for the animation, and, by putting it in the data, allowing the displayed widget to mimic the animation. As the item always refers to its proxy, whichever widget is used to display the item will keep in sync with the animation. ''' from copy import copy from kivy.app import App from kivy.clock import triggered from kivy.lang import Builder from kivy.uix.widget import Widget from kivy.animation import Animation from kivy.uix.button import Button from kivy.properties import ( ObjectProperty, ListProperty ) KV = ''' <Item>: index: None animation_proxy: None on_release: app.animate_item(self.index) RecycleView: data: app.data viewclass: 'Item' RecycleBoxLayout: orientation: 'vertical' size_hint: 1, None height: self.minimum_height default_size_hint: 1, None default_size: 0, dp(40) ''' class Item(Button): animation_proxy = ObjectProperty(allownone=True) _animation_proxy = None def update_opacity(self, proxy, opacity): # sync one animated property to the value in the proxy self.opacity = opacity def on_animation_proxy(self, *args): """When we create an animation proxy for an item, we need to bind to the animated property to update our own. """ if self._animation_proxy: self._animation_proxy.unbind(opacity=self.update_opacity) self._animation_proxy = self.animation_proxy if self.animation_proxy: # when we are assigned an animation_proxy, sync our properties to # the animated version. self.opacity = self.animation_proxy.opacity self.animation_proxy.bind(opacity=self.update_opacity) else: # if we lose our animation proxy, we need to reset the animated # property to their default values. self.opacity = 1 class Application(App): data = ListProperty() def build(self): self.data = [ {'index': i, 'text': 'hello {}'.format(i), 'animation_proxy': None} for i in range(1000) ] return Builder.load_string(KV) # the triggered decorator allows delaying the animation until after the # blue effect on the button is removed, to avoid a flash as widgets gets # reordered when that happens @triggered(timeout=0.05) def animate_item(self, index): # the animation we actually want to do on the item, note that any # property animated here needs to be synchronized from the proxy to the # animated widget (in on_animation_proxy and using methods for each # animation) proxy = Widget(opacity=1) item = copy(self.data[index]) animation = ( Animation(opacity=0, d=.1, t='out_quad') + Animation(opacity=1, d=5, t='out_quad') ) animation.bind(on_complete=lambda *x: self.reset_animation(item)) item['animation_proxy'] = proxy self.data[index] = item animation.start(proxy) def reset_animation(self, item): # animation is complete, widget should be garbage collected item['animation_proxy'] = None if __name__ == "__main__": Application().run()
2cd4eb98d4adb5d85a6a640d653978ac10a54608
neuromaancer/PRD
/nn/preprocess.py
21,478
3.671875
4
import numpy as np import csv class Preprocess: def convertRHtoSeq(self, r, h, size): """ Function can use the numbers : r and h. and create a sequence like (0000011111). 0: the poisiton out of window 1: the position in the window :param r: start position :param h: size of the windows :param size: size of the sequence :return: the binaire sequence which can give the position of the window(like 00000111000). """ seq = [str(0)] * size for i in range(len(seq)): if not i < r and i < r + h: seq[i] = str(1) seq = ''.join(seq) return seq def preprcessingData(self, txtfile, size): """ Function can extracte the data from the txt generated form the CPLEX program and transform to the data form that can be used by the Seq2Seq model. :param txtfile: the path of the database txt file. :param size: size of the sequence :return: the number of the instances and the file csv for the seq2seq """ with open(txtfile) as f: data = f.readlines() data = data[2:] num_ins = 1 with open("../database/database.csv", "a+") as file: file.write(str(num_ins) + '\n') for line in data: if line.count('\n') == len(line): num_ins = num_ins + 1 file.write(str(num_ins) + '\n') else: l = line.split(' ') r = int(l[1]) h = int(l[2]) # print(str(r) + '\t' +str(h)) seq = self.convertRHtoSeq(r, h, size) ptime_seq = l[5:(size * 2 + 5)] # if num_ins < 3: # print(ptime_seq) # print(len(ptime_seq)) ptimes = ' '.join(ptime_seq) file.write("\"" + str(ptimes) + "\"" + ',' + "\"" + seq + "\"" + "\n") return num_ins def preprcessingDatawithC(self, txtfile, size): """ Function can extracte the data from the txt generated form the CPLEX program, calculate the completion time for each job and add to the database, and transform to the data form that can be used by the Seq2Seq model. :param txtfile: the path of the database txt file. :param size: size of the sequence :return: the number of the instances and the file csv for the seq2seq """ with open(txtfile) as f: data = f.readlines() data = data[2:] num_ins = 1 with open("../database/databaseC.csv", "a+") as file: file.write(str(num_ins) + '\n') for line in data: if line.count('\n') == len(line): num_ins = num_ins + 1 file.write(str(num_ins) + '\n') else: l = line.split(' ') r = int(l[1]) h = int(l[2]) # print(str(r) + '\t' +str(h)) seq = self.convertRHtoSeq(r, h, size) ptime_seq = l[5:(size * 2 + 5)] # print(ptime_seq) file.write("\"") # ptimes = ' '.join(ptime_seq) C1 = 0 C2 = 0 for i in range(0, len(ptime_seq), 2): file.write(" " + ptime_seq[i] + " " + ptime_seq[i + 1] + " ") C1 += int(ptime_seq[i]) C2 = max(C1 + int(ptime_seq[i + 1]), C2 + int(ptime_seq[i + 1])) file.write(str(C1) + " " + str(C2)) file.write("\"") # if num_ins < 3: # print(ptime_seq) # print(len(ptime_seq)) ptimes = ' '.join(ptime_seq) file.write(',' + "\"" + seq + "\"" + "\n") return num_ins def MergeTXT(self, filenames): """ Function can merge different txt file into one txt file. :param filenames: the list of diffrent txt file generated by the CPLEX program. :return: """ with open('/Users/alafateabulimiti/PycharmProjects/PRD/database/base.txt', 'w') as outfile: for fname in filenames: with open(fname) as infile: for line in infile: outfile.write(line) def divideData(self, size, num_instance): """ Function can divide the data into 3 part: Training set, Test set and Validation set. :param txtfile: the path of the database txt file. :param size: size of the sequence :return: X_train, y_train, X_test, y_test, X_validation, y_validation X_train: Training set which have the initial sequence with processing time. y_train: Training set which have the binary sequnece that can indicate the window. X_test: Test set which have the initial sequence with processing time. y_test: Test set which have the binary sequnece that can indicate the window. X_validation: Validation set which have the initial sequence with processing time. y_validation: Validation set which have the binary sequnece that can indicate the window. """ # num_instance = self.preprcessingData(txtfile, size) print("num_instance: " + str(num_instance)) num_ins_test = int(num_instance * 0.2) num_ins_validation = num_ins_test num_ins_train = num_instance - num_ins_test * 2 X_train = [] y_train = [] X_test = [] y_test = [] X_validation = [] y_validation = [] with open('../database/database.csv') as data: reader = csv.reader(data) dataSet = list(reader) length = len(dataSet) count = 0 for line in dataSet: if len(line) == 1: count = count + 1 continue if count <= num_ins_train: ptimes_list, solved_list = self.saveLine(line) X_train.append(ptimes_list) y_train.append(solved_list) if num_ins_train < count <= num_ins_train + num_ins_test: ptimes_list, solved_list = self.saveLine(line) X_test.append(ptimes_list) y_test.append(solved_list) if num_ins_train + num_ins_test < count <= num_instance: ptimes_list, solved_list = self.saveLine(line) X_validation.append(ptimes_list) y_validation.append(solved_list) X_train = np.asarray(X_train) y_train = np.asarray(y_train) y_train = np.reshape(y_train, (len(y_train), size, 1)) X_test = np.asarray(X_test) y_test = np.asarray(y_test) y_test = np.reshape(y_test, (len(y_test), size, 1)) X_validation = np.asarray(X_validation) y_validation = np.asarray(y_validation) y_validation = np.reshape(y_validation, (len(y_validation), size, 1)) return X_train, y_train, X_test, y_test, X_validation, y_validation def divideDatawithC(self, size, num_instance): """ Function can divide the data into 3 part: Training set, Test set and Validation set. :param txtfile: the path of the database txt file. :param size: size of the sequence :return: X_train, y_train, X_test, y_test, X_validation, y_validation X_train: Training set which have the initial sequence with processing time and completion time. y_train: Training set which have the binary sequnece that can indicate the window. X_test: Test set which have the initial sequence with processing time and completion time. y_test: Test set which have the binary sequnece that can indicate the window. X_validation: Validation set which have the initial sequence with processing time and completion time. y_validation: Validation set which have the binary sequnece that can indicate the window. """ print("num_instance: " + str(num_instance)) num_ins_test = int(num_instance * 0.2) num_ins_validation = num_ins_test num_ins_train = num_instance - num_ins_test * 2 X_train = [] y_train = [] X_test = [] y_test = [] X_validation = [] y_validation = [] with open('../database/databaseC.csv') as data: reader = csv.reader(data) dataSet = list(reader) length = len(dataSet) count = 0 for line in dataSet: if len(line) == 1: count = count + 1 continue if count <= num_ins_train: ptimes_list, solved_list = self.saveLinewithC(line) X_train.append(ptimes_list) y_train.append(solved_list) if num_ins_train < count <= num_ins_train + num_ins_test: ptimes_list, solved_list = self.saveLinewithC(line) X_test.append(ptimes_list) y_test.append(solved_list) if num_ins_train + num_ins_test < count <= num_instance: ptimes_list, solved_list = self.saveLinewithC(line) X_validation.append(ptimes_list) y_validation.append(solved_list) X_train = np.asarray(X_train) y_train = np.asarray(y_train) y_train = np.reshape(y_train, (len(y_train), size, 1)) X_test = np.asarray(X_test) y_test = np.asarray(y_test) y_test = np.reshape(y_test, (len(y_test), size, 1)) X_validation = np.asarray(X_validation) y_validation = np.asarray(y_validation) y_validation = np.reshape(y_validation, (len(y_validation), size, 1)) return X_train, y_train, X_test, y_test, X_validation, y_validation def divideDataByIns(self,size, num_instance): """ Function can divide the data into 3 part: Training set, Test set and Validation set. But select only one line of data by instance. :param txtfile: the path of the database txt file. :param size: size of the sequence :return:X_train, y_train, X_test, y_test, X_validation, y_validation X_train: Training set which have the initial sequence with processing time. y_train: Training set which have the binary sequnece that can indicate the window. X_test: Test set which have the initial sequence with processing time. y_test: Test set which have the binary sequnece that can indicate the window. X_validation: Validation set which have the initial sequence with processing time. y_validation: Validation set which have the binary sequnece that can indicate the window. """ print("num_instance: " + str(num_instance)) num_ins_test = int(num_instance * 0.2) num_ins_validation = num_ins_test num_ins_train = num_instance - num_ins_test * 2 X_train = [] y_train = [] X_test = [] y_test = [] X_validation = [] y_validation = [] with open('../database/database.csv') as data: reader = csv.reader(data) dataSet = list(reader) length = len(dataSet) count = 0 for i in range(length): if len(dataSet[i]) == 1: count = count + 1 if count <= num_ins_train: ptimes_list, solved_list = self.saveLine(dataSet[i + 1]) X_train.append(ptimes_list) y_train.append(solved_list) if num_ins_train < count <= num_ins_train + num_ins_test: ptimes_list, solved_list = self.saveLine(dataSet[i + 1]) X_test.append(ptimes_list) y_test.append(solved_list) if num_ins_train + num_ins_test < count <= num_instance: ptimes_list, solved_list = self.saveLine(dataSet[i + 1]) X_validation.append(ptimes_list) y_validation.append(solved_list) X_train = np.asarray(X_train) y_train = np.asarray(y_train) y_train = np.reshape(y_train, (len(y_train), size, 1)) X_test = np.asarray(X_test) y_test = np.asarray(y_test) y_test = np.reshape(y_test, (len(y_test), size, 1)) X_validation = np.asarray(X_validation) y_validation = np.asarray(y_validation) y_validation = np.reshape(y_validation, (len(y_validation), size, 1)) return X_train, y_train, X_test, y_test, X_validation, y_validation def divideDataByInswithC(self, size, num_instance): """ Function can divide the data into 3 part: Training set, Test set and Validation set. But select only one line of data by instance. :param txtfile: the path of the database txt file. :param size: size of the sequence :return:X_train, y_train, X_test, y_test, X_validation, y_validation X_train: Training set which have the initial sequence with processing time and completion time. y_train: Training set which have the binary sequnece that can indicate the window. X_test: Test set which have the initial sequence with processing time and completion time. y_test: Test set which have the binary sequnece that can indicate the window. X_validation: Validation set which have the initial sequence with processing time and completion time. y_validation: Validation set which have the binary sequnece that can indicate the window. """ print("num_instance: " + str(num_instance)) num_ins_test = int(num_instance * 0.2) num_ins_validation = num_ins_test num_ins_train = num_instance - num_ins_test * 2 X_train = [] y_train = [] X_test = [] y_test = [] X_validation = [] y_validation = [] with open('../database/databaseC.csv') as data: reader = csv.reader(data) dataSet = list(reader) length = len(dataSet) count = 0 for i in range(length): if len(dataSet[i]) == 1: count = count + 1 print(count) if count <= num_ins_train: ptimes_list, solved_list = self.saveLinewithC(dataSet[i + 1]) X_train.append(ptimes_list) y_train.append(solved_list) if num_ins_train < count <= num_ins_train + num_ins_test: ptimes_list, solved_list = self.saveLinewithC(dataSet[i + 1]) X_test.append(ptimes_list) y_test.append(solved_list) if num_ins_train + num_ins_test < count <= num_instance: ptimes_list, solved_list = self.saveLinewithC(dataSet[i + 1]) X_validation.append(ptimes_list) y_validation.append(solved_list) X_train = np.asarray(X_train) y_train = np.asarray(y_train) y_train = np.reshape(y_train, (len(y_train), size, 1)) X_test = np.asarray(X_test) y_test = np.asarray(y_test) y_test = np.reshape(y_test, (len(y_test), size, 1)) X_validation = np.asarray(X_validation) y_validation = np.asarray(y_validation) y_validation = np.reshape(y_validation, (len(y_validation), size, 1)) return X_train, y_train, X_test, y_test, X_validation, y_validation def saveLine(self, line): """ Supplement function for bulid the diffrent sets of the seq2seq model :param line: one line of the csv file :return: ptimes_list, solved_list. ptimes_list: the sequence with processing time. solved_list: the binary sequence that can indicate the window. """ ptimes = line[0].split(' ') ptimes_list = [] for k in range(0, len(ptimes), 2): ptimes_list.append([int(ptimes[k]), int(ptimes[k + 1])]) solved_list = list(map(int, line[1])) np.array(ptimes_list) np.array(solved_list) return ptimes_list, solved_list def saveLinewithC(self, line): """ Supplement function for bulid the diffrent sets of the seq2seq model. :param line: one line of the csv file :return: ptimes_list, solved_list. ptimes_list: the sequence with processing time and completion time. solved_list: the binary sequence that can indicate the window. """ #print(line) ptimes = line[0].split(' ') ptimes_list = [] # print(ptimes) for k in range(1, len(ptimes), 4): ptimes_list.append( [int(float(ptimes[k])), int(float(ptimes[k + 1])), int(float(ptimes[k + 2])), int(float(ptimes[k + 3]))]) solved_list = list(map(int, line[1])) return ptimes_list, solved_list if __name__ == "__main__": # num_ins_train = int(59 * 0.6) # print(num_ins_train) # preprcessingData('/Users/alafateabulimiti/PycharmProjects/PRD/database/base.txt', 100) # preprcessingDatawithC('/Users/alafateabulimiti/PycharmProjects/PRD/database/base.txt', 100) # print(convertRHtoSeq(1, 10, 100)) # from random import sample # # # List = [0, 1, 2, 3, 4, 5] # print(sample(List, 2)) # print(sample(List, 2)) # print(sample(List, 2)) # print(sample(List, 2)) # with open('database.csv') as data: # reader = csv.reader(data) # for item in reader: # # print(item[0]) # X_train, y_train, X_test, y_test, X_validation, y_validation = divideDataByIns('/Users/alafateabulimiti/PycharmProjects/PRD/database/base.txt', 100) # print(len(X_train)+len(X_test)+len(X_validation)) # print(X_train) # print(len(y_train)) # print(X_train.shape) # print(y_test) # print(X_validation) # print(y_validation) # input_length = 5 # input_dim = 3 # # output_length = 3 # output_dim = 4 # # samples = 100 # hidden_dim = 24 # x = np.random.random((samples, input_length, input_dim)) # y = np.random.random((samples, output_length, output_dim)) # print(x) # print('---------------------') # print(y) # filenames = ['/Users/alafateabulimiti/PycharmProjects/PRD/database/Database.txt','/Users/alafateabulimiti/PycharmProjects/PRD/database/Database2.txt','/Users/alafateabulimiti/PycharmProjects/PRD/database/Database3.txt'] preprocess = Preprocess() # preprocess.MergeTXT([ # '/Users/alafateabulimiti/PycharmProjects/PRD/database/Database.txt', # '/Users/alafateabulimiti/PycharmProjects/PRD/database/Database2.txt', # '/Users/alafateabulimiti/PycharmProjects/PRD/database/Database3.txt', # '/Users/alafateabulimiti/PycharmProjects/PRD/database/Database4.txt', # '/Users/alafateabulimiti/PycharmProjects/PRD/database/Database5.txt', # '/Users/alafateabulimiti/PycharmProjects/PRD/database/Database6.txt', # '/Users/alafateabulimiti/PycharmProjects/PRD/database/Database7.txt', # '/Users/alafateabulimiti/PycharmProjects/PRD/database/Database8.txt', # '/Users/alafateabulimiti/PycharmProjects/PRD/database/Database9.txt', # '/Users/alafateabulimiti/PycharmProjects/PRD/database/Database10.txt', # '/Users/alafateabulimiti/PycharmProjects/PRD/database/Database11.txt', # '/Users/alafateabulimiti/PycharmProjects/PRD/database/Database12.txt', # '/Users/alafateabulimiti/PycharmProjects/PRD/database/Database13.txt', # '/Users/alafateabulimiti/PycharmProjects/PRD/database/Database14.txt', # '/Users/alafateabulimiti/PycharmProjects/PRD/database/Database15.txt', # '/Users/alafateabulimiti/PycharmProjects/PRD/database/Database16.txt', # '/Users/alafateabulimiti/PycharmProjects/PRD/database/Database17.txt', # '/Users/alafateabulimiti/PycharmProjects/PRD/database/Database18.txt', # '/Users/alafateabulimiti/PycharmProjects/PRD/database/Database19.txt', # '/Users/alafateabulimiti/PycharmProjects/PRD/database/Database20.txt', # '/Users/alafateabulimiti/PycharmProjects/PRD/database/Database21.txt', # '/Users/alafateabulimiti/PycharmProjects/PRD/database/Database22.txt', # '/Users/alafateabulimiti/PycharmProjects/PRD/database/Database23.txt', # ]) preprocess.preprcessingDatawithC('/Users/alafateabulimiti/PycharmProjects/PRD/database/base.txt', 100)
fe42adbde67a34e2e1dcafa1292b455520e44afe
amontoya98/MCMC
/MCMCWeather/mcmcWeather.py
810
3.796875
4
#MCMC #Probability of the Weather import random #function definitions def genMarkovDays(n): climate = "SR" days = "" days += random.choice(climate) for i in range(1, n): if days[i-1] == 'S': weather = random.choices(climate, weights=(90,10), k=1) elif days[i-1] == 'R': weather = random.choices(climate, weights=(50,50), k=1) weatherToday = weather[0] days += weatherToday return days def calcProbability(string): dct = {} for letter in string: if letter not in dct: dct.update({letter: 1}) else: dct[letter] += 1 for val in dct: dct[val] /= len(string) return dct #function calls chain = genMarkovDays(1000) probability = calcProbability(chain) print(probability)
e1ce505df346a3f496f6952a53c53e20d1867c6f
BenDataAnalyst/Practice-Coding-Questions
/CTCI/Chapter3/3.1-Three_In_One.py
2,842
3.609375
4
# CTCI 3.1 # Three in One import unittest class ThreeStacks(): def __init__(self): self.array = [None, None, None] self.current = [0, 1, 2] def push(self, item, stack_number): if not stack_number in [0, 1, 2]: raise Exception("Bad stack number") while len(self.array) <= self.current[stack_number]: self.array += [None] * len(self.array) self.array[self.current[stack_number]] = item self.current[stack_number] += 3 def pop(self, stack_number): if not stack_number in [0, 1, 2]: raise Exception("Bad stack number") if self.current[stack_number] > 3: self.current[stack_number] -= 3 item = self.array[self.current[stack_number]] self.array[self.current[stack_number]] = None return item #------------------------------------------------------------------------------- # CTCI Solution class MultiStack: def __init__(self, stacksize): self.numstacks = 3 self.array = [0] * (stacksize * self.numstacks) self.sizes = [0] * self.numstacks self.stacksize = stacksize def Push(self, item, stacknum): if self.IsFull(stacknum): raise Exception('Stack is full') self.sizes[stacknum] += 1 self.array[self.IndexOfTop(stacknum)] = item def Pop(self, stacknum): if self.IsEmpty(stacknum): raise Exception('Stack is empty') value = self.array[self.IndexOfTop(stacknum)] self.array[self.IndexOfTop(stacknum)] = 0 self.sizes[stacknum] -= 1 return value def Peek(self, stacknum): if self.IsEmpty(stacknum): raise Exception('Stack is empty') return self.array[self.IndexOfTop(stacknum)] def IsEmpty(self, stacknum): return self.sizes[stacknum] == 0 def IsFull(self, stacknum): return self.sizes[stacknum] == self.stacksize def IndexOfTop(self, stacknum): offset = stacknum * self.stacksize return offset + self.sizes[stacknum] - 1 #------------------------------------------------------------------------------- #Testing class Test(unittest.TestCase): def test_three_stacks(self): three_stacks = ThreeStacks() three_stacks.push(101, 0) three_stacks.push(102, 0) three_stacks.push(103, 0) three_stacks.push(201, 1) self.assertEqual(three_stacks.pop(0), 103) self.assertEqual(three_stacks.pop(1), 201) self.assertEqual(three_stacks.pop(1), None) self.assertEqual(three_stacks.pop(2), None) three_stacks.push(301, 2) three_stacks.push(302, 2) self.assertEqual(three_stacks.pop(2), 302) self.assertEqual(three_stacks.pop(2), 301) self.assertEqual(three_stacks.pop(2), None) if __name__ == "__main__": unittest.main()
066b67be792f305d212b5a161c082b41fa0ccdd2
hxyair/Google
/2.Using Python to Interact with the Operating System/Week7/csv_to_html.py
400
3.796875
4
#!/usr/bin/env python3 # regexr.com # print(sorted(names)) import re line = "May 27 11:45:40 ubuntu.local ticky: INFO: Created ticket [#1234] (username)" re.search(r"ticky: INFO: ([\w ]*) ", line) fruit = {"oranges": 3, "apples": 5, "bananas": 7, "pears": 2} sorted(fruit.items()) import operator sorted(fruit.items(), key=operator.itemgetter(0)) sorted(fruit.items(), key=operator.itemgetter(1))
9d24913160e0f6c8ac21da6328f3d9b34854bd4b
Platforuma/Beginner-s_Python_Codes
/10_Functions/6_Functions--Reverse-Strings.py
1,088
4.34375
4
''' Write a Python program to reverse a string. Sample String : "1234abcd" Expected Output : "dcba4321" ''' #using string index method print('----String Index Method----') def r_string(fstring): rstring = '' index = len(fstring) while index>0: rstring += fstring[ index - 1 ] index = index - 1 return 'Original: ', fstring, 'Reverse: ', rstring print(r_string('1234abcd')) print(r_string('Platforuma')) print(r_string('Python')) print(r_string('Arduino')) print(r_string('Indore')) print(r_string('Iron Man')) print(' ') #using list reverse method print('----List Index Method----') def reverse_string(text): flip = [] for i in range(len(text)-1,-1,-1): flip.append(text[i]) strings = '' for letters in flip: strings += str(letters) print('Straight Order: ', text,', Reverse Order: ', strings ) reverse_string('1234abcd') reverse_string('Platforuma') reverse_string('Python') reverse_string('Arduino') reverse_string('Indore') reverse_string('Iron Man')
f170e332a4041b2fe14d6482209b667c66237032
AndresNunezG/ejercicios_python_udemy
/ejercicio_04.py
678
4.15625
4
""" Ejercicio 4. - Pedir dos (2) números al usuario - Hacer todas las operaciones básicas matemáticas - Mostrar el resultado en pantalla """ #Solicitar numeros al usuario num_a = int(input('Ingrese el primer número: ')) num_b = int(input('Ingrese el segundo número: ')) #Operaciones básicas suma = num_a + num_b resta = num_a - num_b mult = num_a * num_b try: division = num_a / num_b except: division = 'División entre 0 inválida' print(f'La suma de {num_a} + {num_b} es: {suma}') print(f'La resta de {num_a} - {num_b} es: {resta}') print(f'El producto de {num_a} * {num_b} es: {mult}') print(f'La division de {num_a} / {num_b} es: {division}')
75ec852a74486ad47d532c467798d5cf5a1f7c84
mathuraveeraganesh/IBM-SDET-LONG-Batch-1_Python
/Python/ListSumCalculator.py
273
4.09375
4
"""Write a Python program to calculate the sum of all the elements in a list. Bonus points if you can make the user enter their own list""" num = list(input("Enter the Sequence seperate by comma").split(",")) sum=0 for nums in num: sum+=int(nums) print(sum)
6bf4d215cfbab686736406161b6950dfd5652a26
murali-kotakonda/PythonProgs
/PythonBasics1/functions/FuntionProg2.py
570
3.796875
4
def f2(name): print("input =", name) f2(12) f2("user1") f2(1213.78) f2(True) #sum of two nums def sum(x, y): z = x + y print("sum = ", z) sum(30, 20) a = 40 b = 90 sum(a, b) n1 = int(input("enter n1")) n2 = int(input("enter n1")) sum(n1, n2) #find big of two nums def findLarge(a,b): if a>b: print("bigger is", a) else: print("bigger is", b) findLarge(10,20) findLarge(50,20) def div(x,y): if(y == 0): print("division not possible") else: print(x/y) div(10,2) div(18.4,3) div(9,0) div(10.7,9.0)
b2c89954836f967e02d1ea04e9ed446e7e6a6cc8
vahidsediqi/Python-basic-codes
/Data-Structures/lists/sorting.py
142
4.09375
4
numbers = [3,2,1,5,8,6,10,9,7,4,0] numbers.sort() print(numbers) # if we want to sort it reverse numbers.sort(reverse=True) print(numbers)
42eb167f71336c113b5a5b9c739de078420c675f
learnerofmuses/slotMachine
/csci152Spring2014/lab7/p2.py
614
4.375
4
#Write a program that randomly generates the 2-dimensional list. Make #sizes of the list user input. Program prints all odd elements. import random def main(): row = int(input("enter number of rows: ")) col = int(input("enter number of cols: ")) odd = [] a = [[0 for i in range(col)] for j in range(row)] for i in range(row): for j in range(col): a[i][j]= random.randint(0, 15) print a for i in range(row): for j in range(col): if(a[i][j]%2 != 0): print(a[i][j]) odd.append(a[i][j]) if(len(odd)==0): print("no odd numbers") else: print("odd numbers") print(odd) main()
05fc5b4da34e7ed1e4253b0432ea1474252be0f5
delaven007/project-2
/dict_select.py
2,354
3.5
4
"""用户可以登录和注册 1.确定并发方案,确定套接字,具体细节和需求分析 *Process多进程 tcp套接字 *注册后直接进入二级界面,历史记录最近10个 2.使用dict -->words 用户表:id name passwd create table user (id int primary key auto_increment,name varchar(32) not null ,passwd varchar(128) not null); 历史记录表:id name word time create table hist (id int primary key auto_increment,name varchar(32) not null,word varchar(32) not null,time datetime default now()); 3.结构设计,如何封装,客户端服务端工作流程 *客户端(发请求,展示结果) *服务端(逻辑操作,解决请求) *数据库服务端(操作数据库) 界面处理: while True: 界面1 while True: 界面2 4.功能模块划分 *网络搭建 *注册 *登录 *查单词 *历史记录 * 登录凭借用户名和密码登录 * 注册要求用户必须填写用户名,密码,其他内容自定 * 用户名要求不能重复 * 要求用户信息能够长期保存 可以通过基本的图形界面print以提示客户端输入。 * 程序分为服务端和客户端两部分 * 客户端通过print打印简单界面输入命令发起请求 * 服务端主要负责逻辑数据处理 * 启动服务端后应该能满足多个客户端同时操作 客户端启动后即进入一级界面,包含如下功能:登录 注册 退出 * 退出后即退出该软件 * 登录成功即进入二级界面,失败回到一级界面 * 注册成功可以回到一级界面继续登录,也可以直接用注册用户进入二级界面 用户登录后进入二级界面,功能如下:查单词 历史记录 注销 file:///C:/Users/lvze/Desktop/6%E9%A1%B9%E7%9B%AE%E7%BB%BC%E5%90%88/project.html 12/142019/5/26 project * 选择注销则回到一级界面 * 查单词:循环输入单词,得到单词解释,输入特殊符号退出单词查询状态 * 历史记录:查询当前用户的查词记录,要求记录包含name word time。可以查看所有记录或者前10条均可。 单词本说明 每个单词一定占一行 单词按照从小到大顺序排列 单词和解释之间一定有空格 查词说明 直接使用单词本查询(文本操作) 先将单词存入数据库,然后通过数据库查询。(数据库操作) """
81a8d22c412f507abf0a8ca9713d8f23e8fb2f77
D-Muturi/Zookeeper
/Problems/Calculating S V P/main.py
257
3.84375
4
a = int(input()) b = int(input()) c = int(input()) sum_of_rectangle = (4 * (a + b + c)) area_of_rectangle = (2 * ((a * b) + (b * c) + (a * c))) volume_of_rectangle = (a * b * c) print(sum_of_rectangle) print(area_of_rectangle) print(volume_of_rectangle)
74ee10a79197b18ea12bd8722736302f3c25045e
LinnTaylor/reflections
/MachineLearning/Regressions/QuizOne/studentRegression.py
731
3.53125
4
import numpy as np from sklearn import linear_model def studentReg(ages_train, net_worths_train): ### import the sklearn regression module, create, and train your regression ### name your regression reg ### your code goes here! reg = linear_model.LinearRegression() # Train the model using the training sets reg.fit(ages_train, net_worths_train) # The coefficients print('Coefficients: \n', reg.coef_) # The mean square error print("Residual sum of squares: %.2f", % np.mean((reg.predict(ages_train) - net_worths_train) ** 2)) # Explained variance score: 1 is perfect prediction print('Variance score: %.2f' % reg.score(ages_train, net_worths_train)) return reg
b1bf4a5bb183e1e28e49a2373ae041c8c1ab551a
degerej/homework3
/nodes.py
1,527
3.96875
4
# Joe Degere # 2/24/2020 # Nodes homework; Advanced class Node: def __init__(self, data): self.data = data self.next = None def __repr__(self): return repr(self.data) class LinkedList: def __init__(self): self.head = None def __repr__(self): nodes = [] curr = self.head while curr: nodes.append(repr(curr)) curr = curr.next return '[' + ','.join(nodes) + ']' def add_head(self, data): new_node = Node(data=data) new_node.next = self.head self.head = new_node def add_end(self, data): new_node = Node(data=data) curr = self.head while curr.next: curr = curr.next curr.next = new_node def remove_head(self): new_node = self.head self.head = self.head.next return new_node.data def remove_end(self): curr_node = self.head prev_node = self.head while curr_node.next: prev_node = curr_node curr_node = curr_node.next prev_node.next = None return curr_node.data def clear_list(self): self.head = None def search(self, data): if self.head is None: print("List has no elements") return n = self.head while n is not None: if n.item == data: print("Item found") return True n = n.abs print("item not found") return False
819b9ab6ba3cd04848576ffad17b2d82e2245b08
ahmedmeshref/coffee-shop-ms
/backend/src/models.py
2,368
3.53125
4
import os from sqlalchemy import Column from flask_sqlalchemy import SQLAlchemy import json db = SQLAlchemy() def setup_db(app): """ setup_db(app) binds a flask application and a SQLAlchemy service """ db.app = app db.init_app(app) db.create_all() class Drink(db.Model): """ Drink blueprint is a persistent drink entity, extends the base SQLAlchemy Model """ # Unique primary key id = Column(db.Integer, primary_key=True) # String Title title = Column(db.String(80), unique=True) # the ingredients blob - this stores a lazy json blob # the required datatype is [{'color': string, 'name':string, 'parts':number}] recipe = Column(db.String(180), nullable=False) ''' short() short form representation of the Drink model ''' def short(self): recipe = json.loads(self.recipe) short_recipe = [{'color': recipe[0]['color'], 'parts': recipe[0]['parts']}] return { 'id': self.id, 'title': self.title, 'recipe': short_recipe } ''' long() long form representation of the Drink model ''' def long(self): return { 'id': self.id, 'title': self.title, 'recipe': json.loads(self.recipe) } ''' insert() inserts a new model into a database the model must have a unique name the model must have a unique id or null id EXAMPLE drink = Drink(title=req_title, recipe=req_recipe) drink.insert() ''' def insert(self): db.session.add(self) db.session.commit() ''' delete() deletes a new model into a database the model must exist in the database EXAMPLE drink = Drink(title=req_title, recipe=req_recipe) drink.delete() ''' def delete(self): db.session.delete(self) db.session.commit() ''' update() updates a new model into a database the model must exist in the database EXAMPLE drink = Drink.query.filter(Drink.id == id).one_or_none() drink.title = 'Black Coffee' drink.update() ''' def update(self): db.session.commit() def __repr__(self): return json.dumps(self.short())
f029ced78adb32b6b983c75532b295ba5c65b95d
MichaelENGs/Falcons_Income_Estimator
/src/asuProject_capitalgainloss_visuals_scatter.py
5,347
3.5625
4
# -*- coding: utf-8 -*- """ Created on Thu Apr 8 14:31:12 2021 """ import pandas as pd import matplotlib.pyplot as plt import numpy as np df_columns = ['age','workclass','fnlwgt','education','education-num','marital-status','occupation','relationship','race','sex','capital-gain','capital-loss','hours-per-week','native-country','income'] df_columns_categorical = ['workclass','education','marital-status','occupation','relationship','race','sex','native-country','income'] df_columns_categorical_index = [1,3,5,6,7,8,9,13,14] df_Adult_Data_File = pd.read_csv('adult.data', header=None) df_Adult_Data_File.columns = df_columns #print(df_Adult_Data_File.head()) varList_Dictionary_categorical = [] ######################## ######################## ######################## ######################## ######################## ######################## build main data frame here for general use for all column variables varFactor = 0 ################################### # loop through category column array here for cat_column in df_columns_categorical_index: column_index = cat_column ################################### # loop through column variable here i = 1 varDict_Class = {} for index, row in df_Adult_Data_File.iterrows(): #if index > 10: # break #print(row[1].strip()) varCat = row[column_index].strip() #print(varCat) if varCat not in varDict_Class: varDict_Class[varCat] = i + varFactor i = i + 1 print(i - 1) print(varDict_Class) varList_Dictionary_categorical.append(varDict_Class) varFactor = varFactor + 0 print() print() print() print(varList_Dictionary_categorical) ################################### # iterate through df here to adjust values to numerical varNewList = [] for index, row in df_Adult_Data_File.iterrows(): j = 0 varNewRow = [] for intColumn in range(0,15): if intColumn in df_columns_categorical_index: # convert category to numeric here varCat = row[intColumn].strip() varNumeric = varList_Dictionary_categorical[j][varCat] varNewRow.append(varNumeric) j = j + 1 else: # already numeric variable: varNumericColumnData = row[intColumn] varNewRow.append(varNumericColumnData) varNewList.append(varNewRow) print() print() print() #print("Numerical List") #print(varNewList[:10]) varDataFrameNumeric = pd.DataFrame(varNewList) #print(varDataFrameNumeric) ######################## ######################## ######################## ######################## ######################## ######################## try scatter plot here (currently not used for this assignment) varDataFrameNumeric_capital_gainloss = varDataFrameNumeric.loc[:, [10,11,14]] varDataFrameNumeric_capital_gainloss_clean = varDataFrameNumeric_capital_gainloss.loc[:, [10,11]] #print(varDataFrameNumeric_capital_gainloss.head(50)) varDataFrameNumeric_capital_gainloss_less50 = varDataFrameNumeric_capital_gainloss.loc[varDataFrameNumeric_capital_gainloss[14] == 1] varDataFrameNumeric_capital_gainloss_less50 = varDataFrameNumeric_capital_gainloss_less50.loc[:, [10,11]] varDataFrameNumeric_capital_gainloss_less50 = varDataFrameNumeric_capital_gainloss_less50.replace(0, np.nan) varDataFrameNumeric_capital_gainloss_less50 = varDataFrameNumeric_capital_gainloss_less50.dropna(how='all', axis=0) varDataFrameNumeric_capital_gainloss_less50 = varDataFrameNumeric_capital_gainloss_less50.replace(np.nan, 0) #varDataFrameNumeric_capital_gainloss_less50 = varDataFrameNumeric_capital_gainloss_less50.reset_index(drop=True) #print(varDataFrameNumeric_capital_gainloss_less50.head(50)) varDataFrameNumeric_capital_gainloss_greater50 = varDataFrameNumeric_capital_gainloss.loc[varDataFrameNumeric_capital_gainloss[14] == 2] varDataFrameNumeric_capital_gainloss_greater50 = varDataFrameNumeric_capital_gainloss_greater50.loc[:, [10,11]] varDataFrameNumeric_capital_gainloss_greater50 = varDataFrameNumeric_capital_gainloss_greater50.replace(0, np.nan) varDataFrameNumeric_capital_gainloss_greater50 = varDataFrameNumeric_capital_gainloss_greater50.dropna(how='all', axis=0) varDataFrameNumeric_capital_gainloss_greater50 = varDataFrameNumeric_capital_gainloss_greater50.replace(np.nan, 0) #varDataFrameNumeric_capital_gainloss_greater50 = varDataFrameNumeric_capital_gainloss_greater50.reset_index(drop=True) #print(varDataFrameNumeric_capital_gainloss_greater50.head(50)) y1 = varDataFrameNumeric_capital_gainloss_clean[10] x1 = varDataFrameNumeric_capital_gainloss_clean.index y2 = varDataFrameNumeric_capital_gainloss_clean[11] x2 = varDataFrameNumeric_capital_gainloss_clean.index fig2, ax2 = plt.subplots(1,1) fig2.set_size_inches(25,25) ax2.scatter(x1, y1, c='b', label='capital-gain') ax2.scatter(x2, y2, c='r', label='capital-loss') #ax2.show() ax2.legend(loc='best',fontsize=20) ax2.set_title('Capital Gain, Loss (Population)', fontsize=30) ax2.set_xlabel("number", fontsize=30) ax2.set_ylabel("USD $", fontsize=30) plt.xticks(fontsize=20) plt.yticks(fontsize=20)
7e8153a30feab9b93730d18bfc7365fa6d65fb7d
comp-think/comp-think.github.io
/exercises/development/intermediate/exercise_6.py
1,325
3.515625
4
# -*- coding: utf-8 -*- # Copyright (c) 2019, Silvio Peroni <[email protected]> # # Permission to use, copy, modify, and/or distribute this software for any purpose # with or without fee is hereby granted, provided that the above copyright notice # and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH # REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND # FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, # OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, # DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS # ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS # SOFTWARE. from collections import deque # Test case for the function def test_pal(name, expected): result = pal(name) if expected == result: return True else: return False # Code of the function def pal(name): if name == "": return name else: char = name[0] if char in ("a", "e", "i", "o", "u", "A", "E", "I", "O", "U"): char = "" return pal(name[1:]) + char # Tests print(test_pal("Silvio Peroni", "nrP vlS")) print(test_pal("John Doé", "éD nhJ")) print(test_pal("", ""))
6070dea4fa5b4834d583e3d906d8dca52656dd7f
grayfelt/CS1440
/cs1440-felt-grayson-assn0/lsn/0-ASCIIChars/ex1.py
639
3.75
4
def listOfChars(intList): list = [] # TODO: Append to characters to `list` for val in intList: list.append(chr(val)) return list if __name__ == '__main__': provided = [ 65, 32, 115, 104, 111, 114, 116, 32, 115, 101, 110, 116, 101, 110, 99, 101, 46 ] result = listOfChars(provided) # Turns the list `result` into a string `resultStr` resultStr = "" for char in result: resultStr += char print(resultStr)
87e08c29db5e459b67b54b1b7367cdb55f72a17d
frclasso/turma3_Python1_2018
/Cap05_Operadores_Basicos/op_associacao.py
310
3.921875
4
# in e not in pessoas = ['Fabio', 'Joao', 'Sandro', 'Douglas', 'Guilherme', 'Marcelo', 'Marcelo Caon', 'Mauricio'] print('Mauricio' in pessoas) # True print('Jessica' in pessoas) # False print('Jessica ' not in pessoas) # True # if => se if 'Fabio' in pessoas or 'Jessica' in pessoas: print('OK')
24546e17d82b0e0cde675a5f5162177d550d4522
DimpleOrg/PythonRepository
/Python Crash Course/vAnil/Chapter-10/10-11-part1.py
218
3.6875
4
# -*- coding: utf-8 -*- """ Created on Thu Jan 14 21:49:41 2021 @author: ANIL """ import json fav_num = input('Enter your favorite number: ') with open('fav_num.json', 'w') as f: json.dump(fav_num, f)
313b8533ab6fa8d263c25e2f3aae7ce1e783dbd5
blitu12345/spojCodes
/gregcontor.py
827
3.78125
4
def cloumn1(sum): n=0 p=True while(p): if(sum<=n*(n+1)/2): p=False return n else: n+=1 for i in range(input()): sum1=input() n=cloumn1(sum1) #print "n" #print n count=n*(n-1)/2 #print "count" #print count if(n%2==0): #print "if-1" a=1 b=n p=True #print "a" #print a #print "b" #print b while(p): #print "while-1" #print "count-while" #print count if(count==sum1-1): p=False print "TERM %d IS %d/%d" %(sum1,a,b) count+=1 a+=1 b-=1 #print "while-end" elif(n%2!=0): #print "if-2" b=1 a=n p=True #print "a1" #print a #print "b1" #print b while(p): #print "while2-1" #print "count2-while" #print count count+=1 b+=1 a-=1 if(count==sum1-1): p=False print "TERM %d IS %d/%d" %(sum1,a,b) #print "while-end2"
1977ddef769cbff86257b43a84e3a660c5092389
shg9411/algo
/algo_py/boj/bj2220.py
230
3.53125
4
n = int(input()) heap = [0, 1] for i in range(2, n+1): heap.append(i) heap[i], heap[i-1] = heap[i-1], heap[i] j = i-1 while j!=1: heap[j],heap[j//2] = heap[j//2],heap[j] j = j//2 print(*heap[1:])
26434cf9ea269ace4841bf1ec8c4d17ede18f067
DidiMilikina/DataCamp
/Machine Learning Scientist with Python/23. Winning a Kaggle Competition in Python/02. Dive into the Competition/07. Time K-fold.py
1,289
3.578125
4
''' Time K-fold Remember the "Store Item Demand Forecasting Challenge" where you are given store-item sales data, and have to predict future sales? It's a competition with time series data. So, time K-fold cross-validation should be applied. Your goal is to create this cross-validation strategy and make sure that it works as expected. Note that the train DataFrame is already available in your workspace, and that TimeSeriesSplit has been imported from sklearn.model_selection. Instructions 100 XP Create a TimeSeriesSplit object with 3 splits. Sort the train data by "date" column to apply time K-fold. Loop over each time split using time_kfold object. For each split select training and testing folds using train_index and test_index. ''' SOLUTION # Create TimeSeriesSplit object time_kfold = TimeSeriesSplit(n_splits=3) # Sort train data by date train = train.sort_values('date') # Iterate through each split fold = 0 for train_index, test_index in time_kfold.split(train): cv_train, cv_test = train.iloc[train_index], train.iloc[test_index] print('Fold :', fold) print('Train date range: from {} to {}'.format(cv_train.date.min(), cv_train.date.max())) print('Test date range: from {} to {}\n'.format(cv_test.date.min(), cv_test.date.max())) fold += 1
c1268b4bddddef1aeb0332094fe776e2581869ab
QkqBeer/PythonSubject
/面试练习/15.py
919
3.84375
4
__author__ = "那位先生Beer" def threeSum(nums): """ :type nums: List[int] :rtype: List[List[int]] """ #复杂度是n ** 2 # dic = {} # for num in nums: # dic[num] = dic.get(num, 0) + 1 # print(dic) nums.sort() reList = [] for i in range(len(nums)): if i > 0 and nums[i] == nums[i - 1]: continue l = i + 1 r = len(nums) - 1 while l < r: s = nums[i] + nums[l] + nums[r] if s == 0: reList.append([nums[i], nums[l], nums[r]]) l += 1 r -= 1 while l < r and nums[l] == nums[l - 1]: l += 1 while l < r and nums[r] == nums[r + 1]: r -= 1 elif s > 0: r -= 1 else: l += 1 return reList print(threeSum([-1, 0, 1, 2, -1, -4]))
59ce5f75542580020c3ea0c1b783faf6c992d57e
Tedworthy/ATLAST
/ast/node.py
1,289
3.5
4
''' Node This base class is the basic structure for all nodes in the abstract syntax tree for our first order logic grammar. ''' from codegen.symtable import SymTable class Node(object): def __init__(self, lineNo, position): self._lineNo = lineNo self._position = position self._children = [] self._numChildren = 0 self._symTable = None def getLineNo(self): return self._lineNo def getPosition(self): return self._position def getChild(self, num): if num >= self._numChildren: raise IndexError("Index", num, "out of bounds in Node.getChild") return self._children[num] def getChildren(self): return self._children def setChild(self, num, child): self._children.insert(num, child) self._numChildren += 1 def setChildren(self, children): self._children = children def setSymbolTable(self, symbolTable): self._symTable = symbolTable def generateSymbolTable(self, symbolTable): self._symTable = symbolTable for child in self.getChildren(): child.generateSymbolTable(symbolTable) def accept(self, visitor): for child in self.getChildren(): child.accept(visitor) visitor.visit(self) def __repr__(self): return "Class %s -> %s" % (self.__class__, self.getChildren())
33cbdedef379ff81d9a62df1b908f94099865173
MLN888/CDIOProject2020
/CircleDetectionImage.py
1,435
3.78125
4
import cv2 import numpy as np #https://www.geeksforgeeks.org/circle-detection-using-opencv-python/ # Read image. #img = cv2.imread('eyes.jpg', cv2.IMREAD_COLOR) cap = cv2.VideoCapture(cv2.CAP_DSHOW + 1) #cap = cv2.VideoCapture(0, cv2.CAP_DSHOW) #cap.set(cv2.cv.CV_CAP_PROP_FOURCC, cv2.cv.CV_FOURCC('M','J','P','G')) cap.set(cv2.CAP_PROP_FRAME_WIDTH,1280) cap.set(cv2.CAP_PROP_FRAME_HEIGHT,720) # Convert to grayscale. ret, img = cap.read() gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Blur using 3 * 3 kernel. gray_blurred = cv2.blur(gray, (3, 3)) # Apply Hough transform on the blurred image. detected_circles = cv2.HoughCircles(gray_blurred, cv2.HOUGH_GRADIENT, 1, 20, param1 = 50, param2 = 30, minRadius = 1, maxRadius = 40) # Draw circles that are detected. if detected_circles is not None: # Convert the circle parameters a, b and r to integers. detected_circles = np.uint16(np.around(detected_circles)) for pt in detected_circles[0, :]: a, b, r = pt[0], pt[1], pt[2] # Draw the circumference of the circle. cv2.circle(img, (a, b), r, (0, 255, 0), 2) # Draw a small circle (of radius 1) to show the center. cv2.circle(img, (a, b), 1, (0, 0, 255), 3) print(a) print(b) cv2.imshow("Detected Circle", img) cv2.imwrite("test.png", img) cv2.waitKey(0)
c9e5dc84b0d9847e4d5aa82fee81890998282232
EmonMajumder/All-Code
/Python/Hipsterslocal.py
1,260
4.0625
4
#Don't forget to rename this file after copying the template for a new program! """ Student Name: Emon Majumder Program Title: IT Programming Description: Assignment- 1 (Hipster Local) """ def main(): #<-- Don't change this line! #Write your code below. It must be indented! #1. Print name of shop #2. Input customer name #3. Input distance #4. Input cost of records #5. Assign value for tax rate and distance #6. Calculate delivery cost, purchase cost with tax and total cost #7. Print out put print ("Hipster's Local Vinyl Records- Customer Invoice") customerName= input ("\nCustomer's Name: ") distance= float (input ("Distance for Delivery (in Kilometers): ")) costofRecords= float(input ("Cost of records purchased: ")) deliveryCharge= int (15) salesTax= float (0.14) deliveryCost= distance*deliveryCharge purchaseCost=costofRecords*salesTax+costofRecords totalCost= deliveryCost+purchaseCost print ("\nPurchase summary for "+customerName.title ()) print("Delivery Cost: \t${0:.2f}".format(deliveryCost)+"\nPurchase Cost: \t${0:.2f}".format(purchaseCost)+"\nTotal Cost : \t${0:.2f}".format(totalCost)) #Do not change any of the code below! if __name__ == "__main__": main()
3e6e792b30affb72ed7ba497ebba4c9a14c7e5a3
awkwardbunny97/DangQuangAnh-Fundamentals-C4E32
/Session03/Homework/Turtle_Exercises/turtle_01.py
378
3.734375
4
from turtle import * for i in range(3): color('red') forward(100) left(120) for i in range(4): color('blue') forward(100) left(90) for i in range(5): color('brown') forward(100) left(72) for i in range(6): color('yellow') forward(100) left(60) for i in range(7): color('gray') forward(100) left(52) mainloop()
292ad196eaee7aab34dea95ac5fe622281b1a845
LJ1234com/Pandas-Study
/06-Function_Application.py
969
4.21875
4
import pandas as pd import numpy as np ''' pipe(): Table wise Function Application apply(): Row or Column Wise Function Application applymap(): Element wise Function Application on DataFrame map(): Element wise Function Application on Series ''' ############### Table-wise Function Application ############### def adder(ele1, ele2): return ele1 + ele2 df = pd.DataFrame(np.random.randn(5,3),columns=['col1','col2','col3']) print(df) df2 = df.pipe(adder, 2) print(df2) ############### Row or Column Wise Function Application ############### print(df.apply(np.mean)) # By default, the operation performs column wise print(df.mean()) print(df.apply(np.mean,axis=1)) # operations can be performed row wise print(df.mean(1)) df2 = df.apply(lambda x: x - x.min()) print(df2) ############### Element wise Function Application ############### df['col1'] = df['col1'].map(lambda x: x * 100) print(df) df = df.applymap(lambda x:x*100) print(df)
98d4a9997bac3ed19193bd018580635e2975bd9e
bkbhanu/mytrypy2
/functions.py
461
3.9375
4
def sqaure(n,a): return a**n x=1 a=1 n=2 while (x<=10): ## a = int(input("what is the number:")) ## n = int(input("What is the exponent:")) print(a) print(n) outFile=open('C:\Python34\programs\writefile2.txt','a') ## sq == square(n,a) ## print("returning",y) print("The result is: ", sqaure(n,a)) outFile.write('\nThe result is: '+ str(sqaure(n,a))) a=a+1 n=n+1 x=x+1 outFile.close()
930354b812871c2c41f004a5211293c36b8ac6f5
khinthandarkyaw98/Python_Practice
/ufunc_rounding_decimals.py
950
3.9375
4
# rounding decimals # There are primarily five ways of rounding off decimals in Numpy # truncation # fix # rounding # floor # ceil # Truncation # to integer closet to zero. Use the trunc() and fix() functions. # example # truncate elements of following array: import numpy as np arr = np.trunc([-3.1666, 3.6667]) print('truncation: ', arr) # remove the decimal points # round() increments preceding digit or decimal by 1 if >= 5 else do nothing. # if 3.1666 then 3.2 # import numpy as np arr = np.around(3.1666, 2) print("Around to 2 decimal places: ", arr) # floor() rounds off decimal to nearest lower integer. # import numpy as np arr = np.floor([-3.1666, 3.6667]) print("floor: ", arr) # floor() returns floats, unlike trunc() returns integers # ceil() rounds off decimal to nearest upper integer # import numpy as np arr = np.ceil([-3.1666, 3.6667]) print("Ceil: ", arr)
f2985a94c8d343182b92d75ef3c97144f16be89e
emmet-gingles/Python-Grades
/grade.py
399
3.90625
4
input = raw_input("Enter score between 0 and 1: "); try: score = float(input); if score >= 0 and score <= 1: if score >= 0.9: print "A"; elif score >= 0.7: print "B"; elif score >= 0.5: print "C"; elif score >= 0.4: print "D"; elif score < 0.4: print "F"; except: print "Invalid input";
fba88279ead81d1846bf85db59c1162896808c92
dtingg/Fall2018-PY210A
/students/DanCornutt/session02/fizz_buzz.py
375
3.53125
4
def fizz_buzz(high_num = 100): lst = list(range(1, high_num + 1)) fizz = list(range(3,101,3)) buzz = list(range(5,101,5)) for f in fizz: lst[f-1] = 'Fizz' for b in buzz: if isinstance(lst[b-1], str): lst[b-1] = lst[b-1] + 'Buzz' else: lst[b-1] = 'Buzz' for each in lst: print(each) fizz_buzz()
7a5c55bba2b0e9e49fd4dbe4d634d36f6a0ac9a9
jll2269/python
/20210329/list5.py
157
3.65625
4
L = [1, 2, 3] def Add10(i): return i+10 for i in map(Add10, L): print("Item: {0}".format(i)) X = [1, 2, 3] Y = [2, 3, 4] print(list(map(pow, X, Y)))
80450571bba3d9bdaf71b65ab346bda55437efa6
Athena1004/python_na
/venv/Scripts/nana/set.py
930
3.59375
4
s = set() print(type(s)) print(s) s = {1,2,3,4} print(type(s)) print(s) print("=" * 20 ) s1 = { } print(type(s1)) print(s1) s = {"lala","456",1,2,3} print(s) if 1 in s: print("cool") else: print("bad") s = {4,5,6,"i","love","money"} for i in s: print(i , end = " ") print("=" * 20 ) s = {(4,5,6),("i","love","money")} for k,m,n in s: print(k,"---",m,"---",n,"---") for i in s: print(i) s1 = {1,1,2,3,4,1} print(s1) ss = {i for i in s1} print(ss) sss = {i for i in s1 if i %2 == 0} print(sss) s1 = {1,2,3,4} s2 = {"i","love","money"} s = {m * n for m in s2 for n in s1} print(s) s = {23, 3, 4, 5} s.remove(4) print(s) s.discard(3) print(s) # s.remove(10) # print(s) # # s.discard(10) # print(s) s.pop() print(s) print(" 0 " * 20) s1 = {1,2,3,4,5,6} s2 = {5,6,7,8,9} s3 = s1.intersection(s2) print(s3) s4 = s1.difference(s2) print(s4) s5 = s1.issubset(s2) print(s5) s = frozenset() print(type(s))
5a0f25d200c96ddc6b2c8b336090f6cf0ccdb516
aaa-wen/Project-Euler
/Problem_7.py
280
3.671875
4
def prime(x): if (x == 1): return False i = 2 while i < x: if (x % i == 0): return False i = i+1 else: return True x = 2 count = 0 while count < 10001: print (x) if (prime(x) == True): x += 1 print (x) count += 1 print (count) else: x += 1 print (x)
2dde3b9130ee197923fa9232350b819b805a0435
rsmith-nl/misc
/splitdict.py
677
3.8125
4
# file: splitdict.py # vim:fileencoding=utf-8:fdm=marker:ft=python # # Copyright © 2018 R.F. Smith <[email protected]>. # SPDX-License-Identifier: MIT # Created: 2018-12-04T00:08:57+0100 # Last modified: 2018-12-04T00:18:19+0100 def splitdict(words): """Split a string of whitespace delimited words or a list/tuple of words into a dict definition. >>> splitdict('spam eggs foo bar') "{'spam': spam, 'eggs': eggs, 'foo': foo, 'bar': bar}" """ if isinstance(words, str): items = words.strip().split() elif type(words) in (list, tuple): items = [w.strip() for w in words] return "{" + ", ".join([f"'{item}': {item}" for item in items]) + "}"
3eaaf925c99e2436db9d03f4ed13513ec4c112d2
Pocom/Programming_Ex
/3_LongestSubstringWithoutRepeatingCharacters/t_1.py
697
3.5
4
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: str_list = list() ret_len = 0 for str in s: if str_list.count(str) != 0: # str exists in str_list print("列表中已有该元素: ", str) seq = str_list.index(str) ret_len = max(len(str_list), ret_len) str_list[:] = str_list[seq+1:]+[str] else: str_list.append(str) print("列表中有如下元素: ", str_list) ret_len = max(len(str_list), ret_len) return ret_len t = Solution() s = 'pwwkew' longestSubstring = t.lengthOfLongestSubstring(s) print(longestSubstring)
09855cfbd462b2365ffdce3e99f4c034b9f85cfe
hopnguyen123/Lab3_1_MatMaHoc
/Lab3_1/Task3.1/1_ 10 largest prime number under 10 first Mersenne prime numbers.py
1,217
3.640625
4
from random import randrange, getrandbits def Check_SoNguyenTo(n, k=128): if n <= 1: return False if n <= 3: return True s = 0 r = n - 1 while r & 1 == 0: s += 1 r //= 2 for _ in range(k): a = randrange(2, n - 1) x = pow(a, r, n) if x != 1 and x != n - 1: j = 1 while j < s and x != n - 1: x = pow(x, 2, n) if x == 1: return False j += 1 if x != n - 1: return False return True def is_mersenne(n): m=2**n-1 if Check_SoNguyenTo(m): return True return False list_1=[] for i in range(2,90): if Check_SoNguyenTo(i,128) and is_mersenne(i): x=2**i-1 list_1.append(x) list_2=[] for i in list_1: x = i -1 while x >=2: if Check_SoNguyenTo(x): list_2.append(x) break x=x-1 print("->> 10 first Mersenne prime numbers:") print(list_1) print("\n->> 10 largest prime number under 10 first Mersenne prime numbers") print(list_2) x = 618970019642690137449562111 -1 while x >=2: if Check_SoNguyenTo(x): print(x) break x=x-1
7337e1b5d21ef710901508369057c32e7147d11d
Dikaadityaoctaviana/Praktikum-metnum2
/lat gaus seidal.py
2,687
3.53125
4
# Iterasi Gauss Seidel # Definisikan Persamaan yang akan diselesaikan # Dalam bentuk dominan secara diagonal # Iterasi Gauss Seidel # Definisikan Persamaan yang akan diselesaikan # Dalam bentuk dominan secara diagonal f1 = lambda x,y,z: (-4+3*y-0*z)/4 f2 = lambda x,y,z: (40-2*x+5*z)/-4 f3 = lambda x,y,z: (14+0*x+2*y)/6 # Inisial awal x0 = 2 y0 = -8 z0 = 2 step = 1 # Input nilai galat/error e = float(input('Input Toleransi error: ')) # Implementasi iterasi Gauss Seidel print('\nStep\tx\ty\tz\n') condition = True while condition: x1 = f1(x0,y0,z0) y1 = f2(x1,y0,z0) z1 = f3(x1,y1,z0) print('%d\t%0.4f\t%0.4f\t%0.4f\n' %(step, x1,y1,z1)) e1 = abs(x0-x1); e2 = abs(y0-y1); e3 = abs(z0-z1); step +=1 x0 = x1 y0 = y1 z0 = z1 condition = e1>e and e2>e and e3>e print('\nSolusi: x=%0.3f, y=%0.3f and z = %0.3f\n'% (x1,y1,z1)) # Inisial awal x0 = 1 y0 = 2 z0 = 2 step = 1 # Input nilai galat/error e = float(input('Input Toleransi error: ')) # Implementasi iterasi Gauss Seidel print('\nStep\tx\ty\tz\n') condition = True while condition: x1 = f1(x0,y0,z0) y1 = f2(x1,y0,z0) z1 = f3(x1,y1,z0) print('%d\t%0.4f\t%0.4f\t%0.4f\n' %(step, x1,y1,z1)) e1 = abs(x0-x1); e2 = abs(y0-y1); e3 = abs(z0-z1); step +=1 x0 = x1 y0 = y1 z0 = z1 condition = e1>e and e2>e and e3>e print('\nSolusi: x=%0.3f, y=%0.3f and z = %0.3f\n'% (x1,y1,z1)) # Inisial awal x0 = 1 y0 = 2 z0 = 2 step = 1 # Input nilai galat/error e = float(input('Input Toleransi error: ')) # Implementasi iterasi Gauss Seidel print('\nStep\tx\ty\tz\n') condition = True while condition: x1 = f1(x0,y0,z0) y1 = f2(x1,y0,z0) z1 = f3(x1,y1,z0) print('%d\t%0.4f\t%0.4f\t%0.4f\n' %(step, x1,y1,z1)) e1 = abs(x0-x1); e2 = abs(y0-y1); e3 = abs(z0-z1); step +=1 x0 = x1 y0 = y1 z0 = z1 condition = e1>e and e2>e and e3>e print('\nSolusi: x=%0.3f, y=%0.3f and z = %0.3f\n'% (x1,y1,z1)) # Inisial awal x0 = 1 y0 = 2 z0 = 2 step = 1 # Input nilai galat/error e = float(input('Input Toleransi error: ')) # Implementasi iterasi Gauss Seidel print('\nStep\tx\ty\tz\n') condition = True while condition: x1 = f1(x0,y0,z0) y1 = f2(x1,y0,z0) z1 = f3(x1,y1,z0) print('%d\t%0.4f\t%0.4f\t%0.4f\n' %(step, x1,y1,z1)) e1 = abs(x0-x1); e2 = abs(y0-y1); e3 = abs(z0-z1); step +=1 x0 = x1 y0 = y1 z0 = z1 condition = e1>e and e2>e and e3>e print('\nSolusi: x=%0.3f, y=%0.3f and z = %0.3f\n'% (x1,y1,z1))
22e31f5529bcd5644c9c5121965318fe1a9f6d54
Ashvineekhatri/Vidhymaan_Autonetics
/attendence.py
3,606
3.71875
4
from tkinter import * from tkinter import ttk class Student: def __init__(self,root): self.root=root self.root.title("Student Management System") self.root.geometry("1350x700+0+0") title = Label(self.root, text="Student Management System",bd=10,relief=GROOVE,font=("times new roman",40,"bold"),bg="orange",fg="white") title.pack(side=TOP,fill=X) ##############MANAGE FRAME============================= Manage_Frame= Frame(self.root,bd=4,relief=RIDGE,bg="crimson") Manage_Frame.place(x=20,y=100,width=470,height=600) m_title=Label(Manage_Frame,text="Manage Students",bg="crimson",fg="white",font=("times new roman",30,"bold")) m_title.grid(row=0,columnspan=2,pady=20) lbl_roll = Label(Manage_Frame, text="Roll No.", bg="crimson", fg="white", font=("times new roman", 20, "bold")) lbl_roll.grid(row=1, column=0, padx=10,pady=10,sticky="w") txt_Roll=Entry(Manage_Frame, font=("times new roman", 15, "bold"),bd=2,relief=GROOVE) txt_Roll.grid(row=1, column=1, padx=20, pady=10, sticky="w") lbl_name = Label(Manage_Frame, text="Name", bg="crimson", fg="white", font=("times new roman", 20, "bold")) lbl_name.grid(row=2, column=0, padx=20, pady=10, sticky="w") txt_name = Entry(Manage_Frame, font=("times new roman", 15, "bold"), bd=2, relief=GROOVE) txt_name.grid(row=2, column=1, padx=20, pady=10, sticky="w") lbl_Email = Label(Manage_Frame, text="Email", bg="crimson", fg="white", font=("times new roman", 20, "bold")) lbl_Email.grid(row=3, column=0, padx=10, pady=10, sticky="w") txt_Email = Entry(Manage_Frame, font=("times new roman", 15, "bold"), bd=2, relief=GROOVE) txt_Email.grid(row=3, column=1, padx=20, pady=10, sticky="w") lbl_Gender = Label(Manage_Frame, text="Gender", bg="crimson", fg="white", font=("times new roman", 20, "bold")) lbl_Gender.grid(row=4, column=0, padx=10, pady=10, sticky="w") combo_Gender =ttk.Combobox(Manage_Frame,font=("times new roman", 13, "bold"),state='readonly') combo_Gender['values']=("male","female","other") combo_Gender.grid(row=4, column=1, padx=20, pady=10, sticky="w") lbl_Contact = Label(Manage_Frame, text="Contact", bg="crimson", fg="white", font=("times new roman", 20, "bold")) lbl_Contact.grid(row=5, column=0, padx=10, pady=10, sticky="w") txt_Contact = Entry(Manage_Frame, font=("times new roman", 15, "bold"), bd=2, relief=GROOVE) txt_Contact.grid(row=5, column=1, padx=20, pady=10, sticky="w") lbl_dob = Label(Manage_Frame, text="D.O.B", bg="crimson", fg="white", font=("times new roman", 20, "bold")) lbl_dob.grid(row=6, column=0, padx=10, pady=10, sticky="w") txt_dob = Entry(Manage_Frame, font=("times new roman", 15, "bold"), bd=2, relief=GROOVE) txt_dob.grid(row=6, column=1, padx=20, pady=10, sticky="w") lbl_address = Label(Manage_Frame, text="Address", bg="crimson", fg="white", font=("times new roman", 20, "bold")) lbl_address.grid(row=7, column=0, padx=10, pady=10, sticky="w") txt_address = Text(Manage_Frame,width=20,height=4, font=("times new roman", 15, "bold"), bd=2, relief=GROOVE) txt_address.grid(row=7, column=1, padx=20, pady=10, sticky="w") #=========================Detail FRAME============================= Detail_Frame=Frame(self.root,bd=4,relief=RIDGE,bg="crimson") Detail_Frame.place(x=500,y=100,width=830,height=600) root =Tk() ob=Student(root) root.mainloop()
7939fd860fadd8084fa5d5e2d970eb87fae85d8d
irisnunezlpsr/class-samples
/codetotest.py
181
3.984375
4
print("What is your favorite number?") number = (input()) while number != 14: print("Pick another number!") number = (input()) if number == 14: print("That's the best number!")
bd6f648911b803d558231afe82e5951091314bc1
dkoh12/gamma
/CtCI/python/bits.py
1,510
3.65625
4
# 5.1 def MinN(M, N, i, j): M = int(M, 2) N = int(N, 2) # print(M, bin(M), N, bin(N)) # print(i, j) count = i while M > 0: bit = M & 1 N = (bit << count) | N M = M >> 1 count += 1 # print("M", M, bin(M)) # print("N", N, bin(N)) return bin(N) # 5.6 def conversion(a, b): count = 0 num = a ^ b while num > 0: if (num & 1) == 1: count +=1 num = num >> 1 return count # 5.4 very hacky def pair(num): if num == 1: return (1, 1) n = num count = 0 large = 0 small = 0 while len(bin(n))-2 > 0: bit = n & 1 if bit == 1: large = (num & ~(1 << count)) | (1 << (count+1)) small = (num & ~(1 << count)) | (1 << (count-1)) # small = ~(num ^ (-1 << count)) return (small, large) count += 1 n = n >> 1 """ 5L and 3L cups. Make exactly 4L fill up 5L and pour into 3L >> 2L and 3L throw out the 2L away or throw out 3L away >> 0L and 3L 0L and 2L pour 3L into 5L or pour 2L into 3L cup >> 3L and 0L 2L and 0L fill up 3L or fill up 5L cup >> 3L and 3L 2L and 5L pour 3L into 5L or fill up 3L cup >> 5L and 1L 3L and 4L throw away 5L >> 0L and 1L pour 1L into 5L >> 1L and 0L fill up 3L >> 1L and 3L pour 3L into 5L and get 4L >> 4L and 0L """ if __name__=="__main__": N = "10000000000" M = "10011" i = 2 j = 6 print(MinN(M, N, i, j)) a = 29 b = 15 print(conversion(a, b)) print(pair(10))
589c2abe9d84cc15965bb55cc32862929d1c7f2f
alosaft/NatassjaBot
/graph.py
2,154
3.578125
4
class Transition: def __init__ (self, answer, condition, node_to_go): self.answer = answer self.condition = condition self.node_to_go = node_to_go pass class Node: def __init__ (self, question, transitions, actions): self.question = question self.transitions = transitions self.actions = actions @classmethod def leaf (cls, actions): return cls(None, None, actions) def act(self): for action in self.actions: action() def visit(self): self.act() # Si el nodo es hoja if not self.transitions: print('hoja' + str(self.actions)) return None res = input(self.question) # Si el nodo es interno for tt in self.transitions: print('checking ' + tt.answer) if(tt.condition(res)): print('it is '+ tt.answer) print(tt.node_to_go) return tt.node_to_go return self italia = Node.leaf([ lambda : print('italia') ]) countries = Node('a que pais quieres ir?', [ Transition('italia', lambda name: name == 'italia', Node.leaf([ lambda : print('italia') ])), Transition('polonia', lambda name: name == 'polonia', Node.leaf([ lambda : print('polonia') ])), Transition('inglaterra', lambda name: name == 'inglaterra', Node.leaf([ lambda : print('inglaterra') ])), Transition('francia', lambda name: name == 'francia', Node.leaf([ lambda : print('francia') ])), Transition('paises bajos', lambda name: name == 'paises bajos', Node.leaf([ lambda : print('paises bajos') ])) ], [ lambda: print('action1'), lambda: print('action2'), lambda: print('action2'), lambda: print('action2'), lambda: print('action2'), lambda: print('action2'), lambda: print('action2') ]) act_node = countries print(act_node.question) while act_node: act_node = act_node.visit()
97f3569d1328633e511b8866e21ab0e95c441940
SrikanthParsha14/test
/testpy/timezonecalc.py
236
3.515625
4
from datetime import datetime from datetime import timedelta date = datetime.utcnow() print "PC's Local Time is", datetime.now() print "CN Beijing Time is", date+timedelta(hours=8) print "US Pacific Time is", date+timedelta(hours=-8)
3f03207d052cc47b36c8e21d5d60132317ce73d1
terzeron/PythonTest
/asyncio/test03.py
565
3.59375
4
#!/usr/bin/env python import sys import asyncio async def my_coroutine(task_name, seconds_to_sleep=3): print("%s sleeping for %d seconds" % (task_name, seconds_to_sleep)) await asyncio.sleep(seconds_to_sleep) print("%s is finished" % (task_name)) async def main(): tasks = [ my_coroutine('task1', 4), my_coroutine('task2', 3), my_coroutine('task3', 2)] for task in tasks: #print(task) await asyncio.create_task(task) #await task if __name__ == "__main__": sys.exit(asyncio.run(main()))
ee515c5e8864a5a29494a03acb8503471ec2d922
avalool/Python-Code
/HospitalTemp.py
375
4.03125
4
"""program that prints out a health warning message if one of the patient temperatures is higher than 40 degrees Celsius""" #Temperatures: 36, 32, 45, 38 temperatures = ['36', '32', '45', '38'] for temperature in temperatures: if temperature == '45': print('Warning, possible COVID patient! Isolate immediately.') else: print('No infected patients')
3a03368d5b16d37b6044ca4a356ff6f5374b4ec7
ZJocelyn/sy2.1-server
/server.py
2,496
3.65625
4
# coding:utf8 ''''创建服务器端程序,用来接收客户端传进的字符数据''' from socket import * #引入socket模块内的函数,创建一个套接口 from time import ctime #引入time模块内的ctime()函数,ctime()函数会显示当前日期与时间 def server(): #定义server端函数 HOST = '127.0.0.1' #指定服务器ip为本机ip地址 PORT = 65533 #指定监听端口为65533 ADDR = (HOST,PORT) #指定地址,以元组(host,port)的形式表示地址 server_socket = socket(AF_INET,SOCK_STREAM) #建立服务器之间的网络通信,建立基于TCP的流式套接口(SOCK_STREAM 类型是基于TCP的,有保障的面向连接的socket) server_socket.bind(ADDR) #调用服务端的bind(address)函数,将套接字绑定到指定地址 server_socket.listen(5) #调用服务器端listen(backlog)监听函数开始监听TCP传入连接,backlog指定在拒绝连接之前,操作系统可以挂起的最大连接数量,该值至少为1,大部分应用程序设为5即可。 while True: print 'Waiting for connecting ......' #显示'Waiting for connecting ......'等待client端发送数据 tcpclientsocket,addr = server_socket.accept() #调用服务器端accept()函数,接受client端TCP连接 print 'Connected by ',addr #显示连接端地址 while True: data = serversocket.recv(1024) #服务器接收来自客户端的数据,数据以字符串形式返回,bufsize指定要接收的最大数据量。 if not data: #如果服务器没有接受到数据则跳出循环 break print data #显示从客户端接收到的数据 data = raw_input('Server>>') #调用raw_input()函数,读取在服务器端输入的内容,将数据以字符型式输出 serversocket.send('[%s]%s'%(ctime(),data)) #发送TCP数据,将字符型数据发送到连接的客户端,客户端在收到数据同时也会收到接收数据的时间。 servertsocket.close() #一次会话结束,调用close()函数关闭套接字连接 server_socket.close() #会话结束,调用close()函数关闭服务器套接字 server()
1290eb7cd1d5c6c4d1fca084dfc1c61165f2127c
saetar/pyEuler
/done/py/euler_046.py
1,009
3.875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # Jesse Rubin - project Euler """ Goldbach's other conjecture Problem 46 It was proposed by Christian Goldbach that every odd composite number can be written as the sum of a prime and twice a square. 9 = 7 + 2×1^2 15 = 7 + 2×2^2 21 = 3 + 2×3^2 25 = 7 + 2×3^2 27 = 19 + 2×2^2 33 = 31 + 2×1^2 It turns out that the conjecture was false. What is the smallest odd composite that cannot be written as the sum of a prime and twice a square?. """ from bib.amazon_prime import is_prime from math import sqrt def p046(): n = 3 prime_numbers = set() prime_numbers.add(2) while True: if is_prime(n): prime_numbers.add(n) else: for p in prime_numbers: if sqrt(((n-p)/2)) == int(sqrt(((n-p)/2))): break # break if it works with the conjecture else: return n n += 2 if __name__ == '__main__': answer = p046() print("ANSWER: {}".format(answer))
e2c7876bc034d166dda2491e4f35e8b6600af5ae
aramian-wasielak/python-snippets
/src/snippets/tree.py
1,005
3.75
4
import unittest class TreeNode: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right class TestTreeMethods(unittest.TestCase): @staticmethod def generate_tree(depth): root = node = TreeNode(1) for i in range(depth - 1): node.left = TreeNode(i + 2) node = node.left return root def test_tree_depth_dfs_iterate(self): test_depth = 10 root = self.generate_tree(test_depth) depth = 1 stack = [(root, 1)] while len(stack) > 0: node, cur_depth = stack.pop() if node is not None: depth = max(depth, cur_depth) stack.append([node.left, cur_depth + 1]) stack.append([node.right, cur_depth + 1]) self.assertEqual(test_depth, depth) def test_tree_depth_bfs_iterate(self): # TODO: pass if __name__ == "__main__": unittest.main()
2b4a5b7fd6caa98a32b12fbc5e5eb020ea129661
alicesilva/P1-Python-Problemas
/palavras.py
518
3.765625
4
# coding: utf-8 # Aluna: Alice Fernandes Silva /UFCG, 2015.1, Programação 1 # Mais ocorrência caractere palavras = [] while True: palavra = raw_input() if palavra == "fim": break palavras.append(palavra) caractere = raw_input() N = int(raw_input()) lista1 = [] for i in range(len(palavras)): cont_acima = 0 for item in palavras[i]: if item == caractere: cont_acima += 1 if cont_acima > N: lista1.append(palavras[i]) print palavras[i] break if len(lista1) == 0: print "Nenhuma palavra encontrada."
0dbe0f1f164f3ebe136352fe8eaeb0292b313969
Madhav2108/udemy-python-as
/function/intro/swapfuc.py
139
4.09375
4
def swap(x, y): temp = x; x = y; y = temp; print(x) print(y) x = 2 y = 3 swap(x, y) print(x) print(y)
ee5ab229d06fb8ebc08af5950ccd67025608893e
Burymis/PY4E
/Exer_C3_3.py
651
3.59375
4
# Exercises, part 3 Conditional execution # https://www.py4e.com/html3/03-conditional # Exercis 3: def grade(score): try: score = float(score) if score > 1: user_grade = "Bad score!" elif score >= 0.9: user_grade = "A" elif score >= 0.8: user_grade = "B" elif score >= 0.7: user_grade = "C" elif score >= 0.6: user_grade = "D" else: user_grade = "F" except: user_grade = "Bad score!" return user_grade inp = input("Write Your score:\n") print(grade(inp)) input("Press Enter to terminate")
d9c42239586aeb317254ec62f1d07d56e4e38e46
leealessandrini/bakingcake
/bakingcake/stocks.py
1,314
3.515625
4
""" This module will house all stock related functions. """ import datetime import pandas as pd from iexfinance.stocks import get_historical_data def get_price_action( ticker_list, start=datetime.datetime.today() - datetime.timedelta(days=31), end=datetime.datetime.today() - datetime.timedelta(days=1)): """ This method will pull the stock price volatility given a list of tickers and a start and end date. Args: ticker_list (list): list of tickers start (datetime.datetime): start date end (datetime.datetime): end date Returns: historical pricing DataFrame """ cols = ["ticker", "open", "close", "low", "high", "changePercent"] price_action_list = [] # Iterate over each ticker and add information to the DataFrame for ticker in ticker_list: df = get_historical_data(ticker, start, end) df["ticker"] = ticker # Set name of index to date df.index = df.index.set_names(['date']) # Cast values to floating point numbers for column in cols[1:]: df[column] = df[column].astype(float) # Append DataFrame to list price_action_list.append(df.loc[:, cols]) return pd.concat(price_action_list).reset_index()
5fdef4f708a876c33329509df5ff3626ffd8c903
uthambathoju/30days_leetcode_april_challenge
/group_anagrams.py
2,818
3.5625
4
import collections class Solution: def groupAnagrams(self, strs): hash_table = {} temp_anagrams = [] ang_list = [] #print(strs) """ if all('' == space for space in strs): ang_list.append(strs) return ang_list str_unq = len(list(set(strs))) if(str_unq == 1): ang_list.append(strs) return ang_list """ for ele in strs: hash_table[ele] = len(ele) #print(hash_table) for ele in strs: #print("ele :: " , ele) #break anagrams = [] if ele not in temp_anagrams : listOfKeys = [key for (key, value) in hash_table.items() if value == len(ele)] #anagrams.append(ele) #ele_chars = list(ele) for eq_strs in listOfKeys: ctr = 0 #if eq_strs != ele: check = list(ele) if(check == ''): check = ' ' #print("chars :: " , eq_strs) for k in check: #print("check :: " , check) if k in eq_strs: ctr += 1 if ctr == len(eq_strs): if eq_strs == ' ': anagrams.append('') else: anagrams.append(eq_strs) #print("SUCCESS" , anagrams) #print(" anagrams :: " , anagrams) if anagrams: ang_list.append(anagrams) temp_anagrams = [item for sublist in ang_list for item in sublist] #print(" ang_list :: " , ang_list) #print(" temp_anagrams :: " , temp_anagrams) return ang_list def groupAnagrams2(self , strs): ans = collections.defaultdict(list) for s in strs: count = [0] * 26 for c in s: count[ord(c) - ord('a')] += 1 ans[tuple(count)].append(s) return ans.values() def groupAnagrams3(self, strs): print(strs) result = collections.defaultdict(list) for ele in strs: key = tuple(sorted(ele)) result[key].append(ele) return result.values() if __name__ == "__main__": print(Solution().groupAnagrams3(["eat", "tea", "tan", "ate", "nat", "bat"])) #print(Solution().groupAnagrams(["eat", "tea", "tan", "ate"])) #print(Solution().groupAnagrams([" ","b"]))
53e2a0a7eed63ff673edd590c319b189474dcbcc
windard/leeeeee
/925.long-pressed-name.py
2,532
3.640625
4
# coding=utf-8 # # @lc app=leetcode id=925 lang=python # # [925] Long Pressed Name # # https://leetcode.com/problems/long-pressed-name/description/ # # algorithms # Easy (44.38%) # Likes: 266 # Dislikes: 34 # Total Accepted: 19.9K # Total Submissions: 44.8K # Testcase Example: '"alex"\n"aaleex"' # # Your friend is typing his name into a keyboard.  Sometimes, when typing a # character c, the key might get long pressed, and the character will be typed # 1 or more times. # # You examine the typed characters of the keyboard.  Return True if it is # possible that it was your friends name, with some characters (possibly none) # being long pressed. # # # # Example 1: # # # Input: name = "alex", typed = "aaleex" # Output: true # Explanation: 'a' and 'e' in 'alex' were long pressed. # # # # Example 2: # # # Input: name = "saeed", typed = "ssaaedd" # Output: false # Explanation: 'e' must have been pressed twice, but it wasn't in the typed # output. # # # # Example 3: # # # Input: name = "leelee", typed = "lleeelee" # Output: true # # # # Example 4: # # # Input: name = "laiden", typed = "laiden" # Output: true # Explanation: It's not necessary to long press any character. # # # # # # # # Note: # # # name.length <= 1000 # typed.length <= 1000 # The characters of name and typed are lowercase letters. # # # # # # # # # # # # class Solution(object): def isLongPressedName(self, name, typed): """ :type name: str :type typed: str :rtype: bool """ if len(typed) < len(name): return False index = 0 n_index = 0 last = None while index < len(typed): if n_index < len(name) and typed[index] == name[n_index]: last = typed[index] index += 1 n_index += 1 else: if last == typed[index]: index += 1 else: return False if n_index <= len(name) - 1: return False return True # if __name__ == '__main__': # s = Solution() # print s.isLongPressedName("alex", "aaleex") # print s.isLongPressedName("saeed", "ssaaedd") # False # print s.isLongPressedName("leelee", "lleeelee") # print s.isLongPressedName("laiden", "laiden") # print s.isLongPressedName("vtkgn", "vttkgnn") # print s.isLongPressedName("vtkgn", "vttkgnne") # print s.isLongPressedName("pyplrz", "ppyypllr")
0ab4a7daca04a783f66ed7d6ec066f8e080b092c
sudarsan005/Yelp_Top_Businesses
/yelp_ranking_v2.py
6,438
3.890625
4
""" This code queries data by using the Search API to query for businesses by a search term,location and category. The data is then ranked using True Bayesian Estimate method and Top 50 from the result in the search criteria is printed in the console. This Code also generates two files " Top50_Ranked_Data_"Date/Time" "-Contains top 50 records of the rank system and "Ranked_Data_all"Date/Time""- contains all records sorted with new ranking system. Sample usage of the program: `python yelp_ranking.py --term="cafe" --location="San Francisco, CA" --category="cafes"` """ import argparse import json import sys import urllib import urllib2 import pandas as pd import oauth2 import time #from yelpapi import YelpAPI #250-25 API_HOST = 'api.yelp.com' DEFAULT_TERM = 'cafe' DEFAULT_LOCATION = 'San Francisco, CA' SEARCH_LIMIT = 20 MIN_VOTE=250 DEFAULT_CATEGORY = 'cafes' SEARCH_PATH = '/v2/search/' BUSINESS_PATH = '/v2/business/' # OAuth credential placeholders that must be filled in by users. CONSUMER_KEY = 'Enter your CONSUMER_KEY here' CONSUMER_SECRET = 'Enter your CONSUMER_SECRET here' TOKEN = 'Enter your Token here' TOKEN_SECRET = 'Enter your Token _Secret here' def request(host, path, url_params=None): """Prepares OAuth authentication and sends the request to the API. Args: host (str): The domain host of the API. path (str): The path of the API after the domain. url_params (dict): An optional set of query parameters in the request. Returns: dict: The JSON response from the request. Raises: urllib2.HTTPError: An error occurs from the HTTP request. """ url_params = url_params or {} url = 'http://{0}{1}?'.format(host, urllib.quote(path.encode('utf8'))) consumer = oauth2.Consumer(CONSUMER_KEY, CONSUMER_SECRET) oauth_request = oauth2.Request(method="GET", url=url, parameters=url_params) oauth_request.update( { 'oauth_nonce': oauth2.generate_nonce(), 'oauth_timestamp': oauth2.generate_timestamp(), 'oauth_token': TOKEN, 'oauth_consumer_key': CONSUMER_KEY } ) token = oauth2.Token(TOKEN, TOKEN_SECRET) oauth_request.sign_request(oauth2.SignatureMethod_HMAC_SHA1(), consumer, token) signed_url = oauth_request.to_url() print u'Querying {0} ...'.format(url) conn = urllib2.urlopen(signed_url, None) try: response = json.loads(conn.read()) finally: conn.close() return response def search(term, location, offset, category): """Query the Search API by a search term and location. Args: term (str): The search term passed to the API. location (str): The search location passed to the API. offset (int): The starting value of search index passed to the API. category (str): The search category passed to the API. Returns: dict: The JSON response from the request. """ #http://api.yelp.com/v2/search/?location=San Francisco, CA&category_filter=cafes url_params = { 'term': term.replace(' ', '+'), 'location': location.replace(' ', '+'), 'offset': offset, 'limit': SEARCH_LIMIT, 'category_filter': category.replace(' ', '+'), } return request(API_HOST, SEARCH_PATH, url_params=url_params) def rank_results(term, location, category): """Queries the API by the input values from the user. Args: term (str): The search term to query. location (str): The location of the business to query. category (str): The search category passed to the API. Description: Uses Bayes Estimator algorithm to rank the system """ response = search(term, location,0,category) total = response.get('total') ind=0 r_sum=0 """store the required parameters from json obect into a dataframe""" yelp_df = pd.DataFrame(columns=['Name','R_Count','Yelp_Rating']) """increment the offset value by 20 as YELP api allows only a max of 20 results per api call""" for i in xrange(0,total,20): response=search(term, location, i,category) businesses = response.get('businesses') for j in response['businesses']: name=j['name'] v_count = j["review_count"] rating = j["rating"] r_sum=r_sum+j["rating"] yelp_df.loc[ind] = pd.Series({'Name':name, 'R_Count':v_count, 'Yelp_Rating':rating}) ind=ind+1 print 'Total number of results found: ', total r_avg=r_sum/(total) """The formula for Bayesian Estimate: WR = (vR+mC)/(v+m) where WR-weighted Rating R = yelp review of each businesses in the dataset = (Review) v = number of review count for businesses in the dataset = (Review Count) m = minimum votes required (assumed 250) C = average yelp review of the businesses in the dataset (mean) """ yelp_df['WR'] = ((yelp_df['R_Count']*yelp_df['Yelp_Rating'])+(MIN_VOTE*r_avg))/(yelp_df['R_Count']+MIN_VOTE) yelp_df=yelp_df.sort(['WR'], ascending=[0]) print 'Top 50 Ranked' + term +'in' + 'location' print yelp_df[['Name','WR','Yelp_Rating']].head(50) businesses = response.get('businesses') res_filename = 'Top50_Ranked_Data_' + time.strftime("%m%d%Y-%HH%MM%SS") yelp_df.head(50).to_csv(res_filename+'.csv', sep='\t',encoding='utf-8',index=False) yelp_df.to_csv('Ranked_Data_'+'all'+time.strftime("%m%d%Y-%HH%MM%SS")+'.csv', sep='\t',encoding='utf-8',index=False) if not businesses: print u'No businesses for {0} in {1} found.'.format(term, location) return def main(): parser = argparse.ArgumentParser() parser.add_argument('-q', '--term', dest='term', default=DEFAULT_TERM, type=str, help='Search term (default: %(default)s)') parser.add_argument('-l', '--location', dest='location', default=DEFAULT_LOCATION, type=str, help='Search location (default: %(default)s)') parser.add_argument('-c', '--category', dest='category', default=DEFAULT_CATEGORY, type=str, help='Search category (default: %(default)s)') input_values = parser.parse_args() try: rank_results(input_values.term, input_values.location, input_values.category) except urllib2.HTTPError as error: sys.exit('Encountered HTTP error {0}. Abort program.'.format(error.code)) if __name__ == '__main__': main()
73df1c31a5ad0c35c90dfc4fea4dffe14cedf4fe
Infinidrix/competitive-programming
/Take 2 Week 1/isPalindrome.py
745
3.84375
4
# https://leetcode.com/problems/palindrome-linked-list # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def isPalindrome(self, head: ListNode) -> bool: if head == None: return True length = 1 prev = head next = head.next while next != None: length += 1 next.prev = prev prev = next next = next.next start = head end = prev while length >= 2: if start.val != end.val: return False start = start.next end = end.prev length -= 2 return True
63eeb95dbc9eafa087ea55bfacd8c1a983ae1707
austinsonger/CodingChallenges
/Hackerrank/_Contests/Project_Euler/Python/pe074.py
1,454
3.78125
4
''' Digit factorial chains Problem 74 The number 145 is well known for the property that the sum of the factorial of its digits is equal to 145: 1! + 4! + 5! = 1 + 24 + 120 = 145 Perhaps less well known is 169, in that it produces the longest chain of numbers that link back to 169; it turns out that there are only three such loops that exist: 169 → 363601 → 1454 → 169 871 → 45361 → 871 872 → 45362 → 872 It is not difficult to prove that EVERY starting number will eventually get stuck in a loop. For example, 69 → 363600 → 1454 → 169 → 363601 (→ 1454) 78 → 45360 → 871 → 45361 (→ 871) 540 → 145 (→ 145) Starting with 69 produces a chain of five non-repeating terms, but the longest non-repeating chain with a starting number below one million is sixty terms. How many chains, with a starting number below one million, contain exactly sixty non-repeating terms? ''' __author__ = 'SUN' factorial = [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880] def next_number(n): factorial_sum = 0 while n != 0: factorial_sum += factorial[n % 10] n //= 10 return factorial_sum def chain_len(n): chain = [] while not chain.__contains__(n): chain.append(n) n = next_number(n) return len(chain) if __name__ == '__main__': res = 0 for i in range(1000000): if chain_len(i) == 60: res += 1 print(res)
c1807d4cdcdee1629e6278298d28509df5ad2908
mgclarkson/lqsninohtyp
/test/drop_demo.py
3,640
3.5625
4
======================================================= ##################### ### Original Python2 File: ### drop.py2 ##################### #!/usr/bin/env python2.py for i in range(10): print i, print sql: CREATE TABLE Customers ( name VARCHAR(100) , last VARCHAR(15), phone int ) INSERT INTO Customers VALUES ('Phil', 'Cannata', 7735647) INSERT INTO Customers VALUES ('Matthew', 'Clarkson', 9875643) INSERT INTO Customers VALUES ('Joaquin', 'Casares', 3451878) INSERT INTO Customers VALUES ('Joaquin', 'Joaquin', 9345879) INSERT INTO Customers VALUES ('Joaquin', 'Joaquin', 5123789) INSERT INTO Customers VALUES ('Joaquin', 'Guadalupe', 8845748) PRINT SELECT * FROM Customers DROP INDEX name ON Customers PRINT SELECT * FROM Customers DROP INDEX blah ON Customers DROP TABLE Nope DROP TABLE Customers DATABASEPRINT :sql ======================================================= ### Converted Python File: #!/usr/bin/env python2.py for i in range(10): print i, print print 'Customers:' print '|---------------------------------------------------' print '| name | last | phone |' print '|---------------------------------------------------' print '| Phil | Cannata | 7735647 |' print '| Matthew | Clarkson | 9875643 |' print '| Joaquin | Casares | 3451878 |' print '| Joaquin | Joaquin | 9345879 |' print '| Joaquin | Joaquin | 5123789 |' print '| Joaquin | Guadalupe | 8845748 |' print '|---------------------------------------------------' print 'Customers:' print '|----------------------------------' print '| last | phone |' print '|----------------------------------' print '| Cannata | 7735647 |' print '| Clarkson | 9875643 |' print '| Casares | 3451878 |' print '| Joaquin | 9345879 |' print '| Joaquin | 5123789 |' print '| Guadalupe | 8845748 |' print '|----------------------------------' print "Database:" print "current_record:6" print "datatypes:{}" print "triples:[]" print "valid_datatypes:['VARCHAR', 'INT', 'CHAR', 'TEXT', 'BIT', 'BIGINT', 'REAL']" print ======================================================= ### Console Output: Field: blah does not exist. Table unchanged. Table: Nope does not exist. Database unchanged. 0 1 2 3 4 5 6 7 8 9 Customers: |--------------------------------------------------- | name | last | phone | |--------------------------------------------------- | Phil | Cannata | 7735647 | | Matthew | Clarkson | 9875643 | | Joaquin | Casares | 3451878 | | Joaquin | Joaquin | 9345879 | | Joaquin | Joaquin | 5123789 | | Joaquin | Guadalupe | 8845748 | |--------------------------------------------------- Customers: |---------------------------------- | last | phone | |---------------------------------- | Cannata | 7735647 | | Clarkson | 9875643 | | Casares | 3451878 | | Joaquin | 9345879 | | Joaquin | 5123789 | | Guadalupe | 8845748 | |---------------------------------- Database: current_record:6 datatypes:{} triples:[] valid_datatypes:['VARCHAR', 'INT', 'CHAR', 'TEXT', 'BIT', 'BIGINT', 'REAL']
9861904200baadaa299243a943434ee5ab3d1416
YektaAkhalili/Hello-World
/Hello-World.py
204
4.3125
4
#just a silly code to put on Github for starters! #written May 16th, 2019 n = input("Hey there, What's your name?") print("I wanted to say Hello, World! But, you're not World! You're {}!".format(n))
d4e8a0ca8fea05edbb1808ab6b16632c79e783a3
DylanFouche/RaspberryPi
/Prac1/main.py
1,799
3.546875
4
#!/usr/bin/python3 """ Names: Dylan Fouche Student Number: FCHDYL001 Prac: Prac 1 Date: 22/07/2019 """ # import Relevant Librares import RPi.GPIO as GPIO from time import sleep #integer to store counter value count = 0 #bools to store led state bit_0 = 0 bit_1 = 0 bit_2 = 0 def init_GPIO(): #config GPIO GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) #config inputs GPIO.setup(5, GPIO.IN) GPIO.setup(6, GPIO.IN) #config outputs GPIO.setup(17, GPIO.OUT) GPIO.setup(27, GPIO.OUT) GPIO.setup(22, GPIO.OUT) #config interrupts GPIO.add_event_detect(5, GPIO.RISING, callback=increment, bouncetime=500) GPIO.add_event_detect(6, GPIO.RISING, callback=decrement, bouncetime=500) #tracing print("GPIO configured.") def increment(arg): global count count += 1 def decrement(arg): global count count -= 1 def updateLEDs(): global bit_0 global bit_1 global bit_2 #update led state GPIO.output(17,bit_0) GPIO.output(27,bit_1) GPIO.output(22,bit_2) def main(): global count global bit_0 global bit_1 global bit_2 #update binary values if count & 0b1: bit_0 = 1 else: bit_0 = 0 if count & 0b10: bit_1 = 1 else: bit_1 = 0 if count & 0b100: bit_2 = 1 else: bit_2 = 0 #reflect change on leds updateLEDs() if __name__ == "__main__": try: #set up GPIOs init_GPIO() #loop our main function indefinitely while True: main() except KeyboardInterrupt: print("Exiting gracefully") # Turn off GPIOs GPIO.cleanup() except e: # Turn off GPIOs GPIO.cleanup() print("Some other error occurred") print(e.message)
dba0d69ba88bac69a74bea766bf12be9beaa7a4b
michaelstrefeler/100daysofcode-with-python-course
/days/37-39-csv-data-analsys/alcohol_consumption_analysis/analyse.py
1,482
3.53125
4
from os import path from csv import DictReader from collections import namedtuple from typing import List data = [] Record = namedtuple( 'Record', 'country, beer_servings, spirit_servings, wine_servings,' 'total_litres_of_pure_alcohol') def get_data(): base_folder = path.dirname(__file__) filename = path.join(base_folder, 'data', 'drinks.csv') with open(filename, 'r', encoding='utf-8') as file: reader = DictReader(file) data.clear() for row in reader: record = format_row(row) data.append(record) return data def get_countries(): return [c.country for c in data] def format_row(row): row['beer_servings'] = int(row['beer_servings']) row['spirit_servings'] = int(row['spirit_servings']) row['wine_servings'] = int(row['wine_servings']) row['total_litres_of_pure_alcohol'] = float( row['total_litres_of_pure_alcohol']) return Record(**row) def get_country_stats(choice) -> List[Record]: return [c for c in data if c.country == choice] def beeriest_countries() -> List[Record]: return sorted(data, key=lambda r: -r.beer_servings) def hightest_spirit_countries() -> List[Record]: return sorted(data, key=lambda r: -r.spirit_servings) def winiest_countries() -> List[Record]: return sorted(data, key=lambda r: -r.wine_servings) def alcohlic_countries() -> List[Record]: return sorted(data, key=lambda r: -r.total_litres_of_pure_alcohol)
0c4c47abc6e5c8bd439659850c09ae659b11695d
Rapak/hello-world
/lesson2-1/Task3.py
159
3.75
4
a = (1,2,3,3,5,5,5,1,1) b = (1, 'a',2,3,2,'a') uniq_el = set(a) rez = list(uniq_el) print(rez) uniq_el2 = set(b) rez2 = list(uniq_el2) print(rez2)
c98b7e874549bb11196f36310dba0ce0659c4fc5
digipodium/string-and-string-functions-AdityaKD88
/string_in_uppercase.py
94
3.765625
4
#6. Convert the string "How are you?" in uppercase msg = "How are you?" print(msg.upper())
4288d6a1782a5a840fc39ec588202c9be25feb95
jaycamp23/tlg_learning_python
/elif.py
277
4.09375
4
age = 31 age = float(input('how old are you:')) if age >= 35: print('you are old enough to be a senator or the president') elif age >= 30: print('you are old enough to be a senator or president') else: print('your not old enough') print('have a nice day')
5b3c25fd4cc24ff16fd6d3839e23b241a5a70d23
zazaraisovna/AdventOfCode2020
/Advent Of Code - Day 2.py
1,347
3.609375
4
#!/usr/bin/env python # coding: utf-8 passwords = input().split() a = [] for i in range(0, len(passwords)-2, 3): new_elem = passwords[i], passwords[i + 1], passwords[i + 2] a.append(new_elem) ## first ## берём каждый элемент (подсписок) списка b ## берём первый элемент (подсписка) и достаём их элементы frm и to ## считаем сколько раз встреачется второй элемент подсписка и сравниваем с frm и to valid_cnt = 0 for k in range(0, len(a)): first = (a[k])[0].split('-') second = ((a[k])[1])[0] third = (a[k])[2] frm = int(first[0]) to = int(first[1]) cnt = third.count(second) if third.find(second) >= 0 and cnt >= frm and cnt <= to: valid_cnt +=1 print(valid_cnt) ## second b = [] for j in range(0, len(passwords)-2, 3): new_elem = passwords[j], passwords[j + 1], passwords[j + 2] b.append(new_elem) valid2_cnt = 0 for l in range(0, len(a)): first = (b[l])[0].split('-') second = ((b[l])[1])[0] third = (b[l])[2] frm = int(first[0]) - 1 to = int(first[1]) - 1 if (third[frm] == second and third[to] != second) or (third[frm] != second and third[to] == second): valid2_cnt += 1 print(valid2_cnt)
df48bee32e5094798e0e19e258636f0b9f062c8a
Park-jeong-seop/codility
/codility_lesson_3-1.py
234
3.765625
4
""" X is start from Y is destination D is distance to move X, Y, D are Int X = 10, Y = 85, D = 30 res = 3 """ def solution(X, Y, D): tmp = (Y-X) % D res = int((Y-X) / D) if tmp != 0: return res + 1 return res
cdebb5a25667e67ee52919b43475606ff00604e5
Davisanity/backpropagation
/neural.py
5,052
3.5625
4
import random import math #implement 2D empty list # list=[] # for i in range(10): # new=[] # for i in range(10): # new.append(None) # list.append(new) class Neural: def __init__(self,input,output,i,layerNum_h,h,o): self.input = input self.hidden= [[None for _ in range(h)] for _ in range(layerNum_h)] self.Output = output self.output=[None]*o self.num_i=i self.lnum_h=layerNum_h self.num_h=h self.num_o=o w_i=[] w_h=[[None for _ in range(h)] for _ in range(layerNum_h)] w_o=[] w_ih=[] w_hh=[[None for _ in range(h)] for _ in range(layerNum_h)] w_ho=[] self.learn = 3#learning rate self.sigma_h=[[None for _ in range(h)] for _ in range(layerNum_h)] self.sigma_o=[None]*o self.randWeight(i,layerNum_h,h,o) # self.forword() # self.errorFunc() # self.sigma() # self.updateWeight() def rand(self): a = float('%.2f'%random.uniform(-1,3)) while a == 0 : a = float('%.2f'%random.uniform(-1,3)) return a def randWeight(self,input,layerNum_h,hidden,output): # r=('%.2f'%random.uniform(0,1)) # self.w_i = [self.rand() for h in range(input)] self.w_h=[[ float('%.2f'%random.uniform(-2,-1)) for h in range(hidden)] for i in range(layerNum_h)] self.w_o = [ float('%.2f'%random.uniform(-2,-1)) for h in range(output)] self.w_ih = [[ self.rand() for h in range(hidden)] for i in range(input)] # hidden layer's weight.But last layer is connected to output layer so layerNum_h-1 if layerNum_h>1: self.w_hh=[[ self.rand() for h in range(hidden)] for i in range(layerNum_h-1)] self.w_ho = [[ self.rand() for o in range(output)] for h in range(hidden)] # print(type(self.w_ih[0][0])) #str def forword(self): for h in range(self.num_h): t=0 for i in range(self.num_i): t += float(self.input[i])*float(self.w_ih[i][h]) sum = t + self.w_h[0][h] self.hidden[0][h] = float('%.5f'%float(self.activeFunc(sum)) ) if self.lnum_h>1: for l in range(self.lnum_h): for h in range(self.num_h): t=0 for p in range(self.num_h): #p means prev hidden layer t+= float(self.hidden[p][h])*float(self.w_hh[l][h]) sum = t+self.w_h[l][h] self.hidden[l][h]= float('%.5f'%float(self.activeFunc(sum)) ) for o in range(self.num_o): t=0 for h in range(self.num_h): t += float(self.hidden[self.lnum_h-1][h])*float(self.w_ho[h][o]) sum = t + self.w_o[o] self.output[o] = float( '%.5f'%float(self.activeFunc(sum)) ) # print("hidden") # print self.hidden # print self.output def activeFunc(self,sum): func = 1.0/(1+math.exp(sum*(-1))) return func def errorFunc(self): sum=0 for i in range(self.num_o): sum += (self.Output[i]-float(self.output[i]))**2 # print ("sum/2",sum/2) return sum/2 def sigma(self): #caculate output's sigma for o in range(self.num_o): s=(self.Output[o]-self.output[o])*self.output[o]*(1-self.output[o]) self.sigma_o[o]=float('%.5f'%s) #caculate hidden's sigma for l in range(self.lnum_h-1,-1,-1): for h in range(self.num_h): t=0 for o in range(self.num_o): t+=self.sigma_o[o]*self.w_ho[h][o] self.sigma_h[l][h]=float('%.5f'% ( t*self.hidden[l][h]*(1-self.hidden[l][h]) ) ) if self.lnum_h>1 and l != self.lnum_h-1 : for k in range(self.num_h): self.sigma_h[l][h] += self.sigma_h[l+1][k]*self.w_hh[l][k] self.sigma_h[l][h] = float('%.5f'% self.sigma_h[l][h]) # print ("sigma_h",self.sigma_h) # print ("sigma_o",self.sigma_o) # return self.sigma_h,self.sihma_o #2017 1204 tclin HERE NEED TO THINK MORE def updateWeight(self): delta_o = [] delta_h = [[None for _ in range(self.num_h)] for _ in range(self.lnum_h)] #caculate w_o and w_h for o in range(self.num_o): delta_o.append(float('%.4f'%(self.learn*self.sigma_o[o]))) self.w_o[o]+=delta_o[o] self.w_o[o] = float('%.3f'%self.w_o[o] ) for l in range(self.lnum_h): for h in range(self.num_h): delta_h[l][h] = float('%.4f'%(self.learn*self.sigma_h[l][h])) self.w_h[l][h]+=delta_h[l][h] self.w_h[l][h] = float('%.3f'%self.w_h[l][h] ) #update w_ho for h in range(self.num_h): for o in range(self.num_o): delta_ho = self.learn*(self.Output[o]-self.output[o])*self.output[o]*(1-self.output[o])*self.hidden[self.lnum_h-1][h] self.w_ho[h][o]+=float('%.4f'%delta_ho) self.w_ho[h][o]=float('%.3f'%self.w_ho[h][o]) #update w_hh for l in range(self.lnum_h-2,-1,-1): for h in range(self.num_h): delta_hh = self.learn*self.hidden[l+1][h]*(1-self.hidden[l+1][h])*self.sigma_h[l+1][h]*self.w_hh[l][h]*self.hidden[l][h] self.w_hh[l][h]+=float('%.4f'%delta_hh) self.w_hh[l][h]=float('%.3f'%self.w_hh[l][h]) #update w_ih for i in range(self.num_i): for h in range(self.num_h): delta_ih = self.learn*self.hidden[0][h]*(1-self.hidden[0][h])*self.sigma_h[0][h]*self.input[i] self.w_ih[i][h]+=float('%.4f'%delta_ih) self.w_ih[i][h]=float('%.3f'%self.w_ih[i][h]) # print ("updated w_h",self.w_h) # print ("updated w_o",self.w_o) # print self.w_ho # print self.w_ih
e42e95a442fb8e235c15926b8cedb9daee774840
nisn/exercises
/ex38.py
791
3.796875
4
# min-max hackerearth def maior_menor(): global menor global maior global num_numeros global numeros for i in range(num_numeros): if i == 0: menor = int(numeros[i]) maior = int(numeros[i]) else: if int(numeros[i]) < menor: menor = int(numeros[i]) if int(numeros[i]) > maior: maior = int(numeros[i]) num_numeros = int(input()) numeros = str(input()).split(' ') menor = 0 maior = 0 maior_menor() achou = True for w in range(menor+1, maior, 1): if achou is True: achou = False for i in range(num_numeros): if int(numeros[i]) == int(w): achou = True if achou is True: print('YES') else: print('NO')
a550cad8c05a571d579673395558ca2d768abf96
erinnlebaron3/python
/ImpemetRangeSlice.py
3,961
4.625
5
# ranges and the word slices are used many times interchangeably # advanced ranges and advanced slices inside of Python lists. # start with development and then it's going to go and it's going to go all the way up to the very last element. # It's not going to include it because remember with ranges and slices it is going to simply end right before this element tags = [ 'python', 'development', 'tutorials', 'code', 'programing', 'computer science', ] tag_range = tags[1:-1] print(tag_range) answer = ['development', 'tutorials', 'code', 'programing'] # ADDING ANOTHER INTERVAL INTO THE RANGE AKA SLICING # adding another colon you can pass in an interval # this grabs everyother thing in list # something that you will come across especially in the machine learning space # one of those is going to be doing things such as grabbing every other element in a list and this makes this very easy and straightforward. tags = [ 'python', 'development', 'tutorials', 'code', 'programing', 'computer science', ] tag_range = tags[:-1:2] print(tag_range) answer = ['python', 'tutorials', 'programing'] # FLIP ORDER OF LIST tags = [ 'python', 'development', 'tutorials', 'code', 'programing', 'computer science', ] # tag_range = tags[:-1:2] tag_range = tags[::-1] print(tag_range) answer = ['computer science', 'programing','code', 'tutorials', 'development', 'python'] # All that our method here did was it just cared about the index value and swapping those out sort works very differently. # the way the sorting function works is it looks at the alphabetical value. tags = [ 'python', 'development', 'tutorials', 'code', 'programing', 'computer science', ] # tag_range = tags[:-1:2] # tag_range = tags[::-1] # print(tag_range) # ['computer science', 'programing','code', 'tutorials', 'development', 'python'] # ['tutorials', 'python', 'programing', 'development', 'computer science', 'code'] tags.sort(reverse=True) print(tags) answere = ['tutorials', 'python', 'programing', 'development', 'computer science', 'code'] # performing sorting in both of these options so we sorted our list just like we did here. We also sorted the list right here. However, # they were looking at different criteria to generate the new results set. # SORT FUNCTION # Python is so careful about immutability that sort doesn't actually return anything. # So sort will go and it will change the order of the tags so it will go in and it will, in this case, reverse them it'll sort them alphabetically # it'll perform its full set of tasks and it will change tags but it will not return that value. tags = [ 'python', 'development', 'tutorials', 'code', 'programing', 'computer science', ] # tag_range = tags[:-1:2] # tag_range = tags[::-1] # print(tag_range) # ['computer science', 'programing','code', 'tutorials', 'development', 'python'] # ['tutorials', 'python', 'programing', 'development', 'computer science', 'code'] sorted_tags = tags.sort(reverse=True) print(sorted_tags) answer = None # So sort will go and it will change the order of the tags so it will go in and it will, in this case, reverse them it'll sort them alphabetically # it'll perform its full set of tasks and it will change tags but it will not return that value. # the key is that the sort function goes in and it changes tags but it doesn't store it as a standard operation inside of a variable. tags = [ 'python', 'development', 'tutorials', 'code', 'programing', 'computer science', ] # tag_range = tags[:-1:2] # tag_range = tags[::-1] # print(tag_range) # ['computer science', 'programing','code', 'tutorials', 'development', 'python'] # ['tutorials', 'python', 'programing', 'development', 'computer science', 'code'] tags.sort(reverse=True) # sorted_tags = tags.sort(reverse=True) print(tags) answer = ['tutorials', 'python', 'programing', 'development', 'computer science', 'code']
b55abc80adaf5574c10f990b4e930d381fc5751f
yadmyaso/logical_shem
/summato.py
228
3.75
4
def xor(a,b): if (a==1 and b==0) or (a==0 and b==1): return True else: return False a,b,p=[int(i) for i in input().split()] k=xor(a,b) pr=xor(k,p) print(pr) x1=a and b x2= k and p d=x1 or x2 print(d)
f21d0efea87ed5c184eca149f4698d88c0bcfa3a
akashgupta910/python-practice-code
/oops_5.py
411
3.75
4
# SPEED() AND OVERRIDING class Junior: junior_class1 = ["Akash","Raj"] def __init__(self): self.senior = ["Golu"] self.junior = ["Ranveer_singh"] class Senior(Junior): senior_junior = ["Kashi","Dil Mohammad"] def __init__(self): super().__init__() self.senior = ["Golu"] self.junior = ["Ranveer"] junior = Junior() senior = Senior() print(senior.junior)
baedb7753be411e564b13cf3cf100889ac30a626
reo11/AtCoder
/atcoder/abc/abc101-200/ABC141/b.py
225
3.734375
4
s = list(str(input())) l1 = ["R", "U", "D"] l2 = ["L", "U", "D"] ans = "Yes" for i, c in enumerate(s): if i % 2 == 0 and c not in l1: ans = "No" elif i % 2 == 1 and c not in l2: ans = "No" print(ans)
f4a3bcbc4990d1a510c29e17c0a31368427f91d2
salvadorhm/poo
/semana_2/programa_14.py
321
3.65625
4
class Cadenas: cadena_1 = "Hola" cadena_2 = 'Hola' cadena_3 = """variable cadena de varias lineas""" cadena_4 = '''Variable cadena de varias lineas''' def __init__(self): pass objeto = Cadenas() print(objeto.cadena_1) print(objeto.cadena_2) print(objeto.cadena_3) print(objeto.cadena_4)
caaf9aece2ad385822a941ed975c8e45abe4bbee
windtux/calculadora
/calculadora-sencilla.py
532
3.828125
4
def suma(): nume1 = float(input('ingrese un numero (no necesariamente deben ser enteros) ')) nume2 = float(input('ingrese otro numero (no necesariamente deben ser enteros) ')) resultado = nume1 + nume2 print ('el resultado de ambos numeros es ',resultado) pregunta = (input('desea continuar usando la aplicacion? Si(s) o No(n) ')) if pregunta =='s': suma() elif pregunta == 'n': return 0 print ('aplicacion solo para sumar dos numeros') suma() print ('saliendo del programa, hasta luego')
5ddadacffad4ef04ae3d1d65ff063b497483f70e
matheusclementeg/gerador-de-senhas
/GeradorDeSenhas/GeradorComInterface.py
2,152
3.59375
4
# -*- coding: utf-8 -*- """tkinter Exemplo de utilização do Tkinter. OBS: Não está sendo utilizada orientação a objeto (classes). """ from tkinter import * import random def gerar_senha(): """Gerar senha. Função responsável por gerar uma senha aleatória com base na escolha que o usuário fizer na interface gráfica. """ caracteres = 'abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()?' valor = escolhaVar.get() if valor == 'Fácil': tamanho = 6 senha = ''.join(random.sample(caracteres, tamanho)) lb['text'] = '%s' % senha elif valor == 'Médio': tamanho = 12 senha = ''.join(random.sample(caracteres, tamanho)) lb['text'] = '%s' % senha else: tamanho = 18 senha = ''.join(random.sample(caracteres, tamanho)) lb['text'] = '%s' % senha def sair(): """Sair. Função fecha a janela da aplicação. """ janela.quit() # Janela principal do nosso programa janela = Tk() # Geometria da janela. janela.geometry('400x200+200+200') # Titulo da janela principal. janela.title('Gerador de senha') # A escolha feita na interface gráfica fica armazenada nesta variável. escolhaVar = StringVar() # Opção que será padrão quando a interface iniciar. escolhaVar.set('Fácil') # Escolhas que estão disponíveis. escolhas = ('Fácil', 'Médio', 'Dificil') # Criando os widgets. # widget com as opções. choicebox = OptionMenu(janela, escolhaVar, *escolhas) # Botão que gera a senha. bt1 = Button(janela, width=20, text='Gerar', command=gerar_senha) # Botão para sair da interface. bt2 = Button(janela, width=20, text='Sair', command=sair) # Label que exibe a senha gerada. lb = Label(janela, text='Sua senha será exibida aqui.') # Colocando o widget na tela. # Como estamos utilizando o pack os widget ficam na posição em que são lançados. # Ele equivale ao boxlayout de outras interfaces gráficas. choicebox.pack() bt1.pack() lb.pack() bt2.pack() # Mantem a janela principal aberta. janela.mainloop()
dd814e77957947b9846dee8ee782702a8760b3b3
raygolden/leetcode-python
/src/powersetWDuplicates.py
763
3.75
4
#!/usr/bin/env python """ powerset with duplicates """ def powersetWDup(s): s.sort() results = [[]] cur_dup = None for elm in s: i = 0 if elm != cur_dup: # not a duplicate cur_dup = elm l = len(results) pre = [] while i < l: res = list(results[i]) res.append(elm) results.append(res) pre.append(res) i += 1 else: l = len(pre) while i < l: res = list(pre.pop(0)) res.append(elm) results.append(res) pre.append(res) i += 1 return results print powersetWDup([1,2,2,2,3,4])
df06c0d7cd9891070978efaffa54092fc7d8f82a
RAMESHMAXX/python_refresher
/05_list_tuples_sets_range_code/code.py
799
4.28125
4
l = ["Ramesh", "prince", "maxx"] t = ("Ramesh", "prince", "maxx") s = {"Ramesh", "prince", "maxx"} # Access individual items in lists and tuples using the index. print(l[0]) print(t[0]) # print(s[0]) set is unordered so cannot accessed # Modyfing l[0] = "Smith" #list are mutabe means changable so updated # t[0] = "Smith" tuple are unmutable means not changable print(l) print(t) # Add to a list by using `.append` l.append("Jen") print(l) # Tuples cannot be appended to because they are immutable. # Add to sets by using `.add` s.add("Jen") print(s) # Sets can't have the same element twice. s.add("Ramesh") print(s) #RANGE print(range(10)) #0 to 10 values #summary #list mutable so we can modify it #tuple are unmutable so cannot updated #set have unique element and in unorderd.
b1bf9a87e090aac543f172bddd83f84e47f2103d
hector-han/leetcode
/dp/prob0673.py
2,228
3.53125
4
""" 最长上升子序列,给定一个未排序的整数数组,找到最长递增子序列的个数。 medium 输入: [10,9,2,5,3,7,101,18] 输出: 4 解释: 最长的上升子序列是 [2,3,7,101],它的长度是 4。 说明: 可能会有多种最长上升子序列的组合,你只需要输出对应的长度即可。 你算法的时间复杂度应该为 O(n2) 。 进阶: 你能将算法的时间复杂度降低到 O(n log n) 吗? 1、递归,dp[i] 表示以nums[i]结尾的最长上升子序列。则dp[i+1] = max(dp[j], where j<i+1, and nums[j] < nums[i+1]) 2、分成牌堆。如果当前比所有牌堆下(顶)部都大,新开牌堆,否则防止在最左边的合法位置(下部)。 [10,9,2,5,3,7,101,18] -> 的牌堆 10 5 7 101 9 3 18 2 """ from typing import List class Solution1: def lengthOfLIS(self, nums: List[int]) -> int: if len(nums) == 0: return 0 length = len(nums) dp = [0] * length dp[0] = 1 ans = 1 for i in range(1, len(nums)): j = 0 tmp = 0 while j < i: if nums[j] < nums[i]: tmp = max(tmp, dp[j]) j += 1 ans = max(tmp + 1, ans) dp[i] = tmp + 1 return ans class Solution2: def lengthOfLIS(self, nums: List[int]) -> int: length = len(nums) if length == 0: return 0 heap = [] for num in nums: # find location, 牌堆顶是有序的 begin = 0 end = len(heap) while begin < end: mid = (begin + end) // 2 if heap[mid] == num: begin = mid break elif heap[mid] > num: end = mid else: begin = mid + 1 if begin < len(heap): heap[begin] = num else: heap.append(num) return len(heap) if __name__ == '__main__': nums = [10,9,2,5,3,7,101,18] sol = Solution2() print(sol.lengthOfLIS(nums))
505bff60e81f6c0d51ef19e570c5760c9bcb8fd1
tyriem/PY
/Intro To Python/60 - DateTime - Convert.py
1,687
4.6875
5
### AUTHOR: TMRM ### PROJECT: INTRO TO PYTHON - Convert Seconds / Minutes ### VER: 1.0 ### DATE: 06-25-2020 ############################## ### DATE / TIME - CONVERT ### ############################## ### OBJECTIVE ### # Convert the below code to yield minutes per week, day, hour ### OBJECTIVE ### """ #Python's program to convert number of days, hours, minutes and seconds to #seconds. #Define the constants SECONDS_PER_MINUTE = 60 SECONDS_PER_HOUR = 3600 SECONDS_PER_DAY = 86400 #Read the inputs from user days = int(input("Enter number of Days: ")) hours = int(input("Enter number of Hours: ")) minutes = int(input("Enter number of Minutes: ")) seconds = int(input("Enter number of Seconds: ")) #Calculate the days, hours, minutes and seconds total_seconds = days * SECONDS_PER_DAY total_seconds = total_seconds + ( hours * SECONDS_PER_HOUR) total_seconds = total_seconds + ( minutes * SECONDS_PER_MINUTE) total_seconds = total_seconds + seconds #Display the result print("Total number of seconds: ","%d"%(total_seconds)) """ ### CODE ### #Define the constants MINUTES_PER_WEEK = 10080 MINUTES_PER_HOUR = 60 MINUTES_PER_DAY = 1440 #Read the inputs from user weeks = float(input("Enter number of Weeks: ")) days = float(input("Enter number of Days: ")) hours = float(input("Enter number of Hours: ")) minutes = float(input("Enter number of Minutes: ")) #Calculate the days, hours, minutes and seconds total_minutes = weeks * MINUTES_PER_WEEK total_minutes = total_minutes + (days * MINUTES_PER_DAY) total_minutes = total_minutes + ( hours * MINUTES_PER_HOUR) total_minutes = total_minutes + minutes #Display the result print("Total number of minutes: ","%d"%(total_minutes))
b8b48fc2b2ac8008b7a31085b30997b88db55590
DylanB5402/DrivetrainSim
/src/NerdyMath.py
226
3.609375
4
import math def distance_formula(x1, y1, x2, y2): return math.sqrt((x1-x2)**2 + (y1-y2)**2) def get_greater_value(a, b): if a > b: return a elif a < b: return b elif a == b: return a
df263a7eda99e2923c356290eb8e8e0d3773603b
Te-Stack/Texas-em-Poker-Card-Game
/Tests/test_player.py
1,276
3.625
4
import unittest from unittest.mock import MagicMock from Poker.card import Card from Poker.hand import Hand from Poker.player import Player class PlayerTest(unittest.TestCase): def test_stores_name_and_hand(self): hand = Hand() player = Player(name = "Boris", hand = hand) self.assertEqual(player.name,"Boris") self.assertEqual(player.hand,hand) def test_figures_out_best_hand(self): mock_hand = MagicMock() mock_hand.best_rank.return_value = "Straight Flush" player = Player(name = "Boris", hand = mock_hand) self.assertEqual(player.best_hand(),"Straight Flush") mock_hand.best_rank.assert_called() def test_passes_new_cards_to_hand(self): mock_hand = MagicMock() player = Player(name = "Kimberly", hand = mock_hand) cards = [ Card(rank = "Ace", suit = "Spades"), Card(rank = "Queen", suit = "Diamonds") ] player.add_cards(cards) mock_hand.add_cards.assets_called_once_with(cards) def test_decides_to_continue_or_drop_out_of_the_game(self): player = Player(name = "Sharon", hand = Hand()) self.assertEqual( player.wants_to_fold(), False )
7ed783248e11baa56f173bc7eecc099be40a7625
kdef/example
/str_perm/str_perm.py
377
3.96875
4
import sys # print all permutations of an input string def permute(str_in, str_out): if len(str_in) == 0: print str_out else: for i in range(len(str_in)): tmp = str_out + str_in[i] rest = str_in[:i] + str_in[i+1:] permute(rest, tmp) try: test = sys.argv[1] except IndexError: test = "ABC" permute(test, "")
bb33f40e75ef8e824cf86e37cedbfb37de70470c
medesiv/ds_algo
/matrix/search_2d_matrix.py
1,800
3.796875
4
""" Search 2D matrix: Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: Integers in each row are sorted from left to right. The first integer of each row is greater than the last integer of the previous row. """ class Solution: def searchMatrix(self, matrix, target): m = len(matrix) if m == 0: return False n = len(matrix[0]) # binary search left, right = 0, m * n - 1 while left <= right: pivot_idx = (left + right) // 2 pivot_element = matrix[pivot_idx // n][pivot_idx % n] if target == pivot_element: return True else: if target < pivot_element: right = pivot_idx - 1 else: left = pivot_idx + 1 return False # def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: # m = len(matrix) # n = len(matrix[0]) # low, high = 0, m - 1 # left, right = 0, n - 1 # while low < high: # mid = (high - low) // 2 + low # if target == matrix[mid][right]: # return True # if target > matrix[mid][right]: # low = mid + 1 # else: # high = mid # while left <= right: # mid = left + (right - left) // 2 # if target == matrix[high][mid]: # return True # elif target > matrix[high][mid]: # left = mid + 1 # else: # right = mid - 1 # return False
e0d45c43b11c9984153b30a29220dc4ad37fe683
Tom83B/ProjectEuler
/prob33/prob33.py
637
3.703125
4
from fractions import Fraction pairs = [ (a,b) for a in range(1,10) for b in range(1,10) if a<b ] special = [] for c in range(1,10): for a,b in pairs: if Fraction(int(str(c)+str(a)),int(str(c)+str(b)))==Fraction(a,b): special.append(Fraction(a,b)) if Fraction(int(str(a)+str(c)),int(str(c)+str(b)))==Fraction(a,b): special.append(Fraction(a,b)) if Fraction(int(str(c)+str(a)),int(str(b)+str(c)))==Fraction(a,b): special.append(Fraction(a,b)) if Fraction(int(str(a)+str(c)),int(str(b)+str(c)))==Fraction(a,b): special.append(Fraction(a,b)) product = 1 for frac in special: product*=frac print(product.denominator)
b431200f74464bd11675eb6e52fd49a238680e87
Benjamin-Marks/reversi
/board.py
8,100
3.953125
4
"""Represents the Board of a Reversi game.""" import json import logging class Square(object): """Enum to differentiate between teams. Note: We don't extend from enum to allow for easy serialization. """ white = 0 black = 1 blank = 2 class Board(object): """Represents the board of a reversi game.""" def __init__(self, size, board, turn): if size: self.board = [[Square.blank for _ in range(size)] for _ in range(size)] self.board[size/2][size/2] = self.board[size/2-1][size/2-1] = Square.white self.board[size/2][size/2-1] = self.board[size/2-1][size/2] = Square.black else: self.board = board self.turn = turn # Creating a new board @classmethod def makeboard(cls, size): return cls(size, None, Square.white) # Creating a board in progress @classmethod def remakeboard(cls, board, turn): return cls(None, board, turn) def to_json(self): """Converts the board to json.""" return json.dumps(self.board) @staticmethod def from_json(data, turn): """Parses a json board and returns a new Board object. Args: data: (str) The board, encoded as json. turn: (Square) The team set to move next Returns: Board: The recreated board. """ return Board.remakeboard(json.loads(data), turn) def get_size(self): """Gets the size of a board side.""" return len(self.board) def get_num_moves(self): """Gets the number of moves made in the game.""" return len(self.board) * len(self.board) - 4 - self.get_squares_left() def get_squares_left(self): """Gets the number of blank squares on the board.""" remaining = 0 for r in self.board: for c in r: if c == Square.blank: remaining += 1 return remaining def get_turn(self): """Returns whose turn it is.""" return self.turn def add_piece(self, r, c, team): """Validates input and addes a piece to the board. Args: r: (int) The row. c: (int) The column. team: (Square) The team making the move. Returns: int: The number of points scored by the move """ if not self._validate_input(r, c, team): return 0 points = self._flip(r, c, self.turn) if points == 0: logging.info('Illegal move r%sc%s: no points', r, c) return 0 self.board[r][c] = self.turn self._set_next_turn() return points def _validate_input(self, r, c, team): """Ensures move input is a legal move. Args: r: (int) The row. c: (int) The column. team: (Square) The team making the move. Returns: bool: the legality of the move """ if r < 0 or r >= len(self.board) or c < 0 or c >= len(self.board): logging.error('Move r%sc%s not in range 0, %s', r, c, len(self.board)) elif self.turn != team: logging.info('Bad Move by player%s: Not your turn', team + 1) elif self.board[r][c] != Square.blank: logging.info('Bad Move r%sc%s: Not a blank square', r, c) else: return True return False def _set_next_turn(self): """Determines if players can move and sets the next turn.""" # Check if each player can move cur_turn = self.turn self.turn = Square.black black_able = self.can_move(Square.black) self.turn = Square.white white_able = self.can_move(Square.white) self.turn = cur_turn if not black_able and not white_able: logging.info('No more legal moves') self.turn = Square.blank # Set next turn if self.turn == Square.white: self.turn = Square.black # Break up if statements so that our checks pass validate_input if not black_able: self.turn = Square.white elif self.turn == Square.black: self.turn = Square.white # Break up if statements so that our checks pass validate_input if not white_able: self.turn = Square.black # Method wrapper for flipping def _flip(self, r, c, team): return self._validate_flip(r, c, team, True, True) # Method wrapper for getting score of a potential flip def flip_score(self, r, c, team): if self._validate_input(r, c, team): return self._validate_flip(r, c, team, False, True) return 0 # Method wrapper for seeing if move is legal. Returns Boolean def can_flip(self, r, c, team): logging.getLogger().setLevel(logging.ERROR) # Don't log validation errors if (self._validate_input(r, c, team) and self._validate_flip(r, c, team, False, False)): logging.getLogger().setLevel(logging.DEBUG) return True logging.getLogger().setLevel(logging.DEBUG) return False # Internal method for flipping pieces # Assumes everything has been validated def _flip_pieces(self, pieces): for piece in pieces: if self.board[piece[0]][piece[1]] == Square.white: self.board[piece[0]][piece[1]] = Square.black else: self.board[piece[0]][piece[1]] = Square.white # Internal method for determining move legality and score def _validate_flip(self, r, c, team, should_flip, keep_score): """Handles validating moves and flipping pieces. Args: r: (int) The row we're placing a piece. c: (int) The column we're placing a piece. team: (Square) The team placing the piece. should_flip: (bool) Should we actually flip the pieces or just check move? keep_score: (bool) Are we checking legality or score? Returns: int: The move's score (or 1 for score >= 1 if keep_score is false) """ flip_pieces = [] # Search each direction on the board for dr in xrange(-1, 2): for dc in xrange(-1, 2): if dr == 0 and dc == 0: continue cur_r = r + dr cur_c = c + dc found_other = False while (cur_r < len(self.board) and cur_r >= 0 and cur_c < len(self.board[0]) and cur_c >= 0): if self.board[cur_r][cur_c] == Square.blank: break elif self.board[cur_r][cur_c] == team: # If we found the other player in between, flip. Otherwise break if found_other: if keep_score: # Calculate all the flipped pieces mv_r = -1 * dr mv_c = -1 * dc while cur_r + mv_r != r or cur_c + mv_c != c: cur_r += mv_r cur_c += mv_c flip_pieces.append([cur_r, cur_c]) else: # If we're checking that this square has a legal move, it does return 1 break else: found_other = True cur_r += dr cur_c += dc # Remove duplicate squares flip_set = set(tuple(i) for i in flip_pieces) if should_flip: self._flip_pieces(flip_set) return len(flip_set) def can_move(self, team): """Determines if the given team has a valid move. Args: team: (Square) The team. Returns: bool: If the team has a valid move """ for r in xrange(0, len(self.board)): for c in xrange(0, len(self.board)): if self.can_flip(r, c, team): return True return False # Count Squares on a full board to determine the winner def who_won(self): """Counts the squares on a board to determine the winner. Returns: Square: The winning team. """ white_advantage = 0 if self.turn != Square.blank: return -1 for r in xrange(len(self.board)): for c in xrange(len(self.board)): if self.board[r][c] == Square.white: white_advantage += 1 elif self.board[r][c] == Square.black: white_advantage -= 1 if white_advantage == 0: return Square.blank elif white_advantage > 0: return Square.white else: return Square.black # Count number of pieces that belong to the given team def num_pieces(self, team): pieces = 0 for r in xrange(len(self.board)): for c in xrange(len(self.board)): if self.board[r][c] == team: pieces += 1 return pieces
0da3f8a2808dfed048ad653b059cac1e94673f38
MoonAuSosiGi/Coding-Test
/Python_Algorithm_Interview/Sparta_algorithm/week_3/06_stack.py
1,131
4.0625
4
class Node: def __init__(self, data): self.data = data self.next = None class Stack: def __init__(self): self.head = None def push(self, value): if self.is_empty(): self.head = Node(value) else: new_node = Node(value) new_node.next = self.head self.head = new_node # pop 기능 구현 def pop(self): if self.is_empty(): return None else: result_node = self.head self.head = result_node.next return result_node def peek(self): return self.head # isEmpty 기능 구현 def is_empty(self): return self.head is None def print_all(self): cur = self.head while cur is not None: print(cur.data) cur = cur.next stack = Stack() if stack.is_empty(): print("empty") stack.push(100) stack.push(200) stack.push(300) stack.push(400) if stack.is_empty(): print("empty") #stack.pop() stack.push(500) stack.push(600) stack.print_all()
bce7bedcf84457b53d50a6fa70c39819dfbb9550
NguyenVanDuc2022/Self-study
/101 Tasks/Task 083.py
375
4.15625
4
""" Question 083 - Level 03 By using list comprehension, please write a program to print the list after removing delete numbers which are divisible by 5 and 7 in [12,24,35,70,88,120,155]. Hints: Use list comprehension to delete a bunch of element from a list. --- Nguyen Van Duc --- """ li = [12, 24, 35, 70, 88, 120, 155] li = [x for x in li if x % 5 != 0 and x % 7 != 0] print(li)
9c6fdb5cb664b9113903f092e6b53f651e1e1f14
ssulav/interview-questions
/leetcode/5_longest-palindromic-substring.py
1,040
3.96875
4
""" https://leetcode.com/problems/longest-palindromic-substring/ Given a string s, return the longest palindromic substring in s. Example 1: Input: s = "babad" Output: "bab" Note: "aba" is also a valid answer. """ import timeit class mySolution: def longestPalindrome(self, s: str) -> str: print(s) p = [] for i in range(len(s)): for j in range(1, i+1): temp = s[j:i+1] if temp == temp[::-1]: p.append(temp) print(p) return max(p, key=len) class Solution(object): def longestPalindrome(self, s): res = "" for i in range(len(s)): res = max(self.helper(s, i, i), self.helper(s, i, i + 1), res, key=len) return res def helper(self, s, l, r): while 0 <= l and r < len(s) and s[l] == s[r]: l -= 1 r += 1 return s[l + 1:r] a = Solution() s = "xfsxwjqovpvchyjzdqphjsligzljscmzmjzelmbfnqpukbninfbbljouesngmbdyzhqysroeyagglkgorllkrcditzisqhihmithgjcpilkgfdxxqqjpqnoavgkjhojrldsyucfgtzimdbjehrxxqlpaqdddzismsodvternodzxusuehllpujmjjukrilrubbwzdjxbpmvmmwzbrxcxsjsqljjezgyzmsjpucghjxksdfyucpbvwloyhwevzgudhpspgtvsbjqlzmpequxthdonvbmjpeirttllvmtonqmbqxqtdkgichbfzkbhmhotqpkaeshhecshqjvdwgwkegmujwcnmseicesxddrvutxomsgjeylpqiuyezdccarsiprmoqgyifidxhufocfdrbnqczhtztutspaftwctsmynozhakqgvfsvoffyslhoaptkcktopabrxxwrcbyfftleaotwpoqvjjdzxwwqxjnyszjqwjsghkzpvirwnwgsofkjluyxzgboxybzhnmqhkwgltwdjgnemaaadvflrzdqmjufwyuwzoimnvhlxhxjywbopresdrepulsaaexdeddyzeosqfwlnovfpxothrcxhxnumnymofkkuxvclwvuhcelieengfbhvinckrpbjuuewnwvnrvimgmpsfdlcffpdfwmydgzdvluaejwalueygvvojfovuxwhlwojldfpieqqpoqfxhbkcnrtzrnbaagonnawwaqdzamhnvwdtoxlkexihvrqwwimjn" print(a.longestPalindrome(s)) # t = timeit.Timer(a.longestPalindrome(s)) # print(t.timeit(5))
d32b855ea3eea0f87ccaccf4fa022c5e7046ff30
NilsBergmann/ProjectEuler
/src/Python/Tasks/009.py
577
4.1875
4
""" Project Euler Problem 9 ======================= A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a^2 + b^2 = c^2 For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc. """ def isPythagorean(a, b, c): return a**2 + b**2 == c**2 def solve(sum): for a in range(1,sum): for b in range(1,sum - a): c = sum - a - b if isPythagorean(a,b,c): return a * b * c print(solve(1000))
d7134ec9563951eb5cd81f3dfe6a792e991b2524
henrypj/codefights
/Intro/02-EdgeOfTheOcean/adjacentElementsProduct.py
1,022
4.40625
4
#!/bin/python3 import sys """ # Description # # Given an array of integers, find the pair of adjacent elements that has the # largest product and return that product. # # Example: # # For inputArray = [3, 6, -2, -5, 7, 3], the output should be # adjacentElementsProduct(inputArray) = 21. # # 7 and 3 produce the largest product. # # Input Format # # array.integer inputArray, An array of integers containing at least two elements # 2 ≤ inputArray.length ≤ 10, # -1000 ≤ inputArray[i] ≤ 1000. # # Output Format # # The largest product of adjacent elements. # # Solution: """ ############## # SOLUTION 1 # ############## def adjacentElementsProduct(inputArray): for i in range(len(inputArray)-1): if i == 0: maxProduct = inputArray[i] * inputArray[i+1] if inputArray[i] * inputArray[i+1] > maxProduct: maxProduct = inputArray[i] * inputArray[i+1] return(maxProduct) print(adjacentElementsProduct([3,6,-2,-5,7,3])) print(adjacentElementsProduct([-23,4,-3,8,-12]))
1ffa55b423f202267b53a0eea7da44434a4185b0
nuptaxin/pythonStudy
/d_advanced_features/b_iteration.py
479
4.09375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- d={'a':1,'b':2,'c':3} for key in d: print('key:',key) for value in d.values(): print('value:',value) for k,v in d.items(): print('key:',k,',value:',v) #迭代字符串 for ch in 'ABC': print(ch) #判断是否为可迭代对象 from collections import Iterable print(isinstance('abc',Iterable)) #下标迭代 for i,value in enumerate(['a','B','c']): print('下标:',i,',值:',value)
6fbcf3d126aa31a4548292a16ad9e32926d76cfd
LabosFisicaUBA/Dynamica_Systems
/Capitulo_02/Program_02d.py
279
3.546875
4
# Program 02d : Power series solution of a second order ODE. # See Example 8. from sympy import dsolve, Function, pprint from sympy.abc import t x = Function('x') ODE2 = x(t).diff(t,2) + 2*t**2*x(t).diff(t) + x(t) pprint(dsolve(ODE2, hint='2nd_power_series_ordinary', n=6))
f0c24080bc0458d63dfdb5ba19453431bf8386b3
raymondmar61/pythoncodecademy
/studentbecomestheteacher.py
1,777
4
4
from statistics import mean lloyd = {"name": "Lloyd", "homework":[90.0, 97.0, 75.0, 92.0], "quizzes":[88.0, 40.0, 94.0], "tests":[75.0, 90.0]} alice = {"name": "Alice", "homework":[100.0, 92.0, 98.0, 100.0], "quizzes":[82.0, 83.0, 91.0], "tests":[89.0, 97.0]} tyler = {"name": "Tyler", "homework":[0.0, 87.0, 75.0, 22.0], "quizzes":[0.0, 75.0, 78.0], "tests":[100.0, 100.0]} print(lloyd["name"]) print(alice["homework"]) print(tyler["quizzes"]) students = [lloyd, alice, tyler] #no quotes in list students. I believe the list is variables defining the dictionary. for student in students: print(student["name"]) print(student["homework"]) print(student["quizzes"]) print(student["tests"]) # def average(*numbers): # total = sum(numbers) # print(total) # average(1,2,3) # def average(*numbers): # total = sum(numbers) # total = float(total) / len(numbers) # return total # print(average(1,2,3,4)) #there's no average() function. It's mean. Must Import Statistics to use statistics.mean(). def get_average(student): homework = ((mean(student["homework"])) * .10) + ((mean(student["quizzes"])) * .30) + ((mean(student["tests"])) * .60) return homework #print("Lloyd's average is" ,get_average(lloyd)) def get_letter_grade(score): if score >= 90: return "A" elif score >= 80: return "B" elif score >= 70: return "C" elif score >= 60: return "D" else: return "F" print(get_letter_grade(80.55)) def get_class_average(students): results = [] for student in students: results.append(get_average(student)) #get_average(student) is function at line 30 return mean(results) print(get_class_average(students)) #(students) is from the list at line 11 print(get_letter_grade(get_class_average(students)))
df01632f73d985f1901c3d4c4463fe7888331c76
vovamedentsiy/Deep-Learning
/medentsiy_assignment1/code/train_mlp_numpy.py
6,450
3.875
4
""" This module implements training and evaluation of a multi-layer perceptron in NumPy. You should fill in code into indicated sections. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import numpy as np import os from mlp_numpy import MLP from modules import CrossEntropyModule import cifar10_utils import matplotlib.pyplot as plt from modules import * # Default constants DNN_HIDDEN_UNITS_DEFAULT = '100' LEARNING_RATE_DEFAULT = 2e-3 MAX_STEPS_DEFAULT = 1500 BATCH_SIZE_DEFAULT = 200 EVAL_FREQ_DEFAULT = 100 # Directory in which cifar data is saved DATA_DIR_DEFAULT = './cifar10/cifar-10-batches-py' FLAGS = None def accuracy(predictions, targets): """ Computes the prediction accuracy, i.e. the average of correct predictions of the network. Args: predictions: 2D float array of size [batch_size, n_classes] labels: 2D int array of size [batch_size, n_classes] with one-hot encoding. Ground truth labels for each sample in the batch Returns: accuracy: scalar float, the accuracy of predictions, i.e. the average correct predictions over the whole batch TODO: Implement accuracy computation. """ ######################## # PUT YOUR CODE HERE # ####################### ind_pred = np.argmax(predictions, axis=1) ind_targets = np.argmax(targets, axis=1) accuracy = (ind_pred == ind_targets).mean() ######################## # END OF YOUR CODE # ####################### return accuracy def train(): """ Performs training and evaluation of MLP model. TODO: Implement training and evaluation of MLP model. Evaluate your model on the whole test set each eval_freq iterations. """ ### DO NOT CHANGE SEEDS! # Set the random seeds for reproducibility np.random.seed(42) ## Prepare all functions # Get number of units in each hidden layer specified in the string such as 100,100 if FLAGS.dnn_hidden_units: dnn_hidden_units = FLAGS.dnn_hidden_units.split(",") dnn_hidden_units = [int(dnn_hidden_unit_) for dnn_hidden_unit_ in dnn_hidden_units] else: dnn_hidden_units = [] ######################## # PUT YOUR CODE HERE # ####################### cifar10 = cifar10_utils.get_cifar10(data_dir = FLAGS.data_dir) alpha = FLAGS.learning_rate batch_size = FLAGS.batch_size n_classes = 10 input_dim = 3*32*32 mlp = MLP(input_dim, dnn_hidden_units, n_classes) loss = CrossEntropyModule() X_test, Y_test = cifar10['test'].images, cifar10['test'].labels X_test = np.reshape(X_test, (X_test.shape[0], -1)) X_train, Y_train = cifar10['train'].images, cifar10['train'].labels X_train = np.reshape(X_train, (X_train.shape[0], -1)) x_ax = [] acc_train = [] acc_test = [] loss_print_tr = [] loss_print_te = [] for step in range(FLAGS.max_steps): x_train, y_train = cifar10['train'].next_batch(batch_size) x_train = np.reshape(x_train, (batch_size, -1)) predictions = mlp.forward(x_train) loss_train = loss.forward(predictions, y_train) dout = loss.backward(predictions, y_train) mlp.backward(dout) for layer in mlp.layers: if isinstance(layer, LinearModule): layer.params['weight'] -= alpha * layer.grads['weight'] layer.params['bias'] -= alpha * layer.grads['bias'] if step % FLAGS.eval_freq == 0: print('Iteration ', step) x_ax.append(step) predictions = mlp.forward(X_train) acc_train.append(accuracy(predictions, Y_train)) loss_tr = loss.forward(predictions, Y_train) loss_print_tr.append(loss_tr) predictions = mlp.forward(X_test) acc_test.append(accuracy(predictions, Y_test)) loss_te = loss.forward(predictions, Y_test) loss_print_te.append(loss_te) print('Max train accuracy ', max(acc_train)) print('Max test accuracy ', max(acc_test)) print('Min train loss ', max(loss_print_tr)) print('Min test loss ', max(loss_print_te)) x_ax = np.array(x_ax) acc_test = np.array(acc_test) acc_train= np.array(acc_train) loss_print_tr = np.array(loss_print_tr) loss_print_te = np.array(loss_print_te) print('Max train accuracy ', max(acc_train)) print('Max test accuracy ', max(acc_test)) print('Min train loss ', min(loss_print_tr)) print('Min test loss ', min(loss_print_te)) fig = plt.figure() ax = plt.axes() plt.title("MLP Numpy. Accuracy curves") ax.plot(x_ax, acc_train, label='train'); ax.plot(x_ax, acc_test, label='test'); ax.set_xlabel('Step'); ax.set_ylabel('Accuracy'); plt.legend(); plt.savefig('accuracy_np.jpg') fig = plt.figure() ax = plt.axes() plt.title("MLP Numpy. Loss curves") ax.plot(x_ax, loss_print_tr, label='train'); ax.plot(x_ax, loss_print_te, label='test'); ax.set_xlabel('Step'); ax.set_ylabel('Loss'); plt.legend(); plt.savefig('loss_np.jpg') ######################## # END OF YOUR CODE # ####################### def print_flags(): """ Prints all entries in FLAGS variable. """ for key, value in vars(FLAGS).items(): print(key + ' : ' + str(value)) def main(): """ Main function """ # Print all Flags to confirm parameter settings print_flags() if not os.path.exists(FLAGS.data_dir): os.makedirs(FLAGS.data_dir) # Run the training operation train() if __name__ == '__main__': # Command line arguments parser = argparse.ArgumentParser() parser.add_argument('--dnn_hidden_units', type = str, default = DNN_HIDDEN_UNITS_DEFAULT, help='Comma separated list of number of units in each hidden layer') parser.add_argument('--learning_rate', type = float, default = LEARNING_RATE_DEFAULT, help='Learning rate') parser.add_argument('--max_steps', type = int, default = MAX_STEPS_DEFAULT, help='Number of steps to run trainer.') parser.add_argument('--batch_size', type = int, default = BATCH_SIZE_DEFAULT, help='Batch size to run trainer.') parser.add_argument('--eval_freq', type=int, default=EVAL_FREQ_DEFAULT, help='Frequency of evaluation on the test set') parser.add_argument('--data_dir', type = str, default = DATA_DIR_DEFAULT, help='Directory for storing input data') FLAGS, unparsed = parser.parse_known_args() main()
6bc409697ccf2c17b0d4b2cdc0f2aad9451bc8ee
liuyongchen521/DataStructuresStudy
/.vscode/刷题学习/迭代器和生成器.py
5,954
3.6875
4
# 这里有个关于生成器的创建问题面试官有考: # 问: 将列表生成式中[]改成() 之后数据结构是否改变? # 答案:是,从列表变为生成器 # >>> L = [x*x for x in range(10)] # >>> L # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] # >>> g = (x*x for x in range(10)) # >>> g # at 0x0000028F8B774200> # 通过列表生成式,可以直接创建一个列表。但是,受到内存限制,列表容量肯定是有限的 # 。而且,创建一个包含百万元素的列表,不仅是占用很大的内存空间 # 如:我们只需要访问前面的几个元素,后面大部分元素所占的空间都是浪费的 # 。因此,没有必要创建完整的列表(节省大量内存空间)。 # 在Python中,我们可以采用生成器:边循环,边计算的机制—>generator # Python中关键字yield有什么作用? # def node._get_child_candidates(self, distance, min_dist, max_dist): # if self._leftchild and distance - max_dist < self._median: # yield self._leftchild # if self._rightchild and distance + max_dist >= self._median: # yield self._rightchild # 下面是调用它: # result, candidates = list(), [self] # while candidates: # node = candidates.pop() # distance = node._get_dist(obj) # if distance <= max_dist and distance >= min_dist: # result.extend(node._values) # candidates.extend(node._get_child_candidates(distance, min_dist, max_dist)) # return result # 当_get_child_candidates方法被调用的时候发生了什么?是返回一个列表?还是一个元祖?它还能第二次调用吗?后面的调用什么时候结束? # ------------理解generators(生成器)------理解iterables(迭代器)----- # 为了理解yield有什么用,首先得理解generators,而理解generators前还要理解iterables # iterables(可迭代的) # 当你创建了一个列表,你可以一个一个的读取它的每一项,这叫做iteration(迭代): # >>> mylist = [1, 2, 3] # >>> for i in mylist: # ... print(i) # 1 # 2 # 3 # Mylist是可迭代的.当你用列表推导式的时候,你就创建了一个列表,而这个列表也是可迭代的: # >>> mylist = [x*x for x in range(3)] # >>> for i in mylist: # ... print(i) # 0 # 1 # 4 # 所有你可以用在for...in...语句中的都是可迭代的:比如lists,strings,files...因为这些可迭代的对象你可以随意的读取所以非常方便易用, # 但是你必须把它们的值放到内存里,当它们有很多值时就会消耗太多的内存. # -----------Generators 生成器 # 生成器也是迭代器的一种,但是你只能迭代它们一次. # 原因很简单,因为它们不是全部存在内存里,它们只在要调用的时候在内存里生成: # >>> mygenerator = (x*x for x in range(3)) # >>> for i in mygenerator: # ... print(i) # 0 # 1 # 4 # 生成器和迭代器的区别就是用()代替[] # 还有你不能用for i in mygenerator第二次调用生成器:首先计算0,然后会在内存里丢掉0去计算1,直到计算完4. # Yield # Yield的用法和关键字return差不多,下面的函数将会返回一个生成器: def createGenerator(): mylist = range(3) for i in mylist: print("jinlai-%s"%i) yield i*i mygenerator = createGenerator() # 创建生成器 # >>> print(mygenerator) # mygenerator is an object! # <generator object createGenerator at 0xb7555c34> for i in mygenerator: print(i) # # 在这里这个例子好像没什么用, # # 不过当你的函数要返回一个非常大的集合并且你希望只读一次的话,那么它就非常的方便了. # # 要理解Yield你必须先理解当你调用函数的时候, # # 函数里的代码并没有运行.函数仅仅返回生成器对象,这就是它最微妙的地方:-) # # 然后呢,每当for语句迭代生成器的时候你的代码才会运转. # # 现在,到了最难的部分: # # 当for语句第一次调用函数里返回的生成器对象,数里的代码就开始运作,直到碰到yield,然后会返回本次循环的第一个返回值. # # 所以下一次调用也将运行一次循环然后返回下一个值,直到没有值可以返回. # # 一旦函数运行并且没有碰到yeild语句就认为生成器已经为空了.原因有可能是循环结束或者没有满足if/else之类的. # # 控制迭代器的穷尽 class Bank(): #让我们建一个银行,生产很多的ATM crisis = False def create_atm(self): while not self.crisis: yield "$100" hsbc = Bank() #当一切就绪了你想要的多少ATM就给多少 corner_street_atm = hsbc.create_atm() print(corner_street_atm.__next__()) print([corner_street_atm.__next__() for cash in range(5)]) # hsbc.crisis = True # cao,经济危机来了没有钱了! print(corner_street_atm.__next__()) wall_street_atm = hsbc.create_atm() # 对于其他ATM,它还是True >>> print(wall_street_atm.next()) <type 'exceptions.StopIteration'> >>> hsbc.crisis = False # 麻烦的是,尽管危机过去了,ATM还是空的 >>> print(corner_street_atm.next()) <type 'exceptions.StopIteration'> >>> brand_new_atm = hsbc.create_atm() # 只能重新新建一个bank了 >>> for cash in brand_new_atm: ... print cash # Itertools (迭代器),你的好基友 # itertools模块包含了一些特殊的函数可以操作可迭代对象.有没有想过复制一个生成器?链接两个生成器?把嵌套列表里的值组织成一个列表?Map/Zip还不用创建另一个列表? # 来吧import itertools # 来一个例子?让我们看看4匹马比赛有多少个排名结果: import itertools #迭代器 houses = [1,2,3,4] races = itertools.permutations(houses) print(races) print(list(races)) 迭代是可迭代对象(对应__iter__()方法)和迭代器(对应__next__()方法)的一个过程. 可迭代对象就是任何你可以迭代的对象. 迭代器就是可以让你迭代可迭代对象的对象(有点绕口,意思就是这个意思)
34e0e5bf9739821f5339da3925cbce99a7da7846
KIDJourney/algorithm
/leetcode/algorithm/Pascal's Triangle II.py
676
3.71875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Position: E:\Program\LeetCoder_Python\algorithm\Pascal's Triangle II.py # @Author: KIDJourney # @Email: [email protected] # @Date: 2015-03-16 class Solution: # @return a list of integers def getRow(self, rowIndex): anslist = [] for i in range(rowIndex+1) : anslist.append(self.select(rowIndex,i)) return anslist def select(self,base,num): if num == 0 : return 1 mom = 1 kid = 1 for i in range(base+1)[-num:]: kid *= i for i in range(num+1)[1:] : mom *= i return kid/mom
f5d8e8e219d3b9e28b4051e4b82ceb7560161cef
AlanAS3/Curso-de-Python-Exercicios
/Exercícios/Mundo 2/Exercícios Normais/ex039.py
480
4.09375
4
from datetime import date print('==== Alistamento Militar ====') Anas = int(input('Informe a seu ano de nascimento: ')) Aatual = int(date.today().year) idade = Aatual - Anas if idade == 18: print('É hora de fazer o Alistamento Militar!') elif idade > 18: print('Já passou da hora de se Alistar!!') print(f'Já se passou {(idade) - 18} ano(s) do prazo') else: print('Você ainda vai se Alistar') print(f'Ainda falta {18 - (idade)} ano(s) para o alistamento')