blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
a3b4387c1574d6d8c7c0a4acb4b6fb4bb60479a8
gonzalob24/Learning_Central
/Python_Programming/Queues/Deque.py
1,423
4.3125
4
# Creating a class to create deques # Deque demonstrates behavior of Queues and Stacks # Its a double ended Queue class EmptyQueueError(Exception): pass class Deque: def __init__(self): self.items = [] def is_empty(self): return self.items == [] def add_front(self, item): # This is not the most efficient way self.items.insert(0, item) def add_rear(self, item): # This is not the most efficient way self.items.append(item) def remove_front(self): if self.is_empty(): raise EmptyQueueError("Queue is empty") return self.items.pop(0) def remove_rear(self): if self.is_empty(): raise EmptyQueueError("Queue is empty") return self.items.pop() def first(self): if self.is_empty(): raise EmptyQueueError("Queue is empty") return self.items[0] def last(self): if self.is_empty(): raise EmptyQueueError("Queue is empty") return self.items[-1] def size(self): return len(self.items) def display(self): print(self.items) if __name__ == '__main__': d = Deque() print(d.is_empty()) d.add_rear(4) d.add_rear('dog') d.add_front('cat') d.add_front(True) print(d.size()) print(d.is_empty()) d.add_rear(8.4) print(d.remove_rear()) print(d.remove_front()) d.display()
c1733d7d7ee1434d36b4e771a58fa22951b76d4c
kiranmai524/python_tutorial
/euler10.py
377
4.25
4
def is_prime(digit): now=3 while (now*now)<=digit: if digit%now==0: return False else: now+=2 return True numprime=1 #considering 2 as only even prime we only check the odd numbers num=1;sum=2 while num<2000000: num+=2 if is_prime(num): sum+=num numprime+=1 print "the sum of prime numbers below 2000000 is%r and number of primes is %r"%(sum,numprime)
8ee6cfcff8eb512516a7143844473228ad6d03b2
schw240/Preparing-coding-test
/백준/10단계/별찍기10.py
1,370
3.578125
4
n = int(input()) # 출력할 배열 초기화 모두 *로 채워주고 빈칸이 들어갈부분은 밑에서바꿔준다. list = [['*'] * n for i in range(n)] def starprint(n, list): # if n < 3: # 1일때는 바로 내보내어 *이 출력하게만든다. return if n == 3: # 3일때 빈칸은 직접 채워준다. list[1][1] = " " else: starprint(n//3, list) # 재귀를 통해 이전리스트를 완성시키고 넘겨준다. for i in range(n // 3): # 빈칸들이 일정한 패턴으로 늘어나는것을 이용한다. for j in range(n // 3): if list[i][j] == " ": # 하나의 빈칸에서 파생되는 빈칸들 list[i][j+n//3] = " " list[i][j + 2*n//3] = " " list[i+n//3][j] = " " list[i+n//3][j+2*n//3] = " " list[i+2*n//3][j] = " " list[i+2*n//3][j+n//3] = " " list[i+2*n//3][j+2*n//3] = " " for i in range(n): # 가운데 부분은 직접 비워줬다. for j in range(n): if n//3 <= i < n//3*2 and n//3 <= j < n//3*2: list[i][j] = " " return list starprint(n, list) # 함수실행 for i in range(n): for j in range(n): print(list[i][j], end="") print()
9417be6383f8b5382428b4ba1dcacb4a7b1e66db
E477n/WeWear
/Match/color_match.py
10,152
3.546875
4
def color_match(a, b): scheme = list() main0 = list() # 黑白两色 main1 = list() # 高饱和度配色 main2 = list() # 高饱和度撞色 main3 = list() # 非高饱和度配色 hmin = a[0] - 20 hmax = a[0] + 20 # 0主题色 黑白大类 if a[2]>=0 and a[2]<=0.1: #外套 coat = list() for each in b[0]: if each[3]>=0 and each[3]<=0.1: coat.append(each) main0.append(coat) # 上装 tops = list() for each in b[1]: if each[3] >= 0 and each[3] <= 0.1: tops.append(each) main0.append(tops) # 内衬 lining = [] for each in b[2]: if each[3] >= 0 and each[3] <= 0.1: lining.append(each) main0.append(lining) # 内搭 inside = [] for each in b[3]: if each[3] >= 0 and each[3] <= 0.1: inside.append(each) main0.append(inside) # 连体套装 piece_suit = [] for each in b[4]: if each[3] >= 0 and each[3] <= 0.1: piece_suit.append(each) main0.append(piece_suit) # 连衣套装 dress_suit = [] for each in b[5]: if each[3] >= 0 and each[3] <= 0.1: dress_suit.append(each) main0.append(dress_suit) # 西装套装 suit = [] for each in b[6]: if each[3] >= 0 and each[3] <= 0.1: suit.append(each) main0.append(suit) # 裤装 trousers = [] for each in b[7]: if each[3] >= 0 and each[3] <= 0.1: trousers.append(each) main0.append(trousers) # 裙装 skirt = [] for each in b[8]: if each[3] >= 0 and each[3] <= 0.1: skirt.append(each) main0.append(skirt) # 鞋子 shoes = [] for each in b[9]: if each[3] >= 0 and each[3] <= 0.1: shoes.append(each) main0.append(shoes) # 配饰 accessories = [] for each in b[10]: if each[3] >= 0 and each[3] <= 0.1: accessories.append(each) main0.append(accessories) # 1主题色 高饱和度配色 + 2主题色 高饱和度撞色 if a[2]>=0.35 and a[2]<=0.65 and a[1]>0.5: # 外套 coat1 = list() coat2 = list() if a[0] <= 140 or a[0] >= 280: for each in b[0]: if each[1] in (hmin, hmax): coat1.append(each) if each[1]>=140 and each[1]<=280: coat2.append(each) else: for each in b[0]: if each[1] in (hmin, hmax): coat1.append(each) if float(each[1])<140 or float(each[1])>280: coat2.append(each) main1.append(coat1) main2.append(coat2) # 上装 tops1 = list() tops2 = list() if a[0] <= 140 or a[0] >= 280: for each in b[1]: if each[1] in (hmin, hmax): tops1.append(each) if each[1] >= 140 and each[1] <= 280: tops2.append(each) else: for each in b[1]: if each[1] in (hmin, hmax): tops1.append(each) if float(each[1]) < 140 or float(each[1]) > 280: tops2.append(each) main1.append(tops1) main2.append(tops2) # 内衬 lining1 = list() lining2 = list() if a[0] <= 140 or a[0] >= 280: for each in b[2]: if each[1] in (hmin, hmax): lining1.append(each) if each[1] >= 140 and each[1] <= 280: lining2.append(each) else: for each in b[2]: if each[1] in (hmin, hmax): lining1.append(each) if float(each[1]) < 140 or float(each[1]) > 280: lining2.append(each) main1.append(lining1) main2.append(lining2) # 内搭 inside1 = list() inside2 = list() if a[0] <= 140 or a[0] >= 280: for each in b[3]: if each[1] in (hmin, hmax): inside1.append(each) if each[1] >= 140 and each[1] <= 280: inside2.append(each) else: for each in b[3]: if each[1] in (hmin, hmax): inside1.append(each) if float(each[1]) < 140 or float(each[1]) > 280: inside2.append(each) main1.append(inside1) main2.append(inside2) # 连体套装 piece_suit1 = list() piece_suit2 = list() if a[0] <= 140 or a[0] >= 280: for each in b[4]: if each[1] in (hmin, hmax): piece_suit1.append(each) if each[1] >= 140 and each[1] <= 280: piece_suit2.append(each) else: for each in b[4]: if each[1] in (hmin, hmax): piece_suit1.append(each) if float(each[1]) < 140 or float(each[1]) > 280: piece_suit2.append(each) main1.append(piece_suit1) main2.append(piece_suit2) # 连衣套装 dress_suit1 = list() dress_suit2 = list() if a[0] <= 140 or a[0] >= 280: for each in b[5]: if each[1] in (hmin, hmax): dress_suit1.append(each) if each[1] >= 140 and each[1] <= 280: dress_suit2.append(each) else: for each in b[5]: if each[1] in (hmin, hmax): dress_suit1.append(each) if float(each[1]) < 140 or float(each[1]) > 280: dress_suit2.append(each) main1.append(dress_suit1) main2.append(dress_suit2) # 西装套装 suit1 = list() suit2= list() if a[0] <= 140 or a[0] >= 280: for each in b[6]: if each[1] in (hmin, hmax): suit1.append(each) if each[1] >= 140 and each[1] <= 280: suit2.append(each) else: for each in b[6]: if each[1] in (hmin, hmax): suit1.append(each) if float(each[1]) < 140 or float(each[1]) > 280: suit2.append(each) main1.append(suit1) main2.append(suit2) # 裤装 trousers1 = list() trousers2 = list() if a[0] <= 140 or a[0] >= 280: for each in b[7]: if each[1] in (hmin, hmax): trousers1.append(each) if each[1] >= 140 and each[1] <= 280: trousers2.append(each) else: for each in b[7]: if each[1] in (hmin, hmax): trousers1.append(each) if float(each[1]) < 140 or float(each[1]) > 280: trousers2.append(each) main1.append(trousers1) main2.append(trousers2) # 裙装 skirt1 = list() skirt2 = list() if a[0] <= 140 or a[0] >= 280: for each in b[8]: if each[1] in (hmin, hmax): skirt1.append(each) if each[1] >= 140 and each[1] <= 280: skirt2.append(each) else: for each in b[8]: if each[1] in (hmin, hmax): skirt1.append(each) if float(each[1]) < 140 or float(each[1]) > 280: skirt2.append(each) main1.append(skirt1) main2.append(skirt2) # 鞋子 shoes1 = list() shoes2 = list() if a[0] <= 140 or a[0] >= 280: for each in b[9]: if each[1] in (hmin, hmax): shoes1.append(each) if each[1] >= 140 and each[1] <= 280: shoes2.append(each) else: for each in b[9]: if each[1] in (hmin, hmax): shoes1.append(each) if float(each[1]) < 140 or float(each[1]) > 280: shoes2.append(each) main1.append(shoes1) main2.append(shoes2) # 配饰 accessories1 = list() accessories2 = list() if a[0] <= 140 or a[0] >= 280: for each in b[10]: if each[1] in (hmin, hmax): accessories1.append(each) if each[1] >= 140 and each[1] <= 280: accessories2.append(each) else: for each in b[10]: if each[1] in (hmin, hmax): accessories1.append(each) if float(each[1]) < 140 or float(each[1]) > 280: accessories2.append(each) main1.append(accessories1) main2.append(accessories2) # 2主题色 临近二色 else: main3 = b scheme.append(main0) scheme.append(main1) scheme.append(main2) scheme.append(main3) return scheme ''' coat = list() for h in range(0,18): for s in range(0,10): for l in range(0,10): a = 20*h b = 0.1*s c = 0.1*l coat.append(['1111111',a,b,c]) tops = [] a = [240.00, 0.55, 0.55] b = [coat] array = color_match(a, b) for i in array: print(len(i)) for i in array: for j in i: print(len(j)) for i in array: for j in i: print(j) '''
c0f93681a3a1222bca364f1f62c8fbabdda04057
nyu-ml-final-project/NyuPoly-CS6923-Fall16
/Lesson 10 - Clustering/kmeans_exercise.py
2,444
4.28125
4
""" Simple implementation of K-Means clustering You'll need to complete three methods 1. fit() 2. _compute_centroids() 3. _compute_labels_and_score() @modified by Gustavo Sandoval = Nov 2016 @author Ruben Naeff - August 2015 """ import numpy as np class KMeans(): """Find k clusters in the given data NB Make sure your data is properly scaled! :param k: number of clusters to be found """ def __init__(self, k=3): self.k = k def fit(self, X, max_iter=100): """Find k clusters in the data X :param X: dataframe or numpu ndarray with n-dimensional data """ X = np.array(X) # concert to numpy array to be safe self.n_samples, self.n_features = X.shape # TODO # define k clusters randomly around the center # .... # .... centroids = range(3) # replace this # iterate: # - given centroids, compute labels for each point (and total score) # - given labels, compute centroids to be in the center of each cluster # repeat until labels do not change or max_iter has been reached # keep track of total score to make sure you return the best solution labels = None best_score = np.inf self.history = [dict(score=None, labels=None, centroids=centroids)] for y in range(max_iter): pass # your code here... # labels, score = self._compute_labels_and_score(X, centroids) # centroids = self._compute_centroids(X, labels) # ... # ... if i == max_iter: print ("Warning: algorithm stopped but did not necssarily converge.") def _compute_centroids(self, X, labels): # TODO # Compute coordinates of the centers of each cluster # ... return None def _compute_labels_and_score(self, X, centroids): # TODO # Compute to which center the data is closest, and label accordingly # Also return score (average distance to closest cluster) # ... return labels, score def predict(self, X): """Predict which to which clusters the data in X belongs""" return self._compute_labels_and_score(X, self.centroids)[0] def score(self, X): """Average distance to nearest cluster. Negative value, so that higher is better.""" return -self._compute_labels_and_score(X, self.centroids)[1]
5a22e2d72170b8241ac4b57c85f6c016033ae028
haw230/bubble-sort
/bubble_sort/main.py
274
3.671875
4
def bubble_sort(ls): ''' Write bubble sort! ''' pass def swap(ls, i): ''' Write the code to swap two items in ls. Remember that ls will store a reference so editing it inside of swap() will change it for bubble_sort() as well. ''' pass
a0969dfc22ed4afc68666f814da64d5439fdcdc7
pi408637535/Algorithm
/com/study/algorithm/offer/剑指 Offer 68 - II. 二叉树的最近公共祖先.py
2,173
3.8125
4
class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def lowestCommonAncestor(self, root, p, q): """ :type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode """ if root == None: return None if root.val == p.val or root.val == q.val: return root left_node = self.lowestCommonAncestor(root.left, p, q) #right_node = self.helper(root.right, p.val, q.val) right_node = self.lowestCommonAncestor(root.right, p, q) if left_node == None and right_node != None: return right_node elif right_node == None and left_node != None: return left_node elif left_node != None and right_node != None: return root else: return None class Solution(object): def lowestCommonAncestor(self, root, p, q): """ :type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode """ if not root: return None if root == p or root == q: return root left_res = self.lowestCommonAncestor(root.left, p, q) right_res = self.lowestCommonAncestor(root.right, p, q) if not left_res and right_res: return right_res elif not right_res and left_res: return left_res elif left_res and right_res: return root if __name__ == '__main__': TreeNode3 = TreeNode(3) TreeNode5 = TreeNode(5) TreeNode1 = TreeNode(1) TreeNode6 = TreeNode(6) TreeNode2 = TreeNode(2) TreeNode0 = TreeNode(0) TreeNode8 = TreeNode(8) TreeNode7 = TreeNode(7) TreeNode4 = TreeNode(4) TreeNode3.left = TreeNode5 TreeNode3.right = TreeNode1 TreeNode5.left = TreeNode6 TreeNode5.right = TreeNode2 TreeNode1.left = TreeNode0 TreeNode1.right = TreeNode8 TreeNode2.left = TreeNode7 TreeNode4.right = TreeNode4 print(Solution().lowestCommonAncestor(TreeNode3, TreeNode5, TreeNode2))
1ef3d0932648045ebf1e1eaae3876a8bf18c4858
mublan11/Calculadora-Testing
/calculadora.py
1,766
3.875
4
import math """ Autor: Diego Misael Blanco Murillo. Fecha: 06/SEP/17 """ class Calculadora(): def __init__(self): self.resultado = 0 def obtener_resultado(self): return self.resultado def suma(self, num1, num2): try: self.resultado = num1 + num2 except: self.resultado = 'Datos incorrectos' def resta(self, num1, num2): try: self.resultado = num1 - num2 except: self.resultado = 'Datos incorrectos' def division(self, num1, num2): try: if num2 == 0: self.resultado = "La division por cero no esta definida" else: self.resultado = num1 / num2 except: self.resultado = 'Datos incorrectos' def multiplicacion(self, num1, num2): try: if type(num1) == str or type(num2) == str: self.resultado = "Datos incorrectos" else: self.resultado = num1 * num2 except: self.resultado = 'Datos incorrectos' def potencia(self, num1, num2): try: if type(num1) == str or type(num2) == str: self.resultado = "Datos incorrectos" else: self.resultado = num1 ** num2 except: self.resultado = 'Datos incorrectos' def raiz(self, num1): try: if num1 < 0: self.resultado = "No se aceptan numeros negativos (i)" elif type(num1) == str: self.resultado = "Datos incorrectos" else: self.resultado = math.sqrt(num1) except: self.resultado = 'Datos incorrectos'
30505d4e6aa3aba6ec5353649cfe6d3334e4f370
shaggyday/codes-from-school
/Tic Tac Toe.py
12,845
3.9375
4
# Harry Tian & Star Song: a Tic Tac Toe game using Zelle graphics from graphics import * import time import random class TicTacToe: """Class to represent tic tac toe playable game with simple graphics """ def __init__(self): """ No arguments, 2 instance variables are created here - 1. the graphics window used to display the game and get mouse clicks 2. 3x3 list of lists to represent the actual internal game state """ self.window = GraphWin("Tic-Tac-Toe",700,700) self.board = [ ["-", "-", "-"], ["-", "-", "-"], ["-", "-", "-"] ] self.winner = "" # set initial variables for AIblock function self.mode = "" self.blockX = int() self.blockY = int() def startScreen(self): """ draws the empty initial tic tac toe grid and some text instructions """ # creates initial screen with options 1-player and 2-players onePlayer = Circle(Point(250,350),90) onePlayer.draw(self.window) twoPlayer = Circle(Point(450,350),90) twoPlayer.draw(self.window) txt1 = Text(Point(250,350), "1-player") txt1.setTextColor("red") txt1.setSize(27) txt1.draw(self.window) txt2 = Text(Point(450,350), "2-players") txt2.setTextColor("blue") txt2.setSize(27) txt2.draw(self.window) # sets play mode (self.mode) boolean for future use click1 = self.window.getMouse() if 200 <= click1.x <= 300 and 300 <= click1.y <= 400: onePlayer.undraw() twoPlayer.undraw() txt1.undraw() txt2.undraw() self.mode = True elif 400 <= click1.x <= 500 and 300 <= click1.y <= 400: onePlayer.undraw() twoPlayer.undraw() txt1.undraw() txt2.undraw() self.mode = False # creates game board t = Text(Point(350,25), "Click on a square to play your symbol X or O") t.setSize(18) t.setTextColor("blue") line1 = Line(Point(250, 50), Point(250, 650)) line2 = Line(Point(450, 50), Point(450, 650)) line3 = Line(Point(50, 250), Point(650, 250)) line4 = Line(Point(50, 450), Point(650, 450)) square1 = Rectangle(Point(50, 50), Point(650, 650)) t.draw(self.window) line1.draw(self.window) line2.draw(self.window) line3.draw(self.window) line4.draw(self.window) square1.draw(self.window) def takeTurn(self, player): """ waits for a mouse click, then draws an X or an O centered exactly at the point clicked, depending on which player's turn it is """ # handles invalid clicks out of the bounds of the grid and not in a currently empty square # check for invalid checks and display text, wait for another click if not self.mode or (self.mode and player == 1): click1 = self.window.getMouse() t = Text(Point(350,350), "Your click was INVALID!") t.setSize(30) t.setTextColor("red") draw = False # sets boolean so text is not drawn twice valid = False while not valid: if 50 <= click1.x <= 650 and 50 <= click1.y <= 650 and self.board[(click1.y-50)//200][(click1.x-50)//200] == "-": valid = True if not valid: if not draw: t.draw(self.window) draw = True click1 = self.window.getMouse() if draw: t.undraw() # alternate turns between the two players if player == 1: self.xdraw(click1.x, click1.y) elif player == 0: # differentiates between 1-player and 2-players mode if self.mode: self.odraw(0,0) else: self.odraw(click1.x, click1.y) def xdraw(self, x, y): """ draw an x centered on the point x,y """ # reset x,y coordinates so that its always centered in square gridX = (x-50)//200 gridY = (y-50)//200 x = gridX*200+150 y = gridY*200+150 # draw letter X centered in square lineFive = Line(Point((x - 75), (y - 75)), Point((x + 75), (y + 75))) lineSix = Line(Point((x + 75), (y - 75)), Point((x - 75), (y + 75))) lineFive.draw(self.window) lineSix.draw(self.window) # Update the internal game board with the newly added "X" in the appropriate position self.board[gridY][gridX] = "X" return [lineFive, lineSix] def blockCon1(self,symbol,a,b,c,x): """ help function that sets boolean for conditions when AI or player has 2-in-a-row """ if self.board[x][a] == self.board[x][b] == symbol and self.board[x][c] == "-": self.blockX = c self.blockY = x return True return False def blockCon2(self,symbol,a,b,c,x): """ help function that sets boolean for conditions when AI or player has 2-in-a-row """ if self.board[a][x] == self.board[b][x] == symbol and self.board[c][x] == "-": self.blockX = x self.blockY = c return True return False def blockCon3(self,symbol,a,b,c,x): """ help function that sets boolean for conditions when AI or player has 2-in-a-row """ if x == 1: if self.board[a][a] == self.board[b][b] == symbol and self.board[c][c] == '-': self.blockX = c self.blockY = c return True return False elif x == 2: if self.board[a][c] == self.board[b][b] == symbol and self.board[c][a] == '-': self.blockX = a self.blockY = c return True return False elif x == 3: if self.board[a][b] == self.board[b][a] == symbol and self.board[c][c] == '-': self.blockX = c self.blockY = c return True return False def AIblock(self,symbol): """ uses help function to return boolean for every 2-in-a-row condition""" for x in range(3): if self.blockCon1(symbol,2,1,0,x): return True if self.blockCon1(symbol,0,2,1,x): return True if self.blockCon1(symbol,1,0,2,x): return True if self.blockCon2(symbol,2,1,0,x): return True if self.blockCon2(symbol,0,2,1,x): return True if self.blockCon2(symbol,1,0,2,x): return True if self.blockCon3(symbol,2,1,0,1): return True if self.blockCon3(symbol,1,0,2,1): return True if self.blockCon3(symbol,0,2,1,1): return True if self.blockCon3(symbol,2,1,0,2): return True if self.blockCon3(symbol,0,1,2,2): return True if self.blockCon3(symbol,2,0,1,3): return True def odraw(self, x, y): """ draw an o centered on the point x,y """ if self.mode:#odraw for 1-player mode AIblockX = self.AIblock("X") AIblockO = self.AIblock("O") # sets valid coordinates for AI within grid A = self.blockX*200+150 B = self.blockY*200+150 # calls AIblock function to determine if AI needs to block or not; # calls AIblock for "O" first and exclusive from AIblock for "X" so that # the win condition for "O" is prioritized before blocking "X" from winning if AIblockO: self.board[self.blockY][self.blockX] = "O" elif AIblockX: self.board[self.blockY][self.blockX] = "O" # if block is not needed, AI plays a random move else: valid = False while not valid: # reset valid and random coordinates for AI to play in gridA = random.randint(0,2) gridB = random.randint(0,2) if self.board[gridB][gridA] == "-": valid = True A = gridA*200+150 B = gridB*200+150 self.board[gridB][gridA] = "O" circle = Circle(Point(A, B), 75) circle.draw(self.window) return [circle] # draw letter O centered in square # sets x,y coordinates so that its always centered in square gridX = (x-50)//200 gridY = (y-50)//200 x = gridX*200+150 y = gridY*200+150 circle = Circle(Point(x, y), 75) circle.draw(self.window) # Update the internal game board with the newly added "O" in the appropriate position self.board[gridY][gridX] = "O" return [circle] def drawRed(self,symbol,x,y): """ make winning 3 symbols red by drawing red symbols over current """ x = x*200+150 y = y*200+150 if symbol == "X": lineFive = Line(Point((x - 75), (y - 75)), Point((x + 75), (y + 75))) lineSix = Line(Point((x + 75), (y - 75)), Point((x - 75), (y + 75))) lineFive.setOutline("red") lineSix.setOutline("red") lineFive.draw(self.window) lineSix.draw(self.window) elif symbol == "O": circle = Circle(Point(x, y), 75) circle.setOutline("red") circle.draw(self.window) def isWon(self): """ currently checks each row, column, and diagonal for 3 identical symbols (other than "-") returns True if either player has won, False otherwise; also makes winning 3 symbols red """ rows = 0 for row in self.board: if row[0] != "-" and row[0] == row[1] == row[2]: if row[0] == "X": # update self.winner to be the appropriate symbol X or O for who won; repeat for all win conditions self.winner = "X" for i in range(3): self.drawRed("X",i,rows) return True elif row[0] == "O": self.winner = "O" for i in range(3): self.drawRed("O",i,rows) return True rows += 1 for x in range(3): if self.board[0][x] == self.board[1][x] == self.board[2][x] and self.board[0][x] != "-": if self.board[0][x] == "X": self.winner = "X" for i in range(3): self.drawRed("X",x,i) return True elif self.board[0][x] == "O": self.winner = "O" for i in range(3): self.drawRed("O",x,i) return True if self.board[0][0] == self.board[1][1] == self.board[2][2] and self.board[0][0] != "-": if self.board[0][0] == "X": self.winner = "X" for i in range(3): self.drawRed("X",i,i) return True elif self.board[0][0] == "O": self.winner = "O" for i in range(3): self.drawRed("O",i,i) return True if self.board[0][2] == self.board[1][1] == self.board[2][0] and self.board[0][2] != "-": if self.board[0][2] == "X": self.winner = "X" for i in range(3): self.drawRed("X",i,2-i) return True elif self.board[0][2] == "O": self.winner = "O" for i in range(3): self.drawRed("O",i,2-i) return True return False def gameOver(self): """ displays text declaring winner (or draw) and waits for user to click to close window """ if self.winner == "X": t = Text(Point(350,350), "X WON!") elif self.winner == "O": t = Text(Point(350,350), "O WON!") else: t = Text(Point(350,350), "DRAW!") t.setSize(35) t.setTextColor("red") t.draw(self.window) while self.window.winfo_exists(): self.window.update() def main(): """ finished working code to play one game of graphical tic-tac-toe """ tttGame = TicTacToe() tttGame.startScreen() curTurn = 1 while not tttGame.isWon() and curTurn <= 9: tttGame.takeTurn(curTurn % 2) curTurn += 1 tttGame.gameOver() if __name__ == "__main__": main()
5b9618686446980d6c9a9c1820cfd9c13f154970
AsemDevs/ItemCatalog
/somecities.py
2,442
3.546875
4
from database_setup import User, Base, Place, City from sqlalchemy.orm import sessionmaker from sqlalchemy import create_engine # engine = create_engine('sqlite:///citiescatalog.db') engine = create_engine('postgresql://catalog:password@localhost/catalog') # Bind the engine to the metadata of the Base class so that the # declaratives can be accessed through a DBSession instance DBSession = sessionmaker(bind=engine) # A DBSession() instance establishes all conversations with the database # and represents a "staging zone" for all the objects loaded into the # database session object. Any change made against the objects in the # session won't be persisted into the database until you call # session.commit(). If you're not happy about the changes, you can # revert all of them back to the last commit by calling # session.rollback() session = DBSession() # Create dummy user user1 = User(name="Jhon Doe", email="jhondoe@demo.com", picture='https://imgplaceholder.com/150x150') session.add(user1) session.commit() city1 = City(name="Mecca", user=user1) session.add(city1) session.commit() place1 = Place(name="Grand Mosque (Haram)", description="The grand mosque of Makkah commonly known as Masjid al-Haram is the largest mosque in the world surrounded by the holiest places of Islam. Muslims around the world pray in the direction of Grand Mosque, 5 times a day",city=city1, user=user1) session.add(place1) session.commit() city2 = City(name="Cairo", user=user1) session.add(city2) session.commit() place21 = Place(name="Al-Azhar Mosque", description="Al-Azhar Mosque is the finest building of Cairo's Fatimid era and one of the city's earliest surviving mosques, completed in AD 972.",city=city2, user=user1) place22= Place(name="The Egyptian Museum", description="The absolutely staggering collection of antiquities displayed in Cairo's Egyptian Museum makes it one of the world's great museums. You would need a lifetime to see everything on show.",city=city2, user=user1) session.add(place21) session.add(place22) session.commit() city3 = City(name="Dubai", user=user1) session.add(city3) session.commit() place3 = Place(name="Burj Khalifa", description="Dubai's landmark building is the Burj Khalifa, which at 829.8 meters is the tallest building in the world and the most famous of the city's points of interest",city=city3, user=user1) session.add(place3) session.commit() print('Finished populating the database!')
a20a7e7b8961acf833708d5dc880b933f44f30d5
doctorlove/turtles
/pso.py
2,348
3.65625
4
#See https://visualstudiomagazine.com/Articles/2013/11/01/Particle-Swarm-Optimization.aspx?Page=2 import math import random class Particle: def __init__(self, x, name): self.x = x self.best = x self.velocity = random.random() #TODO try 0 instead self.name = name self.history = [] def __str__(self): return self.name + "::" + 'x:' + str(self.x) + ', best:' + str(self.best) + ', velocity:' + str(self.velocity) def move(particles, min_x, max_x, f): for particle in particles: x = particle.x + particle.velocity if max_x < x: particle.x = max_x elif min_x > x: particle.x = min_x else: particle.x = x particle.history.append((particle.x, particle.velocity)) if f(particle.x) < f(particle.best): particle.best = particle.x def update_velocity(particles, best, w=0.1, c1=0.4, c2=0.2): for particle in particles: #r1 = 1. #r2 = 1. r1 = random.random(); r2 = random.random(); particle.velocity = w * particle.velocity + c1 * r1 * (particle.best - particle.x) + c2 * r2 * (best - particle.x) if -0.00001 < particle.velocity < 0.00001: print particle.name, "slowing down near", particle.x #raise Exception("velocity", particle.velocity) def find_best(particles, best, f): for particle in particles: if f(particle.x) < f(best): best = particle.x return best def initialise(count, min_x, max_x): particles = [] for i in range(count): x = random.uniform(min_x, max_x) particles.append(Particle(x, str(i))) return particles def swarm(count, min_x, max_x, epochs, f, w=0.1, c1=0.4, c2=0.2): print "w", w, "c1", c1, "c2", c2 particles = initialise(count, min_x, max_x) best = find_best(particles, particles[0].best, f) for _ in range(epochs): yield particles best = find_best(particles, best, f) update_velocity(particles, best, w, c1, c2) move(particles, min_x, max_x, f) print "best", best if __name__ == '__main__': f = lambda x: -x+5*math.cos(x) x_points = [x*0.1 for x in range(-62, 62)] count = 10 min_x = 0 max_x = 4 epochs = 100 gen = swarm(count, min_x, max_x, epochs, f) for particles in gen: for p in particles: print p #curr_x = particles #print "curr_x", str(curr_x) print "Final" for p in particles: print p, f(p.x)
268d4610f507daef5fe4626eebc7fb6041825dfc
emir-naiz/first_git_lesson
/Courses/1 month/3 week/day 2/Задача №4 add,remove,pop.py
493
3.9375
4
list1 = [1,2,3,4,5,6] # список def change_list(mode,number): # функция if mode == 'add': list1.append(number) elif mode == 'remove' and number in list1: list1.remove(number) elif mode == 'pop': if number > len(list1): print('Вы ввели слишком большое число') else: print('Вы ввели неверный мод!') change_list('add',7) change_list('remove',7) change_list('pop',4) print(list1)
9dda3a87af440015f9a86d401746093f5d31f2a0
tbindi/Artificial-Intelligence-a4
/Part1/binaryDT.py
18,554
3.5
4
#Disclaimer:- #I wrote this code for an assignment in another course - Applied Machine Learning. I have just reused it here by making necessary changes. #All of this code is written by me only. I am just citing myself if that's a thing. :D # Author: Mohit Galvankar # Builds decision tree and classifies input data based on the tree generated # Creates a decision tree by iterating through the features in this case all the words. Calculates infogain for each value in the columns and based on # that creates a node in the decision tree and so on and so forth. Print tree to display how new data will be classified. #Calculates the confusion matrix and accuracy. Every function is described below. from __future__ import division import math import operator import csv import random import numpy as np from collections import Counter # import arff import sys # from tabulate import tabulate class DNode: def __init__(self, feature=None, value=None,result=None,left = None,right = None): self.feature = feature self.value = value self.result = result self.left = left self.right = right #Main fucntion #Computes best information gain by iterating through all the features. Split data on the best info gain and creates tree nodes. def calculate(data,userdepth,depth,tag): label_index = getLabel() # print data #If the data is null return new node if len(data)== 0: return DNode() # check if the data has only one label class. If yes return that label class as decision tree result. if checkSame(data,label_index) == True: return DNode(result=results(data,label_index)) if depth < userdepth: bgain = 0.0 infogain = 0.0 entrootdata = entropy_main(data) bfeature = 0 bvalue = 0 # print "entropy of root data node",entrootdata #iterate through data uniquedp =[] for feature in range (0,len(data[0])-1): #find unique data points # print "feature",feature uniquedatapoints = uniquedatapoints_fn(data,feature) # print "uniquedatapoints",uniquedatapoints #split data on each unique data point for uniquedatapoint in uniquedatapoints: # print "In calculate : uniquedatapoint for loop", uniquedatapoint # print "bgain in calculate",bgain # print "bgain in calculate for feature,dtapoint", (bgain, bfeature, bvalue) # print "infogain in calculate for datapoint and feature",(infogain,uniquedatapoint,feature) infogain, dleft, dright = splitdata(entrootdata, data, feature, uniquedatapoint,tag) # if feature == bfeature and uniquedatapoint == bvalue: # # print "infogain in calculate and dleft,dright", (infogain, dleft, dright) if infogain > bgain: # print "Inside if infogain >bgain in splitdata" bfeature = feature bvalue = uniquedatapoint bgain = infogain bdleft = dleft bdright = dright # print "bfeature,bvalues in splitdata", (bfeature, bvalue) # raw_input() if bgain>0 and len(bdleft)>0 and len(bdright)>0: # print "In if bgain>0 and len(dleft)>0 or len(dright)>0 in calculate" DNleft = calculate(bdleft,userdepth,depth+1,tag) # print "DNleft" ,DNleft DNright = calculate(bdright,userdepth,depth+1,tag) return DNode(feature=bfeature,value=bvalue,left=DNleft,right=DNright) return DNode(result = results(data,label_index)) def checkSame(data,traindata_label_index): a = [] for i in data: a.append(i[traindata_label_index]) if len(set(a))<=1: return True else: return False def results(data,traindata_label_index): dict={} for row in data: dict.setdefault(row[traindata_label_index],0) dict[row[traindata_label_index]]+=1 return max(dict.iteritems(), key=operator.itemgetter(1))[0] #Calculate the unique data points in a column/feature def uniquedatapoints_fn(data,feature): a = [] #append the data points in the feature column for i in data: a.append(i[feature]) b = list(set(a)) #find list unique data points return b def getLabel(): return -1 #Calculate the distribution.how many 1's and 0's def cal_distribution(p): count_pos = 0 label_index = getLabel() for value in p: # print "value",value # raw_input() if int(value[label_index]) == 1: count_pos = count_pos + 1 return count_pos #calculate the probability def cal_probability(pos,neg): probability = 0.0 probability = pos/(pos+neg) # print "probability",probability return probability #calculate the entropy def entropy_main(p): pos = 0 neg = 0 pos = cal_distribution(p) neg = len(p) - pos # print "pos,neg distribution in entropy_main",(pos,neg) prob_pos = cal_probability(pos,neg) prob_neg = 1.0 - prob_pos if prob_pos == 1 or prob_neg == 1: return 1 # print "prob_pos,neg in main" ,prob_pos,prob_neg ent = entropy(prob_neg,prob_pos) return ent #calculate the actual entropy via formula def entropy(prob_neg,prob_pos): ent = 0.0 ent = -(prob_neg*math.log(prob_neg,2))-(prob_pos*math.log(prob_pos,2)) return ent def cal_infogain(entparentdata,eright,eleft,lendleft,lendright): infogain = entparentdata - (lendleft/(lendleft+lendright))*eleft - (lendright/(lendleft+lendright))*eright return infogain def splitdata(entrootdata,data,feature,uniquedatapoint,tag): # print "feature of split data", feature # print "Unique datapoint in splitdata",uniquedatapoint dleft =[] dright =[] for i in data: if tag == "binary": if i[feature] == uniquedatapoint: # print i[feature] dleft.append(i) else: dright.append(i) else: if i[feature] >= uniquedatapoint: # print i[feature] dleft.append(i) else: dright.append(i) # print "dleft in splitdata",dleft # print "dright in splitdata",dright if len(dright)>0: entright = entropy_main(dright) else: entright =0 if len(dleft) > 0: entleft = entropy_main(dleft) else :entleft = 0 infogain = cal_infogain(entrootdata,entright,entleft,len(dleft),len(dright)) # print "infogain in splitdata",infogain return infogain,dleft,dright # print dleft # print dright def printtree(tree,header,indent=''): col_temp = 0 feature = 0 if tree.result!=None: print "Result",str(tree.result) else: col_temp = int(tree.feature) feature = header[col_temp] print "If Feature ",str(feature)+' and Value '+str(tree.value)+" :" print(indent+'Tree left->') printtree(tree.left,header,indent + ' ') print(indent+'Tree right->') printtree(tree.right,header,indent + ' ') def classify(tree,datapoint): if(tree.result != None): return tree.result feature = tree.feature value = tree.value if(value == datapoint[feature]): label=classify(tree.left,datapoint) else:label = classify(tree.right,datapoint) return label def classify_accu(tree,tdata): count = 0 label_index = getLabel() for i in tdata: predicted = classify(tree,i) # print "predicted for",i,"is",predicted solution = i[label_index] if int(predicted) == int(solution): count = count + 1 accuracy = count/len(tdata) return accuracy def compute_confmatrix(tree,tdata): TN = 0 TP = 0 FN = 0 FP = 0 n = len(tdata) label_index = getLabel() for i in tdata: predicted = classify(tree, i) # print "predicted ",predicted solution = i[label_index] # print "actual solution",solution # raw_input() if int(predicted) == 1 and int(solution) == 1: TP = TP + 1 elif int(predicted) == 0 and int(solution)== 0: TN = TN + 1 elif int(predicted) == 0 and int(solution) == 1: FN = FN + 1 elif int(predicted) == 1 and int(solution) == 0: FP = FP + 1 confusion_matrix = [[TN,FN],[FP,TP]] print confusion_matrix error = (FN+FP)/(n) print "Error ",error print "Confusion Matrix :" for i in confusion_matrix: print i # print tabulate([['Actual : No', TN, FP], ['Actual : Yes', FN,TP]], headers=[' N : %s' %(n),'Predicted : No', 'Predicted : Yes'],tablefmt='orgtbl') def preprocess(f): datatemp = [] data = [] for i in f: i = i.rstrip('\n') i = i.lstrip(' ') datatemp.append(i.split(' ')) for i in datatemp: del i[len(i) - 1] for i in datatemp: i = map(int, i) data.append(i) return data def calculate_bootstrap_accu(b,testdata): TN = 0 TP = 0 FN = 0 FP = 0 k = [] n = len(testdata) final = [] label_index = getLabel() for j in range(0,len(b[0])): k[:] = [] for i in b: k.append(i[j]) # final.append(max(k)) most_common, num_most_common = Counter(k).most_common(1)[0] final.append(most_common) count = 0 solution1 = [] for i in testdata: # print "predicted for",i,"is",predicted solution1.append(i[label_index]) for i in range(0,len(final)): a = final[i] b = solution1[i] if int(a) == int(b): count = count + 1 if int(a) == 1 and int(b) == 1: TP = TP + 1 elif int(a) == 0 and int(b) == 0: TN = TN + 1 elif int(a) == 0 and int(b) == 1: FN = FN + 1 elif int(a) == 1 and int(b) == 0: FP = FP + 1 confusion_matrix = [[TN, FN], [FP, TP]] print "Confusion Matrix :-" for i in confusion_matrix: print i # print tabulate([['Actual : No', TN, FP], ['Actual : Yes', FN, TP]], # headers=[' N : %s' % (n), 'Predicted : No', 'Predicted : Yes'], tablefmt='orgtbl') accuracy1 = count/len(final) print "Accuracy :",accuracy1 def learn_bagged_binary(tdepth, nummbags, datapath,tag): solution =[] data_train = [] data_test = [] a = [] b= [] b[:] = [] with open("pickledata/DT_binary_5k_train.csv") as f: reader = csv.reader(f) header1 = next(reader) f.close() header = header1[1:] temptraindata = np.genfromtxt("pickledata/DT_binary_5k_train.csv", delimiter=",", skip_header=1) temptraindata = temptraindata[:,1:] traindata_label = temptraindata[:,0] traindata = np.append(temptraindata, traindata_label[:, np.newaxis], axis=1) traindata = np.array(traindata).astype(int).tolist() temptestdata = np.genfromtxt("pickledata/DT_binary_5k_test.csv", delimiter=",", skip_header=1) temptestdata = temptestdata[:,1:] testdata_label = temptestdata[:,0] testdata = np.append(temptestdata, testdata_label[:, np.newaxis], axis=1) testdata = np.array(testdata).astype(int).tolist() traindata_label_index = -1 testdata_label_index = -1 sample_size = len(traindata) bootstrapdata = [] for numbag in range(0,nummbags): tree = None a[:] = [] temp = 0 bootstrapdata[:] = [] bootstrapdata = [random.choice(traindata) for _ in range(0,sample_size)] tree = calculate(bootstrapdata,tdepth,0,tag) print "Decision Tree binary ---------------------------------------------------" printtree(tree,header) for datapoint in testdata: temp = classify(tree,datapoint) a.append(temp) # print a # print "For a %s is %s"%(numbag,a) b.append(a) # raw_input() # print "For b %s is %s" %(numbag,b) # for i in b: # print "For b",i confusion_matrix = [] # compute_confmatrix(tree, testdata) # accuracy = classify_accu(tree, testdata) # print "Accuracy : ", accuracy # print "Depth : %s | Bags : %s " %(tdepth,nummbags) print "" calculate_bootstrap_accu(b,testdata) print "------------------------------------------------------------------------" # print "/n" def learn_bagged_continous(tdepth, nummbags, datapath,tag): solution = [] data_train = [] data_test = [] a = [] b = [] b[:] = [] with open("pickledata/DT_continous_5k_train.csv") as f: reader = csv.reader(f) header1 = next(reader) f.close() header = header1[1:] temptraindata = np.genfromtxt("pickledata/DT_continous_5k_train.csv", delimiter=",", skip_header=1) temptraindata = temptraindata[:, 1:] traindata_label = temptraindata[:, 0] traindata = np.append(temptraindata, traindata_label[:, np.newaxis], axis=1) traindata = np.array(traindata).astype(int).tolist() temptestdata = np.genfromtxt("pickledata/DT_continous_5k_test.csv", delimiter=",", skip_header=1) temptestdata = temptestdata[:,1:] testdata_label = temptestdata[:, 0] testdata = np.append(temptestdata, testdata_label[:, np.newaxis], axis=1) testdata = np.array(testdata).astype(int).tolist() traindata_label_index = -1 testdata_label_index = -1 sample_size = len(traindata) bootstrapdata = [] for numbag in range(0, nummbags): tree = None a[:] = [] temp = 0 bootstrapdata[:] = [] bootstrapdata = [random.choice(traindata) for _ in range(0, sample_size)] tree = calculate(bootstrapdata, tdepth, 0,tag) print "Decision Tree continous ---------------------------------------------------" printtree(tree, header) for datapoint in testdata: temp = classify(tree, datapoint) a.append(temp) # print a # print "For a %s is %s"%(numbag,a) b.append(a) # raw_input() # print "For b %s is %s" %(numbag,b) # for i in b: # print "For b",i confusion_matrix = [] # compute_confmatrix(tree, testdata) # accuracy = classify_accu(tree, testdata) # print "Accuracy : ", accuracy # print "Depth : %s | Bags : %s " % (tdepth, nummbags) print "" calculate_bootstrap_accu(b, testdata) print "---------------------------------------------------------------------------" # print "/n" def print_tree_new_(tdepth, nummbags, mode): solution = [] data_train = [] data_test = [] a = [] b = [] b[:] = [] if mode == "continous": with open("pickledata/DT_continous_5k_train.csv") as f: reader = csv.reader(f) header1 = next(reader) f.close() header = header1[1:] temptraindata = np.genfromtxt("pickledata/DT_continous_5k_train.csv", delimiter=",", skip_header=1) temptraindata = temptraindata[:, 1:] traindata_label = temptraindata[:, 0] traindata = np.append(temptraindata, traindata_label[:, np.newaxis], axis=1) traindata = np.array(traindata).astype(int).tolist() temptestdata = np.genfromtxt("pickledata/DT_continous_5k_test.csv", delimiter=",", skip_header=1) temptestdata = temptestdata[:, 1:] testdata_label = temptestdata[:, 0] testdata = np.append(temptestdata, testdata_label[:, np.newaxis], axis=1) testdata = np.array(testdata).astype(int).tolist() sample_size = len(traindata) bootstrapdata = [] for numbag in range(0, nummbags): tree = None a[:] = [] temp = 0 bootstrapdata[:] = [] bootstrapdata = [random.choice(traindata) for _ in range(0, sample_size)] tree = calculate(bootstrapdata, tdepth, 0) print "Decision Tree continous ---------------------------------------------------" printtree(tree, header) print "---------------------------------------------------------------------------" else: with open("pickledata/DT_binary_5k_train.csv") as f: reader = csv.reader(f) header1 = next(reader) f.close() header = header1[1:] temptraindata = np.genfromtxt("pickledata/DT_binary_5k_train.csv", delimiter=",", skip_header=1) temptraindata = temptraindata[:, 1:] traindata_label = temptraindata[:, 0] traindata = np.append(temptraindata, traindata_label[:, np.newaxis], axis=1) traindata = np.array(traindata).astype(int).tolist() temptestdata = np.genfromtxt("pickledata/DT_binary_5k_test.csv", delimiter=",", skip_header=1) temptestdata = temptestdata[:, 1:] testdata_label = temptestdata[:, 0] testdata = np.append(temptestdata, testdata_label[:, np.newaxis], axis=1) testdata = np.array(testdata).astype(int).tolist() sample_size = len(traindata) bootstrapdata = [] for numbag in range(0, nummbags): tree = None a[:] = [] temp = 0 bootstrapdata[:] = [] bootstrapdata = [random.choice(traindata) for _ in range(0, sample_size)] tree = calculate(bootstrapdata, tdepth, 0) print "Decision Tree binary ------------------------------------------------------" printtree(tree, header) print "---------------------------------------------------------------------------" # if __name__ == "__main__": # tdepth = 5 # nummbags = 1 # datapath = "C:/Users/Mohit/PycharmProjects/SpamDetection/data" # learn_bagged(tdepth, nummbags, datapath)
6ff840f43f65f3e2180722f306a1991599463e88
NDCHRIS2003/python_programs
/MINOR PROJECT/comp_int_with_validation.py
1,207
4.34375
4
# Date January 2020 # A simple program to calculate the Area of a Triangle # Author = Ndubuisi Okpala import time # This will give the user the directive on how to use this program print("This program is used to calcualte compound interest") print("You will be asked to provide some parameters to be able to calcualte compound interest") time.sleep(0.5) print("Let's start: ") # ask the user the principal amount principal = int(input("What is your principal amount invested ? : ")) # ask the user the interest rate for all the years interest_rate_in_percent = float( input("What is the interest rate for year 1 (in percent) ? : "))/100 # state the initial compound interest compound_interest = 1000 # set a loop condition while (interest_rate_in_percent != 0): compound_interest = compound_interest * (1 + interest_rate_in_percent) interest_rate_in_percent = float( input("What is the interest rate for year 1 (in percent) ? : ")) / 100 average_yearly_income = (compound_interest - principal) / 3 # print the accumulated interest print(f"At the end of 3 years, your investment will be worth ${compound_interest:.2f} " f"Your average yearly income is ${average_yearly_income:.2f}")
b6c68fef11797a7e91d5abcaa13fd2c91d6496fc
Divij-berry14/Python-with-Data-Structures
/Run Length Encoding.py
218
3.703125
4
def RunLength(s): d = {} output = "" for i in s: d[i] = d.get(i, 0) + 1 for key, value in d.items(): output = output + key +str(value) return output s = input() print(RunLength(s))
d9c3eeaa7fe05426381328c31219b7b495cbdd00
enlambdment/my_pcc
/ch_8/cars.py
414
3.890625
4
def make_car(manufacturer, model_name, **car_specs): """Build a dictionary containing everything we know about a car model.""" profile = {} profile['manufacturer'] = manufacturer profile['model_name'] = model_name for key, value in car_specs.items(): profile[key] = value return profile my_car = make_car('honda', 'accord', convertible=False, seats=4, SUV=True, steering_wheel='left') print(my_car)
6341c2f69eb47a65d21b63a486075640965a6517
Reizerk-amd/Projects-of-school
/Datos.py
236
3.890625
4
#input es para guardar datos input("") #variable con input y mensaje de salida dato=input("Digite un número") #números dato = int(dato) dato + 5 print(dato) #float dato = float(input("Digite un dato ")) print(dato+5)
114c1dc40ff9ca1fe3cb9fefda2957c0d0557a3e
amat17mir/algorithms-and-theorems
/primenumberprinter.py
257
3.515625
4
n = 35 def solution(n): prime_nums = [] for num in range(n): if num > 1 for i in range(2, num) if (num % i) == 0 break else: prime_nums.append(num) return prime_nums solution(n)
8d8fee549b3b0ec66ff10edccdcd524b5342b914
HariniAS/SDET_Python
/act1.py
193
3.90625
4
name = input ("Enter your name") age = int(input("enter your age")) year = str ((2020-age) + 100) print ("you will be 100 years old in" + year) print ("you will be 100 years old in" , year)
4d69e4a54ebd2949d161ae414c91cbd8c283b306
surojitfromindia/PythonAlgos
/SortAlogoExc.py
555
4
4
def InsertSort(A): # first get a key for i in range(1, len(A)): # get first key key = A[i] # get the prior element to compare j = i - 1 # start the loop while A[j] > key and j >= 0 : # swap/ shift 1 room right A[j + 1] = A[j] # decrease j for next comparison j = j - 1 # after exiting the loop # replace the last value with key A[j + 1] = key return A sortedA = InsertSort([6, 7, 34, 2, 1, 5]) print(sortedA)
c46853b16222932c441c304c7f2ca5b29cb82118
potatoHVAC/leetcode_challenges
/algorithm/207.1_course_schedule.py
3,372
3.953125
4
# Course Schedule # https://leetcode.com/problems/course-schedule/ # Completed 4/26/19 ''' Approach 1. Create a doubly linked graph. 2. Remove leaf nodes from tree and delete their references in parent nodes. 3. Repeat 2 until tree is empty or no more leaves exist. 4. Return True if tree is empty. ''' class Node: def __init__(self, label: int): self.label = label self.prerequisites = [] self.children = [] def add_prerequisite(self, node: 'Node') -> 'self': """Add prerequisite to node.""" self.prerequisites.append(node) return self def add_child(self, node: 'Node') -> 'self': """Add child to node.""" self.children.append(node) return self def is_leaf(self) -> bool: """Return True if node is a leaf.""" return len(self.prerequisites) == 0 def remove_leaf_from_children(self) -> 'self': """Remove node references from all parent nodes.""" for child in self.children: child.prerequisites.remove(self) return self class Tree: def __init__(self, node_count: int): self.nodes = [ Node(i) for i in range(node_count) ] def add_edges(self, edges: [[int, int]]) -> 'self': """Add all node relationships defined in edges. Input: :edges: [[int, int]] -- list containint sets of integers that represent relationships between nodes """ for edge in edges: current_class = self.nodes[edge[0]] prerequisit_class = self.nodes[edge[1]] current_class.add_prerequisite(prerequisit_class) prerequisit_class.add_child(current_class) return self def remove_leaf_from_tree(self, leaf: Node) -> 'self': """Remove leaf from tree.""" self.nodes.remove(leaf) return self def prune_leaves(self) -> bool: """Find all leaves and remove them from tree. Output: True -- if leaves are removed False -- if no leaves in tree """ leaves = [ node for node in self.nodes if node.is_leaf() ] if len(leaves) == 0: return False for leaf in leaves: leaf.remove_leaf_from_children() self.remove_leaf_from_tree(leaf) return True def reduce_tree(self) -> [int]: """Remove leaves from tree until tree is empty or no more leaves exist. Output: True -- if tree is empty False -- if tree contains cycles """ while self.prune_leaves(): pass return len(self.nodes) == 0 class Solution: def canFinish(self, numCourses: int, prerequisites: [[int]]) -> bool: return Tree(numCourses).add_edges(prerequisites).reduce_tree() #------------------------------------------------------------------------------- import unittest class TestSolution(unittest.TestCase): def test_canFinish_2_pass(self): tree = Tree(2).add_edges([[0,1]]) self.assertTrue(tree.reduce_tree()) def test_canFinish_4_pass(self): tree = Tree(4).add_edges([[0,1], [0,2], [0,3]]) self.assertTrue(tree.reduce_tree()) def test_canFinish_2_fail(self): tree = Tree(2).add_edges([[0,1],[1,0]]) self.assertFalse(tree.reduce_tree()) unittest.main()
d5db3791621295e8392ae21f0e047bf60645a9d6
anasmansouri/S5_PFA_ABS
/friction_coefficient_plot.py
661
3.546875
4
import math import matplotlib.pyplot as plt A = [0.9, 0.7, 0.3, 0.1] B = [1.07, 1.07, 1.07, 1.07] C = [0.2773, 0.5, 0.1773, 0.38] D = [0.0026, 0.003, 0.006, 0.007] slip_x = [i for i in range(0, 100)] labels = ["dry concrete", "wet concrete", "snow", "ice"] friction = list() for i in range(0, len(A)): friction.append([]) for wheel_slip in slip_x: friction[i].append(A[i] * (B[i] * (1 - math.exp(-C[i] * wheel_slip)) - D[i] * wheel_slip)) for i in range(0, len(friction)): plt.plot(slip_x, friction[i], label=labels[i]) plt.xlabel('Wheel slip [%]') plt.ylabel('Friction coefficient') plt.legend(loc="upper right") plt.grid() plt.show()
06652da7d08f8b4a8db505e5e3f2a1e45c9fa6b9
kaoutarS/Easy-Graph
/easygraph/classes/directed_graph.py
23,387
3.8125
4
from copy import deepcopy class DiGraph(object): """ Base class for directed graphs. Nodes are allowed for any hashable Python objects, including int, string, dict, etc. Edges are stored as Python dict type, with optional key/value attributes. Parameters ---------- graph_attr : keywords arguments, optional (default : None) Attributes to add to graph as key=value pairs. See Also -------- Graph Examples -------- Create an empty directed graph with no nodes and edges. >>> G = eg.Graph() Create a deep copy graph *G2* from existing Graph *G1*. >>> G2 = G1.copy() Create an graph with attributes. >>> G = eg.Graph(name='Karate Club', date='2020.08.21') **Attributes:** Returns the adjacency matrix of the graph. >>> G.adj Returns all the nodes with their attributes. >>> G.nodes Returns all the edges with their attributes. >>> G.edges """ graph_attr_dict_factory = dict node_dict_factory = dict node_attr_dict_factory = dict adjlist_outer_dict_factory = dict adjlist_inner_dict_factory = dict edge_attr_dict_factory = dict def __init__(self, **graph_attr): self.graph = self.graph_attr_dict_factory() self._node = self.node_dict_factory() self._adj = self.adjlist_outer_dict_factory() self._pred = self.adjlist_outer_dict_factory() self.graph.update(graph_attr) def __iter__(self): return iter(self._node) def __len__(self): return len(self._node) def __contains__(self, node): try: return node in self._node except TypeError: return False def __getitem__(self, node): # return list(self._adj[node].keys()) return self._adj[node] @property def adj(self): return self._adj @property def nodes(self): return self._node # return [node for node in self._node] @property def edges(self): edges = list() for u in self._adj: for v in self._adj[u]: edges.append((u, v, self._adj[u][v])) return edges def out_degree(self, weight='weight'): """Returns the weighted out degree of each node. Parameters ---------- weight : string, optinal (default : 'weight') Weight key of the original weighted graph. Returns ------- out_degree : dict Each node's (key) weighted out degree (value). Notes ----- If the graph is not weighted, all the weights will be regarded as 1. See Also -------- in_degree degree Examples -------- >>> G.out_degree(weight='weight') """ degree = dict() for u, v, d in self.edges: if u in degree: degree[u] += d.get(weight, 1) else: degree[u] = d.get(weight, 1) # For isolated nodes for node in self.nodes: if node not in degree: degree[node] = 0 return degree def in_degree(self, weight='weight'): """Returns the weighted in degree of each node. Parameters ---------- weight : string, optinal (default : 'weight') Weight key of the original weighted graph. Returns ------- in_degree : dict Each node's (key) weighted in degree (value). Notes ----- If the graph is not weighted, all the weights will be regarded as 1. See Also -------- out_degree degree Examples -------- >>> G.in_degree(weight='weight') """ degree = dict() for u, v, d in self.edges: if v in degree: degree[v] += d.get(weight, 1) else: degree[v] = d.get(weight, 1) # For isolated nodes for node in self.nodes: if node not in degree: degree[node] = 0 return degree def degree(self, weight='weight'): """Returns the weighted degree of each node, i.e. sum of out/in degree. Parameters ---------- weight : string, optinal (default : 'weight') Weight key of the original weighted graph. Returns ------- degree : dict Each node's (key) weighted in degree (value). For directed graph, it returns the sum of out degree and in degree. Notes ----- If the graph is not weighted, all the weights will be regarded as 1. See also -------- out_degree in_degree Examples -------- >>> G.degree() >>> G.degree(weight='weight') or you can customize the weight key >>> G.degree(weight='weight_1') """ degree = dict() outdegree = self.out_degree(weight=weight) indegree = self.in_degree(weight=weight) for u in outdegree: degree[u] = outdegree[u] + indegree[u] return degree def size(self, weight=None): """Returns the number of edges or total of all edge weights. Parameters ----------- weight : String or None, optional The weight key. If None, it will calculate the number of edges, instead of total of all edge weights. Returns ------- size : int or float, optional (default: None) The number of edges or total of all edge weights. Examples -------- Returns the number of edges in G: >>> G.size() Returns the total of all edge weights in G: >>> G.size(weight='weight') """ s = sum(d for v, d in self.out_degree(weight=weight).items()) return int(s) if weight is None else s def neighbors(self, node): """Returns an iterator of a node's neighbors (sucessors). Parameters ---------- node : object The target node. Returns ------- neighbors : iterator An iterator of a node's neighbors (successors). Examples -------- >>> G = eg.Graph() >>> G.add_edges([(1,2), (2,3), (2,4)]) >>> for neighbor in G.neighbors(node=2): ... print(neighbor) """ # successors try: return iter(self._adj[node]) except KeyError: print("No node {}".format(node)) successors = neighbors def predecessors(self, node): """Returns an iterator of a node's neighbors (predecessors). Parameters ---------- node : object The target node. Returns ------- neighbors : iterator An iterator of a node's neighbors (predecessors). Examples -------- >>> G = eg.Graph() >>> G.add_edges([(1,2), (2,3), (2,4)]) >>> for predecessor in G.predecessors(node=2): ... print(predecessor) """ # predecessors try: return iter(self._pred[node]) except KeyError: print("No node {}".format(node)) def all_neighbors(self, node): """Returns an iterator of a node's neighbors, including both successors and predecessors. Parameters ---------- node : object The target node. Returns ------- neighbors : iterator An iterator of a node's neighbors, including both successors and predecessors. Examples -------- >>> G = eg.Graph() >>> G.add_edges([(1,2), (2,3), (2,4)]) >>> for neighbor in G.all_neighbors(node=2): ... print(neighbor) """ # union of successors and predecessors try: neighbors = list(self._adj[node]) neighbors.extend(self._pred[node]) return iter(neighbors) except KeyError: print("No node {}".format(node)) def add_node(self, node_for_adding, **node_attr): """Add one node Add one node, type of which is any hashable Python object, such as int, string, dict, or even Graph itself. You can add with node attributes using Python dict type. Parameters ---------- node_for_adding : any hashable Python object Nodes for adding. node_attr : keywords arguments, optional The node attributes. You can customize them with different key-value pairs. See Also -------- add_nodes Examples -------- >>> G.add_node('a') >>> G.add_node('hello world') >>> G.add_node('Jack', age=10) >>> G.add_node('Jack', **{ ... 'age': 10, ... 'gender': 'M' ... }) """ self._add_one_node(node_for_adding, node_attr) def add_nodes(self, nodes_for_adding: list, nodes_attr: [dict] = []): """Add nodes with a list of nodes. Parameters ---------- nodes_for_adding : list nodes_attr : list of dict The corresponding attribute for each of *nodes_for_adding*. See Also -------- add_node Examples -------- Add nodes with a list of nodes. You can add with node attributes using a list of Python dict type, each of which is the attribute of each node, respectively. >>> G.add_nodes([1, 2, 'a', 'b']) >>> G.add_nodes(range(1, 200)) >>> G.add_nodes(['Jack', 'Tom', 'Lily'], nodes_attr=[ ... { ... 'age': 10, ... 'gender': 'M' ... }, ... { ... 'age': 11, ... 'gender': 'M' ... }, ... { ... 'age': 10, ... 'gender': 'F' ... } ... ]) """ if not len(nodes_attr) == 0: # Nodes attributes included in input assert len(nodes_for_adding) == len( nodes_attr), "Nodes and Attributes lists must have same length." else: # Set empty attribute for each node nodes_attr = [dict() for i in range(len(nodes_for_adding))] for i in range(len(nodes_for_adding)): try: self._add_one_node(nodes_for_adding[i], nodes_attr[i]) except Exception as err: print(err) pass def _add_one_node(self, one_node_for_adding, node_attr: dict = {}): node = one_node_for_adding if node not in self._node: self._adj[node] = self.adjlist_inner_dict_factory() self._pred[node] = self.adjlist_inner_dict_factory() attr_dict = self._node[node] = self.node_attr_dict_factory() attr_dict.update(node_attr) else: # If already exists, there is no complain and still updating the node attribute self._node[node].update(node_attr) def add_edge(self, u_of_edge, v_of_edge, **edge_attr): """Add a directed edge. Parameters ---------- u_of_edge : object The start end of this edge v_of_edge : object The destination end of this edge edge_attr : keywords arguments, optional The attribute of the edge. Notes ----- Nodes of this edge will be automatically added to the graph, if they do not exist. See Also -------- add_edges Examples -------- >>> G.add_edge(1,2) >>> G.add_edge('Jack', 'Tom', weight=10) Add edge with attributes, edge weight, for example, >>> G.add_edge(1, 2, **{ ... 'weight': 20 ... }) """ self._add_one_edge(u_of_edge, v_of_edge, edge_attr) def add_weighted_edge(self, u_of_edge, v_of_edge, weight): self._add_one_edge(u_of_edge, v_of_edge, edge_attr={"weight": weight}) def add_edges(self, edges_for_adding, edges_attr: [dict] = []): """Add a list of edges. Parameters ---------- edges_for_adding : list of 2-element tuple The edges for adding. Each element is a (u, v) tuple, and u, v are start end and destination end, respectively. edges_attr : list of dict, optional The corresponding attributes for each edge in *edges_for_adding*. Examples -------- Add a list of edges into *G* >>> G.add_edges([ ... (1, 2), ... (3, 4), ... ('Jack', 'Tom') ... ]) Add edge with attributes, for example, edge weight, >>> G.add_edges([(1,2), (2, 3)], edges_attr=[ ... { ... 'weight': 20 ... }, ... { ... 'weight': 15 ... } ... ]) """ if not len(edges_attr) == 0: # Edges attributes included in input assert len(edges_for_adding) == len( edges_attr), "Edges and Attributes lists must have same length." else: # Set empty attribute for each edge edges_attr = [dict() for i in range(len(edges_for_adding))] for i in range(len(edges_for_adding)): try: edge = edges_for_adding[i] attr = edges_attr[i] assert len( edge) == 2, "Edge tuple {} must be 2-tuple.".format(edge) self._add_one_edge(edge[0], edge[1], attr) except Exception as err: print(err) def add_edges_from_file(self, file, weighted=False): """Added edges from file For example, txt files, Each line is in form like: a b 23.0 which denotes an edge `a → b` with weight 23.0. Parameters ---------- file : string The file path. weighted : boolean, optional (default : False) If the file consists of weight infomation, set `True`. The weight key will be set as 'weight'. Examples -------- If `./club_network.txt` is: Jack Mary 23.0 Mary Tom 15.0 Tom Ben 20.0 Then add them to *G* >>> G.add_edges_from_file(file='./club_network.txt', weighted=True) """ import re with open(file, 'r') as fp: edges = fp.readlines() if weighted: for edge in edges: edge = re.sub(',', ' ', edge) edge = edge.split() try: self.add_edge(edge[0], edge[1], weight=float(edge[2])) except: pass else: for edge in edges: edge = re.sub(',', ' ', edge) edge = edge.split() try: self.add_edge(edge[0], edge[1]) except: pass def _add_one_edge(self, u_of_edge, v_of_edge, edge_attr: dict = {}): u, v = u_of_edge, v_of_edge # add nodes if u not in self._node: self._add_one_node(u) if v not in self._node: self._add_one_node(v) # add the edge datadict = self._adj[u].get(v, self.edge_attr_dict_factory()) datadict.update(edge_attr) self._adj[u][v] = datadict self._pred[v][u] = datadict def remove_node(self, node_to_remove): """Remove one node from your graph. Parameters ---------- node_to_remove : object The node you want to remove. See Also -------- remove_nodes Examples -------- Remove node *Jack* from *G* >>> G.remove_node('Jack') """ try: succs = list(self._adj[node_to_remove]) preds = list(self._pred[node_to_remove]) del self._node[node_to_remove] except KeyError: # Node not exists in self raise KeyError("No node {} in graph.".format(node_to_remove)) for succ in succs: # Remove edges start with node_to_remove del self._pred[succ][node_to_remove] for pred in preds: # Remove edges end with node_to_remove del self._adj[pred][node_to_remove] # Remove this node del self._adj[node_to_remove] del self._pred[node_to_remove] def remove_nodes(self, nodes_to_remove: list): """Remove nodes from your graph. Parameters ---------- nodes_to_remove : list of object The list of nodes you want to remove. See Also -------- remove_node Examples -------- Remove node *[1, 2, 'a', 'b']* from *G* >>> G.remove_nodes([1, 2, 'a', 'b']) """ for node in nodes_to_remove: # If not all nodes included in graph, give up removing other nodes assert (node in self._node), "Remove Error: No node {} in graph".format( node) for node in nodes_to_remove: self.remove_node(node) def remove_edge(self, u, v): """Remove one edge from your graph. Parameters ---------- u : object The start end of the edge. v : object The destination end of the edge. See Also -------- remove_edges Examples -------- Remove edge (1,2) from *G* >>> G.remove_edge(1,2) """ try: del self._adj[u][v] del self._pred[v][u] except KeyError: raise KeyError("No edge {}-{} in graph.".format(u, v)) def remove_edges(self, edges_to_remove: [tuple]): """Remove a list of edges from your graph. Parameters ---------- edges_to_remove : list of tuple The list of edges you want to remove, Each element is (u, v) tuple, which denote the start and destination end of the edge, respectively. See Also -------- remove_edge Examples -------- Remove the edges *('Jack', 'Mary')* amd *('Mary', 'Tom')* from *G* >>> G.remove_edge([ ... ('Jack', 'Mary'), ... ('Mary', 'Tom') ... ]) """ for edge in edges_to_remove: u, v = edge[:2] self.remove_edge(u, v) def has_node(self, node): return node in self._node def has_edge(self, u, v): try: return v in self._adj[u] except KeyError: return False def number_of_nodes(self): """Returns the number of nodes. Returns ------- number_of_nodes : int The number of nodes. """ return len(self._node) def number_of_edges(self): """Returns the number of edges. Returns ------- number_of_edges : int The number of edges. """ return int(self.size()) def is_directed(self): return True def copy(self): """Return a deep copy of the graph. Returns ------- copy : easygraph.DiGraph A deep copy of the orginal graph. Examples -------- *G2* is a deep copy of *G1* >>> G2 = G1.copy() """ G = self.__class__() G.graph.update(self.graph) for node, node_attr in self._node.items(): G.add_node(node, **node_attr) for u, nbrs in self._adj.items(): for v, edge_data in nbrs.items(): G.add_edge(u, v, **edge_data) return G def nodes_subgraph(self, from_nodes: list): """Returns a subgraph of some nodes Parameters ---------- from_nodes : list of object The nodes in subgraph. Returns ------- nodes_subgraph : easygraph.Graph The subgraph consisting of *from_nodes*. Examples -------- >>> G = eg.Graph() >>> G.add_edges([(1,2), (2,3), (2,4), (4,5)]) >>> G_sub = G.nodes_subgraph(from_nodes= [1,2,3]) """ G = self.__class__() G.graph.update(self.graph) for node in from_nodes: try: G.add_node(node, **self._node[node]) except KeyError: pass # Edge from_nodes = set(from_nodes) for v, edge_data in self._adj[node].items(): if v in from_nodes: G.add_edge(node, v, **edge_data) return G def ego_subgraph(self, center): """Returns an ego network graph of a node. Parameters ---------- center : object The center node of the ego network graph Returns ------- ego_subgraph : easygraph.Graph The ego network graph of *center*. Examples -------- >>> G = eg.Graph() >>> G.add_edges([ ... ('Jack', 'Maria'), ... ('Maria', 'Andy'), ... ('Jack', 'Tom') ... ]) >>> G.ego_subgraph(center='Jack') """ neighbors_of_center = list(self.all_neighbors(center)) neighbors_of_center.append(center) return self.nodes_subgraph(from_nodes=neighbors_of_center) def to_index_node_graph(self, begin_index=0): """Returns a deep copy of graph, with each node switched to its index. Considering that the nodes of your graph may be any possible hashable Python object, you can get an isomorphic graph of the original one, with each node switched to its index. Parameters ---------- begin_index : int The begin index of the index graph. Returns ------- G : easygraph.Graph Deep copy of graph, with each node switched to its index. index_of_node : dict Index of node node_of_index : dict Node of index Examples -------- The following method returns this isomorphic graph and index-to-node dictionary as well as node-to-index dictionary. >>> G = eg.Graph() >>> G.add_edges([ ... ('Jack', 'Maria'), ... ('Maria', 'Andy'), ... ('Jack', 'Tom') ... ]) >>> G_index_graph, index_of_node, node_of_index = G.to_index_node_graph() """ G = self.__class__() G.graph.update(self.graph) index_of_node = dict() node_of_index = dict() for index, (node, node_attr) in enumerate(self._node.items()): G.add_node(index + begin_index, **node_attr) index_of_node[node] = index + begin_index node_of_index[index + begin_index] = node for u, nbrs in self._adj.items(): for v, edge_data in nbrs.items(): G.add_edge(index_of_node[u], index_of_node[v], **edge_data) return G, index_of_node, node_of_index
f506c682d4480074859dff93c41dcc0800db7cee
Sun-Zhen/leetcode
/0801-0850/0819-MostCommonWord/MostCommonWord.py
1,106
3.859375
4
# -*- coding:utf-8 -*- """ @author: Alden @email: sunzhenhy@gmail.com @date: 2018/4/16 @version: 1.0.0.0 """ class Solution(object): def mostCommonWord(self, paragraph, banned): """ :type paragraph: str :type banned: List[str] :rtype: str """ word_dict = dict() punctuations = ["!", "?", "'", ",", ";", "."] temp_word = "" for v in paragraph: if v in punctuations: continue if v == " ": if temp_word != "" and temp_word not in banned: word_dict[temp_word] = word_dict.get(temp_word, 0) + 1 temp_word = "" else: temp_word += v.lower() if temp_word != "" and temp_word not in banned: word_dict[temp_word] = word_dict.get(temp_word, 0) + 1 return sorted(word_dict.items(), key=lambda x: x[1], reverse=True)[0][0] if __name__ == "__main__": s = Solution() # print s.mostCommonWord("Bob hit a ball, the hit BALL flew far after it was hit.", ["hit"]) print s.mostCommonWord("a.", [])
96753e879f1a94f6b1fefd2d0664da87ef294488
kostas-simi/first_python
/register and login_1.py
2,948
3.703125
4
import sqlite3 from datetime import datetime,date conn = sqlite3.connect('data/Containers.db') c = conn.cursor() def countContainers(x,y): z = x - y if z>=0 and z<=170: return True return False boxesOut = 0 dataIn = list() dataOut = list() while True: choice = input('Do you want to: Register(R/r) or Login(L/l)? ') if choice == 'R' or choice == 'r' : newUser = input('Please choose a username: ') newPassword = input('Please choose a password: ') c.execute (''' INSERT INTO USERS (USERNAME,PASSWORD) VALUES(?,?)''',(newUser,newPassword) ) conn.commit() print('Regitration successful','username: ',newUser,' password: ',newPassword) break elif choice == 'L' or choice == 'l' : Tries = 0 while Tries < 3: username = input('Give me username: ') psw = input('Give me your password: ') c.execute('''SELECT PASSWORD FROM USERS WHERE USERNAME = ? ''',(username,) ) usr = c.fetchone() if usr[0] == psw : print('Welcome, ',username) while True: boxesIn = input('Give the number of containers that entered the warehouse. ') boxesOut = input('Give the number of containers that exited the warehouse. ') boxesIn = int(boxesIn) boxesOut = int(boxesOut) #boxesLeft = boxesIn - boxesOut #if boxesLeft >=0 and boxesLeft <=170: if countContainers(boxesIn,boxesOut): dataIn.append(boxesIn) dataOut.append(boxesOut) c.execute(''' SELECT MAX(DAYNO) FROM CONTAINERS''') DayNo = c.fetchone() if DayNo[0] is None : DayNo = 1 else : DayNo = int(DayNo[0]) + 1 #print (DayNo) c.execute (''' INSERT INTO CONTAINERS (DAYNO,CONTAINERSIN,CONTAINERSOUT,RECORDTIME) VALUES(?,?,?,?)''', (DayNo,boxesIn,boxesOut,datetime.now()) ) conn.commit() else: continue Controler = input('End of Data Entry Yes(Y/y)/No: ') if Controler == 'Y' or Controler == 'y': break print(dataIn) print(dataOut) else: Tries = Tries + 1 print('Wrong combination of username and password') print('Left Tries: ', 3 - Tries) continue else: print('Wrong value, please choose again: ') continue
2bf344be10a708546dbf10334b5b7b7ed97cfed0
Bukacha88/softuni_python_advanced
/tuples_and_sets/04_count_symbols.py
221
3.71875
4
text = tuple(map(str, input())) occur = {} for char in text: if char not in occur: occur[char] = 0 occur[char] += 1 for key, values in sorted(occur.items()): print(f"{key}: {values} time/s")
2618281e85e663127c457e2aead0c0189119c570
MihailFrolov/Programlama_I
/13 Mart 2018/Ödev3.py
1,874
3.59375
4
#ilk6= İlk 6 ay dönemi #yg= Yazılım gelirleri #fg= Finansman gelirleri #usg= Ürün satış gelirleri #cm= Çalışan masrafları #kg= Kira giderleri #dm= Donanım maliyeti #son6= Son 6 ay dönemi #yillikkar= Yıllık kar #kar_ilk6= İlk 6 ayın karlılığı #kar_son6= Son 6 ayın karlılığı def ilk6(yg,fg,usg,cm,kg,dm): gelir_ilk6=yg+fg+usg gider_ilk6=cm+kg+dm global kar_ilk6 kar_ilk6= gelir_ilk6 - gider_ilk6 return kar_ilk6 a = int(input("İlk 6 ayın yazılım gelirinizi giriniz:")) b = int(input("İlk 6 ayın finansman gelirinizi giriniz:")) c = int(input("İlk 6 ayın ürün satış gelirini giriniz:")) d = int(input("İlk 6 ayın çalışan maaşlarını giriniz:")) e = int(input("İlk 6 ayın kira giderlerini giriniz:")) f = int(input("İlk 6 ayın donanım Maliyetini giriniz:")) g=ilk6(a,b,c,d,e,f) print("İlk 6 ayın karlılık sonucu:",kar_ilk6) def son6(yg,fg,usg,cm,kg,dm): gelir_son6=yg+fg+usg gider_son6=cm+kg+dm global kar_son6 kar_son6= gelir_son6 - gider_son6 return kar_son6 z = int(input("son 6 ayın yazılım gelirinizi giriniz:")) x = int(input("son 6 ayın finansman gelirinizi giriniz:")) l = int(input("son 6 ayın ürün satış gelirini giriniz:")) v = int(input("son 6 ayın çalışan maaşlarını giriniz:")) b = int(input("son 6 ayın kira giderlerini giriniz:")) n = int(input("son 6 ayın donanım Maliyetini giriniz:")) m=son6(z,x,l,v,b,n) print("son 6 ayın karlılık sonucu:",kar_son6) yillikkar=kar_ilk6+kar_son6 if(yillikkar>=5000): print("İşletme çok karlıdır. Yıllık karınız:",yillikkar,"TL'dir") elif(yillikkar>=1000 and genelkar<5000): print("İşletme karı normaldir. Yıllık karınız:",yillikkar,"TL'dir") else: print("İşletme yeterince karda değildir. Yıllık karınız:",yillikkar,"TL'dir")
8c4ca0eeb70386827165b124405a1bf4299951fd
dipika-d/Pythonic
/Data-Structures/sorting_with_heapq.py
833
4.125
4
import heapq nums = [-1,2,-3,4,-5,6,-7,8,-9,10] # convert the list into heap heap = list(nums) heapq.heapify(heap) # heap[0] will always be the smallest number in a heap # heap[-1] therefore will be the largest number print(heap) print('*'*20) print("Smallest in heap = ",heap[0]) print('*'*20) print("Largest in heap = ",heap[-1]) # to pop the smallest item and replace it with the next smallest # this happens in O(log N) where N is the size of the heap print(heap) print('*'*20) print("Smallest = ",heapq.heappop(heap)) print('*'*20) print("Next smallest = ",heapq.heappop(heap)) print('*'*20) # printing the numbers from smallest to largest print("Printing from smallest to largest \n") heap = list(nums) heapq.heapify(heap) for i in range(len(heap)): try: print(heapq.heappop(heap)) except KeyboardInterrupt: break
a1a980869143f0fc8eccd7a65ab68444974cba2d
claudiodornelles/CursoEmVideo-Python
/Exercicios/ex089 - Boletim com listas compostas.py
1,517
3.6875
4
""" Crie um programa que leia nome e duas notas de vários alunos e guarde tudo em uma lista composta. No final, mostre um boletim contendo a média de cada aluno e permita que o usuário possa mostrar as notas de cada aluno individualmente. """ notas = [] aluno = [] alunos = [] soma = n_notas = 0 while True: nome = str(input('Nome: ')) aluno.append(nome) n1 = float(input('Nota 1: ')) notas.append(n1) n2 = float(input('Nota 2: ')) notas.append(n2) aluno.append(notas[:]) alunos.append(aluno[:]) notas.clear() aluno.clear() while True: resp = str(input('Quer continuar? [S/N] ')) if resp in 'SsNn': break print('Não entendi... ', end='') if resp in 'Nn': break print('\n-'*30) print(f'Nº\tNome\t\tMédia') print('-'*30) for n, aluno in enumerate(alunos): for nota in aluno[1]: soma += nota n_notas += 1 media = soma / n_notas print(f'{n}\t{aluno[0]}\t\t{media:.1f}') soma = 0 n_notas = 0 print('-'*30) while True: try: resp = int(input('\nDeseja mostrar a nota de qual aluno? (999 interrompe) ')) except: print('Não entendi... ', end='') continue if resp == 999: print('Finalizando...\n<<< VOLTE SEMPRE >>>\n') break elif resp in range(0,len(alunos)): print(f'As notas de {alunos[resp][0]} foram {alunos[resp][1]}') print('-'*30) else: print('Aluno não cadastrado... ', end='')
bd54e1d915c6072465e615aa6e8df7d03819e423
Pranav016/DS-Algo-in-Python
/Stack/BalancedParanthesis.py
608
3.921875
4
def balanced(s): stack=[] for char in s: if char in '{([': stack.append(char) elif char==')': if not stack or stack[-1]!='(': return False stack.pop() elif char==']': if not stack or stack[-1]!='[': return False stack.pop() elif char=='}': if not stack or stack[-1]!='{': return False stack.pop() if not stack: return True return False # main s=str(input()) if balanced(s): print("true") else: print("false")
9761d3da5f4327961448c912e3d37fae3d7aace7
usufruct/knight-rider
/tests/unittests/chess/board_test.py
4,074
3.8125
4
import unittest import math from chess import Board class TestBoard(unittest.TestCase): def test_example(self): self.assertTrue(True) def test_init(self): board = Board() actual = [x.distance for x in board.squares] expected = [math.inf for x in range(64)] expected[0] = 0 self.assertEqual(actual, expected) def test_in_bounds_good(self): board = Board() actual = board.in_bounds([[1, 2]]) expected = [[1, 2]] self.assertEqual(actual, expected) def test_infinite_positions_yes(self): board = Board() actual = board.infinite_positions([[1, 2]]) expected = [[1, 2]] self.assertEqual(actual, expected) def test_in_bounds_bad_first(self): board = Board() actual = board.in_bounds([[-1, 2]]) expected = [] self.assertEqual(actual, expected) def test_in_bounds_bad_second(self): board = Board() actual = board.in_bounds([[1, -2]]) expected = [] self.assertEqual(actual, expected) def test_square_at_position_zero(self): board = Board() actual = board.square_at_position([0,0]) expected = board.squares[0] self.assertEqual(actual, expected) def test_square_at_position_42(self): board = Board() actual = board.square_at_position([2,5]) expected = board.squares[42] self.assertEqual(actual, expected) def test_index_to_position_zero(self): board = Board() actual = board.index_to_position(0) expected = [0, 0] self.assertEqual(actual, expected) def test_index_to_position_42(self): board = Board() actual = board.index_to_position(42) expected = [2, 5] self.assertEqual(actual, expected) def test_incomplete_true(self): board = Board() self.assertTrue(board.incomplete()) def test_incomplete_false(self): board = Board() for i in range(64): board.squares[i].distance = 666 self.assertFalse(board.incomplete()) def test_biggest_measured_distance_zero(self): board = Board() actual = board.biggest_measured_distance() expected = board.squares[0].distance self.assertEqual(actual, expected) def test_biggest_measured_distance_amount(self): board = Board() board.squares[6].distance = 100 actual = board.biggest_measured_distance() expected = 100 self.assertEqual(actual, expected) def test_positions_matching_distance(self): board = Board() board.squares[7].distance = 42 board.squares[15].distance = 42 actual = board.positions_matching_distance(42) expected = [[7, 0], [7, 1]] self.assertEqual(actual, expected) def test_print(self): board = Board() self.maxDiff = None actual = str(board) expected = (" \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " 0 \n") self.assertEqual(actual, expected)
8bfdbde94ed88f87b3abf8b59f8b2a0d9f280756
v-shchenyatskiy/GB_Python
/1. Lesson_1/les01_2.py
1,084
4.0625
4
# Пользователь вводит время в секундах. # Переведите время в часы, минуты и секунды # Выведите в формате чч:мм:сс. Используйте форматирование строк. # 1 s * 60 = 1 m * 60 = 1h = 3600 s # 1h * 24 = 1d = 86400 s user_sec = int(input('Введите время в секундах: ')) # 1 - считаем часы days = 0 hours = user_sec // 3600 if hours > 24: days = hours // 24 hours = hours % 24 if (days // 10) < 1: days = f'0{days}' if (hours // 10) < 1: hours = f'0{hours}' # 2 - считаем минуты minutes = (user_sec % 3600) // 60 if (minutes // 10) < 1: minutes = f'0{minutes}' # 3 - считаем секунды seconds = user_sec % 3600 % 60 if (seconds // 10) < 1: seconds = f'0{seconds}' # 4 - Выводим результат print( f'Вы ввели -> {user_sec}.\n' f'Это -> {days} {hours}:{minutes}:{seconds} (в формате DD hh:mm:ss)' )
fa93578fa64ad4b0151443ef9dbe7b417e1a33e0
JBustos22/Physics-and-Mathematical-Programs
/differential equations/Lorenz.py
1,496
4.25
4
#! /usr/bin/env python """ This program uses the Runge-Kutta method to solve the Lorenz equations. The Lorenz equations model seemingly chaotic weather phenomena. Using the 4th order Runge-Kutta method, the three equations are solved and a plot of y vs t and x vs z is created. The first plot shows the chaotic nature of the motion, and the second shows the famous "Strange Attractor". Jorge Bustos April 12, 2019 """ from __future__ import division, print_function import numpy as np import matplotlib.pyplot as plt def runge_kutta4(f, r, t, h): #Runge Kutta Definition """ 4th order Runge-Kutta method for ODEs """ k1 = h*f(r,t) k2 = h*f(r+0.5*k1,t+0.5*h) k3 = h*f(r+0.5*k2,t+0.5*h) k4 = h*f(r+k3,t+h) return (k1 + 2*k2 + 2*k3 + k4)/6 def lorenz(r,t): #Definition of 3 ODES sigma, r_const, b = 10.0, 28.0, 8/3 #setting constants x,y,z = r[0],r[1],r[2] return np.array([sigma*(y-x), (r_const*x)-y-(x*z), (x*y)-(b*z)],float) nSteps = 1000 tMin,tMax = 0.0,50.0 tStep = (tMax-tMin)/nSteps tPoints = np.arange(tMin, tMax, tStep) #Initial conditions xPoints,yPoints,zPoints = [],[],[] x0,v0,z0 = 0.0,1.0,0.0 r = np.array([x0,v0,z0], float) for t in tPoints: xPoints += [r[0]] yPoints += [r[1]] zPoints += [r[2]] r += runge_kutta4(lorenz,r,t,tStep) plt.plot(tPoints,yPoints) plt.xlabel("time") plt.ylabel("y") plt.title("y component of Lorenz equation vs. time") plt.show() plt.plot(xPoints,zPoints) plt.xlabel("x") plt.ylabel("z") plt.title("The Strange Attractor") plt.show()
354d9f616446ceaf37dc39f45606d57417081bbf
Ambotega/CPT-Questions
/guess_the_number.py
533
4.15625
4
#!usr/bin/python ''' A very simple guess the number program ''' from random import randint random_number = randint(1,10) print("I have a number, its between 1 and 10, Can you guess the number?") while True: your_guess = input("Enter Guess: ") try: your_guess = int(your_guess) break except: print("Invalid, enter a number") continue if random_number == your_guess: print("CORRECT, well done") else: print("Not quite there, Try again")
ce5457678e0742d76a9e7935a257cd1af6e05617
RobertElias/PythonProjects
/GroceryList/main.py
1,980
4.375
4
#Grocery List App import datetime #create date time object and store current date/time time = datetime.datetime.now() month = str(time.month) day = str(time.day) hour = str(time.hour) minute = str(time.minute) foods = ["Meat", "Cheese"] print("Welcome to the Grocery List App.") print("Current Date and Time: " + month + "/" + day + "\t" + hour + ":" + minute) print("You currently have " + foods[0] + " and " + foods[1] + " in your list.") #Get user input food = input("\nType of food to add to grocery list: ") foods.append(food.title()) food = input("\nType of food to add to grocery list: ") foods.append(food.title()) food = input("\nType of food to add to grocery list: ") foods.append(food.title()) #Print and sort the list print("Here is your grocery list: ") print(foods) foods.sort() print("Here is you grocery list sorted: ") print(foods) #Shopping for your list print("\nSimulating Grocery Shopping...") print("\nCurrent grocery list: " + str(len(foods)) + " items") print(foods) buy_food = input("What food did you just buy: ").title() foods.remove(buy_food) print("Removing " + buy_food + " from the list...") print("\nSimulating Grocery Shopping...") print("\nCurrent grocery list: " + str(len(foods)) + " items") print(foods) buy_food = input("What food did you just buy: ").title() foods.remove(buy_food) print("Removing " + buy_food + " from the list...") print("\nSimulating Grocery Shopping...") print("\nCurrent grocery list: " + str(len(foods)) + " items") print(foods) buy_food = input("What food did you just buy: ").title() foods.remove(buy_food) print("Removing " + buy_food + " from the list...") #The store is out of this item print("\nCurrent grocery list: " + str(len(foods)) + " items") print(foods) no_item = foods.pop() print("\nSorry, the store is out of " + no_item + ".") new_food = input("What food would you like instead: ").title() food.insert(0,new_food) print("\nHere is what remains on your grocery list: ") print(foods) #New food
dcf0cfac745c49c289caab2daf993f63d297b42f
ayushchopra96/hangman
/hangman_soln.py
2,329
4.25
4
from string import * from hangman_lib import * ## Constants MAX_MISTAKES = 6 #state variables secret_word = get_random_word() letters_guessed = [] mistakes_made = 0 ##helper function... def word_guessed(): '''Returns True iff player has successfully guessed the word''' for letter in secret_word: if letter not in letters_guessed: return False return True def print_guessed(): list_of_letters = [] for letter in secret_word: if letter in letters_guessed: list_of_letters.append(letter) else: list_of_letters.append('-') return join(list_of_letters, '') ##main game code print "Welcome To Hangman" first_time = lower(raw_input("Is this your first time playing Hangman? (y/n)")) if first_time=="y": print "The objective of Hangman is to guess a secret word letter by letter." print "If you guess a letter in the word, we'll show you that letter." print "But if you guess wrong, we'll draw part of the hangman's body." print "Don't let his whole body get drawn, or else you lose!" print "Great, so you're ready to play. Just two things that might help:" print "1) The secret word has", len(secret_word), "letters." print "2) It takes", MAX_MISTAKES, "wrong guesses to lose." print print "Good luck!" print print "[Press enter when ready to play.]" raw_input() # this just waits for them to press enter... they can type # other stuff but it doesn't affect anything. print_hangman_image(0) while mistakes_made<MAX_MISTAKES: print "The word so far: ", print_guessed() print "Letters guessed so far:", for letter in letters_guessed: print letter, print "Wrong guesses remaining:", MAX_MISTAKES-mistakes_made guess = lower(raw_input("What letter will you guess")) if guess == "": print "You have to guess something" elif len(guess)>1: print "you can guess only one letter at a time." elif guess in letters_guessed: print "you have already guessed this!" else: letters_guessed.append(guess) if guess in secret_word: print "Good Guess" if word_guessed(): print "You Done. Good Job" break else: mistakes_made = mistakes_made+1 print "Sorry No luck" print_hangman_image(mistakes_made) if mistakes_made>=MAX_MISTAKES: print "On No, You Lose" print "GAME OVER" else: print "Congrats" print "The word was: ",secret_word
094d004d2c60cb5452cab57911a7d88fe4037513
InVinCiblezz/algorithm-in-python3
/divide_conquer/merge_sort.py
506
4.03125
4
#!/usr/bin/env python3 data = [2, 5, 8, 1, 23, 21, 14, 22, 9, 7] def merge(lo, hi): res = [] while lo and hi: if lo[0] < hi[0]: res.append(lo.pop(0)) else: res.append(hi.pop(0)) res = res + lo + hi return res def mergeSort(data): length = len(data) if length < 2: return data mid = int(length >> 1) lo = mergeSort(data[:mid]) # low hi = mergeSort(data[mid:]) # high return merge(lo, hi) print(mergeSort(data))
1ed70a531b478790b747bb2d3eb271013becddec
edwardmasih/Python-School-Level
/Class 12/12th - Project/Programs/18 largest no in matrix.py
733
4.0625
4
def locatelargest(a): l=[] for i in range(n): for j in range (x): l.append(a[i][j]) m=max(l) print "Largest No. :- ",m for i in range (n): for j in range (x): if a[i][j]==m: print "Largest Number Found! " print "at row",i+1,"&","column",j+1 n=int(input("Enter no. of Rows :-")) x=int(input("Enter no. of Columns :-")) a=[[i for i in range (n*x)] for j in range (n*x)] print "Enter Values One By One ;- " for i in range (n): for j in range (x): a[i][j]=int(input()) print print "Your Matrix is - " for i in range (n): for j in range (x): print ha[i][j],'\t', print locatelargest(a)
d07176ef66b7c3d4bcd13ee3be09742fbde29d20
mredig/Algorithms
/stock_prices/stock_prices.py
1,201
4.15625
4
#!/usr/bin/python import argparse def find_max_profit(prices): if len(prices) < 2: return 0 # set initial lowest and maxProfit values from actual array values lowest = prices[0] maxProfit = prices[1] - prices[0] # for each item in prices for index in range(1, len(prices)): price = prices[index] # each new item, calculate the difference from the current item and the lowest previous price profitFromTrade = price - lowest # track the lowest price lowest = min(lowest, price) # save the maximum, positive difference maxProfit = max(profitFromTrade, maxProfit) # return maximum when finished return maxProfit if __name__ == '__main__': # This is just some code to accept inputs from the command line parser = argparse.ArgumentParser( description='Find max profit from prices.') parser.add_argument('integers', metavar='N', type=int, nargs='+', help='an integer price') args = parser.parse_args() print("A profit of ${profit} can be made from the stock prices {prices}.".format( profit=find_max_profit(args.integers), prices=args.integers))
86ae6950b1af23548c5c205f44a235357faf3361
HanchengZhao/Leetcode-exercise
/819. Most Common Word/mostCommonWord.py
689
3.578125
4
class Solution: def mostCommonWord(self, paragraph: str, banned: List[str]) -> str: paragraph = paragraph.lower() dic = {} word = "" most, freq = "", 0 for i in paragraph: if i.isalpha(): word += i else: if word and word not in banned: dic[word] = dic.setdefault(word, 0) + 1 if dic[word] > freq: most, freq = word, dic[word] word = "" if word and word not in banned: dic[word] = dic.setdefault(word, 0) + 1 if dic[word] > freq: most = word return most
9dceafbc77f1afac20a362947143528b2f711cf7
mrpandrr/My_scripts
/untitled folder/a116_buggy_image_step_31_AH.py
1,266
3.640625
4
# a116_buggy_image.py import turtle as trtl #Create a spider body spider = trtl.Turtle() #Create turtle object spider.pensize(40) # pen size 40 spider.circle(20) # pen circle #Create a spider head spider.goto(-30,9) spider.circle(2.5) spider.goto(0,0) #Configure spider legs legs = 8 length = 34 angle = 120 / legs spider.pensize(5) # pen size count = 0 #Draw Legs while (count < legs): spider.color("blue") spider.goto(0,20) spider.setheading(angle*count) spider.pendown() spider.circle(length,120) spider.penup() count = count + 1 print("angle*count=", angle*count) count=0 while (count < legs): spider.color("red") spider.goto(0,20) spider.setheading((angle*count)+310) spider.pendown() spider.circle(-length,120) spider.penup() count = count + 1 print("angle*count=", angle*count) eyesize = 1 #Spider Eyes spider.color("Pink") spider.penup() spider.goto(-36,18) spider.pendown() spider.circle(eyesize) spider.penup() spider.goto(-35,2) spider.pendown() spider.circle(eyesize) spider.hideturtle() spider.penup() #hide middle from leg spider.goto(0,20) spider.pendown() spider.color('black') spider.pensize(36) # pen size 40 spider.circle(10) # pen circle wn = trtl.Screen() wn.mainloop()
3c83dee3aaf6eb7cffc040e715ae042a2cfa633e
ccirelli2/asyncio
/asyncio_/asyncio_notes.py
1,613
4.21875
4
# LEARN ASYNCIO ''' Coroutines: Coroutines look like a normal function, but in their behaviour they are stateful objects with resume() and pause() —  like methods. Pause: The way a coroutine pauses itself is by using the 'await' keyword. When you 'await' another coroutine, you 'step off' the event loop and schedule the awaited coroutine to run immediately. Application: it could be anything in a real world scenario like a network request, db query etc. aiohttp apparently is a library specifically for http requests defining rather than def something, you async def something, which notifies that you want to coroutine something. ''' import asyncio import timeit # We need to insert functions into that loop # loop.create_task(function_here) async def counter2(num_start, num_end): list_num = [] start = timeit.timeit() for i in range(num_start, num_end): if i == 5000: print('equals 5000') await asyncio.sleep(0.0001) list_num.append(i) pass else: pass end = timeit.timeit() start = round(start, 6) end = round(end, 6) print('Start => {} End => {}'.format(start, end)) return None async def main2(): test1 = loop.create_task(counter2(0,100000000)) test2 = loop.create_task(counter2(0,1000000)) test3 = loop.create_task(counter2(0,10000)) await asyncio.wait([test1, test2, test3]) if __name__ == "__main2__": loop = asyncio.get_event_loop() # establish loop loop.run_until_complete(main2()) loop.close() # always want to close loop counter2(0,10000)
357d432d04462c6c01fcd6d6e6199cf019300245
sabariks/pythonpgm
/stringsubstring.py
170
3.875
4
a=input() b=input() if a not in b: print(-1) else: print(1) # a,b=map(str,input().split()) # if a in b: # print('No') # else: # print('Yes')
c7bdc7fedaa1abd510616e50a8d9a417fb3acbdf
Pinacolada64/TADA
/server/convert_food_data.py
5,394
3.515625
4
#!/bin/env python3 import json from dataclasses import dataclass import logging @dataclass class Rations(object): number: int name: str kind: str # magical, standard, cursed price: int flags: list def __str__(self): return f'#{self.number} {self.name}' def read_stanza(filename): """ Read block of data [3 lines] from file skipping '#'-style comments; `^` is stanza delimiter :return: data[], the info from the file """ count = 0 line = [] while count < 3: # 'diskin()' discards '#'-style comments temp = diskin(filename) if temp != "^": line.append(temp) count += 1 logging.info("Stanza:") count = 0 for n in line: logging.info(f'{count=} {n=}') count += 1 return line def diskin(filename): # get a line of data from disk file, discarding '#'-style comments while True: data = filename.readline().strip('\n') if data.startswith("#") is False: logging.info(f'keep {data=}') return data else: logging.info(f'toss {data=}') def convert(txt_filename, ration_json_filename): write = True ration_kind = {"F.": "food", "D.": "drink", "C.": "cursed"} ration_flags = {"x": "future expansion"} with open(txt_filename) as file: debug = False ration_list = [] # get ration count: # enter a state where it's only looking for an integer value [ration count] num_rations = 999 # some unrealistic number to serve as a flag while num_rations == 999: # discard '#'-style comments: data = diskin(file) if debug: print(f'{data=}') break # hoping for an integer here: num_rations = int(data) if debug: print(f'{num_rations=}') # I eliminated "^" record separators in this file # _ = diskin(file) count = 0 """ sample data: TODO: finish this """ # capture ration names, then convert to lowercase with .lower(): while count < num_rations: count += 1 data = read_stanza(file) # 1=active: status = int(data[0]) # info: ration kind, name, flags info = data[1] # kind = "F."ood / "D."rink / "C."ursed kind = ration_kind[info[:2]] flag = info.rfind("|") start_name = 2 if flag == -1: # not found flag_list = None name = info[start_name:] logging.info("(No flags)") else: # '|' in ration name. it has ration flags: # trim name to before '|': # can also do: ration[start_name:ration.find('|')].rstrip() name = info[start_name:flag].rstrip() # clear per-ration flag list: flag_list = [] # parse all the flags after the | symbol, # add their English keywords to flag_list logging.info(f'Flags: {info[flag + 1:]}') for k, v in ration_flags.items(): if k in info[flag + 1:]: logging.info(f'with flag: {k=} {v=}') flag_list.append(v) price = int(data[2]) # toss "^" data block separator: # _ = diskin(file) print(f"""Parsed input:\n {count=} {name=} {kind=} {price=} {flag_list=} """) # TODO: maybe descriptions later """ descLines = [] moreLines = True while moreLines: line = diskin(file) if line != "^": descLines.append(line) else: moreLines = False ration_data['desc'] = " ".join(descLines) """ ration_data = {"number": count, 'name': name, 'kind': kind, # food / drink/ cursed "price": price, 'flags': flag_list } if debug: name = ration_data['name'] kind = ration_data['kind'] try: flags = ration_data['flags'] except ValueError: flags = '(None)' logging.info(f'{count=} {name=} {kind=} {flags=}') # add based on dataclass: ration = Rations(**ration_data) logging.info(f"*** processed ration '{ration_data['name']}'") ration_list.append(ration) if debug: # if count % 20 == 0: _ = input("Hit Return: ") if write is True: with open(ration_json_filename, 'w') as ration_json: json.dump(ration_list, ration_json, default=lambda o: {k: v for k, v in o.__dict__.items() if v}, indent=4) logging.info(f"wrote '{ration_json_filename}'") if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG, format='[%(levelname)s] | %(message)s') logging.info("Logging is running") convert('rations.txt', 'rations.json')
757c592d9cb0b99d7229449374ebae18ffbb3e99
subenakhatun/python-task-03
/problem-09.py
238
4.0625
4
''' Write a function that computes the running total of a list. ''' number = int(input('Enter a running number range: ')) def sum(number): sum = 0 for i in number: sum = sum + i print(sum) sum(range(number))
e3cba78810f2d8d65f6e1c9c8233c103d16ac974
DmitryPukhov/pyquiz
/test/leetcode/test_DiameterOfBinaryTree.py
1,144
3.59375
4
from unittest import TestCase from pyquiz.common.TreeNode import TreeNode from pyquiz.leetcode.DiameterOfBinaryTree import DiameterOfBinaryTree class TestDiameterOfBinaryTree(TestCase): def test_diameter_of_binary_tree_12345(self): #[4,-7,-3,null,null,-9,-3,9,-7,-4,null,6,null,-6,-6,null,null,0,6,5,null,9,null,null,-1,-4,null,null,null,-2] root = TreeNode(1, TreeNode(2, TreeNode(4), TreeNode(5)), TreeNode(3)) self.assertEqual(3, DiameterOfBinaryTree().diameterOfBinaryTree(root)) def test_diameter_of_binary_tree_1(self): root = TreeNode(1) d = DiameterOfBinaryTree().diameterOfBinaryTree(root) self.assertEqual(0, d) def test_diameter_of_binary_tree_12(self): root = TreeNode(1, TreeNode(2)) self.assertEqual(1, DiameterOfBinaryTree().diameterOfBinaryTree(root)) def test_diameter_of_binary_tree_123(self): root = TreeNode(1, TreeNode(2), TreeNode(3)) self.assertEqual(2, DiameterOfBinaryTree().diameterOfBinaryTree(root))
834f037ef439654ad22363559557fb118a6ff721
parkermac/ptools
/pm_dev/sphere_light.py
2,010
3.578125
4
# -*- coding: utf-8 -*- """ Plotting a 3D sphere with lighting """ import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D def get_xyz_mesh(lon, lat, r): # makes a Cartesian mesh on a sphere # lon, lat are numpy vectors # r is a scalar (the radius) x = r * np.outer(np.cos(lon), np.cos(lat)) y = r * np.outer(np.sin(lon), np.cos(lat)) z = r * np.outer(np.ones(np.size(lon)), np.sin(lat)) return x,y,z def get_xyz(lon, lat, r): # makes x,y,z vectors on a sphere # lon, lat are numpy vectors (equal length) # r is a scalar (the radius) x = r * np.cos(lon) * np.cos(lat) y = r * np.sin(lon) * np.cos(lat) z = r * np.sin(lat) return x,y,z #%% plotting plt.close() fig = plt.figure(figsize=(8,8)) ax = fig.add_subplot(111, projection='3d') r = 10 lat = np.linspace(-np.pi/2, np.pi/2, 100) slice_rad = np.pi/6 lon = np.linspace(-np.pi, np.pi, 100) x, y, z = get_xyz_mesh(lon, lat, r) from matplotlib.colors import LightSource from matplotlib import cm light = LightSource(45,45) #illuminated_surface = light.shade(z, cmap=cm.rainbow) rgb = np.ones((z.shape[0], z.shape[1], 3)) illuminated_surface = light.shade_rgb(rgb, z) #ax = Axes3D(plt.figure()) ax.plot_surface(x,y,z, rstride=4, cstride=4, linewidth=0, antialiased=False, shade=True) #facecolors=illuminated_surface) # ax.plot_surface(x, y, z, # rstride=4, cstride=4, # color='y', linewidth=0, shade=True, # alpha=1, facecolors=illuminated_surface) lon = np.linspace(-np.pi, np.pi) lat = 0*lon X, Y, Z = get_xyz(lon, lat, r) # ax.plot(X, Y, Z, '-g', alpha=.4) if True: # for development ax.set_xlabel('x') ax.set_ylabel('y') ax.set_zlabel('z') scl = 1.2 else: # much cleaner display scl = .8 ax.set_axis_off() ax.set_xlim(-scl*r, scl*r) ax.set_ylim(-scl*r, scl*r) ax.set_zlim(-scl*r, scl*r) #ax.set_aspect('equal') ax.azim = -18 ax.elev = 14 plt.show()
18425edf1ac86961ed892c1c54a9ca91d21daa18
hyt0617/leetcode
/30-39/lc_39.py
709
3.515625
4
# !/usr/bin/env python # -*-coding: utf-8 -*- def combinationSum(candidates, target): """ :type candidates: List[int] :type target: int :rtype: List[List[int]] """ def dfs(nums, target, index, path, results): if target < 0: return if target == 0: results.append(path) return else: for i in range(index, len(nums)): dfs(nums, target - nums[i], i, path+[nums[i]], results) res = [] dfs(candidates, target, 0, [], res) return res # combinationSum([2, 3, 6, 7], 7) # combinationSum([2, 3, 5], 8) # combinationSum([1, 2], 3) # combinationSum([2, 3, 7], 18) combinationSum([2, 3, 8], 18)
785c16b219d06e5969c26ab00420c9c14c04bff8
durhambn/CSCI_220_Computer_Programming
/Lab 6.py
2,557
4.09375
4
# Lab6.py # Name 1:Evan Tanner # Name 2:Brandi Durham def nameReverse(): """ Read a name in first-last order and display it in last-comma-first order. """ name = input("What is your name? ") name = name.split() firstName = name[0] lastName = name[1] print("The name reversed is", lastName + ", " + firstName) def companyName(): web = input("Enter website: ") web = web.split(".") comName = web[1] print("Company Name is ", comName) def initials(): numOfStud = eval(input("How many students? ")) for i in range(numOfStud): firstName = input("Enter the first name of student#" + str(i+1) + ": ") lastName = input("Enter " + firstName + "'s last name: ") firstInitial = firstName[0] lastInitial = lastName[0] studIni = print(firstName + "'s initals are " + (firstInitial + lastInitial).upper()) print() def names(): names = input("Enter Names separated by commas: ") namesFl = names.split(",") print("Initals are: ", end = " ") for names in namesFl: names = names.split() firstName = names[0][0] lastName = names[1][0] print((firstName +lastName), end = " ") def thirds(): numSent = eval(input("Enter number of sentences: ")) total = [] for i in range (numSent): sent = input("Enter Sentence: ") for i in range(2,len(sent), 3): letters = sent[i] joinLetters = "".join(letters) print(joinLetters, end = " ") print() print() def wordCount(): numSent = eval(input("Enter num of sentences: ")) print() for i in range(numSent): sentence = input("Enter Sentence: ") wordList = sentence.split() print(len(wordList)) print() def wordAverage(): numSent = eval(input("Enter num of sentence: ")) for i in range(numSent): sent = input("Enter Sentence: ") wordList = sent.split() wordCount = len(wordList) sent = "".join(wordList) letterCount = len(sent) average = letterCount/wordCount print("The average of this sentence is", average) print() def pigLatin(): sent = input("Enter Sentence: ") sentSplit = sent.split() for word in sentSplit: print( (word[1:]+word[0]+"ay").lower(), end = " ") ##def main(): ## nameReverse() ## companyName() ## #add other function calls here main()
07c12c44ccd68c92235164240f238f680357f76e
bluwhale97/fc-css
/Linked_List/Double_Linked_List.py
3,374
3.765625
4
class Node: def __init__(self): self.__prev = None self.__next = None self.__data = None @property def prev(self): return self.__prev @prev.setter def prev(self,prev): self.__prev = prev @property def next(self): return self.__next @next.setter def next(self, next): self.__next = next @property def data(self): return self.__data @data.setter def data(self,data): self.__data = data class DoubleLinkedList: def __init__(self): self.head = Node() self.tail = Node() self.head.next = self.tail self.tail.prev = self.head self.d_size = 0 def empty(self): if self.d_size == 0: return True else: return False def size(self): return self.d_size # insert 계열 def add_first(self, data): new_node = Node() new_node.data = data new_node.next = self.head.next new_node.prev = self.head self.head.next.prev = new_node self.head.next = new_node self.d_size += 1 def add_last(self, data): new_node = Node() new_node.data = data new_node.prev = self.tail.prev new_node.next = self.tail self.tail.prev.next = new_node self.tail.prev = new_node self.d_size += 1 def insert_before(self, data, node): new_node = Node() new_node.data = data new_node.prev = node.prev new_node.next = node node.prev.next = new_node node.prev = new_node self.d_size += 1 def insert_after(self, data, node): new_node = Node() new_node.data = data new_node.prev = node new_node.next = node.next node.next.prev = new_node node.next = Node self.d_size += 1 def search_forward(self, target): cur = self.head.next while cur is not self.tail: if cur.data == target: return cur cur = cur.next return None def search_backward(self, target): cur = self.tail.prev while cur is not self.head: if cur.data == target: return cur cur = cur.next return None def delete_first(self): if self.empty(): return self.head.next = self.head.next.next self.head.next.prev = self.head self.d_size -= 1 def delete_last(self): if self.empty(): return self.tail.prev = self.tail.prev.prev self.tail.prev.next = self.tail self.d_size -= 1 def delete_node(self, node): if (node is self.head) or (node is self.tail): return node.prev.next = node.next node.next.prev = node.prev self.d_size -= 1 if __name__ == "__main__": def show_list(dl): cur = dl.head.next while cur is not dl.tail: print(cur.data, end=' ') cur = cur.next dl = DoubleLinkedList() for i in range(5): dl.add_first(i) for i in range(-10,-5): dl.add_last(i) for i in range(3): tmp = dl.search_forward(i) dl.delete_node(tmp) dl.search_backward(100) show_list(dl)
00d068677543215104b1af3276d5c2e7fdff3153
rjzupkoii/SmallProjects
/google/foobar01.py
2,305
4.25
4
#!/usr/bin/python # Module level global to track the primes primes = set([2, 3]) # Given a value between 0 and 10 000, return the next five digits from a concatendated list of primes. def solution(i): # First we need to get the relevent prime numbers, even though the list is concatendated we really # don't care about storing the values - we just need to make sure we start at the right offset and # have the next 5 (or n) values. # Start by getting the first prime and start of string [ prime, value ] = getPrime(i) # Get primes until we have enough for the string employee = str(value) while len(employee) < 5: prime = getNextPrime(prime) employee += str(prime) # Return the result return employee[0:5] # Get the prime number that overlaps with the index, return [ prime, value ] where value is truncated as # needed based upon the length def getPrime(index): # Starting point is two prime = 2 values = str(prime) # Scan until we have the starting point while len(values) < index: prime = getNextPrime(prime) values += str(prime) # Truncate as needed return [ prime, values[index:] ] # Get the next prime number given the current one. def getNextPrime(number): # There's a couple ways of doing this, honestly the best would be to pre-compute the a prime lookup # table and then just pull the values from that... # Deal with two as a special case, since after this we can assume the number is odd if number == 2: return 3 # Apply Bertrand's postulate to restrict the search space for value in range(number + 2, 2 * number, 2): if isPrime(value): return value raise Exception("Prime not found given input, {}".format(number)) # Check to see if the number is prime, references the module level primes variable def isPrime(number): global primes for prime in primes: if number == prime: return True if number % prime == 0: return False # This must be a new prime, add it to the list and return primes.add(number) return True if __name__ == "__main__": print 0, solution(0) print 3, solution(3) print 4, solution(4) print 5, solution(5) print 10000, solution(10000)
14c3e30d3a3c5b12e00c13de15fcf2b09742dbe2
AlexiaAM/Python-Bootcamp
/Problems/foreach.py
124
3.953125
4
#asi se hace un foreach animales = ["perro","gato","caballo","elefante","raton","raton"] for x in animales: print(x)
cc7806cc0ecb6ba83ac908890e384e828a2c3e21
JaminB/SmartTorrent-API
/smarttorrent/search/content/converters.py
553
4
4
#!/usr/bin/python class date: def __init__(self, dateString): self.dateString = dateString self.months = {'Jan' : '01', 'Feb' : '02', 'Mar' : '03', 'Apr' : '04', 'May' : '05', 'Jun' : '06', 'Jul': '07', 'Aug' : '08', 'Sep' : '09', 'Oct' : '10', 'Nov' : '11', 'Dec' : '12'} def convert(self): dateArray = self.dateString.split(' ') if len(dateArray[1]) > 1: return str(dateArray[2]) + "-" + self.months[dateArray[0]] + "-" + dateArray[1] else: return str(dateArray[2]) + "-" + self.months[dateArray[0]] + "-" + "0"+dateArray[1]
65f7df4eb97fec9e7f246597501df6c0af1b0b34
luisprooc/uno_game
/special_cards.py
2,625
3.59375
4
from random import randint class WildCards(): def __init__(self): self.color = "Black" self.list = [] def generate(self): for a in range(0,8): if a < 4: self.list.append(["+ 4",self.color]) else: self.list.append(["Choose color",self.color]) def noCard(self,card,player): for a in player.hand: if a[0] == card[0] or a[1] == card[1]: return False return True def Skip(self,player): player.notOmmited= False def returnCard(self,players,p): players.reverse() players.remove(p) players.insert(0,p) return players def changeColor(self,play,color): change = play change[1] = color return change def showColors(self): print(" Press 1 to choose red color \n Press 2 to choose blue color \n Press 3 to choose green color \n Press 4 to choose yellow color \n Press any key for random color") def optionColor(self,color): chosenColor = "" if color == "1": chosenColor = "Red" elif color == "2": chosenColor= "Blue" elif color == "3": chosenColor= "Green" elif color == "4": chosenColor = "Yellow" else: colors = ["Red","Blue","Green","Yellow"] random = randint(1,4) chosenColor = colors[random] return chosenColor def take2(self,player,cardPack): print("{} you have taken 2 cards \n".format(player.name)) for a in range(2): cardPack.steal(player) def affected(self,players,player): for x in range(-1,len(players)-1): if players[x] == player: p = players[x+1] return p def reSkip(self,players): for p in players: p.notOmmited = True def take4(self,player,nextPlayer,validate,cardPack): if validate: print("{} you have taken 4 cards \n".format(nextPlayer.name)) for t in range(5): cardPack.steal(nextPlayer) self.Skip(nextPlayer) else: print("{} you have taken 6 cards \n".format(player.name)) for t in range(7): cardPack.steal(player) return "" specials = WildCards() specials.generate() ##test #### """ names = ["Juan","Marco","Lucas","Maria"] p = specials.affected(names,"Juan") print(specials.returnCard(names,p)) """
cffb7474a3976cdf8454412176edfebe1e6af984
arunabenji29/Sorting
/src/searching/searching.py
1,942
4.125
4
# STRETCH: implement Linear Search def linear_search(arr, target): # TO-DO: add missing code for i in range(0,len(arr)): if(arr[i] == target): return i return -1 # not found array = [5,3,1,4] target = 1 print(linear_search(array,target)) # STRETCH: write an iterative implementation of Binary Search def binary_search(arr, target): newArr=arr[:] low = 0 high = len(newArr) if len(newArr) == 0: return -1 # array empty elif(len(newArr)==1): if(target == newArr[0]): return arr.index(target) else: for i in range(low,high): middle = int((len(newArr))/2) low = 0 high = len(newArr)-1 if(target == newArr[middle]): return arr.index(target) elif(target < newArr[middle]): array = newArr[low:middle] newArr = array[:] high = middle elif(target > newArr[middle]): array = newArr[middle+1:] newArr = array[:] low = middle+1 # TO-DO: add missing code return -1 # not found binaryArray = [-9, -8, -6, -4, -3, -2, 0, 1, 2, 3, 5, 7, 8, 9] print(binary_search(binaryArray,9)) # STRETCH: write a recursive implementation of Binary Search def binary_search_recursive(arr, target, low, high): high=len(arr) low=0 middle = (low+high)//2 if len(arr) == 0: return -1 elif len(arr) == 1: if target == arr[0]: return bin1.index(target) else: if target == arr[middle]: return bin1.index(target) elif target<arr[middle]: high=middle dang = arr[low:high] return binary_search_recursive(dang[:],target,low,high) elif target>arr[middle]: low=middle+1 dang = arr[low:high] return binary_search_recursive(dang[:],target,low,high) return 'else' return 'wait' bin1 = [-9, -8, -6, -4, -3, -2, 0, 1, 2, 3, 5, 7, 8, 9] print(f'fin: {binary_search_recursive(bin1,-3,0,len(bin1))}')
3a135c0f3da0c2cdbf08bbdae952b944529c2acd
noelis/oo-melons
/melons.py
1,833
3.890625
4
from random import randint """This file should have our order classes in it.""" class AbstractMelonOrder(object): """Covers all orders, domestic and international""" def __init__(self, species, qty, country_code=None, order_type=None, tax=None): self.species = species self.qty = qty # self.country_code = country_code # self.order_type = order_type # self.tax = tax self.shipped = False def mark_shipped(self): """Set shipped to True""" self.shipped = True def get_base_price(self): base_price = randint(5, 10) return base_price def get_total(self): base_price = self.get_base_price() if self.species.lower() == "christmas": base_price = base_price * 1.5 if self.order_type == "international" and self.qty < 10: total = ((1 + self.tax) * self.qty * base_price) + 3 else: total = (1 + self.tax) * self.qty * base_price return total class DomesticMelonOrder(AbstractMelonOrder): country_code = "USA" order_type = "domestic" tax = 0.08 # def __init__(self, species, qty): # super(DomesticMelonOrder, self).__init__(species, qty, "USA", "domestic", 0.08) class InternationalMelonOrder(AbstractMelonOrder): order_type = "international" tax = 0.17 # def __init__(self, species, qty, country_code): # super(InternationalMelonOrder, self).__init__(species, qty, country_code, # "international", 0.17) class GovernmentMelonOrder(DomesticMelonOrder): passed_inspection = False # def __init__(self, species, qty): # super(GovernmentMelonOrder, self).__init__(species, qty, "USA", "domestic", 0.08) def mark_inspection(self, passed): self.passed_inspection = passed
d09eb4a32372910ad67c7bec72982e1d83086df7
jhgrove/P2_SP20
/Labs/CTA Ridership/cta_rider_lab.py
1,812
4.03125
4
""" CTA Ridership (25pts) Get the csv from the following data set. https://data.cityofchicago.org/api/views/w8km-9pzd/rows.csv?accessType=DOWNLOAD This shows CTA ridership by year going back to the 80s It has been updated with 2018 data, but not yet with 2019 unfortunately 1 Make a line plot of rail usage for the last 10 years of data. (year on x axis, and ridership on y) (5pts) 2 Plot bus usage for the same years as a second line on your graph. (5pts) 3 Plot total usage on a third line on your graph. (5pts) 4 Add a title and label your axes. (4pts) 5 Add a legend to show data represented by each of the three lines. (4pts) 6 What trend or trends do you see in the data? Offer a hypotheses which might explain the trend(s). Just add a comment here to explain. (2pts) """ import matplotlib.pyplot as plt import csv with open("CTA_-_Ridership_-_Annual_Boarding_Totals (1).csv") as f: cr = csv.reader(f) data = list(cr) print(data) headers = data.pop(0) print(headers) years1 = [x[0] for x in data] bus1 = [x[1] for x in data] rail1 = [x[3] for x in data] total1 = [x[4] for x in data] years = years1[-10:] bus = bus1[-10:] rail = rail1[-10:] total = total1[-10:] print(years) print(bus) print(rail) print(total) xxx = years[bus] xxx = [int(x) for x in xxx] print(xxx) yyy = years[bus] yyy = [int(x) for x in yyy] # plt.plot(month_numbers, my_library) # plots line graph plt.plot(years, xxx, color='darkgreen', label='Bus') # plots a line graph plt.plot(years, yyy, color='blue', label='Rail') # plt.xticks(month_numbers, month_names, rotation=45) # replaces the shown values on the graph axis plt.axis([-1, 10, 0, 16000]) plt.title("Title", fontsize=20) plt.xlabel('Years') plt.ylabel('Ridership') plt.legend() # axis # labels # title # legend (label plots) plt.show()
9aaa144bdd903da852c47492b1500de505b68354
hguochen/algorithms
/python/linked_list_addition.py
1,662
4.28125
4
################################## ### Title: Linked List addition ## ### Author: GuoChen Hou ######## ################################## # Two numbers represented by a linked list, where each node contains # a single digit. # The digits are stored in reverse order, such that the 1/s digit is at the # head of the list. Write a function that adds the two numbers and returns # the sum as a linked list. from ADT.LinkedList import LinkedList def add(linked_list1, linked_list2): """ This function adds the two numbers(represented as linked lists) and returns the sum as a linked list. """ # check if any of the inputs are empty if linked_list1.get_size() is 0 or linked_list2.get_size() is 0: print "Please check that both lists are not empty." return result = LinkedList() if linked_list1.get_size() is linked_list2.get_size(): list1 = linked_list1.get_head() list2 = linked_list2.get_head() carry = 0 while list1 is not None and list2 is not None: value = (list1.data + list2.data) % 10 + carry print value carry = (list1.data + list2.data) / 10 print carry result.insert(value) list1 = list1.next list2 = list2.next print result.print_list() return result if __name__ == "__main__": test_list1 = LinkedList() test_list2 = LinkedList() test_list1.insert(3) test_list1.insert(1) test_list1.insert(5) test_list2.insert(5) test_list2.insert(9) test_list2.insert(2) test_list1.print_list() test_list2.print_list() add(test_list1, test_list2)
7e8f216a4dc35ed46040924e7440c003a882fbec
wangs0622/learning_Algorithm
/sort/PQ.py
1,821
3.75
4
# _*_ encoding: utf-8 _*_ import queue from sort.maxPQ import printHeap minPQ = queue.PriorityQueue def heappush(heap, item): heap.append(item) _siftdown(heap, startpos = 0, pos = len(heap)-1) def heappop(heap): lastelt = heap.pop() if heap: returnitem = heap[0] heap[0] = lastelt _siftup(heap, 0) return returnitem return lastelt def _siftdown(heap, startpos, pos): newitem = heap[pos] while pos > startpos: parentpos = (pos - 1) >> 1 parent = heap[parentpos] if newitem > parent: heap[pos] = parent pos = parentpos continue break heap[pos] = newitem def _siftup(heap, pos): endpos = len(heap) startpos = pos newitem = heap[pos] childpos = 2*pos + 1 # leftmost child position while childpos < endpos: # Set childpos to index of smaller child. rightpos = childpos + 1 if rightpos < endpos and heap[childpos] < heap[rightpos]: childpos = rightpos # Move the smaller child up. heap[pos] = heap[childpos] pos = childpos childpos = 2*pos + 1 # The leaf at pos is empty now. Put newitem there, and bubble it up # to its final resting place (by sifting its parents down). heap[pos] = newitem _siftdown(heap, startpos, pos) class MaxPQ(queue.Queue): def _init(self, maxsize): self.queue = [] def _qsize(self): return len(self.queue) def _put(self, item): heappush(self.queue, item) def _get(self): return heappop(self.queue) if __name__ == '__main__': items = 'qwertyuiopasdfghjklzxcvbnm' maxpq = MaxPQ() for x in items: maxpq.put(x) print(maxpq.queue) printHeap(maxpq.queue)
6a4e53ef5ebb687b7a776e5387a455ebc51e13c7
muhi28/Algorithms-And-Data-Structures-Python-
/sorting-algorithms/comparison-based-sorting/stooge_sort.py
1,149
4.09375
4
import random # initializes the list with random numbers def getData(n): data = [0] * n for i in range(n): data[i] = random.randint(1, 100) return data def stoogeSort(arr, i, j): # checks whether the value at the start is larger # then the value at the end if arr[j] < arr[i]: # if it's so -> swap them arr[i], arr[j] = arr[j], arr[i] # if there are 3 or more elements if (j - i + 1) >= 3: t = (j - i + 1) / 3 stoogeSort(arr, i, j - t) # stooge sort the initial 2/3 of the data stoogeSort(arr, i + t, j) # stooge sort the final 2/3 of the data stoogeSort(arr, i, j - t) # stooge sort the initial 2/3 of the data again return arr # wrapper function to compute the initial value of j rather then # detecting the sentinel value NONE def stooge(arr): return stoogeSort(arr, 0, len(arr) - 1) def main(): data_size = input("How many elements do you want to insert?\t") data = getData(data_size) print "Before Sorting -> {0:}".format(data) print "After Sorting -> {0:}".format(stooge(data)) if __name__ == '__main__': main()
db3e2242a2af0c1f6ac3975b8ae97c8d542a7834
laomu/py_1709
/python-base/days12_code/demo02_封装.py
2,596
4.5
4
# 定义一个类型——人的类型 class Person: def __init__(self, name, age): # 创建对象的时候,对属性进行赋值 self.name = name self.age = age self.money = 10000 # 创建了一个人的对象,姓名是tom,年龄是48 p = Person("tom", 48) # 生活中各种场景下,人的数据会发生变化,过了一年~年龄+1;派出所等级信息~登记姓名、年龄 # 程序代码中,可以通过不同的代码,操作对象的数据 p.name = "jerry"# 改名字 p.age = 18# 改年龄 print(p.name, p.age, p.money) # 上大学 p.name = "jerry"# 登记姓名 p.age = 118 # 登记年龄 p.money = -10000 print(p.name, p.age, p.money) ################################################ # 如果属性数据,可以直接操作,任何数据都有可能被恶意操作 # 所以,对于数据~只有不同的场景,所有数据都是敏感的! # 女孩的体重! 公安局登记信息 | 相亲对象【体重 敏感】 # 所以~我们在定义类型的时候,所有属性数据都是敏感的,不能让直接操作 ################################################ # 定义一个用户对象 class User: # 定义用户对象的属性 def __init__(self, name, age): # 属性变量,以两个下划线开头 # 属性如果以两个下划线开头,这个属性只能在内部使用【属性私有化】 # 1封装第一步:所有属性私有化 self.__name = name self.__age = age # 封装第二步:提供访问[获取]数据的方法:get方法 # 项目规范:获取属性数据的方法 固定名称::get_属性名称() def get_name(self): return self.__name def get_age(self): return self.__age # 封装第三步:提供访问【赋值】数据的方法:set方法 # 项目规范:设置属性数据的方法 固定名称:set_属性名称(*) def set_name(self, name): self.__name = name def set_age(self, age): # 封装可选:第四步:在set/get方法中,添加限制条件 if age > 0 and age < 100: self.__age = age else: print("非法年龄,不允许修改") u = User("shuke", 16) # 获取对象的数据 #print(u.__name, u.__age) # AttributeError: 'User' object has no attribute '__name' # 属性错误:User对象,没有名称为__name的属性 print(u.get_name(), u.get_age()) # 设置对象的数据 —— 下面的两行代码,并没有生效 #u.__name = "beita" #u.__age = 19 # 标准的设置操作 u.set_name("beita") u.set_age(19) print(u.get_name(), u.get_age()) u.set_name("xiangfei") u.set_age(327)#设置了年龄 print(u.get_name(), u.get_age())
de92dd278093341414d2e4ab4a01b38dd74ec76b
gwqw/LessonsSolution
/checkio/06_Ice_Base/06_IceBase_06_Colder-Warmer.py
4,070
3.546875
4
def calc_area(steps): minX = minY = 0 maxX = maxY = 9 for i in range(1,len(steps)): if steps[i][0] == 2 and steps[i][1] == 2: continue if steps[i][0] > steps[i-1][0]: if steps[i][2] == 1 and minX < steps[i][0]: minX = steps[i][0] elif steps[i] == -1 and maxX > steps[i-1][0]: maxX = steps[i-1][0] elif steps[i][0] < steps[i-1][0]: if steps[i][2] == 1 and maxX > steps[i][0]: maxX = steps[i][0] elif steps[i][2] == -1 and minX < steps[i-1][0]: minX = steps[i-1][0] elif steps[i][1] > steps[i-1][1]: if steps[i][2] == 1 and minY < steps[i][1]: minY = steps[i][1] elif steps[i][2] == -1 and maxY > steps[i-1][1]: maxY = steps[i-1][1] elif steps[i][1] < steps[i-1][1]: if steps[i][2] == 1 and maxY > steps[i][1]: maxY = steps[i][1] elif steps[i][2] == -1 and minY < steps[i-1][1]: minY = steps[i-1][1] return [minX, maxX, minY, maxY] def in_area(x, y, area): return x >= area[0] and x <= area[1] and y >= area[2] and y <= area[3] def has_step(x, y, steps): for s in steps: if x == s[0] and y == s[1]: return True return False def get_direction(steps): if steps[-1][0] > steps[-2][0]: return 0 if steps[-1][0] < steps[-2][0]: return 1 if steps[-1][1] > steps[-2][1]: return 2 if steps[-1][1] < steps[-2][1]: return 3 def get_ave_area(area): x = (area[1] + area[0]) // 2 y = (area[3] + area[2]) // 2 return x,y def checkio(steps): print(f"{len(steps)}steps: {steps}") if len(steps) == 1: if steps[0] != [5, 5, 0]: return 5, 5 else: return 4, 5 area = calc_area(steps) print("area: ", area) x = steps[-1][0] y = steps[-1][1] direction = get_direction(steps) if direction > 1: if in_area(x+1, y, area) and not has_step(x+1, y, steps): return x+1, y elif in_area(x-1, y, area) and not has_step(x-1, y, steps): return x-1, y elif in_area(x, y+1, area) and not has_step(x, y+1, steps): return x, y+1 elif in_area(x, y-1, area) and not has_step(x, y-1, steps): return x, y-1 if direction <= 1: if in_area(x, y+1, area) and not has_step(x, y+1, steps): return x, y+1 elif in_area(x, y-1, area) and not has_step(x, y-1, steps): return x, y-1 elif in_area(x+1, y, area) and not has_step(x+1, y, steps): return x+1, y elif in_area(x-1, y, area) and not has_step(x-1, y, steps): return x-1, y return get_ave_area(area) if __name__ == '__main__': # This part is using only for self-checking and not necessary for auto-testing from math import hypot MAX_STEP = 12 #MAX_STEP = 24 def check_solution(func, goal, start): prev_steps = [start] for step in range(MAX_STEP): row, col = func([s[:] for s in prev_steps]) if [row, col] == goal: print("You find it! ", row, ", ", col) return True if 10 <= row or 0 > row or 10 <= col or 0 > col: print("You gave wrong coordinates.") return False prev_distance = hypot(prev_steps[-1][0] - goal[0], prev_steps[-1][1] - goal[1]) distance = hypot(row - goal[0], col - goal[1]) alteration = 0 if prev_distance == distance else (1 if prev_distance > distance else -1) prev_steps.append([row, col, alteration]) print("Too many steps") return False assert check_solution(checkio, [7, 7], [5, 5, 0]), "1st example" assert check_solution(checkio, [5, 6], [0, 0, 0]), "2nd example" #assert check_solution(checkio([[0,0,0],[2,2,1],[2,3,1],[3,3,1],[3,4,1],[4,4,1],[4,5,1],[5,5,1],[5,6,1],[6,6,1],[6,7,1],[7,7,1],[7,8,1]]), , "3rd example")
46b5c84120b82269c6806ea24a35334818cbe2e5
rafaelperazzo/programacao-web
/moodledata/vpl_data/59/usersdata/260/48826/submittedfiles/testes.py
223
3.71875
4
# -*- coding: utf-8 -*- #COMECE AQUI ABAIXO #!/usr/bin/python b=0 a=float(input("digite a quntidade de discos)) for i in range(1,31,1): if b>a: maior=b else: maior=a b=a print(%d %.2f %(i,maior))
e7e888bdd77c218b707aa8a932ba3082b4c1e373
markloborec/Pythonigra
/src/app.py
1,017
3.71875
4
import random from src.domain import World class Console: def __init__(self,width,height): self.world = World(width,height,10) def draw(self): for y in range(self.world.height): for x in range(self.world.width): if self.world.hero.x == x and self.world.hero.y == y: print("h", end='') continue isenemyDrawn = False for enemy in self.world.enemies: if enemy.x == x and enemy.y == y: print("E", end="") isenemyDrawn = True break if isenemyDrawn: continue print("*",end='') print() def nextiteration(self): dx = int(input("Vnesi dx:")) dy = -int(input("Vnesi dy:")) self.world.hero.move(dx,dy) for enemy in self.world.enemies: enemy.move(random.randint(-5,5),random.randint(-5,5))
aabbb492722ed999af85d7d2f9f312767a8eb3ec
kaci65/Nichola_Lacey_Python_By_Example_BOOK
/2D_Lists_and_Dictionaries/update_single_column.py
548
4.03125
4
#!/usr/bin/python3 """update a column by appending a new value using user input""" simple_array = [[2, 3, 1, 4], [5, 7, 6, 2], [8, 4, 9, 0]] row = int(input("Please enter a row number: ")) print(simple_array[row]) col = int(input("Please enter column number: ")) print(simple_array[row][col]) ques = input("Do you want to change the value shown? ") ans = ["yes", "Yes", "YES", "y", "Y"] if ques in ans: num = int(input("Please enter a new number: ")) simple_array[row][col] = num print("The updated row is: {}".format(simple_array[row]))
0b0252409b69b3c61e51d2fec100389b2bf204d3
amuroni/DataScience
/Pandas_Data.py
921
3.671875
4
import pandas as pd import numpy as np # generating a random Series rng = np.random.RandomState(42) ser = pd.Series(rng.randint(0, 10, 4)) # generating a dataframe with 3 rows and four columns df = pd.DataFrame(rng.randint(0, 10, (3, 4)), columns=["A", "B", "c", "D"]) # applying a np ufunc will preserve the indices (rows and columns) print(np.exp(ser)) print(df * np.pi / 4) # handling missing data (NaN) area = pd.Series({'Alaska': 1723337, 'Texas': 695662, 'California': 423967}, name='area') population = pd.Series({'California': 38332521, 'Texas': 26448193, 'New York': 19651127}, name='population') print(population/area) # NY is NaN # another NaN example A = pd.Series([2, 4, 6], index=[0, 1, 2]) B = pd.Series([1, 3, 5], index=[1, 2, 3]) print(A + B) # shows NaN in 0 and 3 print(A.add(B, fill_value=0)) # in this case it will sum with 0 as filler for NaN value
122e34eea972814519fbc74a2b7d9196fa85caab
rameshkonatala/Programming
/Spoj/TRICOUNT.py
299
3.71875
4
def triangle(x): if x==1: return 1 elif x==2: return 5 elif x==3: return 13 else: if x%2==0: return 2+3*(int(triangle(x-1))-int(triangle(x-2))) else: return 3+3*(int(triangle(x-1))-int(triangle(x-2))) t=int(raw_input()) for j in range(t): a=int(raw_input()) print triangle(a)
d84fc96167144760391f4b8a20f05275bb502c77
mrdziuban/Projects
/my_solutions/Text/count_vowels.py
227
4.09375
4
def count_vowels(string): vowels = {'a': 0, 'e': 0, 'i': 0, 'o': 0, 'u': 0} for l in string: if l in vowels.keys(): vowels[l] += 1 return vowels string = input('Enter your string: ') print(count_vowels(string))
45830c0a489eee714eac5eaefd750d48db500490
CobyHong/CPE-101-Cal-Poly-2017
/Midterm Practice/Question 3/less5.py
190
3.59375
4
def less_than_5(list): list_str = [] for i in range(len(list)): if len(list[i]) < 5: list_str.append(list[i]) result = len(list_str) return result
1ad8ea93f2b3eb3f7e56bd6531be1b6c44b97456
xiholix/testSomething
/decorator/methodDecorator.py
1,658
4.15625
4
# --*--coding:utf8--*-- 'Method decorators allow overriding class properties by decorating,' 'without having to find the calling function.' import functools def wraper(arg1, arg2): def innerFunction(inputFunc): print(arg1) print(arg2) print("inner function") @functools.wraps(inputFunc) def wra(t, *args, **kwargs): print(t) result = inputFunc(*args, **kwargs) print( 'wra') def non(): print('in non') return 'yes' return non return wra return innerFunction @wraper(1,2) def test(*args, **kwargs): print('test'+str(args)) return 'test' ''' 根据对这里的代码的理解,使用functools的wraps时只有该修饰符号后定义的函数才需要与被修饰的函数的函数签名 一样。而且只有该被修饰的函数才会多次执行,其他外面的函数内容只会执行一次。因为只有最里面的函数return的东西才会 被多次return,外面的函数都是return他的结果。猜测是因为被修饰的函数最后会变成最里面返回的那个函数,所以相当于 每次执行最里面的那个函数 而且感觉method修饰和函数修饰没什么区别,因为method修饰是对类的方法进行修饰,所以要签名一致则该修饰函数也会有 一个类似self的参数,从而能够访问类的属性等。 参考博客链接: http://blog.apcelent.com/python-decorator-tutorial-with-example.html ''' def testTest(): test(1, 2, 3) test(1, 2, 3) m = test(1, 2, 3) print m if __name__ == "__main__": testTest()
b1ac7944d325630a2dcc0ca49cd7c42a40c10d05
hijinkim/BOJpractice
/1181.py
184
3.796875
4
n = int(input()) words = [] for i in range(n): words.append(input()) words = list(set(words)) words = sorted(words, key=lambda x: (len(x), x)) for word in words: print(word)
3c1278de7dec1598111586a469dfb81fdc08051f
MingduDing/My_codes
/05_single_cycle_link_list.py
3,423
3.890625
4
# -*- coding: utf-8 -*- class Node(object): """节点""" def __init__(self, elem): self.elem = elem self.next = None class SingleCycleLinkList(object): """单向循环链表""" def __init__(self, node=None): self.__head = node if node: node.next = node def is_empty(self): """链表是否为空""" return self.__head == None def length(self): """链表长度""" if self.is_empty(): return 0 # cur游标,用来遍历节点 cur = self.__head # count记录数量 count = 1 while cur.next != self.__head: count += 1 cur = cur.next return count def travel(self): """遍历整个列表""" if self.is_empty(): return cur = self.__head while cur.next != self.__head: print cur.elem, cur = cur.next # 退出循环,cur指向尾结点,但尾结点的元素未打印 print cur.elem def add(self, item): """链表头部增加一个元素,头插法""" node = Node(item) if self.is_empty(): self.__head = node node.next = node else: cur = self.__head while cur.next != self.__head: cur = cur.next # 退出循环,cur指向尾结点 node.next = self.__head self.__head = node cur.next = node # cur.next = self.__head def append(self, item): """链表尾部插入一个元素,尾插法""" node = Node(item) if self.is_empty(): self.__head = node node.next = node else: cur = self.__head while cur.next != self.__head: cur = cur.next cur.next = node node.next = self.__head # 等同于node.next = cur.next def insert(self, pos, item): """指定位置添加元素""" if pos <= 0: self.add(item) elif pos > (self.length()-1): self.append(item) else: pre = self.__head count = 0 while count < (pos-1): count += 1 pre = pre.next node = Node(item) node.next = pre.next pre.next = node def remove(self, item): """删除节点""" if self.is_empty(): return cur = self.__head pre = None while cur.next != self.__head: # 不是尾结点的情况 if cur.elem == item: if cur == self.__head: # 先判断此结点是否为头结点 # 头结点 rear = self.__head while rear.next != self.__head: rear = rear.next self.__head = cur.next rear.next = self.__head else: # 中间结点 pre.next = cur.next return else: pre = cur cur = cur.next # 退出循环,cur指向尾结点 if cur.elem == item: if cur == self.__head: # 链表只有一个结点 self.__head = None else: pre.next = cur.next def search(self, item): """查找节点是否存在""" if self.is_empty(): return False cur = self.__head while cur.next != self.__head: if cur.elem == item: return True else: cur = cur.next if cur.elem == item: return True return False if __name__ == "__main__": ll = SingleCycleLinkList() print ll.is_empty() # True print ll.length() # 0 ll.append(1) print ll.is_empty() # False print ll.length() # 1 ll.append(2) ll.add(8) ll.append(3) ll.append(4) ll.append(5) ll.append(6) ll.insert(-1, 9) ll.travel() # 9 8 1 2 3 4 5 6 ll.insert(3, 100) ll.travel() # 9 8 1 100 2 3 4 5 6 ll.insert(10, 200) ll.travel() # 9 8 1 100 2 3 4 5 6 200 ll.remove(100) ll.travel() # 9 8 1 2 3 4 5 6 200 ll.remove(9) ll.travel() # 8 1 2 3 4 5 6 200 ll.remove(200) ll.travel() # 8 1 2 3 4 5 6
75e90a9cd8983855132d06e9d4fbde27757295a5
terrameijar/realpy
/sql/update_delete.py
430
3.90625
4
import sqlite3 with sqlite3.connect("new2.db") as connection: cursor = connection.cursor() cursor.execute("UPDATE population SET population = 9000000 WHERE city = 'Chicago'") #delete data cursor.execute("DELETE FROM population WHERE city='Boston'") print "\nNEW DATA: \n" cursor.execute("SELECT * FROM population") rows = cursor.fetchall() for row in rows: print row[0], row[1], row[2]
36d913ec6f630c9ec24c2f9d9af8ba958133afa0
skb30/UCSC-Python2
/homework3/solutions.py
4,666
4.46875
4
''' The standard form of a quadratic expression is ax^2 + bx + c where a, b and c are real numbers and a is not equal to zero. The degree of a quadratic expression is 2 and a, b and c are called the coefficients. For example, in the quadratic expression (3x^2 + 8x − 5), the coefficients are 3, 8 and -5 corresponding to the exponent 2, 1 an 0 respectively. Define and use a Python class that can perform operations on quadratic expressions such as addition and subtraction. Define a Python class called ‘Quadratic’. The Python object that will create this class will be as follows Q1 = Quadratic(3,8,-5) This corresponds to the expression above. Define another Python object Q2 as follows Q2 = Quadratic(2,3,7) which corresponds to the quadratic expression 2x^2 + 3x + 7 Part I – Addition and subtraction of quadratic expressions Perform the addition and subtraction operation by using operator overloading. Make the following Python calls: quadsum = Q1+Q2 quaddiff = Q1-Q2 Print the values of quadsum and quaddiff. The output on your screen must be similar to the one below. The sum is 5x^2+11x+2 The difference is x^2+5x-12 Part II – Equality operator for quadratic expressions Two quadratic expressions are equal only if all the corresponding coefficients are equal. Define an equality operator that will return ‘True’ if two quadratic expressions are equal and ‘False’ when they are not equal. For example, in this code for Q1 == Q1, the value must be ‘True’ and for Q1 == Q2, the value must be ‘False'. ''' class Quadratic: def __init__(self,a,b,c): self.a = a self.b = b self.c = c def __str__(self): return '%d x^2 + %d x + %d' %(self.a,self.b,self.c) def __add__(self,other): return Quadratic(self.a + other.a, self.b + other.b, self.c + other.c) def __sub__(self,other): return Quadratic(self.a - other.a, self.b - other.b, self.c - other.c) def __eq__(self,other): if(self.a == other.a and self.b == other.b and self.c == other.c): print("The two quadratics expression are equal") return True else: print("The two quadratics expression are not equal") return False q1 = Quadratic(3, 8, -5) q2 = Quadratic(2, 3, 7) print("The sum of the given quadratic expressions is ", q1 + q2) print("The difference of the given quadratic expressions is ", q1 - q2) print(q1 == q2) ''' Please ensure that you use space instead of tab for indentation. Then paste your code directly into the response box. Write a program that will read the file, 'red-headed-league.txt', count the frequency of the words and store it as a csv file. Create a class called WordCounter with the following methods. def __init__(self,filename) where filename is the name of the text file, 'red-headed-league.txt'. This function should read the text file def removepunctuation(self) must remove all the punctuations and leave only alphabets and numbers in each word def findcount(self) must count the frequency of each word and store it in a instance variable called countdict def writecountfile(self,csvfilename) writes the content of the countdict variable to a csv file with two columns. The first column is the word and second column is the count. Create an instance of the class and call appropriate method and store the result in a csv file. Printout the five most popular words. NOTE: DO NOT USE THE COUNTER DATA STRUCTURE IN COLLECTIONS MODULE. ''' import string, csv class WordCounter: def __init__(self,filename): self.filename = filename self.contentlist = [] self.cleanlist = [] self.countdict = {} fo = open(self.filename,'r') for lines in fo.readlines(): lineitems = lines.strip().split() self.contentlist.extend(lineitems) def removepunctuation(self): for items in self.contentlist: cleanstring = items for c in string.punctuation: cleanstring = cleanstring.replace(c,"") if cleanstring != '': self.cleanlist.append(cleanstring) def findcount(self): uniqlist = list(set(self.cleanlist)) print(uniqlist) for items in uniqlist: self.countdict[items] = self.cleanlist.count(items) def writecountfile(self,csvfilename): writer = csv.writer(open(csvfilename, 'wb')) for key, value in self.countdict.items(): writer.writerow([key, value]) wc = WordCounter('red-headed-league.txt') wc.removepunctuation() wc.findcount() print(wc.countdict) # wc.writecountfile('my4.csv')
fe23cffec8b5becb2edec5f817d049e11d466352
hguochen/code
/python/questions/google_autocomplete_feature.py
2,207
3.78125
4
""" Implement the google autocomplete feature Given a string which represents characters typed into a text box so far, Write as program to suggest words based on what i have typed so far Eg. input: cat output: [catnip, caterpillar, cats, catskills] """ class Node(object): def __init__(self): self.children = [None for _ in range(26)] self.is_word = False class Dictionary(object): def __init__(self): self.root = Node() def insert_word(self, word): if len(word) < 1: return curr = self.root for i in xrange(len(word)): index = ord(word[i]) - 97 if curr.children[index] is None: curr.children[index] = Node() curr = curr.children[index] curr.is_word = True return def insert_node(self, root, index, node): if root is None: return if root.children[index] is None: root.children[index] = node root.children[index].is_word = True return self.insert_node(root.children[index], index, node) def search_words(self, string): if len(string) < 1: return [] result = [] curr = self.root for i in xrange(len(string)): index = ord(string[i]) - 97 if curr.children[index] is None: break curr = curr.children[index] if curr.is_word: result.append(string) self.get_words(curr, "", result) result = map(lambda item: string + item, result) return result def get_words(self, node, suffix, result): if node is None or node.is_word: result.append(suffix) for i in xrange(len(node.children)): if node.children[i] is not None: suffix += chr(i+97) self.get_words(node.children[i], suffix, result) suffix = suffix[:-1] return if __name__ == '__main__': str1 = "cat" words = ["catnip", "caterpillar", "cats", "catskills"] dictionary = Dictionary() for word in words: dictionary.insert_word(word) print dictionary.search_words(str1)
cf8646270d435ab39634cb27e35c019bc8919380
sj90hwang/ToBigs
/week5/Class/클래스과제_배포/main2.py
1,959
3.53125
4
############# # Apartment # ############# # 다른 파일에서 class import from Apartment import Apartment from Vile import Vile # 파일읽기 f = open("./Apartment.txt", 'r') N = int(f.readline()) # Apartment정보 객체로 만들어 입력받기 apartments = [] for i in range(N): row=f.readline().split(' ') a = Apartment(row[0], int(row[1]), int(row[2].strip())) # 객체 생성 apartments.append(a) f.close() # Q 가장 평수가 큰 아파트를 찾아 "xxx동 xxxx호의 x개의 방이 있는 xx평의 집입니다" 라고 출력 print('Q. 가장 큰 평수 아파트의 정보를 출력하세요.') print("A.", max(apartments)) # magic method가 작동하는 것을 직관적으로 파악해보기 위해 for문을 이용하여 최댓값을 찾아보세요! max_index1=0 max_index2=0 for j in range(N-1): if apartments[max_index1].size < apartments[j+1].size: max_index1 = j+1 if apartments[max_index2] < apartments[j+1]: max_index2 = j+1 print("Max Index 찾기\n1. 객체 속성 비교 :",apartments[max_index1], "\n2. 매직 메소드 :",apartments[max_index2]) # 혹시 같은 인덱스가 있으면 같이 출력한다. print("같은 인덱스 있는지 확인") for j in range(N): if apartments[j] == apartments[max_index2]: print(apartments[j]) ########### ## Vile ### ########### # 파일읽기 f = open("Vile.txt", 'r') N=int(f.readline()) # Vile정보 객체로 만들어 입력받기 viles = [] for i in range(N): row = f.readline().split(' ') v = Vile(row[0], int(row[1]), int(row[2].strip()), row[3]) # 객체 생성 viles.append(v) f.close() # Vile에 대한 최대평수 출력은 max를 활용해보세요~! # Q 가장 평수가 큰 주택을 찾아 "xxxx에 위치해 있는 x개의 방이 있고 마당은 없는 x평의 주택입니다." 라고 출력 print('Q. 가장 큰 평수 주택의 정보를 출력하세요.') print("A.", max(viles))
89fc0954f4c63d31bdcfd4921a67a47c44d2a92f
wypstudy/LeetCode-Python
/Algorithms/13.py
1,004
3.515625
4
# coding=utf-8 class Solution(object): def romanToInt(self, s): """ :type s: str :rtype: int """ # 打表 roman_map = {'': 0, 'M': 1000, 'MM': 2000, 'MMM': 3000, 'C': 100, 'CC': 200, 'CCC': 300, 'CD': 400, 'D': 500, 'DC': 600, 'DCC': 700, 'DCCC': 800, 'CM': 900, 'X': 10, 'XX': 20, 'XXX': 30, 'XL': 40, 'L': 50, 'LX': 60, 'LXX': 70, 'LXXX': 80, 'XC': 90, 'I': 1, 'II': 2, 'III': 3, 'IV': 4, 'V': 5, 'VI': 6, 'VII': 7, 'VIII': 8, 'IX': 9 } roman = list(s) i = 0 length = len(roman) num = 0 while i < length: if i < length - 1 and ''.join(roman[i:i+2]) in ['CD', 'CM', 'XL', 'XC', 'IV', 'IX']: num -= roman_map[roman[i]] else: num += roman_map[roman[i]] i += 1 return num instance = Solution() print(instance.romanToInt("MCMXCIV"))
84519b04581400437f6e7c6d0dd102f1ed482b1a
martinleeq/python-100
/day-09/question-072.py
289
3.9375
4
""" 问题72 生成一个包含5个元素的列表,每个元素是100~200之间的随机数 """ import random a_list = [] for i in range(5): a_list.append(random.choice(range(100,201))) print(a_list) print('==================') a_list.clear() print(random.sample(range(100,201), 5))
bc92a194dc9330e18ecf42c2db2d183a34d89cf9
git874997967/LeetCode_Python
/easy/leetCode543.py
921
3.90625
4
# 543. Diameter of Binary Tree # why we need the global ans which is diff as other recurision? # because the diameter may or may not pass the root def diameterOfBinaryTree(self, root): self.ans = 1 if not root: return 0 def height(root): if not root: return 0 L = height(root.left) R = height(root.right) self.ans = max(L+R+1,self.ans) return 1 + max( L,R) height(root) return self.ans - 1 def diameterOfBinaryTree2(self,root): self.ans = 1 def height(root): # base case if not root: return 0 L = height(root.left) R = height(root.right) self.ans = max(self.ans, L + R - 1) # update the global var height contains itself twice means - 1 return max(L, R) + 1 # because not root return 0 means leaf with hight 0 + 0 + 1(itself) height(root) return self.ans - 1
d3f1b3d7a9221a8dcbb6a9585082ac346cd213b2
Yang-Ding/leetcode_Python
/70_Climbing_Stairs.py
335
3.6875
4
class Solution: # @param {integer} n # @return {integer} def climbStairs(self, n): if n==1: return 1 number_ways=[0]*(n+1) number_ways[1]=1 number_ways[2]=2 for i in range(3,n+1): number_ways[i]=number_ways[i-1]+number_ways[i-2] return number_ways[n]
f08a8709cdf5455b9383b11f6da25c559607220f
uzzal408/learning_python
/basic/string.py
1,080
3.75
4
#asign multiline string a = """ Hello, I am Ismail Hossen Working In Aamra Infotainment Ltd I have 3 years experience in PHP Laravel Now Trying to working on python""" print(a) #Loop on string for ba in "banana": print (ba) #String Lenngth b = "Hello world" print(len(b)) # check phrase, word or character exist in string print("Ismail" in a) if "Ismail" in a: print("Yes, Ismail is exist in variable a") if "Django" not in a: print("No, Djnago is not exist in variable a") #get string from position 2 to 5 print(b[2:5]) #get string from first ot 5 print(b[:5]) #get string from last 5 print(b[5:]) #String Format #This is error #age = 10 #text = "I am a error" +age #print(text) # to use variable in text we need to use python format text = "I am Ismail Hossen, I am {} years Old. I read in class {}" print(text.format(27,12)) #You can use index numbers {0} to be sure the arguments are placed in the correct placeholders: text2 ="I want to pay {2} dollars for {0} pieces of item {1}." quantity = 3 itemno = 246 price = 100 print(text2.format(quantity,itemno,price))
9bab159da348bff509c98a232f11a62588072c69
Matozinho/CNC
/Trabalho3/codes/questao1.py
317
3.515625
4
import numpy as np from sympy import * def metEuler(function, h, x0, y0, endX): exp = lambdify(symbols('y'), (Symbol('y') + h * function)) yn = y0 xn = x0 while xn < endX: yn = exp(yn) xn += h return yn function = 0.8 * Symbol('y') print("Método de Euler: ", metEuler(function, 0.2, 0, 20, 4))
04303c2bc6179a4ebe1d6f7c35620a5186f1bd53
mated-pl/udemy_python1
/Part 3 rozbudowa kodu.py
5,146
3.53125
4
# 3.30 nested loop # listA = list(range(4)) # listB = list(range(4)) # product =[] # for a in listA: # klasyczna petla # for b in listB: # product.append((a,b)) # print(product) # # product = [(a,b) for a in listA for b in listB] # print(product) # # product = [(a,b) for a in listA for b in listB if a%2 == 0 and b%2 == 1] # % podzielne przez # print(product) # 3.31 zadanie # ports = ['WAW', 'KRK', 'GDN', 'KTW', 'WMI', 'WRO', 'POZ', 'RZE', 'SZZ', # 'LUZ', 'BZG', 'LCJ', 'SZY', 'IEG', 'RDO'] # # flights = [(a,b) for a in ports for b in ports] # print(flights) # flights_unique = [(a,b) for a in ports for b in ports if a!=b] # print(flights_unique) # # usuwam duplikaty A-B B-A szukajac pozycji A i B na liscie i porownujac # # zamiast index zadziala tez prostsze a<b # flights_1way = [(a,b) for a in ports for b in ports if a!=b and ports.index(a)<ports.index(b)] # print(flights_1way) # 3.33 generator # listA = list(range(4)) # listB = list(range(4)) # product =[] # # product = [(a,b) for a in listA for b in listB if a%2 == 0 and b%2 == 1] # % podzielne przez # print(product) # # generatorek = ((a,b) for a in listA for b in listB if a%2 == 0 and b%2 == 1) # print(next(generatorek)) # print('-----') # for g in generatorek: # print(g) # generator przechowuje 'temp' dane. 1 pare pobralem recznie, 3 pobrala petla # # # druga opcja z while # print('-----') # generatorek = ((a,b) for a in listA for b in listB if a%2 == 0 and b%2 == 1) # while True: # try: # print(next(generatorek)) # except StopIteration: # print('wszystko') # break # 3.34 zadanie # ports = ['WAW', 'KRK', 'GDN', 'KTW', 'WMI', 'WRO', 'POZ', 'RZE', 'SZZ', # 'LUZ', 'BZG', 'LCJ', 'SZY', 'IEG', 'RDO'] # # flights_gen = ((a,b) for a in ports for b in ports) # flights_unique = ((a,b) for a in ports for b in ports if a!=b) # for item in flights_unique: # print(item) # # usuwam duplikaty A-B B-A szukajac pozycji A i B na liscie i porownujac # # zamiast index zadziala tez prostsze a<b # flights_1way = [(a,b) for a in ports for b in ports if a!=b and ports.index(a)<ports.index(b)] # print(flights_1way) # 3.36 eval # var_x = 10 # password = 'secret password' # source = 'password' # result = eval(source) # eval uruchamia kod przechowywany pod zmienna # print(result) # # print(globals()) # globals pokazuje wszystkie zmienne w srodowisku # globals_copy = globals().copy() # 3.37 zadanie - cos tu nie dziala import math # arg = [a /10 for a in range(0, 101)] # print(arg) # # funkcja = input('podaj wzor f: ') # for x in arg: # exec(funkcja) # print(y) # 3.39 exec() # var_x = 10 # source = 'var_x = 4' # result = exec(source) # exec uruchamia kod przechowywany pod zmienna lub w pliku, nie zwraca wartosci # print(result) # w exec mozna wykonac >1 linie kodu, moze zmieniac wartosci # print(var_x) # 3.40 zadanie exec # import os # paths = [r'C:\Users\MD\PycharmProjects\udemy_py_sred_zaaw',r'3.40 zadanie A.py', # r'C:\Users\MD\PycharmProjects\udemy_py_sred_zaaw',r'3.40 zadanie B.py'] # path_join = [os.path.join(paths[0], paths[1]), os.path.join(paths[2], paths[3])] # # for file in path_join: # with open(file) as f: # otworz plik i wczytaj kod # print(os.path.basename(file)) # source = f.read() # result = exec(source) # print(result) # 3.42 compile # import time # # reportline = 0 # source = 'reportline += 1' # start = time.time() # for i in range(10000): # exec(source) # # print(reportline) # zwraca zmienna po wykonaniu kodu w source # stop = time.time() # time_not_compiled = stop-start # # start = time.time() # compiled = compile(source, 'pobrano ze zmiennej', 'exec') # for i in range(10000): # exec(compiled) # do exec trzeba podac prekompilowany kod do wykonania # stop = time.time() # time_compiled = stop-start # # # skompilowany kod jest 20x szybszy. Przy duzej ilosci danych dobrze skompilowac fragment kodu uzywajac exec # # i podawac go w zmiennej do wykonania # # print(time_not_compiled, time_compiled, time_not_compiled/time_compiled) # # 3.43 zadanie compile # import time, math # formulas_list = [ # "abs(x**3 - x**0.5)", # "abs(math.sin(x) * x**2)" # ] # # args = [] # for i in range(100000): # args.append(i/10) # # for formula in formulas_list: # results = [] # start = time.time() # print(formula) # # for x in args: # result = eval(formula) # eval zwraca wartosc kodu, exec nie # results.append(result) # stop = time.time() # print('min: {}, max: {}, time: {}'.format(min(results), max(results), stop-start)) # # # for formula in formulas_list: # compiled_formula = compile(formula, 'ze zmiennej', 'eval') # kompilacji podlega tylko string # results = [] # start = time.time() # print(formula) # for x in args: # result = eval(compiled_formula) # eval zwraca wartosc kodu, exec nie. # results.append(result) # stop = time.time() # print('min: {}, max: {}, time: {}'.format(min(results), max(results), stop-start))
cbb7c5528897836a536ed94c851de0b186460bb5
pauloalwis/python3
/leia.largura.altura.de.uma.parede.py
537
4
4
# Leia a largura e a altura de uma parede em metros, calcule a sua área e a quantidade # de tinta necessária para pintá-la, sabendo que cada litro de tinta, pinta uma área de 2m² largura = float(input('Digite a largura de uma parede em metros! ')) altura = float(input('Digite a altura de uma parede em metros! ')) area = largura * altura print('Sua parede tem a dimensão de {}x{} e sua área é de {}m².'.format(largura, altura, area)) print('Para pintar essa parede, você prescisará de {:.3f}l de tinta.'.format(area / 2))
098459b4e0cbf7f0b106d153cf04bd8107e39920
Aasthaengg/IBMdataset
/Python_codes/p03136/s742640874.py
170
3.53125
4
n = int(input()) list01 = input().split() list02 = sorted([int(s) for s in list01]) a = sum(list02) - list02[-1] if list02[-1] < a: print('Yes') else: print('No')
502c7caf3223ce5dce9d9547c5ce0a8556a78deb
msk20msk20/Python
/20190918_24.py
190
3.671875
4
print ("Hello PYTHON") a = 100 b = 200 print (a + b) c = input() print (c) n = 10 m = 100 if (n%2 == 0): print ("me") if (m%2 == 0): print ("me, my friend")
19c29551480f5b953b73c61f53d720041bc3df85
Rushi21-kesh/30DayOfPython
/Day-14/Day-14_Yukta.py
295
3.84375
4
arr = [] n = int(input("Enter the number of elements : ")) for i in range (0,n): ele = int(input()) arr.append(ele) for i in range (0,n): for j in range(0,n-1): if(arr[i] < arr[j]): temp = arr[i] arr[i] = arr[j] arr[j] = temp print(arr)
e629b1cbabbeed0edad4b80d5c8a5df4d8af3b65
katgzco/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/0-add_integer.py
441
4.15625
4
#!/usr/bin/python3 """ This is the module for add_integer """ def add_integer(a, b=98): """ add_integer' that add two number """ handle_a = isinstance(a, (int, float)) handle_b = isinstance(b, (int, float)) if handle_a is False or handle_b is False: raise TypeError("{} must be an integer" .format("a" if handle_a is False else "b")) else: return int(a) + int(b)
27c2c85b7cda526fcaacfb4eda5cec4f54098c48
niandrea/comp110-21f-workspace
/exercises/ex01/numeric_operators.py
383
4.0625
4
"""COMP 110 Exercise 01, Numeric Operators.""" __author__ = "730396438" x: str = input("Left-hand side: ") y: str = input("Right-hand side: ") num_1 = int(x) num_2 = int(y) print(x + ' ** ' + y + " is " + str(num_1 ** num_2)) print(x + ' / ' + y + " is " + str(num_1 / num_2)) print(x + ' // ' + y + ' is ' + str(num_1 // num_2)) print(x + ' % ' + y + ' is ' + str(num_1 % num_2))
c02ebf7f8f1bea0c83494695ec6a4e6735afe075
ObiOscar/VariosEjerciciosPython
/desconposicionPrimos.py
1,284
4.0625
4
# Para que un numero sea primo, unicamente tiene que dividirse dos veces: # 1 - divisible entre 1 # 2 - divisible entre el mismo # En este bucle, empezamos por el dos hasta un numero anterior a el, por lo # que si en el bucle, alguna vez se divide el numero, quiere decir que no es # primo numeroFactorial = int(input("Introduce un numero para descomponerlo factorialmente --> ")) numeroOperar = numeroFactorial contador = 0; contador2 = 0 listaFactoriales = [] restoFactoriales = [] divisiblePorSiMismo = True resultadoProvisional = 0 while divisiblePorSiMismo == True: for x in [2,3,5,7,11]: if numeroOperar%x == 0: numeroOperar = numeroOperar / x listaFactoriales.append(x) divisiblePorSiMismo = True print("empieza if" + str(x)) break elif numeroOperar%numeroOperar == 0 and divisiblePorSiMismo==True: print("empieza elseif" + str(numeroOperar)) divisiblePorSiMismo = False restoFactoriales.append(numeroOperar) continue else: print ("FIN") while contador < len(listaFactoriales): print ("Bucle grande") print(str(listaFactoriales[contador])) contador += 1 contador = 0 while contador < len(restoFactoriales): print("Bucle pequeño") print(str(restoFactoriales[contador])) contador += 1
c9148793ee981c1ce4d21c13980254d3e35437fc
hortygp/github-course
/strings.py
419
3.875
4
#s1= 'aaa' #print(s1) #s="para voce meu amor" #print (s[0]) #print (s[5:10]) # cortar de 5 até 10 #print (s[: :-1]) de tras pra frente #print (s[: : 5]) passo de 5 em 5 #exemplo1 #s='iterando strings' #for c in s: # print (c) #exemplo 2 #s='iterando strings' #indice = 0 #while indice < len(s): # print(indice, s[indice]) # indice+=1 #exemplo 3 for k, v in enumerate('iterando strings'): print(k, v)
9a83017150ebebc3bd4d819e9d152adea77243d0
cloubao/ISY_150_HOMEWORK
/week3/file_manipulation.py
684
4.0625
4
#!/usr/bin/python # Open the file for writing file = open("test.txt","w") file.write("Hello world\n") file.close() # Open the file for appending file = open("test.txt","a") file.write("This is the end\n") file.close() # Open the file for reading and modification file = open("test.txt","r+") # Print file contents print "Current contents are:\n" + file.read() # Go to the end of the file and append file.seek(0,2) print "Starting file length is %d" % file.tell() file.write("This is the new end!\n") print "End file length is %d" % file.tell() # Go back to the beginning of the file for reading file.seek(0,0) print "\nNew contents are:\n" + file.read() file.close()
7c95706ca1a9fe0df282f57b9da18c1639a508ae
Mudassir-Hasan/python-46-simple-exercise
/17.py
1,007
4.28125
4
# QUESTION : # 17. Write a version of a palindrome recognizer that also accepts phrase palindromes # such as "Go hang asalami I'm a lasagna hog.", "Was it a rat I saw?", "Step on no pets", # "Sit on a potato pan, Otis", "Lisa Bonetate no basil", "Satan, oscillate my metallic sonatas", # "I roamed under it as a tired nude Maori", "Rise to votesir", or the exclamation "Dammit, I'm mad!". # Note that punctuation, capitalization, and spacing are usuallyignored. # Solution : import string def palindrome(sen) : unwanted = list(string.punctuation + ' ') # loop for ignore punctuations: for i in sen: if i in unwanted: sen = sen.replace(i , '') # to chech whether it is palindrome or not: sen = sen.lower() new_sen = sen[ ::-1] if (sen == new_sen) : return True else: return False sen = input('enter a sentence : ') # calling a function: f = palindrome(sen) print(f)
4ec9764a6923f491e54b3855ff2f82b1791f83fb
harishjhaldiyal/CTCI-Solutions-in-Python
/4.8.py
1,366
4.125
4
""" 6 5 7 9 0 1 2 nodeA = 7 nodeB = 2 smaller example: 8 0 9 nodeA = 9 nodeB = 0 special case: 8 6 Pseudocode: 1) if root.left exists, search on the left subtree of the root whether both nodes (a), or either node (b), or no node exist (c) 2) otherwise update the root node to root.right and repeat step 1 a) update root node to the left child of the actual root node and repeat step 1 b) return root node c) update root node to the right child of the actual root node and repeat step 1 3) if root node is nodeA or nodeB, then return root node time complexity: O (n) -> n is the number of nodes space complexity: O (n) """ # code: def lowestCA ( nodeA, nodeB, root ): if ( root == nodeA or root == nodeB ): return root.value if ( root.left is not None ): foundNodeA = search ( root.left, nodeA ) foundNodeB = search ( root.left, nodeB ) if ( foundNodeA and foundNodeB ): root = root.left return lowestCA ( nodeA, nodeB, root ) if ( ( foundNodeA and not foundNodeB ) or ( foundNodeB and not foundNodeA )): return root.value root = root.right return lowestCA ( nodeA, nodeB, root ) def userInterface ( nodeA, nodeB, root ): if ( input_check ( nodeA, nodeB, root ) ): return lowestCA ( nodeA, nodeB, root ) else: print ( "Invalid Input" ) return
d19711ce50c6b5c09ee52b418ed6914d98f34324
guohaoyuan/algorithms-for-work
/offer/链表/6. 从尾到头打印链表/printListFromTailToHead.py
688
3.546875
4
# -*- coding : utf-8 -*- class Solution(object): def printListFromTailToHead(self, listNode): """ 我们使用一个栈,从头到尾存储节点 再将队列逆序 :param listNode: :return: """ # 1. 特殊情况:链表为空,则返回空 if not listNode: return [] # 2. 初始化栈stack stack = [] # 3. 从头到位遍历节点 while listNode: stack.append(listNode.val) listNode = listNode.next # 4. 逆序 return stack[::-1] """ 时间复杂度:n,遍历一次链表,逆序一次栈 空间复杂度:n,使用栈 """
4d88919fa5328b8cdf7c1f120aadff09ef634fa0
gaoyang836/python_text
/learning_test/mapreduce.py
3,250
3.828125
4
#map例子 # def f(x): # return x * x # r=map(f,[1,2,3,4,5,6,7,8,9]) # print(list(r)) #列表生成式 # print([n*n for n in [1,2,3,4,5,6,7,8,9]]) #基础写法 # def f(x): # return x * x # L = [ ] # for n in [1, 2, 3, 4, 5, 6, 7, 8, 9]: # L.append(f(n)) # print(L) #insert(结果顺序就乱了) # def f(x): # return x * x # L = [ ] # for n in [1, 2, 3, 4, 5, 6, 7, 8, 9]: # L.insert(1,f(n)) # print(L) # extend把f(n)变为列表 # def f(x): # return x * x # L = [ ] # for n in [1, 2, 3, 4, 5, 6, 7, 8, 9]: # L.extend([f(n)]) # print(L) # extend把f(n)变为字典 # def f(x): # return x * x # L = [ ] # for n in [1, 2, 3, 4, 5, 6, 7, 8, 9]: # L.extend({f(n}]) # print(L) #list转化为字符串 # print(list(map(str,[1,2,3,4,5,6,7,8,9]))) #reduce # from functools import reduce # def add(x,y): # return x+y # print(reduce(add,[1,3,5,7,9])) # from functools import reduce # # def fn(x,y): # # return x*10+y # # char2num函数中参数s,按照键找到对应值返回 # #(通过map把一个整的字符串迭代单个的字符串) # def char2num(s): # digits = {'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9} # print(digits[s]) # return digits[s] # # print(reduce(fn,map(char2num,'13579'))) # print(map(char2num,'13579')) # from functools import reduce # DIGITS = {'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9} # def char2int(s): # def fn(x,y): # return x*10+y # def char2num(s): # return DIGITS[s] # return reduce(fn, map(char2num, s)) #练习 #利用map()函数,把用户输入的不规范的英文名字,变为首字母大写,其他小写的规范名字 # def normalize(name): # return name.capitalize() # L1 = ['adam', 'LISA', 'barT'] # L2 = list(map(normalize, L1)) # print(L2) #编写一个prod()函数,可以接受一个list并利用reduce()求积 # from functools import reduce # def prod(x,y): # return x*y # print(reduce(prod,[3, 5, 7, 9])) #编写一个prod()函数,可以接受一个list并利用reduce()求积 # from functools import reduce # def prod(L): # def fn(x,y): # return x*y # return reduce(fn,L) # print('3 * 5 * 7 * 9 =', prod([3, 5, 7, 9])) # if prod([3, 5, 7, 9]) == 945: # print('测试成功!') # else: # print('测试失败!') # 利用map和reduce编写一个str2float函数,把字符串'123.456'转换成浮点数123.456: from functools import reduce # def str2float(s): # def fn(x,y): # return x*10+y # n=s.index('.') # s1=list(map(int,[x for x in s[:n]])) # s2=list(map(int,[x for x in s[n+1:]])) # return reduce(fn,s1)+reduce(fn,s2)/(10**len(s2))#乘幂 # print('str2float(\'123.456\') =', str2float('123.456')) # if abs(str2float('123.456') - 123.456) < 0.00001: # print('测试成功!') # else: # print('测试失败!') #用filter求素数 def _odd_iter(): n=1 while True: n=n+2 yield n def _not_divisible(n): return lambda x:x % n > 0 def primes(): yield 2 it = _odd_iter() while true: n=next(it) yield n it = filter(_not_divisible(n),it) for n in primes(): if n<1000: print(n) else: break
faf173dbc8ed51a013a7f33ed7f304f11cc157d3
nthomps49/firstlocalrepos
/Projects/Learning/addandsub4draft.py
986
4.34375
4
output_text = 'Hello, welcome to my math program\n' print(output_text) while True: try: choice = int(input("Choose 1 to add or 2 to subtract ") break if choice != 'add' or 'sub' or 'subtract': print('You must make a choice') exit() if choice == 'add': quantity = input('How many numbers do you want to add? ') x = 0 s = 0 while x < int(quantity): x += 1 s += (int(input('Enter a number: '))) print('The sum of the numbers is ' + str(s)) elif choice == 'subtract' or 'sub': quantity = input('How many numbers do you want to subtract? ') first_element = int(input('What is the number to start subtracting from? ')) x = 1 s = 0 while x < int(quantity): x += 1 s += (int(input('Enter a number: '))) s1 = int(first_element) - int(s) print('The subtraction equates to ' + str(s1)) else: choice != 'add' or 'subtract' or 'sub' print('You must make a choice')
220cf768d4ec91f744f25da362d19969e38e7c52
federicoemartinez/problem_solving
/leetcode/vowel-spellchecker.py
1,465
3.65625
4
# https://leetcode.com/problems/vowel-spellchecker/ import re class Solution(object): def spellchecker(self, wordlist, queries): """ :type wordlist: List[str] :type queries: List[str] :rtype: List[str] """ d = {} d_vowels = {} for each in wordlist: lower_each = each.lower() if lower_each not in d: d[lower_each] = (set(), [each]) d[lower_each][0].add(each) without_vowel_each = re.sub('[aeiou]', 'a', lower_each, flags=re.I) if without_vowel_each not in d_vowels: d_vowels[without_vowel_each] = (set(), [each]) d_vowels[without_vowel_each][0].add(each) res = [] for each in queries: lower_each = each.lower() if lower_each in d: s,l = d[lower_each] if each in s: res.append(each) else: res.append(l[0]) else: without_vowel_each = re.sub('[aeiou]', 'a', lower_each, flags=re.I) if without_vowel_each in d_vowels: s, l = d_vowels[without_vowel_each] if each in s: res.append(each) else: res.append(l[0]) else: res.append("") return res
3fdb80ff384d96bd95b0ba6f5de8b4638acedffb
njdevengine/python-stats
/quartiles.py
751
3.8125
4
# Dependencies import matplotlib.pyplot as plt from stats import median import numpy as np ### Data Points arr = np.array([2.3, 10.2,11.2, 12.3, 14.5, 14.6, 15.0, 15.1, 19.0, 24.0]) arr # Find the median median(arr) # Use numpy to create quartiles q0 = np.quantile(arr,0) q1 = np.quantile(arr,.25) q2 = np.quantile(arr,.5) q3 = np.quantile(arr,.75) q4 = np.quantile(arr,1) # Print the quartiles print(q0) print(q1) print(q2) print(q3) print(q4) # Calculate the interquartile range iqr = q3-q1 iqr # Find lower boundary low = q1 - 1.5 * iqr # Find upper boundary upper = q3 + 1.5 * iqr # Check for any lower outliers for num in arr: if num <= low: print(str(num) + " lower") elif num <= upper: print(str(num)+ " upper")
7cd139f0a3122b6e8302103be4538817ed426dcd
RaviC19/Rock-Paper-Scissors-Python
/rps_with_random_choice.py
1,335
4.28125
4
from random import choice for i in range(3): player = input("What is your choice? ").lower() options = ["Rock", "Paper", "Scissors"] computer = choice(options) print(player) print(f"The Computer chose {computer}") if player.lower() == computer.lower(): print("You and the computer chose the same option, this game is a draw") elif player == "rock": if computer == "Scissors": print("You chose Rock and the computer chose Scissors. Your Rock Wins!") elif computer == "Paper": print( "You chose Rock and the computer chose Paper. The Computer's Paper Wins!") elif player == "paper": if computer == "Rock": print("You chose Paper and the computer chose Rock. Your Paper Wins!") elif computer == "Scissors": print( "You chose Paper and the computer chose Scissors. The Computer's Scissors Wins!") elif player == "scissors": if computer == "Rock": print( "You chose Scissors and the computer chose Rock. The Computer's Rock Wins!") elif computer == "Paper": print("You chose Scissors and the computer chose Paper. Your Scissors Wins!") else: print("You entered something that wasn't Rock, Paper or Scissors")