blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
cd70f63a295a2d71fe9a4be59b906626e84ea668
benzheren/python-playground
/project-euler/p015.py
507
3.6875
4
''' Starting in the top left corner of a 2x2 grid, there are 6 routes (without backtracking) to the bottom right corner. How many routes are there through a 20x20 grid? ''' def route(max): result = [[0] * (max+1) for x in xrange(max+1)] result[0][0] = 1 for i in range(max+1): for j in range(max+1): if i >= 1: result[i][j] += result[i-1][j] if j >= 1: result[i][j] += result[i][j-1] return result[max][max] print route(20)
793ca0dd99a7d70bc36c13040748d8e510b668b0
benzheren/python-playground
/project-euler/p004.py
507
3.90625
4
''' A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91*99. Find the largest palindrome made from the product of two 3-digit numbers. ''' from time import time start = time() n = 0 for i in xrange(999, 100, -1): if i * i < n: break for j in xrange(i, n/i >=100 and n/i or 100, -1): x = i * j s = str(x) if s == s[::-1] and x > n: n = x end = time() print n print end - start
978f82ca4a28bbdc7ad3ab2d23c9cd4ada89e4db
jholstein/python-examples
/neural-network/neural-network-countdown.py
3,776
3.53125
4
##First Neural Network import numpy as np # X = (hours sleeping, hours studying), y = score on test X = np.array(([2, 5], [1, 5], [3, 5]), dtype=float) y = np.array(([10], [5], [15]), dtype=float) predictTest = np.array(([3,5]), dtype=float) predictTest = predictTest/np.amax(predictTest, axis=0) # scale units X = X/np.amax(X, axis=0) # maximum of X array y = y/np.amax(y, axis=0) # max test score is 100 class Neuron(object): def __init__(self,nextLayerSize): if nextLayerSize != 0: self.Weights = np.random.randn(1,nextLayerSize) #print self.Weights self.output = False else: self.output = True class Neural_Layer(object): def __init__(self,neurons,nextLayerSize): self.Neurons = [] for x in range(neurons): self.Neurons.append(Neuron(nextLayerSize)) #print "adding neuron" #print self.Neurons def Weights(self): outputWeights = [] for n in self.Neurons: if outputWeights == []: outputWeights = n.Weights else: outputWeights = np.concatenate((outputWeights,n.Weights), axis=0) #print "-----"+str(outputWeights) return outputWeights class Neural_Network(object): def __init__(self): self.inputSize = 2 self.hiddenSize = 3 self.outputSize = 1 self.inputLayer = Neural_Layer(self.inputSize,self.hiddenSize) self.hiddenLayer = Neural_Layer(self.hiddenSize,self.outputSize) self.outputLayer = Neural_Layer(self.outputSize,0) def forward(self, inputData): self.firstForward = np.dot(inputData, self.inputLayer.Weights()) self.secondForward = self.sigmoid(self.firstForward) self.thirdForward = np.dot(self.secondForward, self.hiddenLayer.Weights()) forwardOutput = self.sigmoid(self.thirdForward) return forwardOutput def backward(self, inputData, realData, predictedData): self.outputError = realData-predictedData self.outputErrorDelta = self.outputError*self.sigmoidPrime(predictedData) self.hiddenError = self.outputErrorDelta.dot(self.hiddenLayer.Weights().T) # z2 error: how much our hidden layer weights contributed to output error self.hiddenErrorDelta = self.hiddenError*self.sigmoidPrime(self.secondForward) # applying derivative of sigmoid to z2 error self.weightOneAdjust = inputData.T.dot(self.hiddenErrorDelta) # adjusting first set (input --> hidden) weights #Loop over the adjust, and apply changes in weight to each neuron for n in range(len(self.inputLayer.Neurons)): self.inputLayer.Neurons[n].Weights += self.weightOneAdjust[n] self.weightTwoAdjust = self.secondForward.T.dot(self.outputErrorDelta) # adjusting second set (hidden --> output) weights for m in range(len(self.hiddenLayer.Neurons)): self.hiddenLayer.Neurons[m].Weights += self.weightTwoAdjust[m] def sigmoid(self, s): # activation function return 1/(1+np.exp(-s)) def sigmoidPrime(self, s): #derivative of sigmoid return s * (1 - s) def train (self, X, y): o = self.forward(X) self.backward(X, y, o) NTester = Neural_Network() #print "Output: "+str(NTester.forward(X)) NN = Neural_Network() for i in xrange(10000): # trains the NN 1,000 times print "Input: \n" + str(X) print "Actual Output: \n" + str(y) print "Predicted Output: \n" + str(NN.forward(X)) print "Loss: \n" + str(np.mean(np.square(y - NN.forward(X)))) # mean sum squared loss print "\n" NN.train(X, y) print "----"+str(NN.forward(predictTest))
42c4c030d496bec361077236f7b388b45e3761c8
AnuradhaIyer/Python-Code
/walrus_demo.py
1,201
3.984375
4
''' Walrus operator is := official name : PEP 572 Assignment Expressions. Problem being solved: A regular "=" assignments is a statement and statements cant be used inside statement Rules: 1) The assignment expression must be in paranthesis 2) The return value is wjatever was assigning. ''' # New way for loop x = 10 while(y := x * 5) <= 75: print(y) x += 1 #Declarative statements sqrt = {x**2 : x for x in range(10)} #Case whre the walrus operator is good with open('data/stocks.txt') as f: while True: block = f.read(10) if not block: break print(repr(block)) #Better way with walrus # Better way with the walrus with open('data/stocks.txt') as f: while (block := f.read(10)): print(repr(block)) ###### Ways of Pascals Triangle using def binomial_coefficients(n): 'Coefficients of (x + 1) ** n' c = 1 row = [c] for k in range(1, n+1): c = c * (n - k + 1) // k row.append(c) return row def binomial_coefficients(n): 'Coefficients of (x + 1) ** n' return [(c := c * (n - k + 1) // k if k else 1) for k in range(n+1)]
4b5dea2d3c170ede818842a9b5a8e9d9a0e30ea2
webmalc/challenges
/data_structures/max_sliding_window.py
1,332
4.03125
4
# python3 from collections import deque def max_sliding_window(sequence, window_size): """ Given a sequence a 1 , . . . , a n of integers and an integer m ≤ n, find the maximum among {a i , . . . , a i+m−1 } for every 1 ≤ i ≤ n − m + 1. A naive O(nm) algorithm for solving this problem scans each window separately. Your goal is to design an O(n) algorithm. >>> max_sliding_window([2, 7, 3, 1, 5, 2, 6, 2], 4) [7, 7, 5, 6, 6] """ queue = deque() length = len(sequence) result = [] for i in range(window_size): while queue and sequence[i] >= sequence[queue[-1]]: queue.pop() queue.append(i) for i in range(window_size, length): result.append(sequence[queue[0]]) while queue and queue[0] <= i - window_size: queue.popleft() while queue and sequence[i] >= sequence[queue[-1]]: queue.pop() queue.append(i) result.append(sequence[queue[0]]) return result def get_args(): """ Get command line args """ num = int(input()) input_sequence = [int(i) for i in input().split()] assert len(input_sequence) == num window_size = int(input()) return input_sequence, window_size if __name__ == '__main__': print(*max_sliding_window(*get_args()))
8b7133196f3e274e2df6dab18ba45c2508dc71fd
forkcodeaiyc/codelab
/server/engines/python/defaults/defaults.py
2,035
3.9375
4
# Flatten a nested list structure a_list = [0, 1, [2, 3], 4, 5, [6, 7]] def flatten(nestedList): result = [] if not nestedList: return result stack = [list(nestedList)] while stack: current = stack.pop() next = current.pop() if current: stack.append(current) if isinstance(next, list): if next: stack.append(list(next)) else: result.append(next) result.reverse() return result print(flatten(a_list)) # Eliminate consecutive duplicates of list elements a_list = [0, 1, 1, 2, 3, 4, 4, 4, 5, 6, 7, 7] from itertools import groupby def compress(alist): return [key for key, group in groupby(alist)] print(compress(a_list)) # Problem 14: Duplicate the elements of a list a_list = [0, 1, 2, 3, 4, 5, 6, 7] def dupli(L): return [x for x in L for i in (1,2)] print(dupli(a_list)) # Duplicate the elements of a list a given number of times def dupli(L, N): return [x for x in L for i in range(N)] print(dupli(a_list, 3)) # Drop every N'th element from a list def drop(L, N): return [x for i,x in enumerate(L) if (i+1) % N] print(drop(a_list, 2)) # Rotate a list N places to the left def rotate(L, N): return L[N:] + L[:N] print(rotate(a_list, 2)) # Remove the K'th element from a list def remove_at(L, N): return L[N-1], L[:N-1] + L[N:] print(remove_at(a_list, 3)) # Insert an element at a given position into a list def insert_at(x, L, N): return L[:N-1]+[x]+L[N-1:] print(insert_at(8, a_list, 3)) # Calculate the Greatest Common Divisor (GCD) using Euclid's algorithm def gcd(a,b): while b != 0: a, b = b, a%b return a def coprime(a,b): return gcd(a,b) == 1 def phi(m): if m == 1: return 1 else: r = [n for n in range(1,m) if coprime(m,n)] return len(r) print(phi(10)) # Generate list of n-bit Gray codes. def gray(n): if n == 0: return [''] return ['0'+x for x in gray(n-1)]+['1'+y for y in gray(n-1)[::-1]] print(gray(3))
77ffe561d8ff2e08ce5aa7550b81091387ed4981
WellingtonTorres/Pythonteste
/aula10a.py
206
4.125
4
nome = str(input('Qual é o seu nome? ')) if nome == 'Wellington': print('Alem do nome ser bonito é nome da capital da NZ!') else: print('Seu nome é tão normal') print('Bom dia {}!'.format(nome))
a74c53f7de8307a42104fa1d4972e55dc97b2e29
WellingtonTorres/Pythonteste
/aula12a.py
327
3.953125
4
nome = str(input('Qual é o seu nome? ')) if nome == 'Wellington': print('Que nome bonito!') elif nome == 'Lucas' or nome == 'Ana' or nome == 'Victor': print('Seu nome é bem comum no Brazil!') elif nome in 'Barbara Eduarda Claudia Gabriela Jaqueline': print('Um belo nome feminino!') print('Tenha um bom dia, \033[33;m{}\033[m!'.format(nome))
ab0c1381c31007d12bcdafcf3ec0f8c3a9ad814d
bicipeng/python_crash_course_pj1
/alien.py
677
3.53125
4
'''a class to mange aliens''' import pygame from pygame.sprite import Sprite class Alien(Sprite): """docstring for Alien""" def __init__(self, ai_settings,screen): super(Alien, self).__init__() self.screen = screen self.ai_settings = ai_settings #create an alien an place it on the top left corner self.image = pygame.image.load('images/alien.bmp') self.rect = self.image.get_rect() #adding a space to the left of it that's equal to the alien's #width and a spave above it self.rect.x = self.rect.width self.rect.y = self.rect.height def blitme(self): '''Draw the alien at the top left of the screen''' self.screen.blit(self.image,self.rect)
833172bd630823bf9e035fd443f43098bc0c10b7
wansiLiangg/CISC471
/Assignment2/main.py
4,268
3.671875
4
''' CISC 471 HW2 ''' #Part1 -- Programming #Question 1.1 Find an Eulerian Cycle in a Graph class LinkedList: def __init__(self, node): self.node = node self.next = self def insert(self, link): link.next = self.next self.next = link return link def eulerianCycle(graph): cloneGraph = graph.copy() node = next(node for node, neighbour in cloneGraph.items() if neighbour) #Get a node that has edges neighbours = cloneGraph[node] start = currentNode = LinkedList(node) visited = {} while True: cycleStart = node while neighbours != []: visited[node] = currentNode node = neighbours.pop() neighbours = cloneGraph[node] currentNode = currentNode.insert(LinkedList(node)) if node != cycleStart: return "No Eulerian cycle" #A visited node still has edges while visited != {}: node, currentNode = visited.popitem() neighbours = cloneGraph[node] if neighbours != []: break else: break if cloneGraph.values() == []: return "No Eulerian cycle" eulerianCycle = [] currentNode = start while True: eulerianCycle.append(currentNode.node) currentNode = currentNode.next if currentNode == start: break return eulerianCycle #Question 1.2 Generate Contigs from a Collection of Reads def generateContigs(reads): prefixs = {} suffixs = {} k1mer = [] k = len(reads[0]) for seg in reads: prefix = seg[:-1] suffix = seg[1:] if prefix not in k1mer: k1mer.append(prefix) if suffix not in k1mer: k1mer.append(suffix) #Add k-1mer prefix and suffix as keys to the dictionaries for i in k1mer: prefixs[i] = [] suffixs[i] = [] #When the key is the prefix to the element, add k-1mer suffix to the dictionary for seg in reads: prefixs[seg[:-1]].append(seg[1:]) #When the key is the suffix to the element, add k-1mer prefix to the dictionary for key in prefixs.keys(): temp = prefixs[key] for j in temp: if j in suffixs.keys(): suffixs[j].append(key) else: suffixs[j] = [key] #Generate contigs contig = "" for key in prefixs.keys(): if prefixs[key] != [] and len(prefixs[key]) != 1 or len(suffixs[key]) != 1: for k in prefixs[key]: contig = key[:] + k[-1] if prefixs[k] != []: if len(prefixs[k]) != 1 or len(suffixs[k]) != 1: print(contig) continue else: x = prefixs[k][0] contig = contig + x[-1] while prefixs[x] != [] and len(prefixs[x]) == 1 and len(suffixs[x]) == 1: contig = contig + prefixs[x][0][-1] print(contig) else: print(contig) continue #Unit tests for part1 #Inputs for Eulerian Cycle graph1 = {"0":["3"], "1":["0"], "2":["1","6"], "3":["2"], "4":["2"], "5":["4"], "6":["5","8"], "7":["9"], "8":["7"], "9":["6"]} graph2 = {"A":["E","F"], "B":["A"], "C":["A","B"], "D":["C"], "E":["C", "D"], "F":["E"]} graph3 = {"A":["B","C"], "B":["C", "E"], "C":["D"], "D":["B"], "E":["D"]} #Inputs for generate contigs contig1 = ["ATG", "ATG", "TGT", "TGG", "CAT", "GGA", "GAT", "AGA"] contig2 = ["ATG", "TTG", "TGA", "ACA", "GAT", "TGA", "ATT", "GAC"] contig3 = ["ATG", "ATG", "TGT", "TGA", "CAT", "GGA", "GAT", "AGA"] def main(): print("Positive unit test of Eulerian Cycle") print(eulerianCycle(graph1)) print("Positive unit test of Eulerian Cycle") print(eulerianCycle(graph2)) print("Negative unit test of Eulerian Cycle") print(eulerianCycle(graph3)) print("") print("Positive unit test of generate contigs") generateContigs(contig1) print("Positive unit test of generate contigs") generateContigs(contig2) print("Negative unit test of generate contigs") generateContigs(contig3) main()
c3e4d19ad6b650bd400a75799c512bb8eecad4c9
ldswaby/CMEECourseWork
/Week3/Code/get_TreeHeight.py
2,274
4.5
4
#!/usr/bin/env python3 """Calculate tree heights using Python and writes to csv. Accepts Two optional arguments: file name, and output directory path.""" ## Variables ## __author__ = 'Luke Swaby (lds20@ic.ac.uk), ' \ 'Jinkai Sun (jingkai.sun20@imperial.ac.uk), ' \ 'Acacia Tang (t.tang20@imperial.ac.uk), ' \ 'Dengku Tang (dengkui.tang20@imperial.ac.uk)' __version__ = '0.0.1' ## Imports ## import sys import pandas as pd import numpy as np ## Functions ## def TreesHeight(degrees, dist): """This function calculates heights of trees given distance of each tree from its base and angle to its top, using the trigonometric formula height = distance * tan(radians) Arguments: - degrees: The angle of elevation of tree - dist: The distance from base of tree (e.g., meters) Output: - The heights of the tree, same units as "distance" """ radians = degrees * np.pi / 180 height = dist * np.tan(radians) print(height) return height def main(argv): """Writes tree height results to CSV file including the input file name in the output file name. """ if len(argv) < 2: print("WARNING: no arguments parsed. Default filename used: " "'trees.csv'.\n") filename = "trees.csv" outdir = "../Data/" elif len(argv) == 2: filename = argv[1] outdir = "../Data/" elif len(argv) == 3: filename = argv[1] outdir = argv[2] # Accept output directory path as second arg else: print("WARNING: too many arguments parsed.Default filename used: " "'trees.csv'.\n") filename = "trees.csv" outdir = "../Data/" filename_noExt = filename.split('/')[-1].split('.')[0] # Assumes no full # stops in filename save_name = "../Results/%s_treeheights_python.csv" % filename_noExt filepath = outdir + filename trees_data = pd.DataFrame(pd.read_csv(filepath)) trees_data["Height"] = TreesHeight(trees_data["Angle.degrees"], trees_data["Distance.m"]) # Save to csv trees_data.to_csv(save_name, sep=",", index=False) return 0 ## Main ## if __name__ == "__main__": status = main(sys.argv) sys.exit(status)
6f5863262df12da64f2b130ac485b4a76ae282b6
ldswaby/CMEECourseWork
/Week3/Code/Vectorize1.py
1,057
4.0625
4
#!/usr/bin/env python3 """Groupwork: to do vectorize1 using Python""" ## Variables ## __author__ = 'Luke Swaby (lds20@ic.ac.uk), ' \ 'Jinkai Sun (jingkai.sun20@imperial.ac.uk), ' \ 'Acacia Tang (t.tang20@imperial.ac.uk), ' \ 'Dengku Tang (dengkui.tang20@imperial.ac.uk)' __version__ = '0.0.1' ## Imports ## import sys import time import numpy as np ## Functions ## def SumALLElements(M): """Sum all elements of a matrix """ Tot = 0 Dimensions = np.shape(M) for i in range(0, Dimensions[0]): for j in range(0, Dimensions[1]): Tot += M[i, j] return Tot def main(): """Print the execution time of loop-based SumALLElements() and vectorized np.sum() functions. """ M = np.random.rand(1000, 1000) start1 = time.time() SumALLElements(M) print("SumALLElements takes %f s to run" % (time.time() - start1)) start2 = time.time() # print(np.sum(M)) np.sum(M) print("np.sum takes %f s to run" % (time.time() - start2)) return 0 ## Main ## if __name__ == '__main__': status = main() sys.exit(status)
bdf5cc71e2046f299a0327fc71bf903043428130
Minimaximize/IFN680_A1
/IFN 680 - Assessment 1 - Current Best Answer/population_search.py
4,877
4.25
4
''' This module defines an abstract class 'Population' for particle filter search. ''' import numpy as np #----------------------------------------------------------------------------- class Population(object): ''' An abstract container class for a collection of individuals to be used in a 'particle filter' type of search. At each generation, the probability that the ith individual W[i,:] will be selected for the next generation is proportional to exp(-C[i]/T) where C[i] is the cost of W[i,:] and T is a temperature parameter. See 'resample' method. Usage: - Initialize a population 'pop' with the constructor of a subclass derived from Population. - Call pop.particle_filter_search() - Retrieve pop.best_w ''' def __init__(self, W): ''' Initialize the population with a copy of W W[i,:] is a vector coding the ith individual ''' self.n = W.shape[0] # population size self.W = W.copy() self.C = np.zeros((self.n,)) # self.C[i] is the cost of the ith individual self.temperature = 1.0 self.best_cost = np.inf # cost of the best individual seen so far def mutate(self): ''' This function should be overridden in subclasses. Mutate each individual. This operator is application specific. ''' raise NotImplementedError("Method 'mutate' must be implemented in subclasses") def evaluate(self): ''' This function should be overridden in subclasses. Evaluate the cost of each individual. Store the result in self.C That is, self.C[i] is the cost of the ith individual. Keep track of the best individual seen so far in self.best_w = self.W[i_min].copy() self.best_cost = cost_min ''' raise NotImplementedError("Method 'evaluate' must be implemented in subclasses") def resample(self): ''' Resample the population. The whole current population is replaced. The probability that the ith individual W[i,:] will be selected for the next generation is proportional to exp(-C[i]/T) where C[i] is the cost of W[i,:] and T is a temperature parameter. @pre the population has been evaluated by a call to self.evaluate() ''' Ec = np.exp(-self.C/self.temperature) sum_Ec = Ec.sum() P = Ec/sum_Ec # P is a probability vector # first argument of np.random.choice has to be 1D. Cannot use X! lottery_result = np.random.choice(np.arange(self.n), self.n, replace=True, p = P) self.W = self.W[lottery_result,:] def particle_filter_search(self, steps, log=False): ''' Perform a particle filter search with 'steps' generations. @param steps: number of generations to be computed log : if True, return a log (list) of the W arrays at each step. @post self.best_w is the cost of the best solution found self.best_cost is its cost ''' self.best_cost = np.inf # best cost so far if log: Lw = [] Lc = [] temperature_schedule = np.linspace(self.temperature,1,steps) for step in range(steps): self.temperature = temperature_schedule[step] cost = self.evaluate() # update best_cost if log: Lw.append(self.W.copy()) Lc.append(cost) self.resample() self.mutate() if log: return Lw, Lc #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # CODE CEMETARY #def resample_population(X, C, temperature): # ''' # Individual X[i] has non-negative cost C[i] # Its fitness is proportional to exp(-C[i]/temperature) # ''' # n = X.shape[0] # size of the population # Ec = np.exp(-C/temperature) # sum_Ec = Ec.sum() # P = Ec/sum_Ec # # first argument of np.random.choice has to be 1D. Cannot use X # lottery_result = np.random.choice(np.arange(n), n, replace=True, p = P) # X_sampled = X[lottery_result,:] # return X_sampled # # # # n=6 # X = np.arange(10,10+2*6).reshape((-1,2)) # #np.random.seed(42) # C = np.random.rand(n) *4 # temperature = 1
4e44ee0c832595b4e5bca4e3fd185bf95ca74b9a
wangruicsu/LeetCode_practice-python
/25-Reverse_Nodes_in_k-Group.py
2,421
3.921875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def reverseKGroup(self, head, k): """ :type head: ListNode :type k: int :rtype: ListNode """ """ 思路: 约束①:空链表 约束②:链表长度不是 K 的整数倍时,余下的部分不进行逆转 DO: 创建新的逆转后的链表 newList 在每个 长度为(k-1)的 for 循环中 创建逆转的子链表 tmpList 子链表长度不够 k 时,newList直接接上余下的部分 newList 接上 tmpList @date:2018-12-03 @author:Raine """ p1 = head # 依次指向第1,K+1,2K+1,,,个节点 if not p1:return head # 返回空链表 p2 = head # 指向目前正在翻转的节点 newList = ListNode(0) # 创建逆转后的链表 p3 = newList # 链表长度小于 K 就不进行翻转 while(p2 is not None): tmpList = ListNode(0) #新的子 逆序链表 tmpList.val = p2.val #print(tmpList.val) p4 = tmpList # 指向子链表的第一个节点 p5 = tmpList # 指向子链表的最后一个节点,用于 p3 的移动 p1 = p2 # 标记 子链表 tmpList 开始翻转的位置 for i in range(k-1): # 生成子链表 p2 = p2.next if p2 is None: p3.next = p1 #子链表长度不足 k,newList 直接从 p1 接上不进行翻转的部分。 return newList.next newNode = ListNode(p2.val) # 创建新节点,并加入 tmpList newNode.next = tmpList tmpList = newNode # 更新 tmpList p4 = tmpList p3.next = p4 #每次完整得到一个逆序的 k 长度的链表时,才接入 newList p3 = p5 # p3 指向 newList 最后一个节点,也就是当前 tmpList的最后一个节点 p2 = p2.next # p2 指向下一次开始翻转的节点 return newList.next
10801e723093b8d6965312f8546ac7fec37aac17
amitgadhave17/Python_Training
/Day4/Classes.py
920
3.6875
4
from datetime import date class Person: def __init__(self, name, surname, birthdate, email, address, mob, tel): self.name = name self.surname = surname self.birthdate = birthdate self.email = email self.address = address self.mob = mob self.tel = tel return def cal_age(self): d2 = date.today() d3 = d2.year - self.birthdate.year return d3 def __del__(self): print('deleted'+ str(self.birthdate.year)) return if True: P = Person('amit', 'gadhave', date(1995,10,17), 'amitgadhave17', 'Pune', '9890', '020') P1 = Person('amit', 'gadhave', date(1996,10,17), 'amitgadhave17', 'Pune', '9890', '020') P2 = Person('amit', 'gadhave', date(1997,10,17), 'amitgadhave17', 'Pune', '9890', '020') print(P.cal_age()) print(P1.cal_age()) print(P2.cal_age()) del P2 print('done')
eef274367f9d57f490459286d4e4dc6622fa2581
cmesiasd/CC3101-Matematicas-Discretas
/Tarea1/T1.py
3,489
3.71875
4
# Run the file as "python SAT.py -v" # Add further needed modules import unittest # To implement the functions below, you are allowed # to define auxiliary functions, if convenient. def SetLiteral(formula, lit): new = formula[:] #Crea una lista copia de formula, donde se iran eliminando literales for i in formula: #Recorre el arreglo nuevo_i = list(i) for j in nuevo_i: if j == lit: #Si el literal esta en el arreglo, elimina toda su oracion new.remove(i) elif j == -1 * lit: #Si esta la negacion del literal, elimina ese literal i.remove(j) return new #Retorna la nueva lista def IsSatisfiable(formula): if formula == []: #Si la formula es vacia Retorna True return True elif [] in formula: #Si la formula contiene un literal vacio, ie. Falso, retorna False return False else: elemento = formula[0][0] #Toma el primer elemento que pilla lit = elemento nuevo = SetLiteral(formula, lit) #Setea el valor a True y simplifica if nuevo == []: #Si la simplificacion es vacia, retorna True return True elif [] in nuevo: #Si hay un literal vacio en la nueva formula return IsSatisfiable(SetLiteral(formula,-lit)) #Retorna el caso recursivo seteando el litelar a falso else: #Retorna la recursividad sobre la nueva formula return IsSatisfiable(nuevo) def BuildModel(formula): dic = {} sat = IsSatisfiable(formula) if sat == False: #Si la formula no es SAT return (sat,dic) #Retorna False y un diccionario vacio else: #Si la formula es SAT literales = [] #Crea una LISTA while len(formula) >= 1: lit = formula[0][0] if IsSatisfiable(SetLiteral(formula,lit)): #Ve si es SAT la simplificacion con el lit elegido literales.append([lit,True]) #Guarda una tupla con el valor del literal y su valuacion formula = SetLiteral(formula,lit) #Luego actualiza la formula else: #Analogo a lo anterior, pero con la negacion del literal literales.append([-lit,True]) formula = SetLiteral(formula,-lit) for i in literales: #Recorre la lista de tuplas if i[0] < 0: #Si el literal es negativo i[0] = abs(i[0]) #Cambia el signo del literal i[1] = not i[1] #Cambia la valuacion literales.sort() #Ordena los literales for i in literales: dic[i[0]] = i[1] #Pasa la lista a un diccionario return (sat, dic) #Retorna el Booleano y el diccionario class Tests(unittest.TestCase): def setUp(self): pass def test_SetLiteral(self): self.assertEqual(SetLiteral([[1, 2, -3], [-1, -2, 4], [3, 4]], 1), [[-2, 4], [3, 4]]) self.assertEqual(SetLiteral([[1, 2, -3], [-1, -2, 4], [3, 4]], -1), [[2, -3], [3, 4]]) def test_IsSatisfiable(self): self.assertEqual(IsSatisfiable([[1, 2, -3], [-1, -2, 4], [3, 4]]), True) self.assertEqual(IsSatisfiable([[1, 2], [1, -2], [], [-1]]), False) self.assertEqual(IsSatisfiable([]), True) def test_BuildModel(self): self.assertEqual(BuildModel([[-2, 4], [1], [-4,-1]]), (True, {1: True, 2: False, 4: False})) self.assertEqual(BuildModel([[1,2], [-1,-2], [-1,2], [1,-2]]), (False, {})) # Perform the tests when runing the file if __name__ == '__main__': unittest.main()
0b93e8f102c95fae9189001148325937dcb520f9
davide990/IRSW-lab
/PythonApplication1/nltk_ex1.py
3,791
3.8125
4
'''from nltk.book import *''' import nltk import math import numpy def main(): print("hi") ''' Open a text file, tokenize and return an nltk.Text object ''' def open_textfile(fname): f = open(fname, 'r') raw_text = f.read() tokens = nltk.word_tokenize(raw_text) text = nltk.Text(tokens) return text ''' Get the n most common words from a given text text -> nltk.Text object ''' def get_n_most_common_words(text, n): fdist = nltk.FreqDist(text) # creates a frequency distribution from a list most_commons = fdist.most_common(n) return most_commons ''' Remove the n most common words from a given text text -> nltk.Text object ''' def remove_most_common(text, n): # get the frequency distribution for the input text fdist = nltk.FreqDist(text) most_common_words = fdist.most_common(n) most_common = [w[0] for w in most_common_words] ret_text = [word for word in text if word not in most_common] return nltk.Text(ret_text) ''' Remove the n less common words from a given text text -> nltk.Text object ''' def remove_less_common_words(text, n): # get the frequency distribution for the input text fdist = nltk.FreqDist(text) most_common_words = fdist.most_common(len(text)) most_common_words.sort(key=lambda x: x[1]) most_common_words = most_common_words[0:n-1] most_common = [w[0] for w in most_common_words] ret_text = [word for word in text if word not in most_common] return nltk.Text(ret_text) ''' Calculate the shannon information entropy for the specified text, and returns a list of word ordered by information entropy text -> nltk.Text object ''' def calculate_text_entropy(text): # get the frequency distribution for the input text fdist = nltk.FreqDist(text) # get the text lenght words_count = len(set(text)) # initialize the output list, that is, the most relevant words output_list = [] # iterate each word for parola in set(text): # get the word frequency within the text (== Pwi) freq_word = fdist.freq(parola) # calculate the information quantity information = -(freq_word * math.log(freq_word)) # append the couple word-information to the output list output_list.append([parola,information]) # sort the output list by the information quantity in reverse order output_list.sort(key=lambda x: x[1], reverse=True) return output_list def esercizio(text): # get the frequency distribution for the input text fdist = nltk.FreqDist(set(text)) dict = [] for parola in set(text): # get the word frequency within the text dict.append([w,fdist.freq(parola)]) def lexical_diversity(text): return len(set(text)) / len(text) def percentage(count, total): return 100 * (count / total) def jakkard(d1,d2): return len(set(d1).intersection(d2)) / len(set(d1).union(d2)) ''' Calculate the Jakkard distance between all the documents in the input list testi -> list of nltk.Text objects ''' def jakkard_distance(testi): coppie = [[i,j] for i in testi for j in testi] coefficienti = [] for coppia in coppie: j = jakkard(coppia[0],coppia[1]) if(j < 1): coefficienti.append([coppia[0],coppia[1],j]) coefficienti.sort(key=lambda x: x[2]) return coefficienti if __name__ == "__main__": '''main()''' txt = open_textfile('C:\promessi_sposi.txt') cleaned_text = remove_most_common(text, 100) re_cleaned_text = remove_less_common_words(cleaned_text, 100) print(re_cleaned_text) #cleaned = calculate_text_entropy(txt) #print(cleaned) '''lexical_diversity(text3) lexical_diversity(text5) percentage(4,5) percentage(text4.count('a'),len(text4))'''
350abd340322e564c4ff24b4431d14715ac54708
JacksonOsvaldo/bc_calcado-vendas
/fixtures/manager_db.py
8,303
3.859375
4
# -*- coding: utf-8 -*- """ Este App gerencia um banco de dados sqlite3. Pode-se usar o modo interativo com python2. Popula as tabelas do banco de dados com valores randômicos. Banco de dados: 'db.sqlite3' Tabelas: 'vendas_brand', 'vendas_customer', 'vendas_product', 'vendas_sale', 'vendas_saledetail' """ import os import io import sqlite3 import random import datetime import names # gera nomes randomicos import rstr # gera strings randomicas from decimal import Decimal from gen_random_values import gen_doc, gen_ncm, gen_phone, gen_decimal, gen_ipi, gen_timestamp qcustomers = 60 qsellers = 20 qproducts = 1645 # 100 qsales = 300 qsaledetails = 1200 class Connect(object): ''' A classe Connect representa o banco de dados. ''' def __init__(self, db_name): try: # conectando... self.conn = sqlite3.connect(db_name) self.cursor = self.conn.cursor() # imprimindo nome do banco print("Banco:", db_name) # lendo a versão do banco self.cursor.execute('SELECT SQLITE_VERSION()') self.data = self.cursor.fetchone() # imprimindo a versão do banco print("SQLite version: %s" % self.data) except sqlite3.Error: print("Erro ao abrir banco.") return False def commit_db(self): if self.conn: self.conn.commit() def close_db(self): if self.conn: self.conn.close() print("Conexão fechada.") class VendasDb(object): def __init__(self): self.db = Connect('../db.sqlite3') def insert_for_file(self): try: with open('brand.sql', 'rt') as f: dados = f.read() self.db.cursor.executescript(dados) print("Registros criados com sucesso na tabela vendas_brand.") except sqlite3.IntegrityError: print("Aviso: A marca deve ser única.") return False def insert_random_customer(self, repeat=qcustomers): ''' Inserir registros com valores randomicos ''' customer_list = [] for _ in range(repeat): # d = datetime.datetime.now().isoformat(" ") d = gen_timestamp(2014, 2015) + '+00' fname = names.get_first_name() lname = names.get_last_name() email = fname[0].lower() + '.' + lname.lower() + '@example.com' birthday = gen_timestamp() + '+00' customer_list.append( (gen_cpf(), fname, lname, email, gen_phone(), birthday, d, d)) try: self.db.cursor.executemany(""" INSERT INTO vendas_customer (cpf, firstname, lastname, email, phone, birthday, created, modified) VALUES (?,?,?,?,?,?,?,?) """, customer_list) self.db.commit_db() print("Inserindo %s registros na tabela vendas_customer." % repeat) print("Registros criados com sucesso.") except sqlite3.IntegrityError: print("Aviso: O email deve ser único.") return False def insert_random_seller(self, repeat=qsellers): ''' Inserir registros com valores randomicos ''' seller_list = [] for _ in range(repeat): d = gen_timestamp(2014, 2015) + '+00' fname = names.get_first_name() lname = names.get_last_name() email = fname[0].lower() + '.' + lname.lower() + '@example.com' birthday = gen_timestamp() + '+00' active = rstr.rstr('01', 1) internal = rstr.rstr('01', 1) commissioned = rstr.rstr('01', 1) commission = 0.01 seller_list.append( (gen_doc(), fname, lname, email, gen_phone(), birthday, active, internal, commissioned, commission, d, d)) try: self.db.cursor.executemany(""" INSERT INTO vendas_seller (cpf, firstname, lastname, email, phone, birthday, active, internal, commissioned, commission, created, modified) VALUES (?,?,?,?,?,?,?,?,?,?,?,?) """, seller_list) self.db.commit_db() print("Inserindo %s registros na tabela vendas_seller." % repeat) print("Registros criados com sucesso.") except sqlite3.IntegrityError: print("Aviso: O email deve ser único.") return False def insert_random_product(self, repeat=qproducts): product_list = [] for i in range(repeat): imported = rstr.rstr('01', 1) # escolha personalizada de produtos fora de linha if i % 26 == 0: if i > 0: outofline = '1' else: outofline = '0' else: outofline = '0' ncm = gen_ncm() brand = random.randint(1, 20) price = float(gen_decimal(4, 2)) ipi = 0 if imported == '1': ipi = float(gen_ipi()) if ipi > 0.5: ipi = ipi - 0.5 stock = random.randint(1, 999) stock_min = random.randint(1, 20) f = io.open('products.txt', 'rt', encoding='utf-8') linelist = f.readlines() product = linelist[i].split(',')[0] product_list.append( (imported, outofline, ncm, brand, product, price, ipi, stock, stock_min)) try: self.db.cursor.executemany(""" INSERT INTO vendas_product (imported, outofline, ncm, brand_id, product, price, ipi, stock, stock_min) VALUES (?,?,?,?,?,?,?,?,?) """, product_list) self.db.commit_db() print("Inserindo %s registros na tabela vendas_product." % repeat) print("Registros criados com sucesso.") except sqlite3.IntegrityError: print("Aviso: O produto deve ser único.") return False def insert_random_sale(self, repeat=qsales): sale_list = [] for _ in range(repeat): d = gen_timestamp(2014, 2015) + '+00' customer = random.randint(1, qcustomers) seller = random.randint(1, qsellers) sale_list.append((customer, seller, d, d)) try: self.db.cursor.executemany(""" INSERT INTO vendas_sale (customer_id, seller_id, date_sale, modified) VALUES (?,?,?,?) """, sale_list) self.db.commit_db() print("Inserindo %s registros na tabela vendas_sale." % repeat) print("Registros criados com sucesso.") except sqlite3.IntegrityError: return False def insert_random_saledetail(self, repeat=qsaledetails): saledetail_list = [] for _ in range(repeat): sale = random.randint(1, qsales) product = random.randint(1, qproducts) quantity = random.randint(1, 50) # find price and ipi of product r = self.db.cursor.execute( 'SELECT price, ipi FROM vendas_product WHERE id = ?', (product,)) v = r.fetchall()[0] price = v[0] ipi = v[1] subtotal = quantity * float(price) saledetail_list.append( (sale, product, quantity, price, ipi, subtotal)) try: self.db.cursor.executemany(""" INSERT INTO vendas_saledetail (sale_id, product_id, quantity, price_sale, ipi_sale, subtotal) VALUES (?,?,?,?,?,?) """, saledetail_list) self.db.commit_db() print("Inserindo %s registros na tabela vendas_saledetail." % repeat) print("Registros criados com sucesso.") except sqlite3.IntegrityError: return False def close_connection(self): self.db.close_db() if __name__ == '__main__': v = VendasDb() v.insert_for_file() v.insert_random_customer() v.insert_random_seller() v.insert_random_product() # 100 v.insert_random_sale() v.insert_random_saledetail() v.close_connection() # repare que o valor do parâmetro pode ser mudado
3d2f444f1d240b071793b1ffaa99109fa5089a8e
josedesoto/s3-upload
/get_s3_file.py
3,523
3.5
4
#! /usr/bin/env python """Download logs or files from S3 Usage: python get_s3_file.py [options] Options: -f ..., --log=... Name of the log to download -D ..., --datelog=... Date to thelog to donwload -l, --list List all lthe content on the storage -h, --help Show this help -s, size Show total size of the bucket -d Show debugging information while parsing (disable) Examples: python get_s3_file.py --list python get_s3_file.py -f example-of-name.log -D 2011-03-29 This script requires the boto module and dateutil for Python to be installed. For example: apt-get install python-boto python-dateutil """ import boto from boto.s3.key import Key import sys from dateutil import parser import getopt _debug = 0 class LogError(Exception): def __init__(self, message, value=None): self.message = message self.value=value class MyStorage: BUCKET_NAME = 'bucket_name' AWS_ACCESS_KEY_ID='' AWS_SECRET_ACCESS_KEY='' @staticmethod def __connect(): try: conn = boto.connect_s3(MyStorage.AWS_ACCESS_KEY_ID,MyStorage.AWS_SECRET_ACCESS_KEY) bucket = conn.get_bucket(MyStorage.BUCKET_NAME) except: print LogError("ERROR, connecting to Amazon").message sys.exit(1) return bucket @staticmethod def get_list(): list_files=MyStorage.__connect().list() for i in list_files: print str(i.key) @staticmethod def get_size(): """Print the total size of the bucket""" list_files=MyStorage.__connect().list() size=0 for i in list_files: #size in bytes size=size+i.size #SIZE IN GB size = size / 1024 / 1024 / 1024 print "TOTAL SIZE: "+str(size)+"GB" @staticmethod def get_file(logname, datelog): if logname=='': print 'ERROR parsing the log name. The script send exit status.' sys.exit(1) if datelog=='': print 'ERROR parsing the date. The script send exit status.' sys.exit(1) try: day=parser.parse(datelog).strftime("%d") year=parser.parse(datelog).strftime("%Y") month=parser.parse(datelog).strftime("%m") except: print 'ERROR parsing: '+datelog+' the date (date have to be in this format: 2011-03-29). The script send exit status.' sys.exit(2) try: file_key=year+'/'+month+'/'+day+'/'+logname+'.'+datelog+'.bz2' key=MyStorage.__connect().get_key(file_key) key.get_contents_to_filename(logname+'.'+datelog+'.bz2') except: print LogError("ERROR, downloading the file").message sys.exit(2) print "The log have been donwload: "+logname+'.'+datelog+'.bz2' def usage(): print __doc__ def main(argv): datelog='' logname='' try: opts, args = getopt.getopt(argv, "hlf:D:d:s", ["help", "list", "logname=", "datelog=","size"]) except getopt.GetoptError: usage() sys.exit(2) for opt, arg in opts: if opt in ("-h", "--help"): usage() sys.exit() elif opt in ("-l", "--list"): MyStorage.get_list() sys.exit() elif opt == '-d': global _debug _debug = 1 elif opt in ("-f", "--logname"): logname = arg elif opt in ("-D", "--datelog"): datelog= arg elif opt in ("-s", "--size"): MyStorage.get_size() sys.exit() MyStorage.get_file(logname, datelog) if __name__ == "__main__": main(sys.argv[1:])
6f230e46e7f3cdbd542f97613853b825f76273fd
pringlized/phraseware
/python/Phraseware/phraseware.py
1,489
3.5625
4
import sys import csv import random import constants # init vars numWords = 0 wordDict = {} wordKeys = [] thePhrase = "" print "\nLet's make a Diceware inspired password..." print "------------------------------------------" # ask for how many words to use and validate while True: try: numWords = int(raw_input("How many words do you want to use [5 - 12]: ")) except ValueError: print constants.INPUT_ERR_MSG continue else: if (constants.MIN_NUM_WORDS <= numWords) and (numWords <= constants.MAX_NUM_WORDS): break else: print constants.INPUT_ERR_MSG continue # read in the dictionary from csv file try: #TODO: Validate proper csv format in a function with open(constants.DICT_FILE, mode='r') as infile: reader = csv.reader(infile) wordDict = {rows[0]:rows[1] for rows in reader} except IOError as e: sys.exit(e) # roll the dice 5 times for each word and create keys for i in range(0, int(numWords)): theWord = "" for r in range(constants.NUM_ROLLS): # get random number ranNum = str(random.randint(1, constants.NUM_SIDES)) theWord = theWord + ranNum wordKeys.append(theWord) # get words from list based on key for key in wordKeys: thePhrase = thePhrase + " " + wordDict[key] # echo the phase print "\nYour phrase: " + thePhrase print "Phrase length: " + str(len(thePhrase)) print "------------------------------------------"
d9a442c886eb178e2fab6422e8a1ef44e7e9ab07
bizhan/pythontest3
/chapter_1/range_vs_enumerate.py
1,040
4.1875
4
#print("Hello world") def fizz_buzz(numbers): ''' Given a list of integers: 1. Replace all integers that are evenly divisible by 3 with "fizz" 2. Replace all integers divisble by 5 with "buzz" 3. Replace all integers divisible by both 3 and 5 with "fizzbuzz" >>> numbers = [45, 22,14,65, 97, 72] >>> fizz_buzz(numbers) >>> numbers ['fizzbuzz', 22, 14, 'buzz', 97, 'fizz'] ''' ''' for i in range(len(numbers)): num = numbers[i] if num % 3 ==0 and num % 5 == 0: numbers[i] = 'fizzbuzz' elif num % 3 == 0: numbers[i] = 'fizz' elif num % 5 == 0: numbers[i] = 'buzz' ''' for i, num in enumerate(numbers): if num % 3 ==0 and num % 5 == 0: numbers[i] = 'fizzbuzz' elif num % 3 == 0: numbers[i] = 'fizz' elif num % 5 == 0: numbers[i] = 'buzz' #return output #print(fizz_buzz([45, 22, 14, 65, 97, 72])) #ipython --no-banner -i range_vs_enumerate.py #python3 -m doctest range_vs_enumerate.py #[tup for tup in enumerate([1,2,3], start = 10)]
026b22cd4e0ff011b244dfb6308f3b2d44353d3b
osmanuss/prog
/testi/10test/10test.py
625
4
4
##1 # a = 5 # b = 15 # if True and False: # print(a) # else: # print(b) ##2 # a = 5 # b = 6 # print(a, 1 if a < b else "<=", b) ##3 # a = 5 # b = 15 # if True and True: # print(a) # else: # print(b) ##4 # a = 6 # b = 7 # c = 1 + b if a > b else a # print(c) ##5 # a = 5 # b = 15 # if True or False: # print(a) # else: # print(b) ##6 # a = 5 # b = 15 # if True or True: # print(a) # else: # print(b) ##7 # a = 5 # b = 15 # if True: # print(a) # else: # print(b) ##8 # a = 5 # b = 15 # if true: # print(a) # else: # print(b) ##9 # a = 5 # b = 6 # print(b if a > b else a)
08f10c107886ccd9b6f93bfd72e7287a47b29d2e
timmy61109/Introduction-to-Programming-Using-Python
/own_practice/two_twenty_one.py
806
3.765625
4
""" 程式設計練習題 2.2-2.10 2.21 財務金融應用程式:複利值. 利息公式: 100 * (1 + 0.00417) = 100.417 (100 + 100.417) * (1 + 0.00417) = 201.252 (100 + 201.252) * (1 + 0.00417) = 302.507 以下是輸出樣本: ``` Enter the monthly saving amount:100 After the sixth month, the account value is 608.81 ``` """ import ast amount = ast.literal_eval(input("Enter the monthly saving amount:")) account_value = amount amount *= (1 + 0.00417) amount = amount + account_value amount *= (1 + 0.00417) amount = amount + account_value amount *= (1 + 0.00417) amount = amount + account_value amount *= (1 + 0.00417) amount = amount + account_value amount *= (1 + 0.00417) amount = amount + account_value amount *= (1 + 0.00417) print("After the sixth month, the account value is", amount)
954c952dba2e72d6b70c9d345b96090b0a43b732
timmy61109/Introduction-to-Programming-Using-Python
/examples/TestSet.py
549
4.3125
4
from Set import Set set = Set() # Create an empty set set.add(45) set.add(13) set.add(43) set.add(43) set.add(1) set.add(2) print("Elements in set: " + str(set)) print("Number of elements in set: " + str(set.getSize())) print("Is 1 in set? " + str(set.contains(1))) print("Is 11 in set? " + str(set.contains(11))) set.remove(2) print("After deleting 2, the set is " + str(set)) print("The internal table for set is " + set.getTable()) set.clear() print("After deleting all elements") print("The internal table for set is " + set.getTable())
f20df9950890ea3b43729837524065283366aa60
timmy61109/Introduction-to-Programming-Using-Python
/examples/ComputeFactorialTailRecursion.py
322
4.15625
4
# Return the factorial for a specified number def factorial(n): return factorialHelper(n, 1) # Call auxiliary function # Auxiliary tail-recursive function for factorial def factorialHelper(n, result): if n == 0: return result else: return factorialHelper(n - 1, n * result) # Recursive call
43a372bacd7092285e07b4600bfdcdcc8731027d
timmy61109/Introduction-to-Programming-Using-Python
/examples/SimpleIfDemo.py
126
3.96875
4
number = eval(input("Enter an integer: ")) if number % 5 == 0 : print("HiFive"); if number % 2 == 0 : print("HiEven");
0ad23dca684097914370ac9f35a385b80ed74cc4
timmy61109/Introduction-to-Programming-Using-Python
/examples/ComputeLoan.py
687
4.21875
4
# Enter yearly interest rate annualInterestRate = eval(input( "Enter annual interest rate, e.g., 8.25: ")) monthlyInterestRate = annualInterestRate / 1200 # Enter number of years numberOfYears = eval(input( "Enter number of years as an integer, e.g., 5: ")) # Enter loan amount loanAmount = eval(input("Enter loan amount, e.g., 120000.95: ")) # Calculate payment monthlyPayment = loanAmount * monthlyInterestRate / (1 - 1 / (1 + monthlyInterestRate) ** (numberOfYears * 12)) totalPayment = monthlyPayment * numberOfYears * 12 # Display results print("The monthly payment is", int(monthlyPayment * 100) / 100) print("The total payment is", int(totalPayment * 100) /100)
d582d636fd87f6d370a85e3d3632cbfb66e9de25
timmy61109/Introduction-to-Programming-Using-Python
/examples/UseCustomTurtleFunctions.py
431
4
4
import turtle from UsefulTurtleFunctions import * # Draw a line from (-50, -50) to (50, 50) drawLine(-50, -50, 50, 50) # Write a text at (-50, -60) writeText("Testing useful Turtle functions", -50, -60) # Draw a point at (0, 0) drawPoint(0, 0) # Draw a circle at (0, 0) with radius 80 drawCircle(0, 0, 80) # Draw a rectangle at (0, 0) with width 60 and height 40 drawRectangle(0, 0, 60, 40) turtle.hideturtle() turtle.done()
77fc93e8454ea34d6d78599e47fd8739d791d4e6
timmy61109/Introduction-to-Programming-Using-Python
/own_practice/two_fourteen.py
780
3.984375
4
u""" 程式設計練習題 2.2-2.10 2.14 幾何:計算三角形的面積. 請撰寫一程式,提示使用者輸入三角形的三點座標(x1, y1)、(x2, y2)以及(x3, y3),然後顯示期面積。 s = (side1 + side2 + side3) / 2 area = (s * (s - side1)(s - side2)(s - side3)) ** 0.5 以下是輸出樣本: ``` Enter three points for a triangle:1.5, -3.4, 4.6, 5, 9.5, -3.4 The area of the triangle is 33.6 ``` """ import ast x1, y1, x2, y2, x3, y3 = ast.literal_eval( input("Enter three points for a triangle:")) side1 = ((x1 - x2) ** 2 + (y1 + y2) ** 2) ** 0.5 side2 = ((x2 - x3) ** 2 + (y2 + y3) ** 2) ** 0.5 side3 = ((x1 - x3) ** 2 + (y1 + y3) ** 2) ** 0.5 s = (side1 + side2 + side3) / 2 AREA = (s * (s - side1) * (s - side2) * (s - side3)) ** 0.5 print(AREA)
4a2cb417075f45bd0f2691c6e06e4328e54653ad
timmy61109/Introduction-to-Programming-Using-Python
/examples/MatchDemo.py
370
3.921875
4
import re regex = "\d{3}-\d{2}-\d{4}" ssn = input("Enter SSN: ") match1 = re.match(regex, ssn) if match1 != None: print(ssn, " is a valid SSN") print("start position of the matched text is " + str(match1.start())) print("start and end position of the matched text is " + str(match1.span())) else: print(ssn, " is not a valid SSN")
cc6e632af3bba895d4e05d457f17049c20f8b4e1
timmy61109/Introduction-to-Programming-Using-Python
/examples/SubtractionQuizLoop.py
1,158
4.03125
4
import random import time correctCount = 0 # Count the number of correct answers count = 0 # Count the number of questions NUMBER_OF_QUESTIONS = 5 # Constant startTime = time.time() # Get start time while count < NUMBER_OF_QUESTIONS: # 1. Generate two random single-digit integers number1 = random.randint(0, 9) number2 = random.randint(0, 9) # 2. If number1 < number2, swap number1 with number2 if number1 < number2: number1, number2 = number2, number1 # 3. Prompt the student to answer "what is number1 - number2?" answer = eval(input("What is " + str(number1) + " - " + str(number2) + "? ")) # 5. Grade the answer and display the result if number1 - number2 == answer: print("You are correct!") correctCount += 1 else: print("Your answer is wrong.\n", number1, "-", number2, "should be", (number1 - number2)) # Increase the count count += 1 endTime = time.time() # Get end time testTime = int(endTime - startTime) # Get test time print("Correct count is", correctCount, "out of", NUMBER_OF_QUESTIONS, "\nTest time is", testTime, "seconds")
5939d5daba1f8b7ef4fd2803b3363ebe140c66e9
timmy61109/Introduction-to-Programming-Using-Python
/own_practice/two_eight.py
919
3.78125
4
""" 程式設計練習題 2.2-2.10 2.8 計算能量. 請撰寫一程式,計算從起始溫度到最後溫度時熱水所需的能量。程式提示使用者數入多少公斤的水、起始溫度 及最後溫度。計算能量的公式如下: Q = M * (finalTemperature - initialTemperature) * 4184 此處的M逝水的公斤數,溫度是攝氏溫度,而Q是以焦耳(joules)來衡量的能量。 以下是範例輸出的樣本: ``` Enter the amount of water in kilograms: 55.5 Enter the initial temperature: 3.5 Enter the final Temperature:10.5 The energy needed is 1625484.0 ``` """ import ast M = ast.literal_eval(input("Enter the amount of water in kilograms:")) initialTemperature = ast.literal_eval(input("Enter the initial temperature:")) finalTemperature = ast.literal_eval(input("Enter the final Temperature:")) Q = M * (finalTemperature - initialTemperature) * 4184 print("The energy needed is", Q)
81637bd0a27f1ebc4d3606549dc9bfc6e78277a6
timmy61109/Introduction-to-Programming-Using-Python
/own_practice/two_one.py
395
4.03125
4
u""" 程式設計練習題 2.2-2.10 2.1 將攝氏溫度轉換成華氏溫度. 請撰寫一程式,從控制臺讀取攝氏溫度,接著將其轉換為華氏溫度,並顯示結果。轉換的公式如下: fahrenheit = (9 / 5) * celsius + 32 """ CELSIUS = int(input("Enter a degree in Celsius:")) FAHRENHEIT = (9 / 5) * CELSIUS + 32 print(CELSIUS, "Celsius is", FAHRENHEIT, "Fahrenheit")
97a050e009a2c1e53a1842a6c7de60a6d6148b90
timmy61109/Introduction-to-Programming-Using-Python
/examples/QuickSort.py
1,267
4.21875
4
def quickSort(list): quickSortHelper(list, 0, len(list) - 1) def quickSortHelper(list, first, last): if last > first: pivotIndex = partition(list, first, last) quickSortHelper(list, first, pivotIndex - 1) quickSortHelper(list, pivotIndex + 1, last) # Partition list[first..last] def partition(list, first, last): pivot = list[first] # Choose the first element as the pivot low = first + 1 # Index for forward search high = last # Index for backward search while high > low: # Search forward from left while low <= high and list[low] <= pivot: low += 1 # Search backward from right while low <= high and list[high] > pivot: high -= 1 # Swap two elements in the list if high > low: list[high], list[low] = list[low], list[low] while high > first and list[high] >= pivot: high -= 1 # Swap pivot with list[high] if pivot > list[high]: list[first] = list[high] list[high] = pivot return high else: return first # A test function def main(): list = [2, 3, 2, 5, 6, 1, -2, 3, 14, 12] quickSort(list) for v in list: print(str(v) + " ", end = "") main()
2b6c63f938d13dc8103f3cb8d5f7261f04c4676c
timmy61109/Introduction-to-Programming-Using-Python
/examples/Decimal2HexConversion.py
745
4.375
4
# Convert a decimal to a hex as a string def decimalToHex(decimalValue): hex = "" while decimalValue != 0: hexValue = decimalValue % 16 hex = toHexChar(hexValue) + hex decimalValue = decimalValue // 16 return hex # Convert an integer to a single hex digit in a character def toHexChar(hexValue): if 0 <= hexValue <= 9: return chr(hexValue + ord('0')) else: # 10 <= hexValue <= 15 return chr(hexValue - 10 + ord('A')) def main(): # Prompt the user to enter a decimal integer decimalValue = eval(input("Enter a decimal number: ")) print("The hex number for decimal", decimalValue, "is", decimalToHex(decimalValue)) main() # Call the main function
324bb0fd6f126c77d953ba9dc1096f8bdb0d9a50
timmy61109/Introduction-to-Programming-Using-Python
/examples/SierpinskiTriangle.py
2,218
4.25
4
from tkinter import * # Import tkinter class SierpinskiTriangle: def __init__(self): window = Tk() # Create a window window.title("Sierpinski Triangle") # Set a title self.width = 200 self.height = 200 self.canvas = Canvas(window, width = self.width, height = self.height) self.canvas.pack() # Add a label, an entry, and a button to frame1 frame1 = Frame(window) # Create and add a frame to window frame1.pack() Label(frame1, text = "Enter an order: ").pack(side = LEFT) self.order = StringVar() entry = Entry(frame1, textvariable = self.order, justify = RIGHT).pack(side = LEFT) Button(frame1, text = "Display Sierpinski Triangle", command = self.display).pack(side = LEFT) window.mainloop() # Create an event loop def display(self): self.canvas.delete("line") p1 = [self.width / 2, 10] p2 = [10, self.height - 10] p3 = [self.width - 10, self.height - 10] self.displayTriangles(int(self.order.get()), p1, p2, p3) def displayTriangles(self, order, p1, p2, p3): if order == 0: # Base condition # Draw a triangle to connect three points self.drawLine(p1, p2) self.drawLine(p2, p3) self.drawLine(p3, p1) else: # Get the midpoint of each triangle's edge p12 = self.midpoint(p1, p2) p23 = self.midpoint(p2, p3) p31 = self.midpoint(p3, p1) # Recursively display three triangles self.displayTriangles(order - 1, p1, p12, p31) self.displayTriangles(order - 1, p12, p2, p23) self.displayTriangles(order - 1, p31, p23, p3) def drawLine(self, p1, p2): self.canvas.create_line( p1[0], p1[1], p2[0], p2[1], tags = "line") # Return the midpoint between two points def midpoint(self, p1, p2): p = 2 * [0] p[0] = (p1[0] + p2[0]) / 2 p[1] = (p1[1] + p2[1]) / 2 return p SierpinskiTriangle() # Create GUI
d658665811319f345a62ca59cfce5fbec059a735
timmy61109/Introduction-to-Programming-Using-Python
/examples/DefaultListArgument.py
275
4
4
def add(x, lst = []): if x not in lst: lst.append(x) return lst def main(): list1 = add(1) print(list1) list2 = add(2) print(list2) list3 = add(3, [11, 12, 13, 14]) print(list3) list4 = add(4) print(list4) main()
10eda90db24a3fcf34881935a01327d229bc484f
timmy61109/Introduction-to-Programming-Using-Python
/examples/CircleWithPrivateRadius.py
333
3.765625
4
import math class Circle: # Construct a circle object def __init__(self, radius = 1): self.__radius = radius def getRadius(self): return self.__radius def getPerimeter(self): return 2 * self.__radius * math.pi def getArea(self): return self.__radius * self.__radius * math.pi
bf8d3d46a74e9da8fe560231ceb161cd57a3316d
timmy61109/Introduction-to-Programming-Using-Python
/examples/MergeSort.py
1,246
4.21875
4
def mergeSort(list): if len(list) > 1: # Merge sort the first half firstHalf = list[ : len(list) // 2] mergeSort(firstHalf) # Merge sort the second half secondHalf = list[len(list) // 2 : ] mergeSort(secondHalf) # Merge firstHalf with secondHalf into list merge(firstHalf, secondHalf, list) # Merge two sorted lists */ def merge(list1, list2, temp): current1 = 0 # Current index in list1 current2 = 0 # Current index in list2 current3 = 0 # Current index in temp while current1 < len(list1) and current2 < len(list2): if list1[current1] < list2[current2]: temp[current3] = list1[current1] current1 += 1 current3 += 1 else: temp[current3] = list2[current2] current2 += 1 current3 += 1 while current1 < len(list1): temp[current3] = list1[current1] current1 += 1 current3 += 1 while current2 < len(list2): temp[current3] = list2[current2] current2 += 1 current3 += 1 def main(): list = [2, 3, 2, 5, 6, 1, -2, 3, 14, 12] mergeSort(list) for v in list: print(str(v) + " ", end = "") main()
6f72ca0fb36414b3656d118a3d32ecd2b001af71
timmy61109/Introduction-to-Programming-Using-Python
/examples/ControlAnimation.py
2,360
4.0625
4
from tkinter import * # Import tkinter class ControlAnimation: def __init__(self): window = Tk() # Create a window window.title("Control Animation Demo") # Set a title self.width = 250 # Width of the self.canvas self.canvas = Canvas(window, bg = "white", width = self.width, height = 50) self.canvas.pack() frame = Frame(window) frame.pack() btStop = Button(frame, text = "Stop", command = self.stop) btStop.pack(side = LEFT) btResume = Button(frame, text = "Resume", command = self.resume) btResume.pack(side = LEFT) btFaster = Button(frame, text = "Faster", command = self.faster) btFaster.pack(side = LEFT) btSlower = Button(frame, text = "Slower", command = self.slower) btSlower.pack(side = LEFT) self.x = 0 # Starting x position self.sleepTime = 100 # Set a sleep time self.canvas.create_text(self.x, 30, text = "Message moving?", tags = "text") self.dx = 3 self.isStopped = False self.animate() window.mainloop() # Create an event loop def stop(self): # Stop animation self.isStopped = True def resume(self): # Resume animation self.isStopped = False self.animate() def faster(self): # Speed up the animation if self.sleepTime > 5: self.sleepTime -= 20 def slower(self): # Slow down the animation self.sleepTime += 20 def animate(self): # Move the message while not self.isStopped: self.canvas.move("text", self.dx, 0) # Move text self.canvas.after(self.sleepTime) # Sleep self.canvas.update() # Update self.canvas if self.x < self.width: self.x += self.dx # Set new position else: self.x = 0 # Reset string position to the beginning self.canvas.delete("text") # Redraw text at the beginning self.canvas.create_text(self.x, 30, text = "Message moving?", tags = "text") ControlAnimation() # Create GUI
674a0def98a2f37c3dae8cf1ce070c767431b66a
timmy61109/Introduction-to-Programming-Using-Python
/examples/EfficientPrimeNumbers.py
1,451
4.15625
4
def main(): n = eval(input("Find all prime numbers <= n, enter n: ")) # A list to hold prime numbers list = [] NUMBER_PER_LINE = 10 # Display 10 per line count = 0 # Count the number of prime numbers number = 2 # A number to be tested for primeness squareRoot = 1 # Check whether number <= squareRoot print("The prime numbers are \n") # Repeatedly find prime numbers while number <= n: # Assume the number is prime isPrime = True # Is the current number prime? if squareRoot * squareRoot < number: squareRoot += 1 # Test whether number is prime k = 0 while k < len(list) and list[k] <= squareRoot: if number % list[k] == 0: # If true, not prime isPrime = False # Set isPrime to false break # Exit the for loop k += 1 # Print the prime number and increase the count if isPrime: count += 1 # Increase the count list.append(number) # Add a new prime to the list if count % NUMBER_PER_LINE == 0: # Print the number and advance to the new line print(number); else: print(str(number) + " ", end = "") # Check whether the next number is prime number += 1 print("\n" + str(count) + " prime(s) less than or equal to " + str(n)) main()
d5c03365561b6847a3d30d9bf15476235319df44
timmy61109/Introduction-to-Programming-Using-Python
/own_practice/three_eight.py
1,278
3.65625
4
""" 程式設計練習題 2.2-2.10 3.8 財務應用:貨幣單位. 請解決範例程式3.4 ComputeChange.py的float轉成int導致的精確度遺失,以輸入「分」(cents)方式 解決。 """ from ast import literal_eval # Receive the amount amount = literal_eval(input("Enter an amount in cents, e.g., 1156: ")) # Convert the amount to cents remainingAmount = int(amount) # Find the number of one dollars numberOfOneDollars = int(remainingAmount / 100) remainingAmount = int(remainingAmount % 100) # Find the number of quarters in the remaining amount numberOfQuarters = int(remainingAmount / 25) remainingAmount = remainingAmount % 25 # Find the number of dimes in the remaining amount numberOfDimes = int(remainingAmount / 10) remainingAmount = remainingAmount % 10 # Find the number of nickels in the remaining amount numberOfNickels = int(remainingAmount / 5) remainingAmount = remainingAmount % 5 # Find the number of pennies in the remaining amount numberOfPennies = remainingAmount # Display results print("Your amount", amount, "consists of\n", "\t", numberOfOneDollars, "dollars\n", "\t", numberOfQuarters, "quarters\n", "\t", numberOfDimes, "dimes\n", "\t", numberOfNickels, "nickels\n", "\t", numberOfPennies, "pennies")
f077e375871aed2d815b8c0d15babdd3f2a54414
timmy61109/Introduction-to-Programming-Using-Python
/examples/TestPassMutableObject.py
544
4.09375
4
from Circle import Circle def main(): # Create a Circle object with radius 1 myCircle = Circle() # Print areas for radius 1, 2, 3, 4, and 5. n = 5 printAreas(myCircle, n) # Display myCircle.radius and times print("\nRadius is", myCircle.radius) print("n is", n) # Print a table of areas for radius def printAreas(c, times): print("Radius \t\tArea") while times >= 1: print(c.radius, "\t\t", c.getArea()) c.radius = c.radius + 1 times -= 1 main() # Call the main function
3f340f323e9932e48ebbe5212fcef638772ccb13
timmy61109/Introduction-to-Programming-Using-Python
/own_practice/homework1_1.py
129
3.953125
4
"""作業一 Loop, List.""" list1 = [1] for value in range(1, 11): print(list1) list1.append(value + list1[value - 1])
3eea73798a4ddc9043f2123d5ba6f919ca239929
timmy61109/Introduction-to-Programming-Using-Python
/examples/DataAnalysis.py
496
4.15625
4
NUMBER_OF_ELEMENTS = 5 # For simplicity, use 5 instead of 100 numbers = [] # Create an empty list sum = 0 for i in range(NUMBER_OF_ELEMENTS): value = eval(input("Enter a new number: ")) numbers.append(value) sum += value average = sum / NUMBER_OF_ELEMENTS count = 0 # The number of elements above average for i in range(NUMBER_OF_ELEMENTS): if numbers[i] > average: count += 1 print("Average is", average) print("Number of elements above the average is", count)
4bf722a50c7e125cfcc433539edc546b47a0e4b6
timmy61109/Introduction-to-Programming-Using-Python
/examples/CountEachLetter.py
736
3.84375
4
def main(): filename = input("Enter a filename: ").strip() infile = open(filename, "r") # Open the file counts = 26 * [0] # Create and initialize counts for line in infile: # Invoke the countLetters function to count each letter countLetters(line.lower(), counts) # Display results for i in range(len(counts)): if counts[i] != 0: print(chr(ord('a') + i) + " appears " + str(counts[i]) + (" time" if counts[i] == 1 else " times")) infile.close() # Close file # Count each letter in the string def countLetters(line, counts): for ch in line: if ch.isalpha(): counts[ord(ch) - ord('a')] += 1 main() # Call the main function
255e39ff64323b2afa0102ac92302511229317d6
timmy61109/Introduction-to-Programming-Using-Python
/examples/TwoChessBoard.py
1,263
4.15625
4
import turtle def main(): drawChessboard(-260, -20, -120, 120) # Draw first chess board drawChessboard(20, 260, -120, 120) # Draw second chess board turtle.hideturtle() turtle.done() # Draw one chess board def drawChessboard(startx, endx, starty, endy): # Draw chess board borders turtle.pensize(3) # Set pen thickness to 3 pixels turtle.penup() # Pull the pen up turtle.goto(startx, starty) turtle.pendown() # Pull the pen down turtle.color("red") for i in range(4): turtle.forward(240) # Draw a line turtle.left(90) # Turn left 90 degrees # Draw chess board inside drawMultipleRectangle(startx, endx, starty, endy) drawMultipleRectangle(startx + 30, endx, starty + 30, endy) # Draw multiple rectangles def drawMultipleRectangle(startx, endx, starty, endy): turtle.color("black") for j in range(starty, endy, 60): for i in range(startx, endx, 60): fillRectangle(i, j) # Draw a small rectangle def fillRectangle(i, j): turtle.penup() turtle.goto(i, j) turtle.pendown() turtle.begin_fill() for k in range(4): turtle.forward(30) # Draw a line turtle.left(90) # Turn left 90 degrees turtle.end_fill() main()
1759318a2937df482d020000af5d574311dc572d
timmy61109/Introduction-to-Programming-Using-Python
/examples/RandomCharacter.py
662
3.78125
4
from random import randint # import randint def getRandomCharacter(ch1, ch2): """Generate a random character between ch1 and ch2.""" return chr(randint(ord(ch1), ord(ch2))) def getRandomLowerCaseLetter(): """Generate a random lowercase letter.""" return getRandomCharacter('a', 'z') def getRandomUpperCaseLetter(): """Generate a random uppercase letter.""" return getRandomCharacter('A', 'Z') def getRandomDigitCharacter(): """Generate a random digit character.""" return getRandomCharacter('0', '9') def getRandomASCIICharacter(): """Generate a random character.""" return getRandomCharacter(chr(0), chr(127))
3e2002d56082c63e9880ef0f2a9b2012b89a6e6c
timmy61109/Introduction-to-Programming-Using-Python
/own_practice/three_two.py
1,003
4.03125
4
""" 程式設計練習題 2.2-2.10 3.2 幾何:大圓距離. 撰寫一程式提示使用者輸入球面上兩點,並計算出這兩點間在圓表面的最短距離。 地球半徑平均6371.01km。 d = RADIUS * acos(sin(x1) * sin(x2) + cos(x1) * cos(x2) * cos(y1 - y2)) 以下是程式的執行結果: ``` Enter point 1 (latitude and longitude) in degrees: 39.55, -116.25 Enter point 2 (latitude and longitude) in degrees: 41.5, 87.37 The distance between the two points is 10691.79183231593 km ``` """ import ast import math RADIUS = 6371.01 x1, y1 = ast.literal_eval( input("Enter point 1 (latitude and longitude) in degrees:\n")) x2, y2 = ast.literal_eval( input("Enter point 2 (latitude and longitude) in degrees:\n")) x1 = math.radians(x1) y1 = math.radians(y1) x2 = math.radians(x2) y2 = math.radians(y2) d = RADIUS * math.acos( math.sin(x1) * math.sin(x2) + math.cos(x1) * math.cos(x2) * math.cos( y1 - y2)) print("The distance between the two points is", d, "km")
705f0333cd9c94331f8963d40270a1bebb6ab135
timmy61109/Introduction-to-Programming-Using-Python
/own_practice/one_twenty.py
764
3.703125
4
""" 程式設計練習題 1-6 1-20 Turtle:畫一矩形體. 撰寫一程式,顯示矩形體。 """ import time from turtle import Turtle TURTLE = Turtle() TURTLE.showturtle() TURTLE.goto(50, 0) TURTLE.goto(50, -40) TURTLE.goto(0, -40) TURTLE.goto(0, 0) TURTLE.penup() TURTLE.goto(10, 20) TURTLE.pendown() TURTLE.goto(50 + 10, 0 + 20) TURTLE.goto(50 + 10, -40 + 20) TURTLE.goto(0 + 10, -40 + 20) TURTLE.goto(0 + 10, 0 + 20) TURTLE.penup() TURTLE.goto(0, 0) TURTLE.pendown() TURTLE.goto(10, 20) TURTLE.penup() TURTLE.goto(50, 0) TURTLE.pendown() TURTLE.goto(50 + 10, 0 + 20) TURTLE.penup() TURTLE.goto(50, -40) TURTLE.pendown() TURTLE.goto(50 + 10, -40 + 20) TURTLE.penup() TURTLE.goto(0, -40) TURTLE.pendown() TURTLE.goto(0 + 10, -40 + 20) time.sleep(5)
2b1e7281a5c4fdb8bdfa12301ddba38a9f953f94
oskarblo02/exercises
/022list_name.py
164
3.546875
4
name_list = [] def addlist(name): for i in range(50): name_list.append(name) return print(name_list) print(addlist(input('ditt namn: ')))
c8acc009f326bba9ec6a4a5a2d31c317077b0113
marksameh19/mancala
/functions/main.py
3,361
4.03125
4
import global_settings from game import game while(True): mode = 0 print("1. human against human") print("2. human against ai") print("3. exit") while(True): userinput = input("choose which mode to play: ") if(userinput == "1"): mode = 1 break elif(userinput == "2"): mode = 2 break elif(userinput == "3"): mode = 3 break else: print("please enter valid input\n") if(mode == 1): turn = 0 while(True): print("1. player_one") print("2. player_two") userinput = input("which player should start, one or two? ") if( userinput == "1"): turn = 1 break elif( userinput == "2"): turn = 0 break else: print("please enter either 1 or 2\n") playerturn = turn while(True): print("1. with stealing") print("2. without stealing") userinput = input("play with or without stealing? ") if( userinput == "1"): global_settings.stealing = 1 break elif( userinput == "2"): global_settings.stealing = 0 break else: print("please enter either 1 or 2\n") game(0,0) elif(mode == 2): turn = 0 while(True): print("1. human") print("2. ai") userinput = input("which player should start, human or ai? ") if( userinput == "1"): turn = 1 break elif( userinput == "2"): turn = 0 break else: print("please enter either 1 or 2\n") playerturn = turn while(True): print("1. with stealing") print("2. without stealing") userinput = input("play with or without stealing? ") if( userinput == "1"): global_settings.stealing = 1 break elif( userinput == "2"): global_settings.stealing = 0 break else: print("please enter either 1 or 2\n") while(True): print("1. easy (depth=2)") print("2. medium (depth=6)") print("3. hard (depth=10)") userinput = input("choose the ai difficulty: ") if( userinput == "1"): print("\nai is on easy difficulty\n") game(0,1, global_settings.easy) break elif( userinput == "2"): print("\nai is on medium difficulty\n") game(0,1, global_settings.medium) break elif( userinput == "3"): print("\nai is on hard difficulty\n") game(0,1, global_settings.hard) break else: print("please enter either 1 ,2 or 3\n") elif(mode == 3): print("we hope you liked the game") break print("//////////////////////////////////////////") print("//////////////////////////////////////////") print("//////////////////////////////////////////") print("\n")
ec569b9b7975319724f3cc613fe4c45587fda197
peteasy/estrutura-de-dados
/AC 10 - Estrutura de dados - Merge sort.py
1,798
4.34375
4
# Estrutura de dados # Atividade Contínua 10 # Alunos: # André Niimi RA 1600736 # Caique Tuan RA 1600707 # Gustavo Andreotti RA 1600044 #Linguagem de programação utilizada: Python # inicio da função recursiva def mergeSort(lista): # Dividindo a lista em duas partes if len(lista)>1: meio = len(lista)//2 L = lista[:meio] R = lista[meio:] # Executando recursivamente a função da parte esquerda mergeSort(L) # Executando recursivamente a função da parte direita mergeSort(R) # Atribuindo o valor 0(zero) para as variáveis i, j e k i=0 j=0 k=0 # Este while só será encerrado quando a variável i # for maior que a quantidade de números na parte esquerda # e a variável j for maior que a quantidade de números na # parte direita while i < len(L) and j < len(R): # Comparando os valores e decidindo qual valor será trocado if L[i] < R[j]: lista[k]=L[i] i=i+1 else: lista[k]=R[j] j=j+1 k=k+1 # Atribuindo o menor valor na variável lista[posição atual] while i < len(L): lista[k]=L[i] i=i+1 k=k+1 # Atribuindo o menor valor na variável lista[posição atual] while j < len(R): lista[k]=R[j] j=j+1 k=k+1 # Exibindo a lista sem ordenação lista = [54,26,93,17,77,31,44,55,20] print ("Lista sem MergeSort: ", lista) # Exibindo a lista com ordenação mergeSort(lista) print ("Lista com MergeSort: ", lista)
770102a24bd87f633645599dc126511fef189dd8
raghavatgithub/Hello-World
/Project_Final - Copy.py
27,467
3.859375
4
from tkinter import * import sqlite3 from tkMessageBox import * con=sqlite3.Connection("Project database") cur=con.cursor() cur.execute("create table if not exists member(EmailU varchar2(20) primary key,First name varchar2(9),Last name varchar2(9),Mobile number(11),address varchar2(30),Password varchar2(15))") cur.execute("create table if not exists cusord(EmailU varchar2(15),orde varchar2(90),paymode varchar2(10))") roots=Tk() img1=PhotoImage(file="splashscreen.gif") def fun(e): roots.destroy() root=Tk() root.geometry('900x600') Label(root,text="").grid(row=0,column=0) Label(root,text="").grid(row=1,column=0) Label(root,text=" WELCOME TO EXQUISITE.COM !!! ",font='Times 40',fg='purple').grid(row=3,column=0,columnspan=8) Label(root,text="").grid(row=4,column=0) Label(root,text="").grid(row=5,column=0) Label(root,text="").grid(row=6,column=0) Label(root,text="").grid(row=7,column=0) Label(root,text=" Welcome To Exquisite.com . A place where you can find a wide range of products of your choice.",font='Times 16',fg='green').grid(row=8,column=0) Label(root,text=" Just order them from your PC and get it delievered to your doorstep",font='Times 16',fg='green').grid(row=9,column=0) def signupgui(): rot=Tk() rot.geometry('550x550') Label(rot,text=" Fill The Following Details:- ",font='Times 18',fg='brown').grid(row=0,column=0) Label(rot,text="").grid(row=1,column=0) Label(rot,text='Enter Your Email-Id ', font='Times 15',fg='blue').grid(row=2,column=0) Label(rot,text="").grid(row=3,column=0) Label(rot,text="").grid(row=4,column=0) Label(rot,text='Enter First Name ', font='Times 15',fg='blue').grid(row=5,column=0) Label(rot,text="").grid(row=6,column=0) Label(rot,text="").grid(row=7,column=0) Label(rot,text='Enter Last Name ', font='Times 15',fg='blue').grid(row=8,column=0) Label(rot,text="").grid(row=9,column=0) Label(rot,text="").grid(row=10,column=0) Label(rot,text='Enter Mobile Number ', font='Times 15',fg='blue').grid(row=11,column=0) Label(rot,text="").grid(row=12,column=0) Label(rot,text="").grid(row=13,column=0) Label(rot,text='Enter Address ', font='Times 15',fg='blue').grid(row=14,column=0) Label(rot,text="").grid(row=15,column=0) Label(rot,text="").grid(row=16,column=0) Label(rot,text='Enter Password ', font='Times 15',fg='blue').grid(row=17,column=0) EMAIL=Entry(rot) EMAIL.grid(row=2,column=1) EFNAME=Entry(rot) EFNAME.grid(row=5,column=1) ELNAME=Entry(rot) ELNAME.grid(row=8,column=1) MOB=Entry(rot) MOB.grid(row=11,column=1) ADDRESS=Entry(rot) ADDRESS.grid(row=14,column=1) PASS=Entry(rot) PASS.grid(row=17,column=1) def INSERT(): E=EMAIL.get() F=EFNAME.get() L=ELNAME.get() M=MOB.get() A=ADDRESS.get() P=PASS.get() d=[E,F,L,M,A,P] cur.execute("insert into member values (?,?,?,?,?,?)",d) con.commit() Label(rot,text="").grid(row=16,column=0) Label(rot,text="").grid(row=18,column=0) Button(rot,text='SIGNUP',font='Times 10',fg='black',command=INSERT).grid(row=19,column=1) rot.mainloop() def CHK(): RT=Tk() RT.geometry("500x200") Label(RT,text="").grid(row=0,column=0) Label(RT,text=' ENTER YOUR EMAIL-ID ',font='Times 15',fg='black').grid(row=1,column=0) email=Entry(RT) email.grid(row=1,column=1) def check(): cur.execute("select * from member where EmailU=?",(email.get(),)) s=cur.fetchone() if s is not None: showinfo('Information',s) else: Label(RT,text='Sorry Invalid Email-Id',font='Times 12',fg='red').grid(row=7,column=0) Label(RT,text="").grid(row=2,column=0) Button(RT,text=' CHECK ',fg='black',command=check).grid(row=3,column=0) Label(RT,text="").grid(row=4,column=0) Label(RT,text="").grid(row=5,column=0) def login(): ROTN=Tk() ROTN.geometry("600x600") Label(ROTN,text="").grid(row=0,column=0) Label(ROTN,text="").grid(row=1,column=0) Label(ROTN,text=" WELCOME USER GOOD TO SEE YOU !!!",font='Times 22',fg='orange').grid(row=2,column=0,columnspan=8) Label(ROTN,text="").grid(row=3,column=1) Label(ROTN,text=' Enter Your Email-Id ',font='Times 19',fg='black').grid(row=4,column=0) ema=Entry(ROTN) ema.grid(row=4,column=1) Label(ROTN,text="").grid(row=5,column=0) Label(ROTN,text="").grid(row=6,column=0) Label(ROTN,text=' Enter Your Password ',font='Times 19',fg='black').grid(row=7,column=0) pas=Entry(ROTN,show="*") pas.grid(row=7,column=1) def lgn(): if ema.get() == "" or pas.get() == "": Label(ROTN,text='Please Fill The Required fields',fg='RED',font='Times 15').grid(row=12,column=0) else: cur.execute("SELECT * FROM member WHERE EmailU = ? AND Password = ?", (ema.get(), pas.get())) if cur.fetchone() is not None: OT=Tk() OT.geometry('430x550') Label(OT,text="").grid(row=0,column=0) Label(OT,text=' WELCOME USER !!! ',fg='violet',font='Times 23').grid(row=1,column=2,columnspan=8) Label(OT,text="").grid(row=2,column=0) Label(OT,text="").grid(row=3,column=0) Label(OT,text=' LETS BUY SOME STUFF !!! ',fg='green',font='Times 18').grid(row=4,column=2) Label(OT,text="").grid(row=5,column=0) def menord(): R=Tk() R.geometry("400x400") Label(R,text="").grid(row=0,column=0) Label(R,text="").grid(row=1,column=0) Label(R,text=" Click View To View An Item",font='Times 20',fg='red').grid(row=2,column=0,columnspan=15) Label(R,text=" Click Add To Cart To Order",font='Times 20',fg='red').grid(row=3,column=0,columnspan=15) Label(R,text=' Shirt 1').grid(row=4,column=0) Label(R,text="").grid(row=5,column=0) Label(R,text="").grid(row=6,column=0) Label(R,text=' Shirt 2').grid(row=7,column=0) Label(R,text="").grid(row=8,column=0) Label(R,text="").grid(row=9,column=0) Label(R,text=' Shoe 1').grid(row=10,column=0) Label(R,text="").grid(row=11,column=0) Label(R,text="").grid(row=12,column=0) Label(R,text=' Shoe 2').grid(row=13,column=0) def st1(): r=Toplevel() r.geometry("300x300") I1=PhotoImage(file="MC1.gif") lb=Label(r,image=I1) lb.grid(row=0,column=0) Label(r,text='PRICE 700').grid(row=1,column=0) r.mainloop() def st2(): r=Toplevel() r.geometry("300x300") I1=PhotoImage(file="MC2.gif") lb=Label(r,image=I1) lb.grid(row=0,column=0) Label(r,text='PRICE 800').grid(row=1,column=0) r.mainloop() def se1(): r=Toplevel() r.geometry("500x500") I1=PhotoImage(file="MS1.gif") lb=Label(r,image=I1) lb.grid(row=0,column=0) Label(r,text='PRICE 1000').grid(row=1,column=0) r.mainloop() def se2(): r=Toplevel() r.geometry("300x300") I1=PhotoImage(file="MS2.gif") lb=Label(r,image=I1) Label(r,text='PRICE 1100').grid(row=1,column=0) lb.grid(row=0,column=0) r.mainloop() Label(R,text=" ").grid(row=4,column=1) Label(R,text=" ").grid(row=5,column=1) Label(R,text=" ").grid(row=6,column=1) Label(R,text=" ").grid(row=7,column=1) Label(R,text=" ").grid(row=8,column=1) Label(R,text=" ").grid(row=9,column=1) Label(R,text=" ").grid(row=10,column=1) Label(R,text=" ").grid(row=11,column=1) Label(R,text=" ").grid(row=12,column=1) Label(R,text=" ").grid(row=13,column=1) Label(R,text=" ").grid(row=14,column=1) Label(R,text=" ").grid(row=15,column=1) Button(R,text='VIEW',command=st1).grid(row=4,column=2) Button(R,text='VIEW',command=st2).grid(row=7,column=2) Button(R,text='VIEW',command=se1).grid(row=10,column=2) Button(R,text='VIEW',command=se2).grid(row=13,column=2) def atc1(): r=ema.get() f=' Item1 ' d=[r,f] cur.execute("insert into cusord(EmailU,orde) values(?,?)",d) con.commit() def atc2(): r=ema.get() f=' Item2 ' d=[r,f] cur.execute("insert into cusord(EmailU,orde) values(?,?)",d) con.commit() def atc3(): r=ema.get() f=' Item3 ' d=[r,f] cur.execute("insert into cusord(EmailU,orde) values(?,?)",d) con.commit() def atc4(): r=ema.get() f=' Item4 ' d=[r,f] cur.execute("insert into cusord(EmailU,orde) values(?,?)",d) con.commit() def continu(): y=Tk() y.geometry("300x300") Label(y,text='PAYMENT',font='Times 20',fg='black').grid(row=0,column=0) def pay1(): o=Tk() o.geometry("300x300") Label(o,text='ORDER WILL BE DELIEVERED TO YOUR ADDRESS').grid(row=0,column=0) o.mainloop() def pay2(): pa=Tk() pa.geometry("350x350") Label(pa,text='ADD MONEY TO THE PAYTM NUMBER 9.........').grid(row=0,column=0) pa.mainloop() Button(y,text='Cash On Delievery',font='Times 10',fg='green',command=pay1).grid(row=1,column=0) Button(y,text='Paytm',font='Times 10',fg='green',command=pay2).grid(row=1,column=1) y.mainloop() Label(R,text=" ").grid(row=4,column=3) Label(R,text=" ").grid(row=5,column=3) Label(R,text=" ").grid(row=6,column=3) Label(R,text=" ").grid(row=7,column=3) Label(R,text=" ").grid(row=8,column=3) Label(R,text=" ").grid(row=9,column=3) Label(R,text=" ").grid(row=10,column=3) Label(R,text=" ").grid(row=11,column=3) Label(R,text=" ").grid(row=12,column=3) Label(R,text=" ").grid(row=13,column=3) Label(R,text=" ").grid(row=14,column=3) Label(R,text=" ").grid(row=15,column=3) Button(R,text='ADD TO CART',command=atc1).grid(row=4,column=4) Button(R,text='ADD TO CART',command=atc2).grid(row=7,column=4) Button(R,text='ADD TO CART',command=atc3).grid(row=10,column=4) Button(R,text='ADD TO CART',command=atc4).grid(row=13,column=4) Button(R,text='CONTINUE',command=continu).grid(row=14,column=4) R.mainloop() def womenord(): Rw=Tk() Rw.geometry("400x400") Label(Rw,text="").grid(row=0,column=0) Label(Rw,text="").grid(row=1,column=0) Label(Rw,text=" Click View To View An Item",font='Times 20',fg='red').grid(row=2,column=0,columnspan=15) Label(Rw,text=" Click Add To Cart To Order",font='Times 20',fg='red').grid(row=3,column=0,columnspan=15) Label(Rw,text=' Shirt 1').grid(row=4,column=0) Label(Rw,text="").grid(row=5,column=0) Label(Rw,text="").grid(row=6,column=0) Label(Rw,text=' Shirt 2').grid(row=7,column=0) Label(Rw,text="").grid(row=8,column=0) Label(Rw,text="").grid(row=9,column=0) Label(Rw,text=' Shoe 1').grid(row=10,column=0) Label(Rw,text="").grid(row=11,column=0) Label(Rw,text="").grid(row=12,column=0) Label(Rw,text=' Shoe 2').grid(row=13,column=0) def stw1(): r=Toplevel() r.geometry("300x300") I1=PhotoImage(file="WC1.gif") lb=Label(r,image=I1) lb.grid(row=0,column=0) Label(r,text='PRICE 700').grid(row=1,column=0) r.mainloop() def stw2(): r=Toplevel() r.geometry("300x300") I1=PhotoImage(file="WC2.gif") lb=Label(r,image=I1) lb.grid(row=0,column=0) Label(r,text='PRICE 800').grid(row=1,column=0) r.mainloop() def sew1(): r=Toplevel() r.geometry("300x300") I1=PhotoImage(file="WS1.gif") lb=Label(r,image=I1) lb.grid(row=0,column=0) Label(r,text='PRICE 1000').grid(row=1,column=0) r.mainloop() def sew2(): r=Toplevel() r.geometry("300x300") I1=PhotoImage(file="WS2.gif") lb=Label(r,image=I1) Label(r,text='PRICE 1100').grid(row=1,column=0) lb.grid(row=0,column=0) r.mainloop() Label(Rw,text=" ").grid(row=4,column=1) Label(Rw,text=" ").grid(row=5,column=1) Label(Rw,text=" ").grid(row=6,column=1) Label(Rw,text=" ").grid(row=7,column=1) Label(Rw,text=" ").grid(row=8,column=1) Label(Rw,text=" ").grid(row=9,column=1) Label(Rw,text=" ").grid(row=10,column=1) Label(Rw,text=" ").grid(row=11,column=1) Label(Rw,text=" ").grid(row=12,column=1) Label(Rw,text=" ").grid(row=13,column=1) Label(Rw,text=" ").grid(row=14,column=1) Label(Rw,text=" ").grid(row=15,column=1) Button(Rw,text='VIEW',command=stw1).grid(row=4,column=2) Button(Rw,text='VIEW',command=stw2).grid(row=7,column=2) Button(Rw,text='VIEW',command=sew1).grid(row=10,column=2) Button(Rw,text='VIEW',command=sew2).grid(row=13,column=2) def atcw1(): r=ema.get() f=' Item1_w ' d=[r,f] cur.execute("insert into cusord(EmailU,orde) values(?,?)",d) con.commit() def atcw2(): r=ema.get() f=' Item2_w ' d=[r,f] cur.execute("insert into cusord(EmailU,orde) values(?,?)",d) con.commit() def atcw3(): r=ema.get() f=' Item3_w ' d=[r,f] cur.execute("insert into cusord(EmailU,orde) values(?,?)",d) con.commit() def atcw4(): r=ema.get() f=' Item4_w ' d=[r,f] cur.execute("insert into cusord(EmailU,orde) values(?,?)",d) con.commit() Label(Rw,text=" ").grid(row=4,column=3) Label(Rw,text=" ").grid(row=5,column=3) Label(Rw,text=" ").grid(row=6,column=3) Label(Rw,text=" ").grid(row=7,column=3) Label(Rw,text=" ").grid(row=8,column=3) Label(Rw,text=" ").grid(row=9,column=3) Label(Rw,text=" ").grid(row=10,column=3) Label(Rw,text=" ").grid(row=11,column=3) Label(Rw,text=" ").grid(row=12,column=3) Label(Rw,text=" ").grid(row=13,column=3) Label(Rw,text=" ").grid(row=14,column=3) Label(Rw,text=" ").grid(row=15,column=3) def continu(): j=Tk() j.geometry("300x300") Label(j,text='PAYMENT',font='Times 20',fg='black').grid(row=0,column=0) def pay1(): f=Tk() f.geometry("300x300") Label(f,text='ORDER WILL BE DELIEVERED TO YOUR ADDRESS').grid(row=0,column=0) f.mainloop() def pay2(): pat=Tk() pat.geometry("350x350") Label(pat,text='ADD MONEY TO THE PAYTM NUMBER 9.........').grid(row=0,column=0) pat.mainloop() Button(j,text='Cash On Delievery',font='Times 10',fg='green',command=pay1).grid(row=1,column=0) Button(j,text='Paytm',font='Times 10',fg='green',command=pay2).grid(row=1,column=1) j.mainloop() Button(Rw,text='ADD TO CART',command=atcw1).grid(row=4,column=4) Button(Rw,text='ADD TO CART',command=atcw2).grid(row=7,column=4) Button(Rw,text='ADD TO CART',command=atcw3).grid(row=10,column=4) Button(Rw,text='ADD TO CART',command=atcw4).grid(row=13,column=4) Button(Rw,text='CONTINUE',command=continu).grid(row=14,column=4) Rw.mainloop() Label(OT,text=" For Men",fg='grey',font='Times 18').grid(row=6,column=2) Label(OT,text="").grid(row=7,column=0) Label(OT,text="").grid(row=8,column=0) Button(OT,text='MEN',font='Times 18',fg='black',command=menord).grid(row=9,column=2) Label(OT,text="").grid(row=10,column=0) Label(OT,text="").grid(row=11,column=0) Label(OT,text="").grid(row=12,column=0) Label(OT,text=" For Women",fg='grey',font='Times 18').grid(row=13,column=2) Label(OT,text="").grid(row=14,column=0) Label(OT,text="").grid(row=15,column=0) Button(OT,text='WOMEN',font='Times 18',fg='black',command=womenord).grid(row=16,column=2) OT.mainloop() else: Label(ROTN,text="Invalid username or password", fg="red",font='Times 20').grid(row=11,column=0) Label(ROTN,text="").grid(row=8,column=0) Label(ROTN,text="").grid(row=9,column=0) Button(ROTN,text=' LOGIN ',fg='black',command=lgn).grid(row=10,column=1) ROTN.mainloop() def al(): P=Tk() P.geometry("600x300") Label(P,text="").grid(row=0,column=0) Label(P,text="").grid(row=1,column=0) Label(P,text=" WELCOME ADMINISTRATOR ",font='Times 20',fg='orange').grid(row=2,column=0) Label(P,text="").grid(row=3,column=0) Label(P,text=' USERNAME: ',fg='black').grid(row=4,column=0) Label(P,text="").grid(row=5,column=0) Label(P,text="").grid(row=6,column=0) Label(P,text=' PASSWORD: ',fg='black').grid(row=7,column=0) aema=Entry(P) aema.grid(row=4,column=1) apas=Entry(P,show="*") apas.grid(row=7,column=1) def algn(): if aema.get() == "" or apas.get() == "": Label(P,text='Please Fill The Required fields',fg='RED',font='Times 10').grid(row=8,column=0) else: cur.execute("SELECT * FROM member WHERE EmailU = ? AND Password = ?", (aema.get(), apas.get())) if cur.fetchone() is not None: U=Tk() U.geometry("400x500") Label(U,text="").grid(row=0,column=0) Label(U,text="").grid(row=1,column=0) Label(U,text=" SELECT YOUR CHOICE",font='Times 19',fg='orange').grid(row=2,column=0) Label(U,text="").grid(row=3,column=0) Label(U,text='SEE MEMBERS DETAILS',font='Times 12',fg='brown').grid(row=4,column=0) Label(U,text="").grid(row=5,column=0) Label(U,text="").grid(row=6,column=0) Label(U,text='SEE ORDER DETAILS',font='Times 12',fg='brown').grid(row=7,column=0) Label(U,text="").grid(row=8,column=0) Label(U,text="").grid(row=9,column=0) Label(U,text='DELETE MEMBERS DETAILS',font='Times 12',fg='brown').grid(row=10,column=0) Label(U,text="").grid(row=11,column=0) Label(U,text="").grid(row=12,column=0) Label(U,text='DELETE ORDER DETAILS',font='Times 12',fg='brown').grid(row=13,column=0) def memdet(): cur.execute("select * from member") md=cur.fetchall() if md is not None: MDE=Tk() MDE.geometry("2000x2000") Label(MDE,text=md).grid(row=0,column=0) MDE.mainloop() else: Label(U,text='NO MEMBER DETAIL ',font='Times 10',fg='black').grid(row=15,column=0) def orddet(): cur.execute("select * from cusord") od=cur.fetchall() if od is not None: showinfo('Information',od) else: Label(U,text='NO ORDER AVAILABLE ',font='Times 10',fg='black').grid(row=16,column=0) def memdel(): cur.execute("delete from member") con.commit() def orddel(): cur.execute("delete from cusord") con.commit() Button(U,text='VIEW',command=memdet).grid(row=4,column=2) Button(U,text='VIEW',command=orddet).grid(row=7,column=2) Button(U,text='DELETE',command=memdel).grid(row=10,column=2) Button(U,text='DELETE',command=orddel).grid(row=13,column=2) U.mainloop() else: Label(P,text="Invalid Username Or Password",fg='red',font='Times 10').grid(row=14,column=1) Label(P,text="").grid(row=8,column=0) Button(P,text='LOGIN',command=algn).grid(row=9,column=1) Label(root,text="").grid(row=10,column=0) Label(root,text="").grid(row=11,column=0) Button(root,text=' LOGIN ',font='Times 10',fg='black',command=login).grid(row=12,column=0) Label(root,text="").grid(row=13,column=0) Label(root,text="").grid(row=14,column=0) Button(root,text=' SIGN UP ',font='Times 10',fg='black',command=signupgui).grid(row=15,column=0) Label(root,text="").grid(row=16,column=0) Label(root,text="").grid(row=17,column=0) Button(root,text=' Check Your Account Details ',fg='black',command=CHK).grid(row=18,column=0) Label(root,text="").grid(row=19,column=0) Label(root,text="").grid(row=20,column=0) Button(root,text=' Administrator Login ',font='Times 10',fg='black',command=al).grid(row=21,column=0) root.mainloop() lb=Label(roots,image=img1) lb.bind('<Motion>',fun) lb.pack() roots.mainloop()
b371194186fe7f5de4958638626a731701c4a22b
Aquassaut/Serpentide
/Segment.py
1,211
3.96875
4
from constants import * from math import sin, cos, pi class Segment: """ Defines a segment with a length of 1 according to its starting point and its direction """ def __init__(self, x, y, dct): assert dct <= 3 and dct >= 0 self.x = x self.y = y self.dct = dct def move(self, dx, dy): """moves a segment by a given offset""" self.x += dx self.y += dy def getEndPoint(self): """returns the ending point of the segment in a tuple""" return { 0: (self.x + SSIZE, self.y), 1: (self.x, self.y + SSIZE), 2: (self.x - SSIZE, self.y), 3: (self.x, self.y - SSIZE), }[self.dct] def getStartPoint(self): """returns the starting point of the segment in a tuple""" return (self.x, self.y) def getDct(self): return self.dct def addGraphicObject(self, go): self.go = go def getGraphicObject(self): return self.go def rmGraphicObject(self): self.go = None def place(self, point): self.x, self.y = point def rotate(self, angle=pi): self.dct = int((2*angle/pi + self.dct) % 4)
43bc9e6f5d5d844cda2887a0c55fd88ea24497da
wjr0102/Leetcode
/Medium/Trie_Tree.py
1,806
4.0625
4
class Trie: def __init__(self): """ Initialize your data structure here. """ self.root = Node() def insert(self, word: str) -> None: """ Inserts a word into the trie. """ # print("Insert %s"%word) node = self.root for c in word: node = node.add(c) node.terminate() def search(self, word: str) -> bool: """ Returns if the word is in the trie. """ node = self.root for c in word: if c in node.child: node = node.child[c] else: return False if "END" in node.child: return True return False def startsWith(self, prefix: str) -> bool: """ Returns if there is any word in the trie that starts with the given prefix. """ node = self.root for c in prefix: if c in node.child: node = node.child[c] else: return False return True class Node: def __init__(self,char=None): self.char = char self.child = {} def add(self,c: str): if not self.child.__contains__(c): self.child[c] = Node(c) return self.child[c] def show(self): print("The node is %s"%self.char) print("Children:") for c in self.child: print(self.child[c].char) def show_tree(self): self.show() for node in self.child: self.child[node].show_tree() def terminate(self): self.child["END"] = 1 # Your Trie object will be instantiated and called as such: # obj = Trie() # obj.insert(word) # param_2 = obj.search(word) # param_3 = obj.startsWith(prefix)
d6fa40520eed414c30c468bcd27765412ffa19f5
wjr0102/Leetcode
/Easy/Middle_Node.py
344
3.765625
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def middleNode(self, head: ListNode) -> ListNode: fp = head sp = head while fp and fp.next: sp = sp.next fp = fp.next.next return sp
0ff9c9b0aeefe4b689b10d718addaf4b34635a92
wjr0102/Leetcode
/Easy/Majority.py
1,175
3.71875
4
#!/usr/local/bin # -*- coding: utf-8 -*- # @Author: Jingrou Wu # @Date: 2019-03-29 21:10:12 # @Last Modified by: Jingrou Wu # @Last Modified time: 2019-03-29 21:22:10 def majorityElement(nums): """ :type nums: List[int] :rtype: int """ dic = {} for num in nums: if dic.__contains__(num): dic[num] += 1 else: dic[num] = 1 result = sorted(dic.items(), key=lambda x: x[1]) return result[-1][0] def majorityElement(nums): """ :type nums: List[int] :rtype: int """ dic = {} max_value = -1 result = -1 for num in nums: if dic.__contains__(num): dic[num] += 1 else: dic[num] = 1 if dic[num] > max_value: max_value = dic[num] result = num return result ''' 摩尔投票法证明: 因为出现次数>n/2,所以必会大于0 ''' def majorityElement(nums): """ :type nums: List[int] :rtype: int """ res = 0 cnt = 0 for num in nums: if cnt == 0: res = num elif num != res: cnt -= 1 else: cnt += 1 return res
363d786add9a3507ab2808c76363eb6fd3adbbd7
wjr0102/Leetcode
/Medium/Integer to Roman.py
2,227
3.671875
4
#!/usr/local/bin # -*- coding: utf-8 -*- # @Author: Jingrou Wu # @Date: 2018-12-17 00:06:23 # @Last Modified by: Jingrou Wu # @Last Modified time: 2018-12-17 00:38:15 # Input range: [1,3999] def intToRoman2(num): # divide the number thousand = num // 1000 hundred = (num // 100) % 10 ten = (num // 10) % 10 one = num % 10 dic = {1: {0: "I", 1: "X", 2: "C", 3: "M"}, 5: {0: "V", 1: "L", 2: "D"}, 4: { 0: "IX", 1: "XL", 2: "CD"}, 9: {0: "IX", 1: "XC", 2: "CM"}} l = [thousand, hundred, ten, one] result = "" for i in range(len(l)): # print l[i] j = 3 - i if dic.has_key(l[i]): result += dic[l[i]][j] else: if l[i] > 5: result += dic[5][j] l[i] -= 5 result += dic[1][j] * l[i] else: result += dic[1][j] * l[i] return result def intToRoman(num): """ :type num: int :rtype: str """ # divide the number thousand = num // 1000 hundred = (num // 100) % 10 ten = (num // 10) % 10 one = num % 10 # print thousand, hundred, ten, one result = "" while thousand > 0: result += "M" thousand -= 1 while hundred > 0: if hundred == 9: result += "CM" hundred -= 9 elif hundred >= 5: result += "D" hundred -= 5 elif hundred == 4: result += "CD" hundred -= 4 else: result += "C" hundred -= 1 while ten > 0: if ten == 9: result += "XC" ten -= 9 elif ten == 4: result += "XL" ten -= 4 elif ten >= 5: result += "L" ten -= 5 else: result += "X" ten -= 1 while one > 0: if one == 9: result += "IX" one -= 9 elif one == 4: result += "IV" one -= 4 elif one >= 5: result += "V" one -= 5 else: result += "I" one -= 1 return result if __name__ == "__main__": print(intToRoman(4)) print(intToRoman2(4))
cf12b1f7b9196c8b8a431746aac4636d1062f029
wjr0102/Leetcode
/Medium/Swap_Pairs.py
839
3.84375
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def swapPairs(self, head: ListNode) -> ListNode: if not head: return None node1 = head node2 = head.next if not node2: return head ans = node2 last_node = None while node1 and node2: # print(node1.val,node2.val) next_node = node2.next # 交换next node1.next = node2.next node2.next = node1 # 与前面建立连接 if last_node: last_node.next = node2 last_node = node1 node1 = next_node if node1: node2 = next_node.next return ans
39be6f6875de70abe7e3613d526adc7298b8acd4
wjr0102/Leetcode
/Medium/Gray_code.py
1,351
3.671875
4
#!/usr/local/bin # -*- coding: utf-8 -*- # @Author: Jingrou Wu # @Date: 2019-04-04 13:24:21 # @Last Modified by: Jingrou Wu # @Last Modified time: 2019-04-04 19:23:56 ''' G(i) = i ^ (i/2); 如 n = 3: G(0) = 000, G(1) = 1 ^ 0 = 001 ^ 000 = 001 G(2) = 2 ^ 1 = 010 ^ 001 = 011 G(3) = 3 ^ 1 = 011 ^ 001 = 010 G(4) = 4 ^ 2 = 100 ^ 010 = 110 G(5) = 5 ^ 2 = 101 ^ 010 = 111 G(6) = 6 ^ 3 = 110 ^ 011 = 101 G(7) = 7 ^ 3 = 111 ^ 011 = 100 ''' def grayCode(n): """ :type n: int :rtype: List[int] """ res = [0] for i in range(1, 2**n): res.append(i ^ (i // 2)) return res def grayCode2(n): """ :type n: int :rtype: List[int] """ dic = {} dic[0] = [[0 for i in range(n)]] for i in range(1, n + 1): print(i - 1, dic[i - 1]) dic[i] = dic[i - 1] + extend(dic[i - 1]) print(i - 1, dic[i - 1]) print(i, dic[i]) return dic[n] def extend(nums): res = [] for i in range(len(nums) - 1, -1, -1): new = nums[i][:] i = 0 while new[i] == 0 and i < len(new): i += 1 if i >= len(new): break new[i - 1] = 1 res.append(new) print(res) return res if __name__ == "__main__": print(grayCode2(2))
6bfb64ca94d7670bada63dfcd9229cba6baa3d25
wjr0102/Leetcode
/Easy/MinCostClimb.py
1,094
4.21875
4
#!/usr/local/bin # -*- coding: utf-8 -*- # @Author: Jingrou Wu # @Date: 2019-05-07 01:46:49 # @Last Modified by: Jingrou Wu # @Last Modified time: 2019-05-07 01:53:03 ''' On a staircase, the i-th step has some non-negative cost cost[i] assigned (0 indexed). Once you pay the cost, you can either climb one or two steps. You need to find minimum cost to reach the top of the floor, and you can either start from the step with index 0, or the step with index 1. Example 1: Input: cost = [10, 15, 20] Output: 15 Explanation: Cheapest is start on cost[1], pay that cost and go to the top. Example 2: Input: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1] Output: 6 Explanation: Cheapest is start on cost[0], and only step on 1s, skipping cost[3]. ''' import sys def minCostClimbingStairs(cost): """ :type cost: List[int] :rtype: int """ result = [sys.maxsize for i in range(len(cost))] result[0] = cost[0] result[1] = min(cost[0], cost[1]) for i in range(2, len(cost)): result[i] = min(result[i - 1], result[i - 2] + cost[i]) return result[len(cost) - 1]
690421a4a89a926506c86dda2e7b03a7a846c343
wjr0102/Leetcode
/Easy/addBinary.py
1,158
3.75
4
''' 67. 二进制求和 tips: list转string要求元素都为字符串 ''' class Solution: ''' 高精度加法——二进制版 ''' def addBinary(self, a: str, b: str) -> str: la = len(a) lb = len(b) def add(s1,s2): """ 要求s1的长度小于等于s2时的二进制高精度加法 Args: s1: 较短的字符串 s2: 较长的字符串 Returns: res: 字符串形式的答案 """ res = [0]*(len(s2)+1) c = 0 for i in range(-1,-len(s1)-1,-1): s = int(s1[i]) + int(s2[i]) + c c = s//2 res[i] = str(s % 2) for i in range(-len(s1)-1,-len(s2)-1,-1): s = int(s2[i]) + c c = s//2 res[i] = str(s % 2) if c==0: res = res[1:] else: res[0] = '1' return "".join(res) if la<=lb: return add(a,b) else: return add(b,a)
9a5d17afe593e265bda23221eadff2b9d83fb86c
Ash515/hacktoberfest2021-1
/Python/equal_subarrays.py
526
3.65625
4
# Find the index of the element in the array such that the sum of all the elements left to the index is equal to the sum of all the elements right to the index. print("enter list elements: ") sample = list(map(int, input().split())) sumi = 0 sum_left=[] for val in sample: sumi += val sum_left.append(sumi) sum_right=[] for val in sample: sum_right.append(sumi) sumi -= val k=len(sum_left) for i in range(k): if sum_left[i] == sum_right[i]: print(f"Matching index is {i}.") break
849e57081867107d996ccb2459f06fb89d257ebc
Ash515/hacktoberfest2021-1
/Python/sum_of_two_numbers.py
108
4.03125
4
num1=float(input('Write the first number:')) num2=float(input('Write the second number:')) print(num1+num2)
4ddb1334805625f56a0c04a57ce80a2165796f54
Ash515/hacktoberfest2021-1
/Python/GUI_sorting.py
4,567
3.5625
4
import tkinter as tk import random #Function to swap two bars that will be animated def swap(pos_0, pos_1): bar11, _, bar12, _ = canvas.coords(pos_0) bar21, _, bar22, _ = canvas.coords(pos_1) canvas.move(pos_0, bar21-bar11, 0) #canvas.itemconfig(pos_0, bar21-bar11, fill='yellow') canvas.move(pos_1, bar12-bar22, 0) #canvas.itemconfig(pos_1, bar12-bar22, fill='orange') worker = None #Insertion Sort def _insertion_sort(): global barList global lengthList for i in range(len(lengthList)): cursor = lengthList[i] cursorBar = barList[i] pos = i while pos > 0 and lengthList[pos - 1] > cursor: lengthList[pos] = lengthList[pos - 1] barList[pos], barList[pos - 1] = barList[pos - 1], barList[pos] swap(barList[pos],barList[pos-1]) yield pos -= 1 lengthList[pos] = cursor barList[pos] = cursorBar swap(barList[pos],cursorBar) #Bubble Sort def _bubble_sort(): global barList global lengthList for i in range(len(lengthList) - 1): for j in range(len(lengthList) - i - 1): if(lengthList[j] > lengthList[j + 1]): lengthList[j] , lengthList[j + 1] = lengthList[j + 1] , lengthList[j] barList[j], barList[j + 1] = barList[j + 1] , barList[j] swap(barList[j + 1] , barList[j]) yield #Selection Sort def _selection_sort(): global barList global lengthList for i in range(len(lengthList)): min = i for j in range(i + 1 ,len(lengthList)): if(lengthList[j] < lengthList[min]): min = j lengthList[min], lengthList[i] = lengthList[i] ,lengthList[min] barList[min] , barList[i] = barList[i] , barList[min] swap(barList[min] , barList[i]) yield #Merge Sort def _merge_Sort(): return 0 #Shell Soer def _shell_sort(): return 0 #Triggering Fuctions def insertion_sort(): global worker worker = _insertion_sort() animate() def selection_sort(): global worker worker = _selection_sort() animate() def bubble_sort(): global worker worker = _bubble_sort() animate() def merge_sort(): return 0 def shell_sort(): return 0 #Animation Function def animate(): global worker if worker is not None: try: next(worker) window.after(10, animate) except StopIteration: worker = None finally: window.after_cancel(animate) #Generator function for generating data def generate(): global barList global lengthList canvas.delete('all') barstart = 1 barend = 8 barList = [] lengthList = [] #Creating a rectangle for bar in range(1, 100): randomY = random.randint(1, 360) bar = canvas.create_rectangle(barstart, randomY, barend, 365, fill='blue') barList.append(bar) barstart += 10 barend += 10 #Getting length of the bar and appending into length list for bar in barList: bar = canvas.coords(bar) length = bar[3] - bar[1] lengthList.append(length) #Maximum is colored Red #Minimum is colored Black for i in range(len(lengthList)-1): if lengthList[i] == min(lengthList): canvas.itemconfig(barList[i], fill='red') elif lengthList[i] == max(lengthList): canvas.itemconfig(barList[i], fill='green') #Making a window using the Tk widget window = tk.Tk() window.title('Sorting Visualizer By Anoop') window.geometry('1000x450') #Making a Canvas within the window to display contents canvas = tk.Canvas(window, width='1000', height='400') canvas.grid(column=0,row=0, columnspan =30) #Buttons insert = tk.Button(window, text='Insertion Sort', command=insertion_sort) merge = tk.Button(window, text='Merge Sort', command=merge_sort) select = tk.Button(window, text='Selection Sort', command=selection_sort) bubble = tk.Button(window, text='Bubble Sort', command=bubble_sort) shuf = tk.Button(window, text='Shuffle', command=generate) shell = tk.Button(window, text='Shell Sort', command=shell_sort) insert.grid(column=1,row=1) select.grid(column=2,row=1) bubble.grid(column=3,row=1) merge.grid(column=4,row=1) shell.grid(column=5,row=1) shuf.grid(column=0, row=1) generate() window.mainloop()
e7827a558cdeda6943d8c67f8ab234e13618db6d
ujjwalbaid0408/Python-Tutorial-with-Examples
/Ex22_Morphological Transformations.py
1,584
3.65625
4
# Morphological Transformations """ Opening is just another name of erosion followed by dilation. It is useful in removing noise, as we explained above. Here we use the function, cv2.morphologyEx() Closing is reverse of Opening, Dilation followed by Erosion. It is useful in closing small holes inside the foreground objects, or small black points on the object. Morphological Gradient: It is the difference between dilation and erosion of an image. The result will look like the outline of the object. Top Hat It is the difference between input image and Opening of the image. Below example is done for a 9x9 kernel. Black Hat It is the difference between the closing of the input image and input image. """ import cv2 import numpy as np #img = cv2.imread('morph1.bmp',0) img = cv2.imread('j.jpg',0) kernel = np.ones((5,5),np.uint8) erosion = cv2.erode(img,kernel,iterations = 1) dilation = cv2.dilate(img,kernel,iterations = 1) opening = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel) closing = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel) gradient = cv2.morphologyEx(img, cv2.MORPH_GRADIENT, kernel) tophat = cv2.morphologyEx(img, cv2.MORPH_TOPHAT, kernel) blackhat = cv2.morphologyEx(img, cv2.MORPH_BLACKHAT, kernel) cv2.imshow('original', img) cv2.imshow('Eroded',erosion) cv2.imshow('dilated',dilation) cv2.imshow('opening',opening) cv2.imshow('closing', closing) cv2.imshow('Morphological Gradient',gradient) cv2.imshow('Top Hat', tophat) cv2.imshow('Black Hat',blackhat); cv2.waitKey(0) cv2.destroyAllWindows()
c4dd541b364d0a493af3810f8580f045098d2dd4
ujjwalbaid0408/Python-Tutorial-with-Examples
/Ex17_ImageRotation.py
374
3.5625
4
# Program for rotatin of an image # rotates the image by degree with respect to center without any scaling import cv2 import numpy as np img = cv2.imread('messi5.jpg',0) rows,cols = img.shape M = cv2.getRotationMatrix2D((cols/2,rows/2),27,1) dst = cv2.warpAffine(img,M,(cols,rows)) cv2.imshow('Rotated Image',dst) #cv2.waitKey(0) #cv2.destroyAllWindows()
f7a5fe592f5c42ffa1b5d8f6d63d11d588403556
ujjwalbaid0408/Python-Tutorial-with-Examples
/Ex22_StructuringElementForMorphological Transformations.py
697
4.15625
4
# Structuring element """ We manually created a structuring elements in the previous examples with help of Numpy. It is rectangular shape. But in some cases, you may need elliptical/ circular shaped kernels. So for this purpose, OpenCV has a function, cv2.getStructuringElement(). You just pass the shape and size of the kernel, you get the desired kernel. """ import cv2 import numpy as np # Rectangular Kernel rect = cv2.getStructuringElement(cv2.MORPH_RECT,(5,5)) # Elliptical Kernel ellipt = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5)) # Cross-shaped Kernel cross = cv2.getStructuringElement(cv2.MORPH_CROSS,(5,5)) print rect print ellipt print cross
4d777c7fe80e213e8c01615b69750ab20732c583
MattCrutchley/python_excersises
/applications/functions.py
370
4.0625
4
def hello(name,age): greeting = "hello " + str(name) + " you are " + str(age) +" years old" return greeting def age (dob): age = 2020 - dob return age dob = int(input("enter the year you where born")) name = input("enter your name") print(hello(name,age(dob)) def pletters(greeting): for char in greeting print(char) print (pletters(hello(name,age(dob)))):
19c87e27a36f1547b692b45a901ce06d8b5dc60e
njsdias/automated_sw_test_python
/1_refresh_python/10_passing_functions.py
586
3.890625
4
import os os.system("clear") def methodception(another): return another() def add_two_numbers(): return 35 + 77 # print(methodception(add_two_numbers)) ## lambda function # print(methodception(lambda: 35 + 77)) # declarative or functional programming # usefull when we are working with data my_list = [13, 56, 77, 484] print(list(filter(lambda x: x!=13, my_list))) def not_thirtheen(x): return x!=13 # Filter is used in many other languages print(list(filter(not_thirtheen, my_list))) # List comprehension: used only in python print([x for x in my_list if x !=13])
6b0b4068cb73f0b37189703f8e0046f203259d94
njsdias/automated_sw_test_python
/1_refresh_python/7_classes_objects_advance.py
1,094
3.84375
4
# classmethod and staticmethod ## Student Class class Student(object): """docstring for Student.""" def __init__(self, name, school): super(Student, self).__init__() self.name = name self.school = school self.marks = [] def average(self): return sum(self.marks) / len(self.marks) @classmethod #this avoid the need to use self and we don't have errors def go_to_scholl(cls): # cls means we are pass the class itself and not the self # print("I'm going to {}".formart(self.scholl)) print("I'm going to scholl!") print("I'm a {}".format(cls)) @staticmethod #this avoid the need to pass the class and the self def go_to_scholl_v2(): print("I'm going to scholl.") anna = Student("Anna", "MIT") ramon = Student("Ramon", "Oxford") anna.marks.append(56) anna.marks.append(71) print(anna.marks) print(anna.average()) anna.go_to_scholl() anna.go_to_scholl_v2() Student.go_to_scholl_v2() # we don't have self so we don't care who is calling # the method go_to_scholl_v2
af0aa9ae06659cd275bb93ffd98f2bee27ead545
Tozman99/JeuDeCombatPartieTir
/projectiles.py
599
3.5625
4
import pygame class Projectile(pygame.sprite.Sprite): def __init__(self, x, y, taille, direction, image): self.x = x self.y = y self.taille = taille self.direction = direction self.image = image self.rect = pygame.Rect(self.x, self.y, self.taille[0], self.taille[1]) def afficher(self, surface): pygame.draw.rect(surface, (255, 0, 255), self.rect) def mouvement(self, vitesse): # -1 alors vitesse est negative => deplacement du projectile vers la gauche # 1 alors vitesse positive => deplacement du projectile vers la droite self.rect.x += (vitesse * self.direction)
da60d5b35c0c7be1a238dd303ce6ce1f07d9ae80
Max-Fu/MNISTPractice
/Digits_With_Neural_Network.py
1,035
4.21875
4
#!/usr/bin/python #Import data and functions from scikit-learn packets, import plotting function from matplotlib from sklearn.neural_network import MLPClassifier import matplotlib.pyplot as plt from sklearn import datasets from sklearn import svm #load the digits and asign it to digits digits = datasets.load_digits() #Use MLPClassifier (provided by sci-kit learn) to create a Neural Network with five layers (supervised learning) #lbfgs: stochastic gradient descent #hidden_layer_sizes: five hidden units and two hidden layer #alpha: regulation penalty clf = MLPClassifier(solver='lbfgs', alpha=1e-5, hidden_layer_sizes=(5,2), random_state = 4) #load trainning data sets to two vectors X and y X,y = digits.data[:-10], digits.target[:-10] #Apply the neural network to the data set clf.fit(X,y) #print the prediction print('Prediction: ', clf.predict(digits.data[-2])) #print the picture of the digit plt.imshow(digits.images[-2], cmap=plt.cm.gray_r, interpolation = "nearest") #show the digit with matplotlib plt.show()
afaeeaacdd727241728cd009634681c70153699f
ramushetty/CSPP1
/day_5/GuessMyNumber/GuessMyNumber/guess_my_number.py
430
3.765625
4
#Guess My Number Exercise def main(): #s = raw_input() #your code here m_m = 50 l_l = 0 h_h = 100 i_i = 'l' g_g = 0 while (i_i != 'c'): print(m_m) i_i = input("enter h to guess the number is too high,'l' if number is low 'c' indicate number is correct") if(i_i=='h'): h_h=m_m m_m=(h_h+l_l)//2 elif(i_i=='l'): l_l=m_m m_m=(h_h + l_l)//2 print('guess number is ',m_m) if __name__== "__main__": main()
c4bbdc40782b90e3bef4373e3a384df5b5bda57b
ramushetty/CSPP1
/day_5/p3 (2)/p3/square_root_bisection.py
692
4.0625
4
'''# Write a python program to find the square root of the given number # using approximation method # testcase 1 # input: 25 # output: 4.999999999999998 # testcase 2 # input: 49 # output: 6.999999999999991''' def main(): ''' bisection ''' s_s = int(input()) # epsilon and step are initialized # don't change these values epsilon = 0.01 #step = 0.1 # your code starts her l_l = 0 h_h = s_s a_a = (h_h+l_l)/2 while abs(a_a**2-s_s) >= epsilon: #print(str(a_a)) if a_a**2 < s_s: l_l = a_a else: h_h = a_a a_a = (h_h+l_l)/2.0 print(str(a_a)) if __name__ == "__main__": main()
c2e859effb367bbd7ddf72285b5f7ee240deb8d2
ramushetty/CSPP1
/day_3/iterate_even_reverse.py
51
3.8125
4
a=10 print("hello!") while a>0: print(a) a=a-2
2fd44882878ff55c7128ff2e6ce243e323dcee40
sdjunaidali/dice
/interface.py
726
3.59375
4
import d6 import d20 import sys while True: try: type = input("Please enter the type of die you want to roll\n(d6 or d20): ") num = int(input("Enter the number of die you want to roll: ")) myResult = [] if type == "d6": print ("rolling d6s") myResult = d6.SixSidedDice(num) elif type =="d20": print ("rolling d20s") myResult = d20.roll20(num) else: print ("Invalid input") print (myResult) except ValueError: print('Value error! Please try again!')
19115600647d00d9acebfb4ce1f6f41d74b67924
Ing-salcedo/Exercism_Python
/sum-of-multiples/sum_of_multiples.py
299
3.65625
4
def sum_of_multiples(limit, multiples): sum = 0 lowest_multiply = sorted(multiples)[0] if len(multiples) != 0 else 0 for i in range(lowest_multiply, limit): for j in multiples: if j != 0 and i % j == 0: sum += i break return sum
ff467efbfd95363b36e2e88a5543c7d59c09cdbf
timo-bronseth/student-record-manager
/src/ExceptionHandling.py
4,231
3.765625
4
# ------------------------------------------------------------------------------------- # Timo Brønseth, January 2020. # ------------------------------------------------------------------------------------- class ExceptionHandlingClass: """All input queries to the user are handled via this class. First, inputs are checked for ValueErrors, and the user is queried for valid entries until there is not ValueError. Second, inputs are checked for all exceptions, just in case there are any that aren't ValueErrors. The program notifies the user that something is buggy, and then exits.""" @classmethod def QueryInt(cls, varName: str) -> str: """Queries the user for an integer, and recursively calls itself until user has successfully entered an integer.""" # userInput needs to be raised to global so that it can be updated # while recursively calling this function in the except clause. global userInput try: userInput = input("{}: ".format(varName.capitalize())) # Raises a ValueError if userInput cannot be recast as integer. if not userInput.isdigit(): raise ValueError except ValueError: # Reprompt user for valid entry. print("\nPlease enter a valid {}.".format(varName)) cls.QueryInt(varName) # If input somehow causes an error which is not a ValueError, this catches it, # and prints the error message "Oops something is buggy". except Exception: # Only runs for errors which are not ValueErrors. # Assignment says to catch all input errors like this. # Don't blame me if it's silly! print("\nOops something is buggy") return userInput @classmethod def QueryStr(cls, varName: str) -> str: """Queries the user for a string, and recursively calls itself until user has successfully entered an string.""" global userInput try: userInput = input("{}: ".format(varName.capitalize())) # Raises a ValueError if userInput CAN be recast as integer. if userInput.isdigit(): raise ValueError except ValueError: # Reprompt user for valid entry. print("\nPlease enter a valid {}.".format(varName)) cls.QueryStr(varName) except Exception: print("\nOops something is buggy") return userInput @classmethod def QueryCourse(cls, varName: str) -> str: """Queries the user for a programming course string, and recursively calls itself until user has successfully entered such.""" global userInput _programmingCourses = ["python", "java", "c", "php", "ruby"] try: userInput = input("{}: ".format(varName.capitalize())) # Raises a ValueError if userInput is not part of programmingCourses. if userInput.lower() not in _programmingCourses: raise ValueError except ValueError: # Reprompt user for valid entry. print("\nWe do not offer that course.\nPlease specify one of {}." .format(str(_programmingCourses).strip('[]'))) cls.QueryCourse(varName) except Exception: print("\nOops something is buggy") return userInput @classmethod def QueryStrGeneral(cls, queryString: str, errorPrompt: str, conditionList: list) -> str: """A more general version, with more arguments, to query user for a string.""" global userInput try: userInput = input(queryString).upper() # Check if userInput points to either of the options, and recursively call # the function until userInput has an actionable value. if userInput not in conditionList: raise ValueError except ValueError: # Reprompt user for valid entry. print(errorPrompt) cls.QueryStrGeneral(queryString, errorPrompt, conditionList) except Exception: print("\nOops something is buggy") return userInput
c42e9e31a2ffd2d59b576aabef22283c4a7ed0ee
Kunika28/positive-numbers-in-a-list
/list.py
184
3.8125
4
list1=[12,-7,5,64,-14] for num in list1: if num>=0: print(num,end=",") list2=[12,14,-95,3] for num2 in list2: if num2>=0: print(num2,end=",")
5058b9265da455110f041cc25e2b1a1842fb34d8
ozgurfiratcelebi/UdacityWeatherTrends
/WeatherTrends.py
958
3.546875
4
""" istanbul verilerini al Dünyanın sıcaklık değerlerini al csv leri python ile açgrafiği dök Şehriniz, küresel ortalamaya kıyasla ortalama olarak daha sıcak mı yoksa daha soğuk mu? Fark zaman içinde tutarlı oldu mu? Şehrinizin sıcaklıklarındaki zaman içindeki değişimler, küresel ortalamadaki değişikliklerle karşılaştırıldığında nasıl? Genel eğilim neye benziyor? Dünya daha da ısınıyor mu, soğuyor mu? Trend, son birkaç yüz yılda tutarlı oldu mu? """ import pandas as pd import matplotlib.pyplot as plt dfIstanbul = pd.read_csv("Istanbul.csv") dfGlobal = pd.read_csv("Global.csv") plt.plot(dfIstanbul['year'],dfIstanbul['avg_temp'] ,label="Istanbul Data") plt.plot(dfGlobal['year'],dfGlobal['avg_temp'] ,label="Global Data") plt.legend() plt.title('Temperature in Istanbul and Global', fontsize=20) plt.xlabel('Year', fontsize=16) plt.ylabel('Temperature [°C]', fontsize=16) plt.show()
6da441db203174f2ba781c98d26eaf7149745598
tainenko/Data-Structure-and-Algorithmic
/Course1 Algorithmic Toolbox/Week5/primitive_calculator.py
1,335
3.984375
4
# Uses python3 import sys def optimal_sequence(n): sequence = [] while n >= 1: sequence.append(n) if n % 3 == 0: n = n // 3 elif n % 2 == 0: n = n // 2 else: n = n - 1 return reversed(sequence) def dynamic_sequence(n): sequence=[] a=[0]*(n+1) #build a reach table from zero to number n #we have three operation methods: #-add 1 #-times 2 #-times 3 #for each i-th element we have to find the minimun steps from( i-1)th element #which means we chose the minimun from (i-1)th element add 1, (i/2)th element times 2 and (i/3)th element times 3 #all of them add the steps by 1 for i in range(1,len(a)): a[i]=a[i-1]+1 if i % 2 == 0: a[i]=a[i//2]+1 if a[i//2] < a[i-1] else a[i-1]+1 if i % 3 == 0: a[i]=a[i//3]+1 if a[i//3] < a[i-1] else a[i-1]+1 while n>0: sequence.append(n) if a[n - 1] == a[n] - 1: n = n - 1 elif n % 2 == 0 and a[n // 2] == a[n] - 1: n = n // 2 elif n % 3 == 0 and a[n // 3] == a[n] - 1: n = n // 3 return reversed(sequence) input = sys.stdin.read() n = int(input) sequence = list(dynamic_sequence(n)) print(len(sequence) - 1) for x in sequence: print(x, end=' ')
9fdfd978d2c141649aa3d16892c97c9d09e47893
tainenko/Data-Structure-and-Algorithmic
/Course1 Algorithmic Toolbox/Week2/lcm.py
395
3.75
4
# Uses python3 import sys def gcd_naive(a, b): while b!=0: a=a%b if a==0: break b=b%a current_gcd =a if a!=0 else b return current_gcd def lcm_naive(a, b): gcd=(gcd_naive(a,b)) lcm=gcd*(a//gcd)*(b//gcd) return lcm if __name__ == '__main__': input = sys.stdin.read() a, b = map(int, input.split()) print(lcm_naive(a, b))
cfcf599e3264dabc0b063edf6e4a3a554a22830e
tainenko/Data-Structure-and-Algorithmic
/Course3 Algorithms on Graphs/Week2/acyclicity.py
894
3.53125
4
#Uses python3 import sys def acyclic(adj): visited=[] path=[] for u in range(len(adj)): if u not in visited and explore(u,adj,path,visited): return 1 return 0 def explore(u,adj,path,visited): if u in path: return True #add the vertex u to visited and path list visited.append(u) path.append(u) #if we can go through from vertex u to vertex v, return True. for v in adj[u]: if explore(v,adj,path,visited): return True #remove current vertex u from path path.pop() return False if __name__ == '__main__': input = sys.stdin.read() data = list(map(int, input.split())) n, m = data[0:2] data = data[2:] edges = list(zip(data[0:(2 * m):2], data[1:(2 * m):2])) adj = [[] for _ in range(n)] for (a, b) in edges: adj[a - 1].append(b - 1) print(acyclic(adj))
afe93a41c67a025389c0101436fb05079f664a7a
kakashi-wells/python-basics
/for.py
87
3.578125
4
numbers = [1,2,3,4,5,20] nombre = "Arthur Wells" for elemento in nombre: print(elemento)
6ea67fe9633ceb8c5d0c7bf8afb067dcf9ad06f7
pedromesmer/python-speech-recognition
/src/db.py
5,282
3.609375
4
import sqlite3 import os def realPath(): return os.path.dirname(os.path.realpath(__file__)) def wait(text = '\nTecle Enter para continuar'): input(text) def create(): # o python não assume o caminho do arquivo como raiz, essa função faz esse 'ajuste técnico' filePath = realPath() conn = sqlite3.connect(filePath + '/../db/actions.db') # banco criado na pasta ../db cursor = conn.cursor() try: cursor.execute(""" CREATE TABLE actions ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, expression TEXT NOT NULL, action TEXT NOT NULL ) """) except sqlite3.OperationalError as err: print(err) return print('> Tabela criada com sucesso!') conn.close() wait() def insertExpression(expression, action): filePath = realPath() conn = sqlite3.connect(filePath + '/../db/actions.db') # banco criado na pasta ../db cursor = conn.cursor() cursor.execute(""" INSERT INTO actions (expression, action) VALUES (?,?) """, (expression, action)) conn.commit() print('> Dados cadastrados com sucesso!') conn.close() def deleteExpression(id): filePath = realPath() conn = sqlite3.connect(filePath + '/../db/actions.db') cursor = conn.cursor() try: cursor.execute(""" DELETE FROM actions WHERE id = ? """, (id,)) except: print('Ocorreu um erro!\nA expressão foi digitada corretamente?\n') conn.close() wait() return conn.commit() conn.close() print('> Expressão deletada com sucesso!') wait() def readExpression(table = 'actions'): filePath = realPath() conn = sqlite3.connect(filePath + '/../db/actions.db') # banco criado na pasta ../db cursor = conn.cursor() cursor.execute(""" SELECT * FROM {}; """.format(table)) expressions = cursor.fetchall() # percorre todos os itens da tabela e salva na lista # print(cursor.fetchall()) """ for line in expressions: print(line) """ conn.close() return expressions def viewAll(table = 'actions'): filePath = realPath() conn = sqlite3.connect(filePath + '/../db/actions.db') # banco criado na pasta ../db cursor = conn.cursor() cursor.execute(""" SELECT * FROM {}; """.format(table)) expressions = cursor.fetchall() # percorre todos os itens da tabela e salva na lista # print(cursor.fetchall()) print('ID','Expressão','Função', sep = '\t') print('------------------------------') for line in expressions: print(line[0], end = '\t') print(line[1], end = '') for space in range((9 - len(line[1]) + 7)): print(' ', end= '') print(line[2]) conn.close() wait() # Menu do DB """ def menuDB(): opt = 0 print('Menu do banco de dados - SpeechRecognition\n' + '1 - Criação do banco\n' + '2 - Adição de expressão e função atribuida\n' + '3 - Exclusão de expressão do banco\n' + '4 - Visualizar tudo\n' + '0 - Voltar ao menu inicial\n') try: opt = int(input('Insira a opção: ')) except: print('Opção inválida!\n') menuDB() if (opt == 1): # criar banco create() elif (opt == 2): # cadastrar expressão primeiro = True while (True): if (not primeiro): sair = input('\nNovo cadastro? (Sim / S / Yes / Y): ') if ((sair.lower() == 'sim') or (sair.lower() == 'yes') or (sair.lower() == 's') or (sair.lower() == 'y')): pass else: print('Encerrando cadastro...') break expression = input('\nExpressão: ') action = input('Ação: ') sair = input('Confirma? (Sim / S / Yes / Y): ') if ((sair.lower() == 'sim') or (sair.lower() == 'yes') or (sair.lower() == 's') or (sair.lower() == 'y')): insertExpression(expression, action) primeiro = False else: print('Encerrando cadastro...') break menuDB() elif (opt == 3): # deletar expressão expression = -1 view = input('Deseja ver a lista de IDs?\n(Sim / S / Yes / Y): ') if ((view.lower() == 'sim') or (view.lower() == 'yes') or (view.lower() == 's') or (view.lower() == 'y')): viewAll() try: expression = int(input('Insira o ID da expressão para exclusão: ')) except: print('A opção so aceita inteiros!\n') menuDB() sair = input('Confirma? (Sim / S / Yes / Y): ') if ((sair.lower() == 'sim') or (sair.lower() == 'yes') or (sair.lower() == 's') or (sair.lower() == 'y')): deleteExpression(expression) else: print('Fim da exclusão...\n') menuDB() elif (opt == 4): # ver todas as expressões e IDs viewAll() menuDB() elif (opt == 0): # menu principal print('Saindo...') else: print('Opção inválida!\n') menuDB() """
7dbab4080831e5bbc9cee498cd3436d9e61cea39
Jaisinghani/AutomataFromRNN
/generator.py
353
3.828125
4
import random chars = 'etaoinsmpru' #num = int(input('How long do you want the string to be? ')) #How long do you want the string to be? 10 word_list=[] number=[3,4,5,6,7] for num in number: for i in range(50): str = [] for k in range(1, num+1): str.append(random.choice(chars)) str = "".join(str) word_list.append(str) print(word_list)
e7931aaecf8b518c31002176ef1f49f02bafe296
bronzeRaf/ai-models
/Netflix/main.py
5,108
3.5
4
import numpy as np import kmeans import common import naive_em import em # Read toy data X = np.loadtxt("toy_data.txt") X_netflix_incomplete = np.loadtxt("netflix_incomplete.txt") X_netflix_complete = np.loadtxt("netflix_complete.txt") # Parameters K = 1 seed = 1 # Testing the Kmeans along K (number of clusters) and seed (random init) ######################################################################## # Initialize min cost per K array min_cost = np.ones(4)*np.inf min_cost_seed = np.zeros(4) for K in range(1,5): for seed in range(0,5): mixture, post = common.init(X, K, seed) mixture, post, cost = kmeans.run(X, mixture, post) # uncomment following line to print cost per K/seed # print('K='+str(K)+' seed='+str(seed)+' cost='+str(cost)) # collect the min cost if min_cost[K-1] > cost: min_cost[K-1] = cost min_cost_seed[K-1] = seed # uncomment following line to plot the clusters # common.plot(X, mixture, post, 'K='+str(K)+' seed='+str(seed)) print('______________________________________________________________________') print('Kmeans results: Min cost per K (1-5) and seed with this min cost (0-4)') print(min_cost) print(min_cost_seed) ######################################################################## # Testing the EM along K (number of clusters) and seed (random init) ######################################################################## # Initialize max log likelihood per K array max_ll = np.zeros(4) max_ll_seed = np.zeros(4) for K in range(1,5): for seed in range(0,5): mixture, post = common.init(X, K, seed) mixture, post, ll = naive_em.run(X, mixture, post) # uncomment following line to print cost per K/seed # print('K='+str(K)+' seed='+str(seed)+' Log Likelihood='+str(ll)) # collect the max likelihood if max_ll[K-1] < abs(ll): max_ll[K-1] = ll max_ll_seed[K-1] = seed # uncomment following line to plot the clusters # common.plot(X, mixture, post, 'K='+str(K)+' seed='+str(seed)) print('______________________________________________________________________') print('EM results: Max abs Log Likelihood per K (1-5) and seed with this likelihood (0-4)') print(max_ll) print(max_ll_seed) ######################################################################## # Testing the EM along K (number of clusters) with seed = 4 (random init) using the BIC metric ######################################################################## # Initialize max log likelihood per K array max_bic = -np.inf max_bic_K = 0 seed = 4 for K in range(1,5): mixture, post = common.init(X, K, seed) mixture, post, ll = naive_em.run(X, mixture, post) bic = common.bic(X, mixture, ll) # uncomment following line to print cost per K/seed # print('K='+str(K)+' seed='+str(seed)+' Log Likelihood='+str(ll)) # collect the max bic if max_bic < bic: max_bic = bic max_bic_K = K # uncomment following line to plot the clusters # common.plot(X, mixture, post, 'K='+str(K)+' seed='+str(seed)) print('______________________________________________________________________') print('EM results: Max BIC metric to select K (1-5) with seed=4') print('MAX BIC: ', max_bic) print('Selected number of clusters: ', max_bic_K) ######################################################################## # Testing the EM along K (number of clusters) for K=1 and K=12 and seed=[0,1,2,3,4] (random init) ######################################################################## # Initialize max log likelihood per K array max_ll = np.zeros(2) max_ll_seed = np.zeros(4) i = 0 for K in (1, 12): for seed in range(0,5): mixture, post = common.init(X_netflix_incomplete, K, seed) mixture, post, ll = em.run(X_netflix_incomplete, mixture, post) # uncomment following line to print cost per K/seed # print('K='+str(K)+' seed='+str(seed)+' Log Likelihood='+str(ll)) # collect the max likelihood if max_ll[i] < abs(ll): max_ll[i] = ll max_ll_seed[i] = seed # uncomment following line to plot the clusters # common.plot(X, mixture, post, 'K='+str(K)+' seed='+str(seed)) i += 1 print('______________________________________________________________________') print('EM results: Max abs Log Likelihood per K [1,12] and seed with this likelihood (0-4)') print(max_ll) print(max_ll_seed) ######################################################################## # Estimate the missing ratings and evaluate model with the Test set using the RMSE metric # K = 12 (number of clusters and seed = 4 (random init) ######################################################################## # Parameters K = 12 seed = 4 # Build the mixture models mixture, post = common.init(X_netflix_incomplete, K, seed) mixture, post, ll = em.run(X_netflix_incomplete, mixture, post) X_pred = em.fill_matrix(X_netflix_incomplete, mixture) rmse = common.rmse(X_netflix_complete, X_pred) print(rmse)
028692a752e6b44f2aa073dc03c760846c2281a7
Mezheneva/ITMO-Python
/lesson 2/birthday.py
266
3.921875
4
nowDay = 4 nowMonth = 10 nowYear = 2019 day = int(input('Enter day>')) month = int(input('Enter month>')) year = int(input('Enter year>')) if (month > nowMonth) or (month == nowMonth and day > nowDay): print (nowYear - year - 1) else: print(nowYear - year)
475e9cfb8b043e59c74717b57aaec3b5d01e1532
Gabrihalls/Estudos-de-python
/desafios/dsf016.py
253
3.640625
4
import math print('-'*20,'DECIMO-SEXTO DESAFIO','-'*20) nome = input('Olá , digite seu nome:') num = float(input('{},por favor escolha um número:'.format(nome))) ni = (math.trunc(num)) print('O seu número de uma forma inteira é: {}'.format(ni))
e070f5c318c6b44e4d5661509b855ff82f2621d7
Gabrihalls/Estudos-de-python
/desafios/dsf003.py
244
4.125
4
print('-----------------------TERCEIRO DESAFIO-----------------------') primeiro = int(input('Qual primeiro número de sua soma?')) segundo = int(input('Qual segundo número de sua soma?')) print('O resulta de sua soma é:',primeiro+segundo)
dbd2d7f4af28f43a5b3ef927627abb706c181eb7
Mohanbarman/hackerrank-problems
/DayOfProgrammer/main.py
760
4.09375
4
""" Hackerrank - Day Of Programmer. 1. Calculate day of the year in Russia. 2. Years -> 1700 - 2700 3. From 1700 to 1917 : Julian calender. 4. From 1919 : Gregorian calender. 5. 1918 of 31st jan : Julian calender. ***After 31st jan 14th feb came in 1918*** 6. 1918 of 14th feb : Gregorian calender. * In both calenders february have 29 days during leap year Julian_calender | | Leap years are divisible by 4. Gregorian_calender | | Leap years are divisible by 400 or 4 not 100. """ def dayOfProgrammer(y): if (y == 1918): return '26.09.1918' elif (y <= 1917 and y%4 == 0) or (y > 1917 and (y%400 == 0 or y%4 == 0 and (y%100 != 0))): return '12.09.' + str(y) else : return '13.09.' +str(y)
0e71cb0ac7dd5ccadf9142fffff83b37403cbd52
linkpark/study
/pythonProgram/pythonForDataBase/SQLiteHandler.py
1,039
3.53125
4
#!/usr/bin/python # Filename: SQLiteHandler.py from BaseHandler import*; import sqlite3; class SQLiteHandler(BaseHandler): def __init__(self): BaseHandler.__init__(self); print "SQLiteHandler created successful!"; def connectDataBase(self,baseName): self.conn = sqlite3.connect(baseName); self.cursor = self.conn.cursor(); def excuteQuery(self,query): try: self.cursor.execute(query); self.conn.commit(); except AttributeError: print "you must connect the DataBase first!"; #get Value By the key; def getValueByKey(self,key): selectQuery = "select * from user where swift_id='%s'" % (key); self.cursor.execute(selectQuery); result = self.cursor.fetchone(); value = ""; for f in result[1:]: value = value + f + ":"; return value; #set Value By the key; def setValueByKey(self,key,value): insertQuery = "insert into user(swift_id,s3_id) values('%s','%s')" % (key,value); self.excuteQuery(insertQuery);
9614b6922dcfbb9ed5a1184543ce999da5cf0238
linkpark/study
/pythonProgram/pythonForProcess/thread_2.py
591
3.765625
4
#!/usr/bin/python # Filename: thread_2.py import threading; import time; class ThreadDemo(threading.Thread): def __init__(self,index,create_time): threading.Thread.__init__(self); self.index = index; self.create_time = create_time; def run(self): time.sleep(1); print(time.time() - self.create_time),"\t",self.index; print "Thread %d exit..." % (self.index); #threads = []; for index in range(5): thread = ThreadDemo(index,time.time()); thread.start(); # threads.append(thread); #for thread in threads: # thread.join(); time.sleep(10) print "Main thread exit ...";
d24d68173565aefbd768a8378c9d9ada9d9e4bb0
blackhen/Python
/gradex.py
416
3.859375
4
'''Grade''' def grade(med, mid): '''grade''' if med <= 100 and mid <= 100: med2 = med*30/100 mid2 = mid*70/100 grad = med2+mid2 if grad >= 80: print 'A' elif grad >= 70: print 'B' elif grad >= 60: print 'C' elif grad >= 50: print 'D' elif grad < 50: print 'F' grade(input(), input())
bbb2bfad8385c47b1e0f39508806995fbecd31a5
blackhen/Python
/patland.py
796
3.53125
4
'''patland''' def pat(num): '''check''' num = int(num) while num >= 0: fff = ['a king.', 'a queen.', 'nobody.'] for i in range(num): word = raw_input() bbb = 0 while word[-1] == 'a': bbb = 1 break while word[-1] == 'e': bbb = 1 break while word[-1] == 'i': bbb = 1 break while word[-1] == 'o': bbb = 1 break while word[-1] == 'u': bbb = 1 break while word[-1] == 'y': bbb = 2 break print 'Case #'+str(i+1)+': '+word+' is ruled by '+fff[bbb] break pat(input())
8eec237f290ebf572b469d67fe8b1a0a7042d6ad
blackhen/Python
/center.py
223
3.796875
4
'''center''' def center(): '''cen''' wwww = input() letter = raw_input() lengh = len(letter) space = wwww - lengh space2 = space/2 space3 = ' '*space2 print space3 + letter + space3 center()
40968f50bbd929cde9f0f5777c810e3b64ed7300
blackhen/Python
/primetest.py
910
3.921875
4
'''primes''' def prime(number, loop, check): '''primes''' if number >= 0: if loop > number: pass elif loop % 2 == 0 and loop != 2: prime(number, loop+1, check) elif loop % 3 == 0 and loop != 3: prime(number, loop+1, check) elif loop % 4 == 0 and loop != 4: prime(number, loop+1, check) elif loop % 5 == 0 and loop != 5: prime(number, loop+1, check) elif loop % 6 == 0 and loop != 6: prime(number, loop+1, check) elif loop % 7 == 0 and loop != 7: prime(number, loop+1, check) elif loop % 8 == 0 and loop != 8: prime(number, loop+1, check) elif loop % 9 == 0 and loop != 9: prime(number, loop+1, check) else: print loop, 'is a prime number.' prime(number, loop+1, check) prime(input(), 2, 2)
ac92d16f89772e50084e5f5d4c4dcb8a9d75476e
blackhen/Python
/classroom.py
363
3.515625
4
'''classroom''' def classroom(aaa): '''classroom''' colum = aaa row = aaa lis = [] for i in range(colum): lid = [] for i in range(row): num = input() lid.append(num) lis.append(lid) for i in range(aaa): lis[i].sort() lis.sort(reverse=True) print lis[0][0] classroom(input())