blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
3a2757a475ab406af61d18d472f6e98c8c6c6486
xiaojiangzhang/algorithm010
/Week09/Assignment/[85]最大矩形.py
1,106
3.578125
4
# 给定一个仅包含 0 和 1 的二维二进制矩阵,找出只包含 1 的最大矩形,并返回其面积。 # # 示例: # # 输入: # [ # ["1","0","1","0","0"], # ["1","0","1","1","1"], # ["1","1","1","1","1"], # ["1","0","0","1","0"] # ] # 输出: 6 # Related Topics 栈 数组 哈希表 动态规划 # 👍 539 👎 0 # leetcode submit region begin(Prohibit modification and deletion) class Solution(object): def maximalRectangle(self, matrix): """ :type matrix: List[List[str]] :rtype: int """ maxArea = 0 dp = [[0] * len(matrix[0]) for _ in range(len(matrix))] for i in range(len(matrix)): for j in range(len(matrix[0])): if matrix[i][j] == '0': continue width = dp[i][j] = dp[i][j - 1] + 1 if j else 1 for k in range(i, -1, -1): width = min(width, dp[k][j]) maxArea = max(maxArea, width * (i - k + 1)) return maxArea # leetcode submit region end(Prohibit modification and deletion)
a457e98793396b428a5c0620b50861b481faa2d9
Apizz789/DATA_STRUCTURES_AND_ALGORITHM
/LAB_04_Queue/4.4.py
3,083
3.796875
4
class Queue: def __init__(self): self.item = [] def enqueue(self, data): self.item.append(data) def dequeue(self): self.item.pop(0) def print_program1(self): print('My Activity:Location = ', end='') i = 0 while i < len(self.item)-1: print(self.item[i], end=', ') i += 1 print(self.item[len(self.item)-1]) def print_program2(self): print('Your Activity:Location = ', end='') i = 0 while i < len(self.item)-1: print(self.item[i], end=', ') i += 1 print(self.item[len(self.item)-1]) def my_program(lst): act = {0: 'Eat', 1: 'Game', 2: 'Learn', 3: 'Movie'} loc = {0: 'Res.', 1: 'ClassR.', 2: 'SuperM.', 3: 'Home'} program1 = Queue() for ew in lst: s = '' for i in range(len(act)): if int(ew.split(':')[0]) == i: s += str(act[i]) s += ':' for j in range(len(loc)): if int(ew.split(':')[1]) == j: s += str(loc[j]) program1.enqueue(s) program1.print_program1() def ur_program(lst): act = {0: 'Eat', 1: 'Game', 2: 'Learn', 3: 'Movie'} loc = {0: 'Res.', 1: 'ClassR.', 2: 'SuperM.', 3: 'Home'} program2 = Queue() for ew in lst: s = '' for i in range(len(act)): if int(ew.split(':')[0]) == i: s += str(act[i]) s += ':' for j in range(len(loc)): if int(ew.split(':')[1]) == j: s += str(loc[j]) program2.enqueue(s) program2.print_program2() def compare_score(pro1, pro2): score = 0 i = 0 while i < len(pro1): if pro1[i].split(':')[0] == pro2[i].split(':')[0] and pro1[i].split(':')[1] == pro2[i].split(':')[1]: score += 4 elif pro1[i].split(':')[0] != pro2[i].split(':')[0] and pro1[i].split(':')[1] == pro2[i].split(':')[1]: score += 2 elif pro1[i].split(':')[0] == pro2[i].split(':')[0] and pro1[i].split(':')[1] != pro2[i].split(':')[1]: score += 1 elif pro1[i].split(':')[0] != pro2[i].split(':')[0] and pro1[i].split(':')[1] != pro2[i].split(':')[1]: score -= 5 i += 1 if score >= 7: print('Yes! You\'re my love! : Score is %d.' % score) elif 0 < score < 7: print('Umm.. It\'s complicated relationship! : Score is %d.' % score) elif score <= 0: print('No! We\'re just friends. : Score is %d.' % score) if __name__ == '__main__': inp = input('Enter Input : ').split(',') me = [] u = [] for e in inp: me.append(e.split(' ')[0]) u.append(e.split(' ')[1]) i = 0 print('My Queue = ', end='') while i < len(me) - 1: print(me[i], end=', ') i += 1 print(me[len(me) - 1]) i = 0 print('Your Queue = ', end='') while i < len(u) - 1: print(u[i], end=', ') i += 1 print(u[len(u) - 1]) my_program(me) ur_program(u) compare_score(me, u)
d55e1469880f9f4db974e21f739e4e1d8373c49b
jshafto/tdd_project
/app/roman_numerals.py
354
3.5625
4
def parse(numeral): translator = { "I":1, "V":5, "X":10, "L":50, "C": 100, "D": 500, "M": 1000 } vals = [translator[c] for c in numeral] total = 0 for i in range(len(vals)-1): if vals[i]>=vals[i+1]: total+=vals[i] else: total-=vals[i] total += vals[-1] return total # print(parse("XIV"))
4bf45238e5fafadf8406218b3f0301e6abfad53b
kamladi/harder_puzzles
/flow/flow.py
8,189
3.671875
4
from random import randint import time import copy # Pipe object to connect End Points class Pipe(object): def __init__(self, color): self.color = color def __str__(self): return "Pipe:" + str(self.color) # End Points set at beginning of game class EndPoint(object): def __init__(self, color): self.color = color def __str__(self): return "End:" + str(self.color) # solve a flow board class FlowSolver(object): def solve(self, puzzle): row, col = puzzle.starting_board[0][0] solved, expanded = self.solve_color(puzzle, 0, row, col, 0) if not solved: return None return -expanded # try to move closer to end goal, then stay on edge, make admissible --> manhattan distance - hard coded values def heuristic(self, puzzle, color, row, col): end_row, end_col = puzzle.starting_board[color][1] dist = abs(row - end_row) + abs(col - end_col) return dist def solve_color(self, puzzle, color, row, col, expanded): start, end = puzzle.starting_board[color] if puzzle.is_solved_color(color, start[0], start[1], end, set([])): if color == len(puzzle.starting_board) - 1: if puzzle.is_solved(): return True, expanded return False, expanded new_row, new_col = puzzle.starting_board[color + 1][0] return self.solve_color(puzzle, color + 1, new_row, new_col, expanded + 1) next_moves = puzzle.get_valid_moves(color, row, col) if len(next_moves) == 0: return False, expanded h_moves = [] for move in next_moves: color, r, c = move h = self.heuristic(puzzle, color, r, c) h_moves.append((h, move)) for move in sorted(h_moves): color, r, c = move[1] puzzle.apply_move(color, r, c) solved, expanded_ret = self.solve_color(puzzle, color, r, c, expanded + 1) expanded = expanded_ret if solved and color == len(puzzle.starting_board) - 1: if puzzle.is_solved(): return True, expanded return False, expanded elif solved: new_row, new_col = puzzle.starting_board[color + 1][0] return self.solve_color(puzzle, color + 1, new_row, new_col, expanded + 1) puzzle.undo_move(r, c) return False, expanded # Flow board and moves class FlowPuzzle(object): def __init__(self, size, starting_board): self.size = size # map of starting boards (from last level of game) self.starting_board = starting_board self.board = self.make_init_board() # create an initial board based on size def make_init_board(self): board = [[None for _ in xrange(self.size)] for _ in xrange(self.size)] # randomly place end points for color in self.starting_board: for (r,c) in self.starting_board[color]: board[r][c] = EndPoint(color) return board # see if a move is valid def is_valid_move(self, color, row, col): return self.is_in_bounds(row,col) and self.board[row][col] is None # apply a move to the board def apply_move(self, color, row, col): self.board[row][col] = Pipe(color) # undo a move at a particular row and column def undo_move(self, row, col): self.board[row][col] = None # get all valid moves def get_valid_moves(self, color, row, col): possibilities = [(1,0), (-1,0), (0,1), (0,-1)] moves = [] for r, c in possibilities: if self.is_valid_move(color, row + r, col + c): moves.append((color, row + r, col + c)) return moves # make a random move by moving a starting or ending point def make_random_move(self): # get a random move for a random color moves = [] while len(moves) == 0: color = randint(0,len(self.starting_board)-1) start, end = self.starting_board[color] # get either start or end point start_end = randint(0,1) # get the coordinates row, col = self.starting_board[color][start_end] # get all of the moves moves = self.get_valid_moves(color, row, col) self.undo_move(row, col) color, row, col = moves[randint(0,len(moves)-1)] # update the starting point of the end point self.starting_board[color][start_end] = (row, col) self.board[row][col] = EndPoint(color) # check if board is solved def is_solved(self): # check that entire grid is not None for r in xrange(self.size): for c in xrange(self.size): if self.board[r][c] is None: return False # check that all end points are connected for color in self.starting_board: start, end = self.starting_board[color] if not self.is_solved_color(color, start[0], start[1], end, set([])): return False return True # check if a particular color is already solved using flood fill def is_solved_color(self, color, row, col, end, seen): if (row, col) == end: return True if not self.is_in_bounds(row, col): return False if self.board[row][col] is None: return False if self.board[row][col].color != color: return False rc = str(row) + str(col) if rc in seen: return False seen.add(rc) return (self.is_solved_color(color, row+1, col, end, seen) or self.is_solved_color(color, row-1, col, end, seen) or self.is_solved_color(color, row, col+1, end, seen) or self.is_solved_color(color, row, col-1, end, seen)) # see if coordinates are in bounds on the board def is_in_bounds(self, r, c): if r < 0 or r >= self.size or c < 0 or c >= self.size: return False return True # print out a game board def print_board(self): for row in self.board: for col in row: print str(col).ljust(7), print # generate a puzzle class FlowGenerator(object): def generate_puzzles(self, puzzle, solver, branching_factor, step, iterations): generations = [] for i in xrange(iterations): print("Running Iteration %d"%(i)) proposals = [] p_move = copy.deepcopy(puzzle) puzzle_efficiency = solver.solve(p_move) print puzzle_efficiency k = 0 while k < branching_factor: p_move = copy.deepcopy(puzzle) for s in xrange(step): p_move.make_random_move() efficiency = solver.solve(p_move) if efficiency is None: continue proposals.append((efficiency, p_move)) k += 1 generations.append((puzzle_efficiency,puzzle)) min_efficiency,min_puzzle = min(proposals, key=lambda s:s[0]) if (min_efficiency <= puzzle_efficiency): puzzle = min_puzzle return (puzzle, generations) starting_pos = { 2: {0: [(0,0),(1,0)], 1: [(0,1),(1,1)]}, 4: {0: [(1,0),(3,1)], 1: [(3,0),(1,1)]}, 5: {0: [(0,0),(3,2)], 1: [(0,4),(4,2)], 2: [(2,1),(4,1)], 3: [(4,0),(2,2)]}, 6: {0: [(1,0),(3,5)], 1: [(1,1),(4,5)], 2: [(1,3),(4,4)], 3: [(2,1),(4,1)], 4: [(5,0),(3,1)]}, 7: {0: [(0,0),(4,0)], 1: [(0,2),(0,4)], 2: [(0,5),(3,6)], 3: [(1,0),(4,2)], 4: [(1,2),(2,4)], 5: [(1,5),(3,4)], 6: [(4,1),(5,5)]}, 8: {0: [(0,4),(0,6)], 1: [(0,5),(3,5)], 2: [(1,4),(6,3)], 3: [(1,6),(3,6)], 4: [(2,2),(4,2)], 5: [(4,3),(6,1)], 6: [(6,2),(5,5)]} } n = 4 P = FlowPuzzle(n, starting_pos[n]) S = FlowSolver() G = FlowGenerator() branching_factor = 1 step = 1 iterations = 10
4a7f97a31ff4fe52d0da8992feb3b9713ad218cb
DzulCancheJ/Ejercicios-Python
/Programa7.py
264
3.90625
4
#Programa 7 Intervalo de cuadrados de n numeros mayores a 100 numero=int(input("Ingresa un numero: ")) def intervalo(X): for x in range(X): resultado = pow(x+1,2) if resultado>100: print(x+1,"^2 es:", resultado) intervalo(numero)
f33e5381871821b2d9d2bfae7577a75131a1c943
breadpitt/SystemsProgramming
/python_stuff/tuple_test.py
119
3.71875
4
#!/usr/local/bin/python3 tuple = ("hello", 3, 4) print(tuple[0]) print(tuple[1]) print(tuple) f = tuple[0] print(f)
615f4b371a0aaebfe9cee01c80a11a8b9875164a
tahir24434/py-ds-algo
/src/main/python/pdsa/lib/Heaps/max_heap.py
6,730
4.0625
4
""" Binary Heap Data Structure is an array object that we can view as a nearly complete binary tree. The tree is completely filled on all levels except possibly the lowest, which is filled from the left up to a point. In a max-heap, the max-heap property is that for every node i other than the root, A[Parent(i)] >= A[i] that is, the value of node is at most the value of its parents. Thus the largest element in a max-heap is stored at the root, and the subtree rooted at a node contains values no larger than that contained at the node itself. """ from nose.tools import assert_equal class HeapItem(object): def __init__(self, key, value=None): self.key = key self.value = value def __lt__(self, other): return self.key < other.key def __gt__(self, other): return self.key > other.key class MaxHeap(object): # Since the entire binary heap can be represented by a single list, all # the constructor will do is initialize the # list and an attribute currentSize to keep track of the current size of # the heap def __init__(self): # notice that an empty binary heap has a single zero as the first # element of heapList and that this zero is not used, but is there # so that simple integer division can be used in later methods. self._data = [0] self._size = 0 @staticmethod def _parent(i): return i//2 @staticmethod def _left(i): return 2*i @staticmethod def _right(i): return 2 * i + 1 def _has_left(self, i): return self._left(i) <= self._size # index beyond end of list? def _has_right(self, i): return self._right(i) <= self._size # index beyond end of list? def _swap(self, i, j): self._data[i], self._data[j] = self._data[j], self._data[i] def __len__(self): return self._size def _max_heapify(self, i): """ max_heapify assumes that the binary tree rooted at left(i) and right(i) are max-heaps, but that A[i] might be smaller than its children, thus violating the max-heap property. max_heapify() lets the value at _data[i] 'float down' in the max-heap so that the subtree rooted at index i obeys the max-heap property. It runs in O(lgn) time. Parameters ---------- i : int index of the element which is violating the max-heap property. Returns ------- """ if self._has_left(i): left = MaxHeap._left(i) bigger_child = left if self._has_right(i): right = MaxHeap._right(i) if self._data[right] > self._data[left]: bigger_child = right if self._data[bigger_child] > self._data[i]: # Exchange A[i] with A[largest_val_idx] self._swap(i, bigger_child) # Call max_heapify self._max_heapify(bigger_child) def build_heap_from_list(self, item_lst): """ We can use the procedure max-heapify in a bottom-up manner to convert an array A[1 .. n], where n=A.length, into a max-heap. Elements in the subarray A[(floor(n/2)+1) .. n] are all leaves of the tree, and so each is a 1-element heap to begin with. The procedure Build-max-heap goes through the remaining nodes of the tree and run max-heapify on each one. Returns ------- """ self._size = len(item_lst) self._data = [HeapItem(0, 0)] + item_lst[:] for i in range(self._size // 2, 0, -1): self._max_heapify(i) def increase_key(self, i, key): """ Parameters ---------- i : int index i identifies the priority queue element whose key we wish to increase. key new key with whom existing key will be replaced. Returns ------- """ if key < self._data[i].key: print ("new key is smaller than the current key") return self._data[i].key = key while i > 1 and self._data[MaxHeap._parent(i)] < self._data[i]: # exchange items at i and parent self._swap(i, MaxHeap._parent(i)) i = MaxHeap._parent(i) def insert(self, key, value=None): """ Insert takes as an input the key of the new element to be inserted into max-heap. """ self._size += 1 self._data.append(HeapItem(float("-inf"), value)) self.increase_key(self._size, key) def extract_max(self): """ Extract the maximum element of heap. It takes O(lgn) time """ if self._size == 0: raise Exception("Empty heap") # Root item is max. max_item = self._data[1] # To restore root, place last item as root self._data[1] = self._data.pop() self._size -= 1 # restore heap order property by moving root to appropriate place. # Swap the root with its smallest child less than the root. Keep doing # this unless root becomes smaller than both of his children. self._max_heapify(1) return max_item def get_max(self): """ Get maximum element of heap in O(1) time. """ if self._size == 0: raise Exception("Empty heap") return self._data[1] def sort(self, item_lst): """ Sorts the input array. """ self.build_heap_from_list(item_lst) while self._size > 1: self._data[1], self._data[self._size] = \ self._data[self._size], self._data[1] self._size -= 1 self._max_heapify(1) if __name__ == '__main__': key_val = {4: "", 1: "", 3: "", 2: "", 16: "", 9: "", 10: "", 14: "", 8: "", 7: ""} item_lst = [] for key, val in key_val.items(): item_lst.append(HeapItem(key, val)) mh = MaxHeap() mh.sort(item_lst) sorted_list = [] for item in mh._data: sorted_list.append(item.key) assert_equal(sorted_list, [0, 1, 2, 3, 4, 7, 8, 9, 10, 14, 16]) # Test priority queue key_val = {4: "", 1: "", 3: "", 2: "", 16: "", 9: "", 10: "", 14: "", 8: "", 7: ""} item_lst = [] for key, val in key_val.items(): item_lst.append(HeapItem(key, val)) mh = MaxHeap() mh.build_heap_from_list(item_lst) mh.insert(5) assert_equal(mh.get_max().key, 16) assert_equal(mh.extract_max().key, 16) assert_equal(mh.extract_max().key, 14) mh.insert(25) assert_equal(mh.extract_max().key, 25) print("SUCCESS ...")
d77424cb96b871a0319ca766f6bdfbf174162c4c
MandeepSingh35/Training
/table.py
124
3.828125
4
a = int(input("Enter the number of which table you want to print")) for i in range(1, 11): print(i , " X ", a, " = ", i*a )
32de5f1a1efd188c92992adf668a483f4482f66b
Jasoncho1125/PythonTest
/py_p167.py
282
3.796875
4
import turtle import random import time t = turtle.Turtle() t.speed(0) t.width(3) colors = ["red","green","blue","orange","purple","pink","yellow"] for angle in range(100): t.color(random.choice(colors)) t.left(angle * 7) t.circle(100) time.sleep(3) # t.mainloop()
136cd2871e62c6d1cdf071d2e523926611196b01
MajorGerman/Python-Programming-Georg-Laabe
/Депозит и Футбольная команда.py
1,447
3.9375
4
#Набор в футбольную команду print("Программа набора в футбольную команду") while True: sex = input("Выберите пол (М/Ж) : ") if sex == "Ж": print("Вы нам не подходите!");break elif sex == "М": age = int(input("Введите ваш возраст: ")) if age in range (16,19): print("Вы нам подходите!");break else: print("Вы нам не подходите!");break else: print("Выберите корректный пол!");continue #Депозитный банк print("Депозитный банк") money = int(input("Введите сумму депозита : ")) percent = int(input("Введите процент: ")) years = int(input("Введите количество лет: ")) benefit = 0 print("") for x in range(1,years+1): print("#", x, "Начальная сумма - ", "{0:2d}".format(int(round(money,2))), ", интресс - ", "{0:2d}".format(int(round(money * (percent / 100),2))),", итоговая сумма - ", "{0:2d}".format(int(round(money + money * (percent / 100),2)))) benefit += money * (percent / 100); money += money * (percent / 100) print("");print("Итоговая сумма составила - ",round(money, 2),", а прибыль составила - ", round(benefit,2))
2bf16a28b351a74c94ccdc2849442ecf7eb7a595
AbbelDawit/Python
/Float_Average/FloatAverage.py
458
4.21875
4
#Name: Abbel Dawit #Date: 09/15/2015 #Email: abbeldawit@gmail.com #Description: Script takes in 3 floating point numbers and calculates the average. def main(): number1 = input("Please enter a floating point number: ") number2 = input("Please enter a floating point number: ") number3 = input("Please enter a floating point number: ") num4 = (number1+number2+number3)/3 print("The Average of the three floats is:", num4) main()
9b63444f7b4e4aad95011a034a8644a52af82515
JigarShah110/Python
/Pattern/pattern1.py
548
3.953125
4
class SimplePlaybutton: row_counter = 1 # Class variable for counting row def __init__(self): """Constructor of which will be called automatically""" self.height = input("Enter Height: ") self.symbol = "*" self.total_height = self.height*2 - 1 def draw(self): """Method which will draw pattern""" for row_counter in range(1, (self.total_height)+1): if row_counter <= self.height: print row_counter * self.symbol else: print self.symbol * (self.total_height-row_counter+1) button1 = SimplePlaybutton() button1.draw()
90d8dbb82881991a3818bebf5c426f114d44b7ec
katherinehuwu/Word_Fit
/vocab_resources/lemma.py
516
3.8125
4
"""Creates a lemmatized dictionary of all academic words""" def create_lemma_dict(lemma_file): """Creates a dictionary of lemmatized academic words. For each pair, the key is the word inflection; the value is the stem.""" academic_words= open(lemma_file) LEMMA_DICT = {} for line in academic_words: line =line.rstrip().rstrip(',') words = line.split(',') stem = words[0] for word in words: LEMMA_DICT[word] = stem return LEMMA_DICT LEMMA_DICT = create_lemma_dict('vocab_resources/Lemma.csv')
6015fef2dbd9cb7ab940198eb30b57b11c7db6b6
Oussama1342/RecomandationSystem
/FonctionModuChap5.py
1,220
3.8125
4
import math def table_par_7(): nb = 7 i = 0 # Notre compteur ! L'auriez-vous oublié ? while i < 10: # Tant que i est strictement inférieure à 10, print(i + 1, "*", nb, "=", (i + 1) * nb) i += 1 # On incrémente i de 1 à chaque tour de boucle. ########################### #def table(nb): # i=0 # while i<10: # print(i + 1, "*", nb, "=", (i + 1) * nb) # i+=1 ################Exempl3######### def table(nb, max): i=0 while i<max: print(i + 1, "*", nb, "=", (i + 1) * nb) i+=1 ################Exempl4######### def table(nb, max=20): i=0 while i<max: print(i + 1, "*", nb, "=", (i + 1) * nb) i+=1 ###################Exrmple5###### def fonc(a=1, b=2, c=3, d=4, e=5): print("a =", a, "b =", b, "c =", c, "d =", d, "e =", e) ##########Surcharge#######333 def exemple(): print("Un exemple d'une fonction sans paramètre") def exemple(): # On redéfinit la fonction exemple print("Un autre exemple de fonction sans paramètre") #################Return###########33 def carre(valeur): return valeur * valeur a= carre(5) val = lambda x:x*x test = math.sqrt(5)
2f3c0ff1eb25456fb23571150c0f3377b723f8a9
QuartzShard/Turtle-Client-and-server
/Client/Programs/TestTurt2.py
191
3.859375
4
import turtle def triangle(length): for i in range(3): turtle.forward(length) turt.right(120) for i in range(8): triangle(25) turtle.right(45) turt.exitonclick()
465da8501ba191711ea6566a7ac1d240dc515def
BlueMonday/advent_2015
/12/12.py
697
3.859375
4
#!/usr/bin/env python import json import sys def sum_of_all_numbers(o): if isinstance(o, dict): sum_of_dict = 0 for _, v in o.items(): if v == 'red': return 0 sum_of_dict += sum_of_all_numbers(v) return sum_of_dict elif isinstance(o, list): sum_of_list = 0 for item in o: sum_of_list += sum_of_all_numbers(item) return sum_of_list elif isinstance(o, str): return 0 elif isinstance(o, int): return o raise Exception("Unsupported type") if __name__ == '__main__': with open(sys.argv[1]) as f: o = json.load(f) print(sum_of_all_numbers(o))
f9c19d43cf8d0aaa75e34122549883049b837d49
Hassanabazim/Python-for-Everybody-Specialization
/2- Python Data Structure/Week_4/8.5.py
1,008
4.375
4
''' 8.5 Open the file mbox-short.txt and read it line by line. When you find a line that starts with 'From ' like the following line: From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008 You will parse the From line using split() and print out the second word in the line (i.e. the entire address of the person who sent the message). Then print out a count at the end. Hint: make sure not to include the lines that start with 'From:'. Also look at the last line of the sample output to see how to print the count. You can download the sample data at http://www.py4e.com/code3/mbox-short.txt ''' file = input("Enter the file name :") try: fh = open(file) except: print("The file does not exist") quit() count = 0 for line in fh: line = line.lstrip() if not line.startswith('From:'): continue words = line.split() if len(words) < 1 : continue count = count + 1 print(words[1]) count_str = str(count) print(("There were ") + count_str + (" lines in the file with From as the first word"))
e066645abef01fe4754cb6d545dc7645c1e1e2a7
dpaneda/code
/jams/euler/29.py
147
3.75
4
#!/usr/bin/env python3 MAX = 100 terms = set() for a in range(2, MAX + 1): for b in range(2, MAX + 1): terms.add(a**b) print(len(terms))
40593a314660770b97667c58bb78a7d880d93f66
RonaldoDs/...
/ListaDuplamenteEncadeada.py
2,954
3.578125
4
'''Universidade Federal de Pernambuco (UFPE) (http://www.ufpe.br) Centro de Informtica (CIn) (http://www.cin.ufpe.br) Graduando em Sistemas de Informao Autor: Ronaldo Daniel da Silva (rds) Email: rds@cin.ufpe.br Data: 06/06/2018 Descrio: Implementao de Lista Duplamente Encadeada utilizando POO. Copyright(c) 2018 Ronaldo Daniel da Silva''' class No: def __init__(self,item=None, ante=None ,prox=None): self.item = item self.ante = ante self.prox = prox class Lista: def __init__(self): self.primeiro = self.ultimo = No() def vazia(self): return self.primeiro == self.ultimo def pesquisar(self,item): if self.vazia(): return None aux = self.primeiro.prox while aux != None and aux.item != item: aux = aux.prox item = aux.item return item def addFinal(self,item): novoNo = No(item,self.ultimo,None) self.ultimo.prox = novoNo self.ultimo = self.ultimo.prox def addInicio(self,item): novoNo = No(item,self.primeiro,self.primeiro.prox) self.primeiro.prox = novoNo if self.vazia(): self.ultimo = novoNo else: novoNo.prox.ante = novoNo def remover(self,item): if self.vazia(): return None aux = self.primeiro.prox while aux != None and aux.item != item: aux = aux.prox if aux == None: return None elif aux.prox == None: item = aux.item aux.ante.prox = None self.ultimo = aux.ante del aux return item else: item = aux.item aux.prox.ante = aux.ante aux.ante.prox = aux.prox del aux return item def removerInicio(self): if self.vazia(): return None delNo = self.primeiro.prox #No a ser deletado delNo.prox.ante = self.primeiro #Muda a referencia do anterior do proximo no a ser deletado(passa a apontar para o primeiro No) self.primeiro.prox = delNo.prox #muda a referencia do proximo do primeiro No(No de cabeca) temp = delNo del temp return delNo.item def removerFinal(self): if self.vazia(): return None delNo = self.ultimo self.ultimo = delNo.ante self.ultimo.prox = None item = delNo.item del delNo return item def __str__(self): aux = self.primeiro.prox modelo = '[' while aux != None: modelo += str(aux.item) + ',' aux = aux.prox modelo = modelo.strip(',') modelo += ']' return modelo def __repr__(self): return self.__str__()
f5e08be961af6b18383ea6bfef138fa1ff3ee06c
xiangkangjw/interview_questions
/leetcode/python/103_binary_tree_zigzag_level_order_traversal.py
1,121
3.78125
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def zigzagLevelOrder(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ if not root: return [] stack = [root] direction = 0 res = [] while stack: cur_level = [] next_level = [] for item in reversed(stack): cur_level.append(item.val) if direction == 0: if item.left: next_level.append(item.left) if item.right: next_level.append(item.right) else: if item.right: next_level.append(item.right) if item.left: next_level.append(item.left) stack = next_level direction = (direction + 1) % 2 res.append(cur_level) return res
bde33bdc63fd18132677c34354f3b92c5965c16e
j16949/Programming-in-Python-princeton
/1.5/test.py
214
3.890625
4
#num_list = [1, 2, 2, 4, 5] num_list=[1, 1, 0, 2, 0, 0, 8, 3, 0, 2, 5, 0, 2, 6] print(num_list) for item in num_list: if item == 0: num_list.remove(item) else: print(item) print(num_list)
328b1e2d82cf4b201e8a556d22f979993ab903ba
praj0098/income-prediction
/Assignment/prime and armstrong.py
817
3.796875
4
## prime numbers 100 to 300 ## brute force ##prime=[] ##for i in range(100,301): ## c=0 ## for j in range(1,i+1): ## ## if(i%j==0): ## c+=1 ## ## if(c==2): ## prime.append(i) ## ##print(*prime) ################################################################## ################################################################## ## to check the num is armstrong or not def armstrong(a,a1): s=str(a) l=list(s) ans=[] for i in l: ans.append(str(pow(int(i),3))) num=0 for i in ans: num+=int(i) if(num==a1): return True else: return False a=int(input("enter the number")) a1=int(a) if(armstrong(a,a1)): print("yes") else: print("no")
97b02768d943030313bffacb0beb32c886b35942
HankerZheng/LeetCode-Problems
/python/064_Minimum_Path_Sum.py
1,219
3.59375
4
# Given a m x n grid filled with non-negative numbers, # find a path from top left to bottom right which minimizes # the sum of all numbers along its path. # Note: You can only move either down or right at any point in time. # Subscribe to see which companies asked this question # Key Point: DP # Subproblem: dp[i][j] the minimum path sum to position(i,j) # dp[i][j] = min(dp[i-1][j], dp[i][j-1]) # # Runtime: 84ms class Solution(object): def minPathSum(self, grid): """ :type grid: List[List[int]] :rtype: int """ col, row = len(grid[0]), len(grid) dp = [[0 for x in grid[0]] for y in grid] for i in xrange(row): for j in xrange(col): if i==0 and j==0: dp[i][j] = grid[i][j] elif i==0: dp[i][j] = dp[i][j-1] + grid[i][j] elif j==0: dp[i][j] = dp[i-1][j] + grid[i][j] else: dp[i][j] = min(dp[i][j-1], dp[i-1][j]) + grid[i][j] return dp[row-1][col-1] if __name__ == '__main__': sol = Solution() grid = [[1,2,3], [2,3,4], [3,4,5]] print sol.minPathSum(grid)
b7670eae848e3cfb0accc93a3f83df89a4893d9a
kxu68/BMSE
/examples/AY_2017_2018/semester_1/Week 6- Object-oriented design/original_person.py
12,522
3.65625
4
""" Person, with heredity and other characteristics :Author: Arthur Goldberg <Arthur.Goldberg@mssm.edu> :Date: 2017-10-12 :Copyright: 2017, Arthur Goldberg :License: MIT """ class Person(object): """ Person Attributes: name (:obj:`str`): a person's name gender (:obj:`str`): a person's gender mother (:obj:`Person`): a person's mother father (:obj:`Person`): a person's father children (:obj:`set` of `Person`): a person's children """ # TODO: add a data structure containing this person's variants, and methods that add a variant, # and list all variants def __init__(self, name, gender, mother=None, father=None): """ Create a Person instance Create a new Person object, AKA a Person instance. This is used by the expression Person(). The parameters name and gender are required, while other parameters are optional. Args: name (:obj:`str`): the person's name gender (:obj:`str`): the person's gender mother (:obj:`Person`, optional): the person's mother father (:obj:`Person`, optional): the person's father """ # TODO: standardize the representations of gender, so that M, m, and male are valid inputs # for male, but only one standard stored constant represents male, and similarly for female. self.name = name self.gender = gender self.mother = mother self.father = father self.children = set() # a method annotated with '@staticmethod' is a 'static method' that does not receive an # implicit first argument. Rather, it is called C.m(), where the class C identifies the # class in which the method is defined. @staticmethod def get_persons_name(person): """ Get a person's name; if the person is not known, return 'NA' Returns: :obj:`str`: the person's name, or 'NA' if they're not known """ if person is None: return 'NA' return person.name def add_child(self, child): """ Add a child to this person's set of children Args: child (:obj:`Person`): a child of `self` """ self.children.add(child) # TODO: write 'set_father' and 'set_mother' methods that set a person's father or mother, # and adds the person to the father's or mother's children. Replace all statements below # that set a person's father or mother attribute with these methods. # TODO: remove the 'add_child' method and replace any statements that use it with a call to # 'set_father' or 'set_mother' # TODO: write 'remove_father' and 'remove_mother' methods that removes a person's father or mother, # and removes the person from the father's or mother's children. Test these methods. # TODO: create a 'siblings' method that returns a person's siblings, and write a 'half_siblings' # method that returns a person's half-siblings. def siblings(self): """ Get this person's siblings, i.e., people with the same parents Returns: :obj:`list` of `Person`: the person's siblings """ # cannot be done if a parent is not known if self.father is None or self.mother is None: # exceptions not being used yet print("cannot get siblings for '{}'".format(self.name)) return # siblings are other people with same parents all_joint_offspring = self.father.children.intersection(self.mother.children) return all_joint_offspring - self def half_siblings(self): """ Get this person's half-siblings, i.e., people with exactly one parent in common Both of a `Person`'s parents must be known for them to be evaluated as a possible half-sibling Returns: :obj:`list` of `Person`: the person's siblings """ # cannot be done if a parent is not known if self.father is None or self.mother is None: # exceptions not being used yet print("cannot get half-siblings for '{}', as one or more parents unknown".format(self.name)) return # half-siblings have exactly one parent in common with self offspring_of_one_parent = set() for offspring in self.father.children.symmetric_difference(self.mother.children): # both of a half-sib's parents must be known if not (offspring.father is None or offspring.mother is None): offspring_of_one_parent.add(offspring) return offspring_of_one_parent def sons(self): """ Get this person's sons Returns: :obj:`list` of `Person`: the person's sons """ sons = [] for child in self.children: if child.gender == 'male': sons.append(child) return sons def __str__(self): """ Provide a string representation of this person """ return "{}: gender {}; mother {}; father {}".format( self.name, self.gender, Person.get_persons_name(self.mother), Person.get_persons_name(self.father)) def grandparents_structured(self): ''' Provide this person's grandparents Returns: :obj:`tuple`: the person's grandparents, in a 4-tuple: (maternal grandmother, maternal grandfather, paternal grandmother, paternal grandfather) Missing individuals are identified by None. ''' grandparents = [] if self.mother: grandparents.extend([self.mother.mother, self.mother.father]) else: grandparents.extend([None, None]) if self.father: grandparents.extend([self.father.mother, self.father.father]) else: grandparents.extend([None, None]) return tuple(grandparents) # TODO: EXTRA CREDIT: implement this descendants method, which has analogous semantics to the # ancestors method below. The implementation may use a while loop or be recursive. Use # your 'descendants' method to implement 'children', 'grand_children', and 'all_descendants'. def descendants(self, min_depth, max_depth=None): """ Return this person's descendants within a generational depth range Obtain descendants whose generational depth satisfies `min_depth` <= depth <= `max_depth`. E.g., this person's children would be obtained with `min_depth` = 1, and this person's grandchildren and great-grandchildren would be obtained with `min_depth` = 3 and `max_depth` = 3. Args: min_depth (:obj:`int`): the minimum depth of descendants which should be provided; this person's depth is 0, their children's depth is 1, etc. max_depth (:obj:`int`, optional): the minimum depth of descendants which should be provided; if `max_depth` is not provided, then `max_depth` == `min_depth` so that only descendants at depth == `min_depth` will be provided; a `max_depth` of infinity will obtain all descendants at depth >= `min_depth`. Returns: :obj:`set` of `Person`: this person's descendants Raises: :obj:`ValueError`: if `max_depth` < `min_depth` """ pass def ancestors(self, min_depth, max_depth=None): """ Return this person's ancestors within a generational depth range Obtain ancestors whose generational depth satisfies `min_depth` <= depth <= `max_depth`. E.g., a person's parents would be obtained with `min_depth` = 1, and this person's parents and grandparents would be obtained with `min_depth` = 1 and `max_depth` = 2. Args: min_depth (:obj:`int`): the minimum depth of ancestors which should be provided; this person's depth is 0, their parents' depth is 1, etc. max_depth (:obj:`int`, optional): the minimum depth of ancestors which should be provided; if `max_depth` is not provided, then `max_depth` == `min_depth` so that only ancestors at depth == `min_depth` will be provided; a `max_depth` of infinity will obtain all ancestors at depth >= `min_depth`. Returns: :obj:`set` of `Person`: this person's ancestors Raises: :obj:`ValueError`: if `max_depth` < `min_depth` """ if max_depth is not None: if max_depth < min_depth: raise ValueError("max_depth ({}) cannot be less than min_depth ({})".format( max_depth, min_depth)) else: # collect just one depth max_depth = min_depth collected_ancestors = set() return self._ancestors(collected_ancestors, min_depth, max_depth) def _ancestors(self, collected_ancestors, min_depth, max_depth): """ Obtain this person's ancestors who lie within the generational depth [min_depth, max_depth] This is a private, recursive method that recurses through the ancestry via parent references. Args: collected_ancestors (:obj:`set`): ancestors collected thus far by this method min_depth (:obj:`int`): see `ancestors()` max_depth (:obj:`int`): see `ancestors()` Returns: :obj:`set` of `Person`: this person's ancestors Raises: :obj:`ValueError`: if `max_depth` < `min_depth` """ # TODO: EXTRA CREDIT: can a cycle in the ancestry graph create an infinite loop? # if so, avoid this problem. if min_depth <= 0: collected_ancestors.add(self) if 0 < max_depth: for parent in [self.mother, self.father]: if parent is not None: parent._ancestors(collected_ancestors, min_depth-1, max_depth-1) return collected_ancestors def parents(self): ''' Provide this person's parents Returns: :obj:`set`: this person's known parents ''' return self.ancestors(1) def grandparents(self): ''' Provide this person's known grandparents, by using ancestors() Returns: :obj:`set`: this person's known grandparents ''' return self.ancestors(2) def great_grandparents(self): return self.ancestors(3) def all_grandparents(self): ''' Provide all of this person's known grandparents, from their parents' parents on back Returns: :obj:`set`: all of this person's known grandparents ''' return self.ancestors(2, max_depth=float('inf')) def all_ancestors(self): ''' Provide all of this person's known ancestors Returns: :obj:`set`: all of this person's known ancestors ''' return self.ancestors(1, max_depth=float('inf')) def print_people(people): for p in people: print('\t', p) # create a Person Joe, and store it in the variable 'joe' joe = Person('Joe', 'male') # check joe's name assert joe.name == 'Joe' print('Joe self'); print_people(joe.ancestors(0)) print('Joe parents None'); print_people(joe.ancestors(1)) # create a Person Mary, and make her Joe's mother joe.mother = Person('Mary', 'F') print('Joe parents mother'); print_people(joe.ancestors(1)) maternal_gm = joe.mother.mother = Person('Agnes', 'female') # create a Person Joe Sr., and make him Joe's father joe.father = Person('Joe Sr.', 'male') print('joe parents(): Mary, Joe Sr.'); print_people(joe.parents()) # create joe's paternal grandfather joe.father.father = Person('Old Joe', 'male') # create joe's maternal grandmother maternal_gm.mother = Person('Maternal ggm', 'female') print('joe.grandparents_structured(), Agnes, Old Joe'); print_people(joe.grandparents_structured()) print('joe.grandparents(), Agnes, Old Joe'); print_people(joe.grandparents()) print('joe great-grandparents: Maternal ggm'); print_people(joe.great_grandparents()) # play with an infinite ancestry depth limit inf = float('inf') print('joes ancestors: Mary, Joe Sr., Agnes, Old Joe, Maternal ggm'); print_people(joe.all_ancestors()) print('joe and his ancestors'); print_people(joe.ancestors(0, inf)) # make Joe his mother's son joe.mother.add_child(joe) print('joe.mother.sons():'); print_people(joe.mother.sons()) print('joe.sons():', joe.sons()) kid = Person('kid', 'male', father=joe) joe.add_child(kid)
65c6ca4ec30f1cd82061c562bf3b3c0f64ef5a2c
RRoundTable/Data_Structure_Study
/sort/RedixSort.py
946
3.546875
4
import random import time import numpy as np N=100 lstNumbers=list(range(N)) random.seed(1) random.shuffle(lstNumbers) print(lstNumbers) def get_digit(num, index): """ :param num: 10진법 숫자 :param index :return: index번째 digit """ return int(num / (10 ** index)) % int(10) def reditSort(lstNum): """ :param lstNum: unsorted integer list :return: sorted list """ max_val = -9999 for iter in range(len(lstNum)): if lstNum[iter] > max_val: max_val = lstNum[iter] D = int(np.log10(max_val)) # 최댓값의 자릿수 : digit bucket의 수 for iter in range(0, D+1): bucket = [] for i in range(0, 10): bucket.append([int(ele) for ele in lstNum if get_digit(ele, iter) == i]) lstNum =[] for b in bucket: for ele in b: lstNum.append(ele) return lstNum print(reditSort(lstNumbers))
62ec91bdabcd51a880eeb034e1af43683981fc95
yaoYiheng/PythonPractice
/小甲鱼练习/@course_1.py
369
4.15625
4
import math def area_triangle_sss(side1,side2,side3): """ Return area of a triangle, given the lenths of its three sides. """ #Heron's formula semi_perim = (side1 + side2 + side3)/2.0 return math.sqrt(semi_perim * (semi_perim - side1) * (semi_perim - side2) * (semi_perim - side3))
fecf837113a250656d7e73d849b658b6ebc49d99
tflhyl/FFXIII-2ClockSolver
/FFXIII-2ClockSolver.py
1,431
3.625
4
CLOCK_SIZE = 12 def get_input(): input = raw_input("Enter clocks (12 values from top-most clockwise): ").strip() if len(input) != CLOCK_SIZE*2 - 1: print 'Invalid size!' return None else: return input.split(" ") #idx - index of current node #val - value of current node #d - direction (1 clockwise, -1 anticlockwise) def solve(clock, solution, idx, val, d): new = (idx + d*val)%CLOCK_SIZE if new in solution: return 0 solution.append(new) if len(solution) == CLOCK_SIZE: return 1 else: if solve(clock, solution, new, clock[new], 1) == 0: if solve(clock, solution, new, clock[new], -1) == 0: solution.pop() return 0 return 1 def main(): clock = get_input() if clock == None: return None try: clock = map(int, clock) except ValueError: print 'Invalid clock!' return None solution = [] for x in range(0, CLOCK_SIZE): solution.append(x) if solve(clock, solution, x, clock[x], 1) == 0: if solve(clock, solution, x, clock[x], -1) == 0: solution.pop() else: break else: break if len(solution) == 0: print 'Clock cannot be solved!' else: print solution if __name__ == "__main__": main()
dee02b6a94621111f1c2cee39cc6a9ff9cc14b42
codeAligned/coding-practice
/Pramp/flatten-dictionary.py
1,036
4.09375
4
""" Given a dictionary, write a function to flatten it. Consider the following input/output scenario for better understanding: Input: { 'Key1': '1', 'Key2': { 'a' : '2', 'b' : '3', 'c' : { 'd' : '3', 'e' : '1' } } } Output: { 'Key1': '1', 'Key2.a': '2', 'Key2.b' : '3', 'Key2.c.d' : '3', 'Key2.c.e' : '1' } """ import json def flatten(sample, parent=None, flat={}): for key in sample.keys(): if isinstance(sample[key], dict): if parent is None: flatten(sample[key], key, flat) else: flatten(sample[key], str(parent) + '.' + str(key), flat) else: if parent is None: flat[key] = sample[key] else: flat[str(parent) + '.' + str(key)] = sample[key] sample = { 'Key1': '1', 'Key2': { 'a': '2', 'b': '3', 'c': { 'd': '3', 'e': '1' } } } flat = {} flatten(sample, None, flat) print(json.dumps(flat, indent=4, sort_keys=True))
67bb00cbb493f04f9505d0e547ef38f324f33fde
hsyao/algorithm
/模拟训练/day04/选择排序.py
692
3.75
4
""" """ def selection_sort(alist): n = len(alist) # 需要进行n-1次选择操作 for i in range(n - 1): # 记录最小位置 min_index = i # 从i+1位置到末尾选择出最小数据 for j in range(i + 1, n): if alist[j] < alist[min_index]: min_index = j # 如果选择出的数据不再正确位置,进行交换 if min_index != i: alist[i], alist[min_index] = alist[min_index], alist[i] if __name__ == '__main__': li = [9, 8, 7, 6, 5, 4, 3, 2, 1] selection_sort(li) print(li) alist = [54, 226, 93, 17, 77, 31, 44, 55, 20] selection_sort(alist) print(alist)
2fd9b7437e551b978626abb1831a564392085209
quyixiao/python_lesson
/listxx.py
134
3.5625
4
list = [1,2,3,"zhangsan",{"username":"瞿贻晓","age":28}] print(list) print(list[3]) a = {"username":"瞿贻晓","age":28} print(a)
91c49b4d072a76342baa8aef9c90dfdc27379a39
Mariappan/LearnPython
/Excercises/findListSizeInArray.py
328
3.671875
4
#!/usr/bin/env python def solution(A): # write your code in Python 3.6 index=0 count=0 viewedIndex = set() while (index not in viewedIndex) and index !=-1: viewedIndex.add(index) index=A[index] count+=1 return count a = [1, 4, -1, 3, 2] print ("Count is " + str(solution(a)))
13babfebfa5b92a403ac897a5afbec2c45f7d5eb
panbenson/adventofcode2020
/13.py
2,931
3.71875
4
def load_file(file: str): lines = [] # just load all the lines with open(file, 'r') as reader: lines = [line.strip() for line in reader] return (int(lines[0]), lines[1].split(',')) def day_thirteen_part_one(file: str): start, busses = load_file(file) # ignoring x for now busses = list(map(int, filter(lambda x: x != 'x', busses))) next_bus = start bus = None # maybe just loop thru all the possible values while bus == None: for i in busses: if next_bus % i == 0: bus = i break if bus == None: next_bus += 1 print((next_bus - start) * bus) def day_thirteen_part_two(file: str): start, busses = load_file(file) # convert int for possible numbers busses = list(map(lambda x: int(x) if x != 'x' else x, busses)) lcm = busses[0] # maybe just find when pattern repeats? for i in range(1, len(busses)): print(lcm, busses[i]) if busses[i] == 'x': continue n = 1 q = (lcm * n + i) // busses[i] while lcm * n + i != busses[i] * q: if lcm * n + i < busses[i] * q: n += 1 elif lcm * n + i > busses[i] * q: q += 1 # print(lcm * n) lcm *= n print(lcm) def valid(busses, multiples): # they should all match busses[0] * multiple[0] for i in range(1, len(busses)): if busses[i] == 'x': continue if busses[i] * multiples[i] - i != busses[0] * multiples[0]: return False return True def day_thirteen_part_two_bf(file: str): start, busses = load_file(file) # convert int for possible numbers busses = list(map(lambda x: int(x) if x != 'x' else x, busses)) # couldn't math it, just brute force again? multiples = [1 for i in range(len(busses))] # find the max in list multiples_max = 0 for i in range(len(busses)): if busses[i] == 'x': continue if busses[i] * multiples[i] > multiples_max: multiples_max = busses[i] * multiples[i] while not valid(busses, multiples): # increase the others for i in range(len(busses)): if busses[i] == 'x': continue if busses[i] * multiples[i] < multiples_max: multiples[i] = multiples_max // busses[i] + 1 if busses[i] * multiples[i] > multiples_max: multiples_max = busses[i] * multiples[i] # while busses[i] * multiples[i] < multiples_max: # multiples[i] += 1 print(multiples[0] * busses[0]) # solution: find the first multiple which matches the # offset, keep adding otherwise # day_thirteen_part_one('13-example.in') # day_thirteen_part_one('13.in') day_thirteen_part_two_bf('13-short.in') day_thirteen_part_two_bf('13-example.in')
e879db6b80eb1ee188075a8c073fff04cd9f1c29
ryanyoon/lovelybot-emotion
/tasks.py
1,377
3.640625
4
from microsoftbotframework import ReplyToActivity import requests import json # https://westus.api.cognitive.microsoft.com/text/analytics/v2.0/sentiment """ POST https://westus.api.cognitive.microsoft.com/text/analytics/v2.0/sentiment Ocp-Apim-Subscription-Key:4cfe6f744f1b486db3fa83d874bafdd9 Content-Type:application/json Accept:application/json """ # https://api.korbit.co.kr/v1/ticker def echo_response(message): print(message) if message["type"] == "message": if "s8" and "capture" in message["text"]: msg = "A screenshot is a snapshot of your device screen saved as a photo. There are several ways to capture screenshots on your device. After the screenshots are captured, they will be automatically saved to the Gallery. If you want to know how to capture the screen on your galaxy S8 & S8+, click the link below." print(msg) msg2 = "http://www.samsung.com/us/support/answer/ANS00062596/" print(msg2) ReplyToActivity(fill=message, text=msg).send() ReplyToActivity(fill=message, text=msg2).send() ReplyToActivity(fill=message, text=msg4).send() else: msg = "Sorry. I can't understand. Please enter the product name with the keyword. For example, you can ask me like \"S8 screen capture\" or \"How can I capture my screen on my S8?\"." print(msg) ReplyToActivity(fill=message, text=msg).send()
4288d3f3da61b534747ae75adfccff220f5882d7
ultraasi-atanas/MIT-6.00.1x-Exercises
/MIT6.00.1x-Week2-function-iteration-vs-recursion.py
1,779
4.4375
4
# -*- coding: utf-8 -*- """ Created on Thu Oct 8 16:56:41 2020 @author: Atnaas Kozarev - github.com/ultraasi-atanas Week 2 MIT 6.00.1x Introduction to Computer Science and Programming Using Python https://learning.edx.org/course/course-v1:MITx+6.00.1x+2T2020a """ # Exercise: iter power - Your code must be iterative - use of the ** operator is not allowed. # Write an iterative function iterPower(base, exp) that calculates the exponential baseexp by simply using successive multiplication. For example, iterPower(base, exp) should compute baseexp by multiplying base times itself exp times. Write such a function below. # This function should take in two values - base can be a float or an integer; exp will be an integer ≥ 0. It should return one numerical value. Your code must be iterative - use of the ** operator is not allowed. # ============================================================================= # def iterPower(base, exp): # ''' # base: int or float. # exp: int >= 0 # # returns: int or float, base^exp # ''' # result = 1 # # if exp == 0: # return 1 # elif exp == 1: # return base # elif base == 1: # return 1 # else: # while (exp > 0): # result = result * base # exp -= 1 # return result # # print(iterPower(2,40)) # # ============================================================================= def recurPower(base, exp): ''' base: int or float. exp: int >= 0 returns: int or float, base^exp ''' if exp == 0: return 1 elif exp == 1: return base elif base == 1: return 1 else: return base * recurPower(base,exp-1) print(recurPower(0,2))
79a25e7eebd5c187e1e95b8bdc9bd7a51c2b83ed
laurentziudmm/PythonProject
/Exercices/dictionary.py
651
3.84375
4
# name: John Smith # email: john # phone: # customer = { # "name":"John Smith", # "age": 30, # "is_verified":True # } # customer["name"] = "Jack Smith" # customer["birthdate"] = "Yan 1 1980" # # print(customer["name"]) # # print(customer.get("birthdate", "yan 1 1980")) # print(customer["birthdate"]) # print(customer["name"]) #exercitiu phone = input('Phone: ') # "1" -> "One" # "2" -> "Two" digits_mapping = { "1": "One", "2": "Two", "3": "Three", "4": "For", "5": "Five", "6": "Six", "7": "Seven", "8": "Eight" } output = "" for ch in phone: output += digits_mapping.get(ch, "!") + " " print(output)
041b486478ae82657129b3430669d0ffd2dea833
gargisha29/Hello-World
/If_else.py
190
4.125
4
name=input(" enter your name") age=int(input ("enter your age")) if age<30: print("your name is"+ name + "you are" + str(age) + "years Old") else: print(" You may leave")
09e9ccc2a2d468d70943fb84020c1fec902bd9d0
PeterGrainfield/AltCoder
/py/abc126_b.py
244
3.53125
4
S = input() first = int(S[0:2]) second = int(S[2:4]) if 1 <= first <= 12: if 1 <= second <= 12: print("AMBIGUOUS") else: print("MMYY") else: if 1 <= second <= 12: print("YYMM") else: print("NA")
358acaff7f6d766573773ffa7eb1e90858b44ee5
HamzaQahoush/data-structures-and-algorithms--Python
/tests/test_merge_sort.py
827
3.703125
4
from data_structures_and_algorithms_python.challenges.merge_sort.merge_sort import * def test_insert_sample(): sample_array = [8, 4, 23, 42, 16, 15] actual = f'{mergeSort(sample_array)}' expected = '[4, 8, 15, 16, 23, 42]' assert actual == expected def test_insert_reverse_sorted(): reverse_sorted = [20, 18, 12, 8, 5, -2] actual = f'{mergeSort(reverse_sorted)}' expected = '[-2, 5, 8, 12, 18, 20]' assert actual == expected def test_insert_few_uniques(): few_uniques = [5, 12, 7, 5, 5, 7] actual = f'{mergeSort(few_uniques)}' expected = '[5, 5, 5, 7, 7, 12]' assert actual == expected def test_insert_nearly_sorted(): nearly_sorted = [2, 3, 5, 7, 13, 11] actual = f'{mergeSort(nearly_sorted)}' expected = '[2, 3, 5, 7, 11, 13]' assert actual == expected
d96fa3c5f00eb0dd32ab0fee5b69137eb0f75bfc
wecsam/CS4783-Project-1
/frequencies/json_to_brace_init.py
2,323
3.609375
4
#!/usr/bin/python3 # This script converts JSON data on STDIN to a C++ 2011 brace initialization list for a map. # Any data that is not a dict/object or list/array is left as-is. # The result is written to STDOUT. import json, sys # This class keeps track of the indentation level in the output text. class PrettyPrinter: def __init__(self, stream=sys.stdout): self.output_stream = stream self.indentation_level = 0 self.at_beginning_of_line = True # The following two functions increase and decrease the current indentation level. def increase_indent(self): self.indentation_level += 1 def decrease_indent(self): if self.indentation_level > 0: self.indentation_level -= 1 # This function automatically outputs a number of tabs based on the indentation level. def do_indent(self): self.output_stream.write("\t" * self.indentation_level) self.at_beginning_of_line = False # Call this function to write something to the output stream. def write(self, stuff): if self.at_beginning_of_line: self.do_indent() # Convert \n to calls to self.newline(). split_at_newlines = iter(stuff.split("\n")) # Write the first line. self.output_stream.write(next(split_at_newlines)) # Write the other lines, calling self.newline() before each line. for tail_line in split_at_newlines: self.newline() # Do not indent empty lines. if len(tail_line): self.do_indent() self.output_stream.write(tail_line) # This function writes a new line to the stream. def newline(self): self.output_stream.write("\n") self.at_beginning_of_line = True out = PrettyPrinter() def handle_dict(d): global out out.write("{") out.increase_indent() for key in d: out.write("\n{") handle_data(key) out.write(", ") handle_data(d[key]) out.write("},") out.decrease_indent() out.write("\n}\n") def handle_list(l): raise NotImplementedError def handle_data(o): global out t = type(o) if t is list: handle_list(o) elif t is dict: handle_dict(o) else: out.write(repr(o)) handle_data(json.load(sys.stdin))
d5918dba39a56ec95963f764e48017b623aead95
ChrisProgramming2018/algoritm
/Graphs/SingleCycleCheck/python/program.py
512
3.703125
4
# Check array for single cycle def hasSingleCycle(array): """ Checks the given array O(n) time | O(1) space n := length of array Args: param1:(list) array of int Return bool """ counter = 0 pos = 0 length = len(array) while counter < length: jump = array[pos] counter += 1 pos += jump pos = pos % length if pos == 0 and counter != length: return False if pos == 0: return True return False
a5318d036c5beb3bdcae3e70e46562c7995e05ee
grosuclaudia/dojos
/firstweek/palindrom.py
297
3.890625
4
#s= input("word: ") s="abba" text = list(s) print(text) i=0 size = len(text) ispalindrom=1 while i<(size/2): n=size-1-i if text[i]==text[n]: i=i+1 else: ispalindrom=0 break if ispalindrom==1: print("a palindrom") else: print("not a palindrom")
59168227f1c34e6568c92b1c9f34688615492a87
dassowmd/UsefulTools
/hash_cash.py
742
3.546875
4
import string import random import hashlib example_challenge = "9Kzs52jSfxa65s4df6s5a4" def generation(challenge=example_challenge, size=25): answer = "".join( random.choice(string.ascii_lowercase) + random.choice(string.ascii_uppercase) + random.choice(string.digits) for x in range(size) ) attempt = challenge + answer return attempt, answer shaHash = hashlib.sha256() def testAttempt(): attempt, answer = generation() shaHash.update(attempt) solution = shaHash.hexdigest() return solution for x in xrange(1, 100000): solution = testAttempt() lower = 0 upper = 3 if solution[lower:upper] == "af3ebab695bf674bdcda"[lower:upper]: print solution
8c707e411513ef77ccc52a7366b7f5b857289c76
wookiekim/CodingPractice
/codility/genomic_range_query.py
1,686
3.890625
4
# Find the minimal nucleotide from a range of sequence DNA # Medium ``` A DNA sequence can be represented as a string consisting of the letters A, C, G and T, which correspond to the types of successive nucleotides in the sequence. Each nucleotide has an impact factor, which is an integer. Nucleotides of types A, C, G and T have impact factors of 1, 2, 3 and 4, respectively. You are going to answer several queries of the form: What is the minimal impact factor of nucleotides contained in a particular part of the given DNA sequence? The DNA sequence is given as a non-empty string S = S[0]S[1]...S[N-1] consisting of N characters. There are M queries, which are given in non-empty arrays P and Q, each consisting of M integers. The K-th query (0 ≤ K < M) requires you to find the minimal impact factor of nucleotides contained in the DNA sequence between positions P[K] and Q[K] (inclusive). Write an efficient algorithm for the following assumptions: N is an integer within the range [1..100,000]; M is an integer within the range [1..50,000]; each element of arrays P, Q is an integer within the range [0..N − 1]; P[K] ≤ Q[K], where 0 ≤ K < M; string S consists only of upper-case English letters A, C, G, T. ``` # Iterating << "in" operation def solution(S, P, Q): impacts = [] for i in range(len(P)): scope = S[P[i]:Q[i] + 1] if 'A' in scope: impacts.append(1) continue elif 'C' in scope: impacts.append(2) continue elif 'G' in scope: impacts.append(3) continue else: impacts.append(4) return impacts
115cab933e589c0536b236d325b9ca76a03ed9a8
chengong825/python-test
/343整数拆分.py
704
3.53125
4
# 给定一个正整数 n,将其拆分为至少两个正整数的和,并使这些整数的乘积最大化。 返回你可以获得的最大乘积。 # # 示例 1: # # 输入: 2 # 输出: 1 # 解释: 2 = 1 + 1, 1 × 1 = 1。 # 示例 2: # # 输入: 10 # 输出: 36 # 解释: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36。 class Solution: def integerBreak(self, n): """ :type n: int :rtype: int """ if n==2: return 1 if n==3: return 2 product=1 while n>4: product*=3 n-=3 return n*product solution=Solution() solution.integerBreak(32) #3=1+2 4=2+2 6=3+3 11 4 4 3*3*3*3 16 3*3*3*3*3*3*1
93c74c9e9b18efed0a6d0e5dbebac1c85c31731b
amragl/Project1
/Functions/function_return.py
151
4.0625
4
def maximum(x,y): if x>y: return x elif x==y: return 'The number are equals' else: return y print(maximum(2,3))
45a6ea3707b2b379a0fa398db98cf185c006fa61
amazingrobocat/python-project-lvl1
/brain_games/games/gcd.py
1,202
4.03125
4
"""Brain-Greatest common divisor game module.""" import random FIRST_MIN_NUMBER = 1 FIRST_MAX_NUMBER = 45 SECOND_MIN_NUMBER = 1 SECOND_MAX_NUMBER = 15 RULES = 'Find the greatest common divisor of given numbers.' def gcd(number_one, number_two): """Find greatest common divisor of two numbers. Args: number_one(int): first generated number number_two(int): second generated number Returns: GCD number """ while number_two != 0: number_one, number_two = ( number_two, number_one % number_two, ) return number_one def get_question_and_answer(): """Round of the Brain-GCD game. Generate two random numbers. Ask the user a question for a round of the game. Returns: - question for the user - correct answer value """ first_generated_number = random.randint(FIRST_MIN_NUMBER, FIRST_MAX_NUMBER) second_generated_number = random.randint( SECOND_MIN_NUMBER, SECOND_MAX_NUMBER, ) question = '{0} {1}'.format(first_generated_number, second_generated_number) correct_answer = gcd(first_generated_number, second_generated_number) return question, correct_answer
9113437dd59c0579ae0399ef3f1d86f4aae4845a
dicao425/algorithmExercise
/LeetCode/strobogrammaticNumber.py
488
3.640625
4
#!/usr/bin/python import sys class Solution(object): def isStrobogrammatic(self, num): """ :type num: str :rtype: bool """ d = {'6': '9', '9': '6', '1': '1', '8': '8', '0': '0'} if set(num) - set(d.keys()): return False new = [] for n in num: new.append(d[n]) return num == ''.join(new[::-1]) def main(): aa = Solution() return 0 if __name__ == "__main__": sys.exit(main())
54bbc72996b1dbe9476ac541429bcdf3d3e38ce5
cjim8889/Practice
/LongestCommonPrefix.py
1,234
3.5
4
class Solution: def longestCommonPrefix(self, strs: 'List[str]') -> 'str': if (not len(strs)): return "" if (len(strs) == 1): return strs[0] firstStr = strs[0] strs = strs[1:] currentPrefix = "" for i in range(len(firstStr)): for j in strs: if not j.startswith(firstStr[:i + 1]): return currentPrefix currentPrefix = firstStr[:i + 1] return currentPrefix class Solution2: def longestCommonPrefix(self, strs: 'List[str]') -> 'str': if (not len(strs)): return "" elif (len(strs) == 1): return strs[0] firstStr = strs[0] prefix = "" lengthList = [len(i) for i in strs] strs = strs[1:] for i in range(min(lengthList)): for j in strs: if (not j[i] == firstStr[i]): return prefix prefix = firstStr[:i + 1] return prefix if __name__ == "__main__": Solution2().longestCommonPrefix(["","b"])
49c09759bb866c28e181151f1e5f28f19e7a8732
gabriellaec/desoft-analise-exercicios
/backup/user_348/ch65_2020_04_27_21_58_38_841423.py
197
3.703125
4
def capitaliza (string): resto = string[1:] primeira_letra = string[0] captaliza = string.upper(primeira_letra) soma = captaliza + resto return soma print(capitaliza ('Thais'))
7dc6a7d230f1eed6f8f0f860b21128ae6810579d
lalaboom/algorithm-practice
/LeetCode/验证回文字符串.py
643
3.625
4
class Solution: def isPalindrome(self, s: str) -> bool: if len(s) == 0: return True s = s.lower() left = 0 right = len(s) - 1 while left < right: if (s[left] in "1234567890qwertyuioplkjhgfdsazxcvbnm" and s[right] in "1234567890qwertyuioplkjhgfdsazxcvbnm"): if s[left] == s[right]: left += 1 right -= 1 else: return False else: if s[left] not in "1234567890qwertyuioplkjhgfdsazxcvbnm": left += 1 elif s[right] not in "1234567890qwertyuioplkjhgfdsazxcvbnm": right -= 1 return True
2042e4d1d110d05aede2155e5d180a31ab7ac927
sx1616039/ecnp-simulation
/Task.py
674
3.5
4
class Task: def __init__(self, id, time, target): """ initializes a new task Arguments: id: id of the task : integer time: when will the task be published/offered for Agents : integer target: target node (city/place) of a task : tuple """ self.id = id #self.good = good probably not needed? self.time = time self.target = target def toString(self): return " Task nr "+str(self.id)+" at the time "+str(self.time)+" to "+str(self.target) def show(self): print("Task nr",self.id,"at the time",self.time,"to",self.target)
1faf6cf09c80b0a339fda57d4d6879e8e80f4d31
kevinfal/CSC120
/Assignment5/short/reverse_list.py
1,068
4.375
4
""" File: reverse_list.py Author: Kevin Falconett Purpose: reverses a linked list """ from list_node import * def reverse_list(head: ListNode): """ Reverses a linked list (head) without constructing any new nodes or using arrays Parameters: head (ListNode): front of linked list to sort Returns: (ListNode) - List of all of the elements in head reversed """ new = None while head is not None: print("head: ", head) print("new: ", new, "\n") current = head head = head.next current.next = new new = current print("head: ", head) print("new: ", new, "\n") return new def main(): """ Used to test functionality of reverse_list() Creates a linked list and reverses it, list can be changed for testing """ head = ListNode(1) head.next = ListNode(2) head.next.next = ListNode(3) print(reverse_list(head)) if __name__ == "__main__": main()
5c7130e155c6a5265a17493df238d47009316edc
Ash0492/DataStructures
/toh_testing.py
386
3.90625
4
count = 0 def Hanoi(count , N , fromm, to,aux): if(N == 1): print("move disk", N, "from rod", fromm, "to rod", aux) count+=1 return count count = Hanoi(count , N-1, fromm, to, aux) print("move disk", N, "from rod", fromm, "to rod", aux) count+=1 count = Hanoi(count , N-1, to, aux, fromm) print(count) Hanoi(count , 3, 'A', 'C', 'B')
ebd6e9a98a979c46d0b85544def2c93ffe87062b
OokGIT/pythonproj
/nlp/facts.py
857
3.703125
4
import spacy import textacy.extract # Загрузка английской NLP-модели nlp = spacy.load('en_core_web_lg') # Текст для анализа text = """London is the capital and most populous city of England and the United Kingdom. Standing on the River Thames in the south east of the island of Great Britain, London has been a major settlement for two millennia. It was founded by the Romans, who named it Londinium. """ # Анализ doc = nlp(text) # Извлечение полуструктурированных выражений со словом London statements = textacy.extract.semistructured_statements(doc, "London") # Вывод результатов print("Here are the things I know about London:") for statement in statements: subject, verb, fact = statement print(f" - {subject}, {verb}, {fact}")
57118357dbe6fa99c4ff23edb1fe0eb32f8b883f
shibata-kento/AtCoder
/ABC043/a.py
88
3.671875
4
n = int(input()) candy = 0 for i in range(n+1): candy = candy + i print(candy)
9444e1d63176ba63b188fbcf2231b3b496b0f1f6
redbassett/CS112-Spring2012
/hw10/dicts.py
2,122
4.65625
5
#!/usr/bin/env python """ dicts.py Dictionaries ============================================================ In this section, write some functions which build and manipulate python dictionaries. """ # 1. freq # Return a dictionary of the number of times each value # is in data. # >>> freq([ 1, 2, 2, 2, 2, 3, 4, 5, 1, 4, 1, 9, 10 ]) # { 1: 3, 2: 4, 3: 1, 4: 1, 5: 1, 9: 1, 10: 1} def freq(data): occ = {} for x in data: if x in occ: occ[x] += 1 else: occ[x] = 1 return occ # 2. Movie Reviews # Write two functions to help with scoring a movie. # # score: # stores a score in the "movies" dictionary # # avg_score: # returns the average score of a movie # # Examples: # >>> score("Fargo", 4) # >>> score("Fargo", 5) # >>> score("Fargo", 5) # >>> avg_score("Fargo") # 4.6666666667 # >>> avg_score("missing movie") # None movies = {} def score(title, value): if title in movies: movies[title].append(value) else: movies[title] = [1] def avg_score(title): if title in movies: # Int added trying to solve "wrong" average issue… return int(sum(movies[title])/len(movies[title])) else: return None # 3. parse_csv (Advanced) # Takes an input string and spits back a list of comma # separated values (csv) entries. Hint, check the zip # and dict functions. # # The point of this is to create your own parser, not to # use pythons builtin 'csv' library. # # >>> csv = """ # name,age,email # Foo, 24, foo@example.com # Bar ,22 ,bar@example.com # Baz, 20 , baz@gmail.com # """ # >>> parse_csv(csv) # [ { "name": "Foo", "age": "24", "email": "foo@example.com" }, # { "name": "Bar", "age": "22", "email": "bar@example.com" }, # { "name": "Baz", "age": "20", "email": "baz@example.com" } ] import string def parse_csv(data): dict = {} rows = data.split("\n") for r in rows: r.split(',')
299140a9c1afee360c499311ba012e5101ce5675
ofisser86/jb-rock-paper-scissors
/Problems/Stick together/main.py
103
3.59375
4
numbers = [int(x) for x in input().split()] # print all numbers without spaces print(*numbers, sep="")
a64f6343d17421b43891c5b10083e65d003f2280
jackalsin/Python
/15112/Quiz/H2P7_nthPowerfulNumber.py
1,359
3.734375
4
import math def almostEqual(x,y): if abs(x-y)<0.0000001: return True def isFactor(factor,n): if n%factor==0: return True else: return False def isSquare(n): #to test n contain a square factor factor=1 limit=round(math.sqrt(n))+1 for factor in range(1,limit): if isFactor(factor,n) and isFactor(factor**2,n): print("factor and n=", factor,", ",n) return True#return factor else: factor+=1 return False def selfSquare(n): divid=round(math.sqrt(n)) if not almostEqual(divid, math.sqrt(n)):# ensure divid is integer rather round return False #print("n and sqrt are", n,"and ",divid) if n%divid**2==0: return True else: return False def isPowerful(n): guess=1 limit=round((n)**(1/3))+1 for factorA in range (1,limit): #print("we are testing factorA=",factorA,",") if isFactor(factorA**3,n): remain=n/(factorA**3) if selfSquare(remain): #print("factorA=",factorA,"remain=",remain) return True return False def nthIsPowerfulNumber(n): count=0 guess=1 while (count<=n): if (isPowerful(guess)): count+=1 guess+=1 return guess-1 for i in range (11): print(nthIsPowerfulNumber(i))
0c2ebfdff13a2c5556315e3962e062d77513e50c
brunoprela/keras_mnist
/keras_mnist.py
4,004
3.65625
4
# external import numpy as np import matplotlib.pyplot as plt # keras from keras.datasets import mnist from keras.models import Sequential from keras.layers.core import Dense, Dropout, Activation from keras.utils import np_utils # make the plot figures bigger plt.rcParams['figure.figsize'] = (7,7) # loading the training data nb_classes = 10 # we shuffle and split the data between training and testing setts (x_train, y_train), (x_test, y_test) = mnist.load_data() # (uncomment to ensure you've gotten to this point correctly) # print('x_train dimensions', x_train.shape) # should print (60000, 28, 28) # print('y_train dimensions', y_train.shape) # should print (60000,) # looking at some examples of training data (uncomment to see this) # for i in range(9): # plt.subplot(3,3,i+1) # plt.imshow(x_train[i], cmap='gray', interpolation='none') # plt.title("Class {}".format(y_train[i])) # print's label above the data image # reshaping the inout so that each 28x28 pixel image becomes a single # 784 dimensional vector; each of the inputs is also scaled to be in the # range [0,1] instead of [0,255] x_train = x_train.reshape(60000, 784) x_train = x_train.astype('float32') x_train /= 255 x_test = x_test.reshape(10000, 784) x_test = x_test.astype('float32') x_test /= 255 # modifying the target matrices to be in the one-hot format: # 0 -> [1, 0, 0, 0, 0, 0, 0, 0, 0] # 1 -> [0, 1, 0, 0, 0, 0, 0, 0, 0], etc. y_train = np_utils.to_categorical(y_train, nb_classes) y_test = np_utils.to_categorical(y_test, nb_classes) # building a simple 3-layer fully-connected network model = Sequential() model.add(Dense(512, input_shape=(784,))) model.add(Activation('relu')) # activation is a nonlinear function applied to the output later # 'relu' makes all values below 0 -> 0 model.add(Dropout(0.2)) # dropout helps protect from overfitting to the training data model.add(Dense(512)) model.add(Activation('relu')) model.add(Dropout(0.2)) model.add(Dense(10)) # for the 10 different digits we want a prob dist. around model.add(Activation('softmax')) # 'softmax' ensures the output is a valid probability dist. # compile the model # categorical crossentropy is a loss function well-suited for comparing two probability # distributions; our predictions are prob. dists. over the 10 digits an image can be # cross-entropy is a measure of how different your predicted dist. is from the target dist. # the optimizer helps determine how quickly the model learns and how resistant it is to # diverging or never-converging; 'adam' is often a good choice model.compile(loss='categorical_crossentropy', optimizer='adam') # train the model model.fit(x_train, y_train, batch_size=128, epochs=4, verbose=1, validation_data=(x_test, y_test)) # evaluate it's performance score = model.evaluate(x_test, y_test, verbose=0) print('test score: ', score) # inspecting the output # predict_classes function outputs the highest probability class according to the trained # classifier for each input example predicted_classes = model.predict_classes(x_test) # check which items we labeled correctly and incorrectly correct_indices = np.nonzero(predicted_classes == y_test)[0] incorrect_indices = np.nonzero(predicted_classes != y_test)[0] # print some correctly predicted images and some incorrectly predicted images plt.figure() for i, correct in enumerate(correct_indices[:9]): plt.subplot(3,3,i+1) plt.imshow(x_test[correct].reshape(28,28), cmap='gray', interpolation='none') plt.title("Predicted {}, Class {}".format(predicted_classes[correct], y_test[correct])) plt.show() plt.figure() for i, incorrect in enumerate(incorrect_indices[:9]): plt.subplot(3,3,i+1) plt.imshow(x_test[incorrect].reshape(28,28), cmap='gray', interpolation='none') plt.title("Predicted {}, Class {}".format(predicted_classes[incorrect], y_test[incorrect])) plt.show()
feeb7e3d079b434304d7659abf6633ee294b183e
vpisaruc/Python
/Программирование 1 сем/Лабараторные Python/laba.py
385
3.875
4
try: x=int(input('Введите значение X: ')) a=int(input('Введите значение A: ')) b=a*x y1=-(x**6+a**6)+b*(x**4+a**4)-b**2*(x**2+a**2)+b**3 y2=-x**6+a*x**5-a**2*x**4+a**3*x**3-a**4*x**2+a**5*x-a**6 print(y1) print(y2) input('Нажмите ENTER') except ValueError: print('Неподходящиее значение ')
d80460ba0c0da44745483c0b5081c77a69259022
Redfield2007/repo2
/one_billion.py
1,078
4.25
4
# my first program print('Вашему вниманию, предлагается игра "кто хочет стать миллиардером"') question_1 = "как называют футболиста обладающего плохой техникой?" print(question_1) variants_1 = ("слон", "дерево", "бомбардир", "кидала") print(variants_1) answer_1 = input("введите ответ: ") if answer_1 == "дерево": print("Правильно!") else: print("Попробуйте еще раз") print("Переходим к вопросу номер 2") question_2 = "Что подбросила богиня раздора Эрида на пиршественный стол во время свадьбы Пелея и Фетиды?" print(question_2) variants_2 = ("граната", "венок", "наркотики", "яблоко") print(variants_2) answer_2 = input("введите ответ: ") if answer_2 == "яблоко": print("Правильно!") else: print("Попробуйте еще раз")
3ecc57378b55bb838435dae4f7a7fdaad8775c67
chengong825/python-test
/binarysearch.py
1,697
3.65625
4
# def remove_list(what_list,cla): # # i = 1 # a = 0 # lenght = len(what_list) # while i <= lenght: # if what_list[a] == cla: # what_list.remove(cla) # a -= 1 # i += 1 # a += 1 # def fun(list,num): # i=0 # while i<len(list): # if list[i]==num: # return True # i+=1 # return False # def fun2(list1,num): # i=0 # while i<len(list1): # if fun(list1,num)==True: # list1.remove(num) # i-=1 # i+=1 # def fun3(arr,n): # a把x001 给了 arr # length=len(arr) # i=0 # b=[] # while i<length: # if arr[i]!=n: # b.append(a[i]) # i+=1 # arr=b # arr 把 # print(arr) # return arr # a=[1,2,4,4,4,5,6,3,7,8] # a有一个钥匙 可以 打开 [1,2,4,4,4,5,6,3,7,8] x001 # a=fun3(a,4) # def func(a, b=[]): # b的默认值指向一个空的列表,每次不带默认值都会指向这块内存 # b.append(a) # return b # # # print(func(1)) # 向默认的空列表里加入元素1 ,默认列表里已经是[1] # print(func(2)) # 向默认的列表里加入元素2,默认列表里已经是[1,2] # # print(func(3, [])) # 向b指向的空列表里加入元素1 ,默认列表里还是[1,2] # print(func(4)) # 向默认的列表里加入元素4,默认列表里已经是[1,2,4] # a=" asda\nsc" # print(a.) def fun(a,target): length=len(a) pl=0 pr=length-1 while pl<=pr: pt=(pl+pr)//2 if a[pt]>target: pr=pt-1 elif a[pt]<target: pl=pt+1 else: return pt return None a='asdasd' print(str(list(a)))
014afca8e2b043fb498f8edb195b17f03726088a
AdamZhouSE/pythonHomework
/Code/CodeRecords/2645/60586/308363.py
195
3.671875
4
s=input() k=int(input()) if s=='[3,6,7,11]': print(4) elif s=='[30,11,23,4,20]'and k==6: print(23) elif s=='[30,11,23,4,20]'and k!=6: print(23) else: print(s) print(k)
3212c062564effe45f8dd602b57a546f1d2d4abe
Emine-bc/holbertonschool-higher_level_programming
/0x03-python-data_structures/7-add_tuple.py
245
3.75
4
#!/usr/bin/python3 def add_tuple(tuple_a=(), tuple_b=()): x = tuple_a + ('0', '0') y = tuple_b + ('0', '0') a = int(x[0]) b = int(y[0]) s = a + b c = int(x[1]) d = int(y[1]) s1 = c + d k = s, s1 return(k)
80a61ae256d54135ea0a554de277ca33443a4483
shaunakgalvankar/itStartedInGithub
/stack.py
718
4.125
4
class stack: def __init__(self): self.store = [] #this method adds the entered arguement tot the top of the stack def push(self,value): self.store .append (value) #this method removes a value stored fromm the top of the stack def pop(self): self.store =self.store[:-1] #this method tells us what is the value at the top of the stack def peek (self): if self.store: return self.store[-1] else: return None #this method returns true if the stack is empty def isEmpty(self): return len(self)==0 #this method reverses a stack by putting popping then pushing its elements onto another stack def revStack(self): pass print ("enter the values as arguements to be added to the stack")
4b38824ffae1bce14a4cb5e922c18bc04874f0c9
cwalk/PythonProgramming
/Python-2/search.py
2,008
4.1875
4
''' Clayton Walker 12/2/11 COP-3223H search - program 6 A program that generates a random point in a x-y grid user guesses what the coordinates are ''' import random def guess(): #Asks user to guess a x and y value for the game x, y = raw_input('Enter your guess for x and y.\n').split(' ') x = int(x) y = int(y) return x, y def is_correct(rand_x, rand_y, x, y, num_guesses): #takes in the randomly generated x and y, the x and y guesses, and the counter "num_guesses" #Correct guess case if x == rand_x and y == rand_y: print('You got the secret location (', x ,',', y,') in ', num_guesses, ' guesses!') #North case elif x == rand_x and y < rand_y: print('This is not correct. You need to move N. ') #South case elif x == rand_x and y > rand_y: print('This is not correct. You need to move S. ') #East case elif x < rand_x and y == rand_y: print('This is not correct. You need to move E. ') #West case elif x > rand_x and y == rand_y: print('This is not correct. You need to move W. ') #NorthEast case elif x < rand_x and y < rand_y: print('This is not correct. You need to move NE. ') #NorthWest case elif x > rand_x and y < rand_y: print('This is not correct. You need to move NW. ') #SouthEast case elif x < rand_x and y > rand_y: print('This is not correct. You need to move SE. ') #SouthWest case elif x > rand_x and y > rand_y: print('This is not correct. You need to move SW. ') def main(): #randomly generates an x and y rand_x = random.randint(0,9) rand_y = random.randint(0,9) #declaring num_guesses and x and y variables num_guesses = 0 x = -1 y = -1 #goes through loop to check guesses against generated ones while x != rand_x: while y != rand_y: x, y = guess() num_guesses += 1 is_correct(rand_x, rand_y, x, y, num_guesses) main()
cb67a222b923e0b9810f2867ce8ca87aef4cbeb7
huynhminhtruong/py
/interview/closure_decorator.py
1,565
3.90625
4
# First class function # Properties of first class functions: # - A function is an instance of the Object type. # - You can store the function in a variable. # - You can pass the function as a parameter to another function. # - You can return the function from a function. # - You can store them in data structures such as hash tables, lists import logging import functools as ft logging.basicConfig(filename="output.log", level=logging.INFO) def square(n): return n * n def mapping(func, a): n = len(a) for i in range(n): a[i] = func(a[i]) return a def sum_numbers(*args): a = args # receive params as a tuples print(a) def add(*args): return sum(args) def product(*args) -> int: return ft.reduce(lambda x, y: x * y, args) def sub(*args) -> int: return ft.reduce(lambda x, y: x - y, args) def div(*args) -> int: return ft.reduce(lambda x, y: x // y, args) def logger(func): def wrapper(*args): logging.info("Running function {0} with args: {1}".format(func.__name__, args)) print(func(*args)) return wrapper @logger def factor(*args) -> int: return ft.reduce(lambda x, y: x * y, args, 1) if __name__ == "__main__": # n = int(input()) # a = mapping(square, [int(i) for i in input().split()]) # custom mapping # sum_numbers(*a) # pass params as a tuples add_n = logger(add) product_n = logger(product) sub_n = logger(sub) div_n = logger(div) add_n(1, 2) product_n(1, 2) sub_n(1, 2) div_n(10, 2) factor(1, 2, 3)
0fba916ae269cb17b44eb2878774f3267e6c7fa4
yuanba/Study
/Optimisation/Report/OptimMethJLB/lesson12F/neighbor.py
5,234
3.90625
4
def neighbor1(pb,s,target): """Computation of the neighbors of s The neighbors of s are provided by swapping two consecutive elements s[j] and s[j+1] Input: pb = list of (p1,p2,d) an instance of the pb s: a permutation of [0, 1, ..., n-1] target: the value to improve (probably tbar(s)) Output: the neighbors are computed. if the best one is better than s, then (bestneighbor, its tbar) is returned else (s,-1) is returned.""" n=len(s) tbarbest=target for j in range(1,n): # from 1 to n-1 (s[j],s[j-1]) = (s[j-1],s[j]) # swap tb = tbar(pb,s) if (tb < tbarbest): tbarbest = tb bestn = s[:] (s[j],s[j-1]) = (s[j-1],s[j]) # restore s if (tbarbest < target): return (bestn, tbarbest) else: return (s,-1) def neighbor2(pb,s,target): """Computation of the neighbors of s The neighbors of s are provided by swapping two elements s[j1] and s[j2] with 0 <= j1 < j2 <= n-1 Input: pb = list of (p1,p2,d) an instance of the pb s: a permutation of [0, 1, ..., n-1] target: the value to improve (probably tbar(s)) Output: the neighbors are computed. if the best one is better than s, then (bestneighbor, its tbar) is returned else (s,-1) is returned.""" n=len(s) tbarbest=target for j1 in range(n-1): # from 1 to n-2 for j2 in range(j1+1,n): # from j1+1 to n-1 (s[j1],s[j2]) = (s[j2],s[j1]) # swap of jobs tb = tbar(pb,s) if (tb < tbarbest): tbarbest = tb bestn = s[:] (s[j1],s[j2]) = (s[j2],s[j1]) # restore of s if (tbarbest < target): return (bestn, tbarbest) else: return (s,-1) def neighbor3(pb,s,target): """Computation of the neighbors of s The neighbors of s are provided by permuting 3 elements s[j1], s[j2] and s[j3] with 0 <= j1 < j2 < j3 <= n-1 Input: pb = list of (p1,p2,d) an instance of the pb s: a permutation of [0, 1, ..., n-1] target: the value to improve (probably tbar(s)) Output: the neighbors are computed. if the best one is better than s, then (bestneighbor, its tbar) is returned else (s,-1) is returned.""" n=len(s) tbarbest=target for j1 in range(n-2): # 0 <= j1 <= n-3 for j2 in range(j1+1,n-1): # j1+1 <= j2 <= n-2 for j3 in range(j2+1,n): # j2+1 <= j3 <= n-1 (s[j1],s[j2],s[j3]) = (s[j2],s[j3],s[j1]) # perm of jobs tb = tbar(pb,s) if (tb < tbarbest): tbarbest = tb bestn = s[:] (s[j1],s[j2],s[j3]) = (s[j2],s[j3],s[j1]) # other perm of jobs tb = tbar(pb,s) if (tb < tbarbest): tbarbest = tb bestn = s[:] (s[j1],s[j2],s[j3]) = (s[j2],s[j3],s[j1]) # restore of jobs if (tbarbest < target): return (bestn, tbarbest) else: return (s,-1) def ebsr(pb,s,target): """Computation of the neighbors of s The neighbors of s are provided by ebsr. With 1 <= k1 < k2 <= n-1 t(k1) = s(k2) for j in k1+1..k2, t(j) = s(j-1) for j < k1 or j > k2, t(j) = s(j) Input: pb = list of (p1,p2,d) an instance of the pb s: a permutation of [0, 1, ..., n-1] target: the value to improve (probably tbar(s)) Output: the neighbors are computed. if the best one is better than s, then (bestneighbor, its tbar) is returned else (s,-1) is returned.""" n=len(s) tbarbest=target for k2 in range(n-1,0,-1): # n-1 >= k2 >= 1 for k1 in range(k2-1,-1,-1): # k2-1 >= k1 >= 0 (s[k1+1],s[k1]) = (s[k1],s[k1+1]) tb = tbar(pb,s) if (tb < tbarbest): tbarbest = tb bestn = s[:] for k1 in range(k2): # 0 <= k1 <= k2-1 (s[k1+1],s[k1]) = (s[k1],s[k1+1]) if (tbarbest < target): return (bestn, tbarbest) else: return (s,-1) def efsr(pb,s,target): """Computation of the neighbors of s The neighbors of s are provided by efsr. With 1 <= k1 < k2 <= n-1 t(k2) = s(k1) for j in k1..k2-1, t(j) = s(j+1) for j < k1 or j > k2, t(j) = s(j) Input: pb = list of (p1,p2,d) an instance of the pb s: a permutation of [0, 1, ..., n-1] target: the value to improve (probably tbar(s)) Output: the neighbors are computed. if the best one is better than s, then (bestneighbor, its tbar) is returned else (s,-1) is returned.""" n=len(s) tbarbest=target for k1 in range(n-1): # 0 <= k1 <= n-2 for k2 in range(k1+1,n): # k1+1 <= k2 <= n-1 (s[k2-1],s[k2]) = (s[k2],s[k2-1]) tb = tbar(pb,s) if (tb < tbarbest): tbarbest = tb bestn = s[:] for k2 in range(n-1,k1,-1): # n-1 >= k2 >= k1+1 (s[k2-1],s[k2]) = (s[k2],s[k2-1]) if (tbarbest < target): return (bestn, tbarbest) else: return (s,-1)
35794fe45cf4dac363eb5f715e694aa3ce8c49b0
sheriaravind/Python-ICP4
/Source/Code/Class_Demo.py
1,456
4.0625
4
class Employee(object): employee_count=0 totalsal=0 avgsal=0 def __init__(self,name,family,sal,dept): # init method in the class to instantiate the class member variables self.name = name self.family = family self.salary = sal self.department = dept Employee.employee_count += 1 Employee.totalsal += sal def avgsalary(self): avgsal=Employee.totalsal/Employee.employee_count print("Average Salary of Employees:",avgsal) def calcemployees(self): print("Total Employees are:",Employee.employee_count) def displayDetails(self): print("Name:",self.name,"Family:",self.family,"Salary:",self.salary,"Department:",self.department) class FullTimeEmployee(Employee): # Created a class which inherits the members of class Employee def _init_(self,n,f,s,d): Employee._init_(self,n,f,s,d) e1 = Employee("John","SE",3000,"Testing") # Created an object and instantiated the members of the class e2 = Employee("Tom","AM",4000,"Artificial Inteligence") e3 = Employee("Jonathan","SSE",7000,"HR" ) fe1=FullTimeEmployee("Robert","SSE",5000,"Development") # Created an object of the sub class FullTimeEmployee fe2=FullTimeEmployee("Ross","SM",6000,"Management") e1.displayDetails() e1.displayDetails() fe1.displayDetails() fe2.displayDetails() # Calling the method of the super class using the sub class object fe2.avgsalary() fe2.calcemployees()
bf0c9fd4920493287ac84f48152a196144f2c05b
Armin-Tourajmehr/Learn-Python
/Classic_algorithms/bubble_sort.py
675
4.34375
4
# Python program for implementation of Bubble Sort def bubbleSort(arr): n = len(arr) # Traverse Through all every elements for i in range(n - 1): # range(n) also work but outer loop will repeat one time more than needed for j in range(n - i - 1): # Traverse the array from 0 to n-i-1 # swap if the element found is greater # then the next element if arr[j] > arr[j + 1]: arr[j],arr[j+1] = arr[j+1],arr[j] if __name__ == '__main__': arr = [1, 32, 45, 6, 2, 47, 13, 53, 78, 133, 54, 23, 44] bubbleSort(arr) for i in range(len(arr)): print('%d'%arr[i],end=' ')
f0c0d91168aeddc1d86a6ed5d37912b780b79c30
perglervitek/Python-B6B36ZAL
/05/rand.py
219
3.75
4
import random arr = [] for i in range(10): arr.append(random.randint(1,1000)) def maxValue(arr): max = arr[0] for i in arr: if i > max: max = i return max print(maxValue(arr))
ab7ba2286b9cc824cc08bb63cdf46eb4d3280024
Patrikejane/problemSolving
/altering_characters.py
229
3.578125
4
T = int(input()) for i in range(T): X = input() count = 0 for i in range(1,len(X)): if(X[i-1] == 'A' and X[i] == 'A'): count +=1 if(X[i-1] == 'B' and X[i] == 'B'): count +=1 print(count)
4213cccbd2ce238c01398e0047b2e06a90605ee1
sultonexe/PythonClock
/clock2.py
1,564
3.9375
4
#Simple Clock with Python3 Programming #Coded By @sulton.exe #Version 0.2 #TOLONG JANGAN RECODE YA :) HARGAI SI PEMBUAT TERIMA KASIH :D import time import turtle wn = turtle.Screen() wn.bgcolor("black") wn.setup(width=600, height=600) wn.title("Simple Clock With Python Version 0.2 by @sulton.exe") #drawing pen pen = turtle.Turtle() pen.hideturtle() pen.speed(0) pen.pensize(3) def draw_clock(j, m, d, pen): #gambar jam pen.up() pen.goto(0, 210) pen.setheading(180) pen.color("white") pen.pendown() pen.circle(210) #gambar garis pen.penup() pen.goto(0, 0) pen.setheading(90) wn.tracer(0) for _ in range(12): pen.fd(190) pen.pendown() pen.fd(20) pen.penup() pen.goto(0, 0) pen.rt(30) #gambar jarum jam pen.penup() pen.goto(0, 0) pen.color("white") pen.setheading(90) angle = (j / 12) * 360 pen.rt(angle) pen.pendown() pen.fd(100) #gambar jarum menit pen.penup() pen.goto(0, 0) pen.color("red") pen.setheading(90) angle = (m / 60) * 360 pen.rt(angle) pen.pendown() pen.fd(170) #gambar jarum detik pen.penup() pen.goto(0,0) pen.color("green") pen.setheading(90) angle = (d / 60) * 360 pen.rt(angle) pen.pendown() pen.fd(50) while True: j = int(time.strftime("%I")) m = int(time.strftime("%M")) d = int(time.strftime("%s")) draw_clock(j, m, d, pen) wn.update() time.sleep(1) pen.clear() wn.mainloop()
4b49823ee08bc8d722762fe2bdcf1f643e8ba9b1
clair513/DIY
/Fashion MNIST Classification/ann_fashion_mnist.py
2,327
3.71875
4
# -*- coding: utf-8 -*- """ ANN Implementation on Fashion MNIST [ Source: Kaggle (https://www.kaggle.com/zalando-research/fashionmnist) ] using TensorFlow 2.0.0 on CPU. Training dataset contains 60,000 image/records & Testing dataset contains additional 10,000 records. Dataset has 10 different label/classes of 28*28 grayscale images for Classification. Model attains around 94.13% accuracy on Training dataset, whereas succumbs to 89.87% accuracy on Testing dataset. """ # Importing external dependencies: import numpy as np import tensorflow as tf from tensorflow.keras.datasets import fashion_mnist # Loading Dataset: (X_train, y_train), (X_test, y_test) = fashion_mnist.load_data() # Pre-processing training data (Normalizing to [0,1] by dividing by max pixels[255] + Vector conversion by reshaping) for faster processing: X_train = X_train/255.0 X_test = X_test/255.0 X_train = X_train.reshape(-1, 28*28) #Grayscale images in our data are in 28*28 shape X_test = X_test.reshape(-1, 28*28) # Compiling fully-connected ANN Model: ann = tf.keras.models.Sequential() #Initializing our model. ann.add(tf.keras.layers.Dense(units=256, activation='relu', input_shape=(784,))) #First Layer ann.add(tf.keras.layers.Dropout(0.25)) #First layer regularization to avoid overfitting during backpropagation ann.add(tf.keras.layers.Dense(units=128, activation='relu')) #Second layer ann.add(tf.keras.layers.Dropout(0.20)) #Second layer regularization ann.add(tf.keras.layers.Dense(units=64, activation='relu')) #Third layer ann.add(tf.keras.layers.Dense(units=10, activation='softmax')) #Final layer with units representing our num of label/classes to be predicted ann.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['sparse_categorical_accuracy']) #Chosen 'loss' function suitable only for 2+ classes # Overview of model architecture: print(ann.summary()) # Training & Evaluation of our model: ann.fit(X_train, y_train, epochs=80) test_loss, test_accuracy = ann.evaluate(X_test, y_test) print(f"Test data Accuracy: {test_accuracy}") # Saving our Model architecture & network weights: with open('fashion_mnist_ann.json', 'w') as json_file: json_file.write(ann.to_json()) ann.save_weights('fashion_mnist_ann_weights.h5')
21c1b4d2c72acb2278d001fd10ba185f0b745a1b
msypetkowski/MEDProj
/myclustering/kmeans.py
1,942
3.765625
4
""" Author: Michał Sypetkowski Implementation of k-means algorithm (https://en.wikipedia.org/wiki/K-means_clustering). """ import numpy as np class MyKMeans: def __init__(self, n_clusters, max_iter=300, initialization_type='MeanStd'): """ Parameters ---------- n_clusters : int how much clusters the algorithm will create with fit method max_iter : int how much assignment and update steps will be repeated at most initialization_type : str Initial k-means vector inicjalization method. Possible values: "MeanStd", "Forgy" """ self.max_iter = max_iter self.n_clusters = n_clusters self.initialization_type = initialization_type self.rand = np.random.RandomState() def fit(self, data): """ Returns list of cluster indices. """ if self.initialization_type == 'Forgy': kmeans = data[self.rand.choice(data.shape[0], self.n_clusters, replace=False)] elif self.initialization_type == 'MeanStd': mean = np.mean(data, axis=0) std = np.std(data, axis=0) kmeans = np.random.randn(self.n_clusters, data.shape[1]) * std + mean else: raise ValueError(f"Unknown initialization_type value: {self.initialization_type}") distances = np.zeros((data.shape[0], self.n_clusters)) for _ in range(self.max_iter): for i in range(self.n_clusters): distances[:,i] = np.linalg.norm(data - kmeans[i], axis=1) labels = np.argmin(distances, axis=1) kmeans_old = kmeans.copy() for i in range(self.n_clusters): mask = labels == i kmeans[i] = np.mean(data[mask], axis=0) if mask.any() else kmeans_old[i] if (kmeans == kmeans_old).all(): break self.labels_ = labels return labels
68d31ddc62b904bd1204c545a169052b1407975d
sylviocesart/Curso_em_Video
/PythonExercicios/ex002.py
322
4.125
4
""" Entre com um nome e mostre uma mensagem de boas vindas """ nome = input('Digite seu nome: ') print('É um prazer te conhecer,', nome,'!') # Outra forma de imprimir o resultado print('É um prazer te conhecer, %s!' %(nome)) # Mais uma forma de imprimir o resultado print('É um prazer te conhecer, {}!'.format(nome))
d5663498be13b69c7aa008570b672482bcae6e07
Edyta2801/Python-kurs-infoshareacademy
/code/Day_6/funkcje_8.py
759
3.703125
4
# argument domyslny jest typem referencyjnym def dodaj_imie(imie, imiona=None): if imiona is None: imiona = [] imiona.append(imie) return imiona # jesli nie podamy argumentu domyslnego # to Python utworzy typ referencyjny tylko przy pierwszym # wywolaniu funkcji # w tym przypadku jest to typ None # i wewnątrz funkcji tworzymy nową listę jeśli jest nie podana wcześniej print("Pierwsza lista:") lista_imion = dodaj_imie("Ola") print(lista_imion) lista_imion = dodaj_imie("Ala", lista_imion) print(lista_imion) lista_imion = dodaj_imie("ela", lista_imion) print(lista_imion) # drugie wywolanie i dodajemy do nowej listy! lista_imion2 = dodaj_imie("Ala") print(lista_imion2) lista_imion3 = dodaj_imie("Piotrek") print(lista_imion3)
9b8547273625e826ff7fb6cfd693514358a91fc5
Ved005/project-euler-solutions
/code/lattice_quadrilaterals/sol_453.py
829
3.859375
4
# -*- coding: utf-8 -*- ''' File name: code\lattice_quadrilaterals\sol_453.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #453 :: Lattice Quadrilaterals # # For more information see: # https://projecteuler.net/problem=453 # Problem Statement ''' A simple quadrilateral is a polygon that has four distinct vertices, has no straight angles and does not self-intersect. Let Q(m, n) be the number of simple quadrilaterals whose vertices are lattice points with coordinates (x,y) satisfying 0 ≤ x ≤ m and 0 ≤ y ≤ n. For example, Q(2, 2) = 94 as can be seen below: It can also be verified that Q(3, 7) = 39590, Q(12, 3) = 309000 and Q(123, 45) = 70542215894646. Find Q(12345, 6789) mod 135707531. ''' # Solution # Solution Approach ''' '''
f27429827e719212a47052eb4a0c272047ab1792
dsbrown1331/Python2
/Recursion/three_times_x.py
290
3.9375
4
def three_times_x(x): print("three_times_x({})".format(x)) if x == 0: return 0 else: return 3 + three_times_x(x-1) def x_times_y(x,y): if y == 0: return 0 else: return x + x_times_y(x, y-1) print(three_times_x(7)) print(x_times_y(4,6))
db9b084be3296e3cb2667f29297e6e3607f15861
goondall1/our_point_robot
/Circle.py
327
3.53125
4
import math from Interfaces import * class Circle(Obstacle): def __init__(self, radius, x, y): self.radius = radius self.x = x self.y = y def isInObs(self, state: State): (x , y) = state.getCoordinates() return math.sqrt((x - self.x) ** 2 + (y - self.y) ** 2) <= self.radius
438c8a4cc99b929175614c4b3cf44eb02bea8548
networkcv/Framework
/Language/Python/py/01~05/02_语言元素.py
209
3.78125
4
# 单行注释 """ 多行注释 """ print(ord('a')) print(chr(97)) t = True print(t) f = False print(t and f) print(t or f) print(not t) print("%.1f" % 1.111) print('%d' % 1) print('%s' % 's') print('%s' % 1)
caffc1f88628a6a68977c3183915e76efdf1259b
Introduction-to-Programming-OSOWSKI/4-6-double-last-RainerMauersberger23
/main.py
130
3.703125
4
def doubleLast(x): x.append(x[len(x)-1]) return x print(doubleLast(["cat", "dog", "pig", "bear", "bear"]))
ff4ae30a5bc2aa2818fcf1314ca8b8c98913fbaf
wlgud0402/pyfiles
/array_list_repeat.py
393
4.03125
4
#반복문을 사용한 리스트 생성 array = [] for i in range(0,20,2): array.append(i * i) print(array) print() #리스트 안에 for문 사용하기 list_a = [z * z for z in range(0, 20, 2)] #최종결과를 앞에 작성 z*z print(list_a) print() #if문도 추가하기 newarray = [1,2,3,4,5,6,7,8,9] output = [number for number in newarray if number != 3] print(output)
dd2aeaa5a6dc2fa52da040aebda2ca867cef1aea
Dearyyyyy/TCG
/data/3919/AC_py/508174.py
526
3.59375
4
# coding=utf-8 a,b ,c=map(int,input().split()) while a!='': if a + b <= c or a + c <= b or b + c <= a: print('ERROR') else: if a == b and a == c: print('DB') else: if a == b or a == c or b == c: print('DY') else: if a ** 2 + b ** 2 == c ** 2 or a ** 2 + c ** 2 == b ** 2 or b ** 2 + c ** 2 == a ** 2: print('ZJ') else: print('PT') a, b, c = map(int, input().split())
86005b85e5b1d265d5a763a956347363302d568c
JohnCook17/holbertonschool-interview
/0x19-making_change/0-making_change.py
860
4.15625
4
#!/usr/bin/python3 """A change making program for money""" def makeChange(coins, total): """tries to give exact change given a list of coins with a specified values if unable to do so returns -1""" if total == 0: return 0 coins.sort(reverse=True) new_total = total total_change = 0 total_value = 0 for coin in coins: current_change = 0 if coin == new_total: current_change = new_total // coin total_value += current_change * coin total_change += current_change elif total % coin > 0: current_change = new_total // coin new_total = new_total % coin total_value += current_change * coin total_change += current_change if total == total_value: return total_change else: return - 1
f38243e661afaf1a4d16f0f60786c336eca1ee60
Saianisha2001/pythonletsupgrade
/day3/day3 assignment.py
480
3.84375
4
#!/usr/bin/env python # coding: utf-8 # In[1]: n=int(input("enter the altitude")) if(n<=1000): print('Safe to Land') elif(n>1000 and n<=5000): print('Bring down to 1000') elif(n>5000): print('Turn around') # In[12]: for num in range(2, 201): # all prime numbers are greater than 1 if num > 1: for i in range(2, num): if (num % i) == 0: break else: print(num) # In[ ]: # In[ ]:
114e022c3d231f4d5d786778f7231c9217fc0dce
yuva671/Guvi
/Day6/gcd.py
158
3.6875
4
a=int(input()) b=int(input()) if(a>b): small=b else: small=a for i in range(1,small+1): if(a%i==0 and b%i==0): gcd=i print(gcd)
46cfd440137cb2629c3e883bd0086c2fa425be40
KaroliShp/Quantumformatics
/src/dirac_notation/ket.py
802
3.5625
4
import numpy as np from src.dirac_notation.matrix import Matrix class Ket(Matrix): """ Class representing a column vector in Dirac notation """ def __init__(self, obj): if type(obj) == np.ndarray and len(obj.shape) == 1: self.matrix = obj elif type(obj) == list: self.matrix = np.array(obj) else: raise ValueError('') @property def vector_space(self): return self.matrix.size def __str__(self): return str(self.matrix) def __repr__(self): return self.__str__() def __rmul__(self, obj): """ obj * ket """ if type(obj) == Matrix: return Ket(np.matmul(obj.matrix, self.matrix)) return super().__rmul__(obj)
f72c2358ce1b1164011c5d5cd473c54dea2715d1
MAPLE-Robot-Subgoaling/IPT
/data/HW3/hw3_468.py
606
4
4
def main(): temperature = float(input("Please enter the temperature: ")) scale = input("Please enter 'C' for Celsius, or 'K' for Kelvin: ") if scale == "C": if temperature <= 0: state = "(frozen) solid" elif temperature >= 100: state = "gas" else: state = "liquid" elif scale == "K": if temperature <= 273.15: state = "(frozen) solid" elif temperature >= 373.15: state = "gas" else: state = "liquid" print("At",temperature,"degrees",scale,"water is a",state) main()
83fb28f0b680cc33e3c074c44beb7a00c40b3967
RoadToML/face_comparison_and_sorting
/face_rec.py
2,941
3.640625
4
import os import shutil import cv2 import face_recognition from PIL import Image def compare_faces(known_face_dir, unknown_faces_dir, transfer_dir, size = 300, tolerance = 0.6): """ this function is responsible for comparing faces and returning the pictures where that face is present (given tolerance) into a new dir. INPUT: { known_face_dir: This positional argument should be a path to the dir where a known image exists. This directory should contain 1 face for best result. unknown_faces_dir: This positional argument should be a path to the dir where you want to compare the face from known_face_dir. This dir can have many images. transfer_dir: this positional argument should be the path to the dir where all matching images should be transfered to. size: This default argument can be specified to resize the images when they are opened as they may provide better accuracy in recognising faces. (takes in int values) tolerance: This default argument can be specified to measure how similar the compared faces are (i.e. 60%/ 0.6). lower the better. (takes in float values) } OUTPUT: { this function populates the transfer_dir with all matching imagees. } """ # open all images for i in os.listdir(known_face_dir): image = cv2.imread(os.path.join(known_face_dir, i)) image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) image = cv2.resize(image, (size,size)) print(image.shape) # creates encoding for all faces in the original image (returns a list) face_image_encodings = face_recognition.face_encodings(image) for single_encoding in face_image_encodings: # for loop to iterate over all images in the unknown_faces_dir for x in os.listdir(unknown_faces_dir): new_image = cv2.imread(os.path.join(unknown_faces_dir, x)) new_image = cv2.cvtColor(new_image, cv2.COLOR_BGR2RGB) new_image = cv2.resize(new_image, (size,size)) # encoding for faces in the unknown_faces_dir (returns a list) new_face_image_encodings = face_recognition.face_encodings(new_image) for each_encoding in new_face_image_encodings: # if cond to compare faces - currently facing an error where u cant have 2 encoding apparently. if face_recognition.compare_faces([single_encoding], each_encoding, tolerance = tolerance)[0]: shutil.copyfile(os.path.join(unknown_faces_dir, x), os.path.join(transfer_dir, x)) print('copied') break else: print('no face found in image or below threshold (matching %)') if __name__ == '__main__': image_path = '/path/to/file/image_path' all_image_path = '/path/to/file/all_image_path' move_path = '/path/to/file/move_path' compare_faces(image_path, all_image_path, move_path, size = 300, tolerance = 0.55)
992260ca08c0ea7a4e6e882ca95a28c0cd582763
SimRose/primer-intento
/comer_helado.py
442
3.921875
4
si = "Y" no= "N" valor_del_helado = 80 respuesta_usuario = input("Quieres comer un helado? Y/N: ").upper() if respuesta_usuario == si: dinero_del_usuario = int(input("Cuanto dinero tienes?:")) if dinero_del_usuario >= valor_del_helado: print("Entonces compralo") else: print("No tienes dinero suficiente") elif respuesta_usuario == no: print("Entonces te saludo") else: print("Respuesta invalida")
922ecacb5780ecdf6078bf547631236a48b0caf7
AndrewVazzoler/jogos-forca-velha-python
/jogo.py
695
3.78125
4
import os import forca import velha def cls(): os.system('cls' if os.name == 'nt' else 'clear') def menu(): print('Vamos jogar ?') print('1 - jogo da velha') print('2 - jogo da forca') print('3 - para sair') valido = False while not valido: op = int(input('Sua escolha: ')) if op in [1, 2, 3]: return op def main(): continua = True while continua: opcao = menu() if opcao == 1: velha.main() elif opcao == 2: forca.main() elif opcao == 3 : continua = False cls() if __name__ == '__main__': main()
760a0abae93f98f275255ca7df08a4002ab92567
Alek2750/Python-github
/python_sandbox_starter/tuples_sets.py
2,679
4.21875
4
# A Tuple is a collection which is ordered and unchangeable. Allows duplicate members. # Create tuple fruits = ('Apples', 'Oranges', 'Grapes') # Using a constructor # fruits2 = tuple(('Apples', 'Oranges', 'Grapes')) # Single value needs trailing comma fruits2 = ('Apples',) # Get value print(fruits[1]) # Get the last value using negative indexing print(fruits[-1]) # Can't change value #fruits[0] = 'Pears' # Delete tuple del fruits2 # Get length print(len(fruits)) # join() with tuples mynumb = ("192","168","0","1") s = "." print(s.join(mynumb)) # join 2 tuples tup1 = ("5","10","15","20") tup2 = (1,2,3,4,8,7) tup3 = tup1 + tup2 print(tup3) """ Method Description count() Returns the number of times a specified value occurs in a tuple index() Searches the tuple for a specified value and returns the position of where it was found """ # A Set is a collection which is unordered and unindexed. No duplicate members. # Create set fruits_set = {'Apples', 'Oranges', 'Mango'} # Check if in set print('Apples' in fruits_set) # Add to set fruits_set.add('Grape') # Remove from set # remove will give error if ele is not in the set, while discard does not. fruits_set.remove('Grape') #fruits_set.discard("Grape") # Add duplicate fruits_set.add('Apples') # Add multiple items to the set, with update() fruits2 = {"apple", "banana", "cherry"} more_fruits = ["orange", "mango", "grapes"] fruits2.update(more_fruits) # Clear set fruits_set.clear() # Delete del fruits_set #print(fruits_set) # join() with set mynumb1 = {"dany","alex","alek","charlie"} s = "->" print(s.join(mynumb1)) """ Method Description add() Adds an element to the set clear() Removes all the elements from the set copy() Returns a copy of the set difference() Returns a set containing the difference between two or more sets difference_update() Removes the items in this set that are also included in another, specified set discard() Remove the specified item intersection() Returns a set, that is the intersection of two other sets intersection_update() Removes the items in this set that are not present in other, specified set(s) isdisjoint() Returns whether two sets have a intersection or not issubset() Returns whether another set contains this set or not issuperset() Returns whether this set contains another set or not pop() Removes an element from the set remove() Removes the specified element symmetric_difference() Returns a set with the symmetric differences of two sets symmetric_difference_update() inserts the symmetric differences from this set and another union() Return a set containing the union of sets update() Update the set with the union of this set and others """
8f87b25113369c261fc83de811f88385e6443eee
TahaCoder43/TahaCoder43
/Unidentified testts/tuple_compairing_test.py
210
3.78125
4
Tuple = ('Taha', 'Munawar','14','Rawalpindi') *names, age, city = Tuple x = '' for i in names: if i != 'Taha': x = x + ' ' + i else: x = x + i full_name = x print(full_name)
6f0e72d1b685e506ae0689311ef12253e5432041
JohnHaines/datawranglingMongoDB
/udacity_2_1_parsecsv.py
1,371
3.78125
4
""" From Udacity Data Wrangling With MongoDB Processes a csv file . Each file contains information from one meteorological station about the amount of solar and wind energy for each hour of day. The first line of the datafile describes the data source. The name of the weather station is extracted from it. Data is returned as a list of lists . Uses "reader" method to get data . next() method - to get the next line from the iterator. """ import csv import os DATADIR = "data" DATAFILE = "745090.csv" def parse_file(datafile): name = "" data = [] with open(datafile,'r') as f: #csv.reader creates a list object reader = csv.reader(f, delimiter=",") for i, row in enumerate(reader): #print ("i ", i, "row ", row) if i== 0: # pick up weather station name name = row[1] else: if i == 1: next else: data.append(row) return (name, data) def test(): datafile = os.path.join(DATADIR, DATAFILE) name, data = parse_file(datafile) assert name == "MOUNTAIN VIEW MOFFETT FLD NAS" assert data[0][1] == "01:00" assert data[2][0] == "01/01/2005" assert data[2][5] == "2" if __name__ == "__main__": test()
9b5e95a1e638e37aa409c918434f251bdae28f07
govindak-umd/HackerRank_Python
/arrays_reversed.py
213
3.6875
4
import numpy def arrays(input_array): input_array = numpy.array(arr, float) reversed_arr = input_array[::-1] return reversed_arr arr = input().strip().split(' ') result = arrays(arr) print(result)
3deadfb840460f4c165a7ef53f2bcf03b0cfc713
te14017/ML_Q-learning
/helpers.py
4,831
4.09375
4
# copyright (C) Team Terminator # Authors: V. Barth, A. Eiselmayer, J. Luo, F. Panakkal, T. Tan class Position(object): """ Position in the maze """ def __init__(self, row, column): self.row = row self.column = column def __eq__(self, other): return self.row == other.row and self.column == other.column def __repr__(self): return "%s (%d,%d)" % (self.__class__.__name__, self.row, self.column) def __hash__(self): return hash((self.row, self.column)) def __ne__(self, other): return not (self == other) def __cmp__(self, other): if self.row < other.row: return -1 elif self.row == other.row: if self.column == other.column: return 0 elif self.column < other.column: return -1 else: return 1 else: return 1 def moveUp(self): """ Gets position which is above the robot (looking onto the maze not through the "eyes" of the robots) :return: Position """ return Position(row=self.row - 1, column=self.column) def moveDown(self): """ Gets position which is underneath the robot (looking onto the maze not through the "eyes" of the robots) :return: Position """ return Position(row=self.row + 1, column=self.column) def moveRight(self): """ Gets position which is to the right of the robot (looking onto the maze not through the "eyes" of the robots) :return: Position """ return Position(row=self.row, column=self.column + 1) def moveLeft(self): """ Gets position which is to the left of the robot (looking onto the maze not through the "eyes" of the robots) :return: Position """ return Position(row=self.row, column=self.column - 1) class Reward(object): """ Rewards which can be found in the maze """ def __init__(self, value, position, name): """ :param value: number value :param position: Position :param name: Label """ self.value = value self.position = position self.name = name class Movement(object): """ Movement from a position to another """ def __init__(self, current_position, desired_position): """ Movement is directed from one position to the other :param current_position: Position :param desired_position: Position """ self.current_position = current_position self.desired_position = desired_position def __eq__(self, other): return self.current_position == other.current_position and self.desired_position == other.desired_position def __repr__(self): return "%s from %s to %s" % (self.__class__.__name__, self.current_position, self.desired_position) def __hash__(self): return hash((self.current_position, self.desired_position)) def __ne__(self, other): return not (self == other) def reverse(self): """ Reverses the direction of a movement :return: Movement in the opposite directoin """ return Movement(current_position=self.desired_position, desired_position=self.current_position) def turnLeft(self): """ Change straight movement to the a left movement :return: Movement to the left of the positions point of view """ if self.desired_position == self.current_position.moveUp(): return Movement(self.current_position, self.current_position.moveLeft()) elif self.desired_position == self.current_position.moveLeft(): return Movement(self.current_position, self.current_position.moveDown()) elif self.desired_position == self.current_position.moveDown(): return Movement(self.current_position, self.current_position.moveRight()) else: return Movement(self.current_position, self.current_position.moveUp()) def turnRight(self): """ Change straight movement to the a right movement :return: Movement to the right of the positions point of view """ if self.desired_position == self.current_position.moveUp(): return Movement(self.current_position, self.current_position.moveRight()) elif self.desired_position == self.current_position.moveLeft(): return Movement(self.current_position, self.current_position.moveUp()) elif self.desired_position == self.current_position.moveDown(): return Movement(self.current_position, self.current_position.moveLeft()) else: return Movement(self.current_position, self.current_position.moveDown())
f95de29aeebc6827320854cb43ff4ca769e41196
jasonwee/asus-rt-n14uhp-mrtg
/src/lesson_algorithms/operator_sequences.py
918
3.515625
4
from operator import * a = [1, 2, 3] b = ['a', 'b', 'c'] print('a =', a) print('b =', b) print('\nConstructive:') print(' concat(a, b):', concat(a, b)) print('\nSearching:') print(' contains(a, 1) :', contains(a, 1)) print(' contains(b, "d"):', contains(b, "d")) print(' countOf(a, 1) :', countOf(a, 1)) print(' countOf(b, "d") :', countOf(b, "d")) print(' indexOf(a, 5) :', indexOf(a, 1)) print('\nAccess Items:') print(' getitem(b, 1) :', getitem(b, 1)) print(' getitem(b, slice(1, 3)) :', getitem(b, slice(1, 3))) print(' setitem(b, 1, "d") :', end=' ') setitem(b, 1, "d") print(b) print(' setitem(a, slice(1, 3), [4, 5]):', end=' ') setitem(a, slice(1, 3), [4, 5]) print(a) print('\nDestructive:') print(' delitem(b, 1) :', end=' ') delitem(b, 1) print(b) print(' delitem(a, slice(1, 3)):', end=' ') delitem(a, slice(1, 3)) print(a)
73a71a6e84f6314a7dbe472618669011d18be62d
ajaycc17/password-generator
/password-generator.py
1,496
3.875
4
import random # define the set of characters we want to use digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] lowercase = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] uppercase = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] special = ['@', '#', '$', '%', '=', ':', '?', '.', '/', '|', '~', '>', '*', '(', ')', '<', '•', 'α', 'ß', 'γ'] collection = digits + uppercase + lowercase + special # User input for number of characters print('Enter the number of characters (12-100): ') strn = int(input()) # limit the number of characters between 12 to 100 if strn < 12: strn = 12 elif strn > 100: strn = 100 # Take at least one letter from each character set randomly dig = random.choice(digits) low = random.choice(lowercase) up = random.choice(uppercase) sym = random.choice(special) # append the above characters in an empty list rnd_char = [] rnd_char.append(dig) rnd_char.append(low) rnd_char.append(up) rnd_char.append(sym) # apart from above 4 characters fill rest randomly and append to list for i in range(strn-4): rnd_char.append(random.choice(collection)) # shuffle the final list of characters random.shuffle(rnd_char) # generate the password as a string password = "" for j in rnd_char: password = password + j # print the password print(password)
5a53c7bd1c085e02ceca3154b580f8beece1aadb
robjailall/stack-ranking
/review_game.py
12,876
4.0625
4
import csv import random from argparse import ArgumentParser from collections import defaultdict from sys import stdout def _map_bins_to_labels(bins): """ Maps integers 0-99 to a label according to the distribution specified in `bins`. Example: bins = [10, 20] # implies bin sizes of 10 - 20 - 70 maps to => [0]*10 + [1]*20 + [2]*70 Note that if the integers in `bins` don't add up to 100, this function will fill in the remaining difference with a new label :param bins: A list of integers from 0-100. Each value specifies how many times the label for the bin is repeated :return: """ labels = [len(bins)] * 100 label = 0 i = 0 for bin in bins: for _ in range(0, bin): labels[i] = label i += 1 label += 1 return labels def _calculate_sample_label_monte_carlos(sample_size, bins): """ Creates a mapping between position in a sample of `sample_size` and a rating distribution defined by `bins` This uses a monte carlo process to do this: 1. Create an arbitrarily large population according to the distribution in `bins` 2. Sample the population at `sample_size` number of intervals that are evently spaced out 3. Repeat above a sufficient number of trials and take the average label at each sample position as the sample label :param sample_size: :param bins: :return: """ sample_values = defaultdict(lambda: 0) for _ in range(0, 100): population = _generate_population(bins=bins, population_size=1000) population.sort() chunk_size = len(population) / sample_size for i in range(0, sample_size): sample_values[i] += population[int(i * chunk_size + chunk_size / 2)] return [int(round(sample_idx / 100)) for key, sample_idx in sample_values.items()] def _calculate_sample_labels_oversample(sample_size, bins, population_size=10000): """ Creates a mapping between position in a sample of `sample_size` and a rating distribution defined by `bins` This uses oversampling to do this: 1. Create an arbitrarily large population according to the distribution in `bins` 2. Sample the population at `sample_size` number of intervals that are evently spaced out :param sample_size: :param bins: :param population_size: :return: """ population = _generate_population(bins=bins, population_size=population_size) population.sort() sample_labels = [] chunk_size = len(population) / sample_size for i in range(0, sample_size): sample_labels.append(population[int(i * chunk_size + chunk_size / 2)]) return sample_labels def _generate_population(bins, population_size): """ Generates a population of `population_size` with the ratings distribution specified by `bins`. :param bins: :param population_size: :return: """ range_labels = _map_bins_to_labels(bins=bins) population = [] # Apply the `range_labels` to `population_size` random numbers between 0-100 for _ in range(0, population_size): bin = range_labels[random.randint(0, len(range_labels) - 1)] population.append(bin) return population def _rate_population(population, sample_size, get_sample_labels): """ Goes through the population and applies ratings to the population usings groups of size `sample_size` :param population: :param sample_size: :param get_sample_labels: :return: """ ratings = [0] * len(population) # `sample_labels` is basically a lookup table that says what rating to apply to what individual in the sample. This # lookup table assumes both the labels and the sample are sorted # Reverse the sorting so that we apply the highest ratings to first sample_labels_high_to_low = list(get_sample_labels(sample_size=sample_size)) sample_labels_high_to_low.reverse() # Go through the population in chunks of sample_size i = 0 while True: # Get the indexes of the sample in sorted order sample = population[i: min(len(population), i + sample_size)] sorted_sample_indices = [i[0] for i in sorted(enumerate(sample), key=lambda x: x[1])] # Reverse so we apply ratings to the top individuals in the sample first sorted_sample_indices.reverse() # The last iteration of this loop may consider a group smaller than `sample_size`, so we need to get a # different set of sample_labels for this group if len(sample) != sample_size: sample_labels_high_to_low = list(get_sample_labels(sample_size=len(sample))) sample_labels_high_to_low.reverse() # Apply the sample ratings for sample_rating, sample_idx in zip(sample_labels_high_to_low, sorted_sample_indices): ratings[i + sample_idx] = sample_rating # Go to the next chunk i += sample_size if i >= len(population): break return ratings def _score_ratings(population, ratings, production, correct_score=100, underestimate_score=-100, over_estimate_score=50): """ Apply a simple model to score how well the ratings represents the true ratings of the population. :param population: :param ratings: :param production: :param correct_score: :param underestimate_score: :param over_estimate_score: :return: """ scores = [] for employee, rating in zip(population, ratings): if rating < employee: scores.append(production[employee] * underestimate_score) elif rating > employee: scores.append(production[employee] * over_estimate_score) else: scores.append(production[employee] * correct_score) return scores def _get_rating_accuracy_stats(population, ratings): """ Calculate how accurate our ratings were. :param population: :param ratings: :return: """ num_overestimates = 0 num_underestimates = 0 num_correct = 0 for employee, rating in zip(population, ratings): if rating < employee: num_underestimates += 1 elif rating > employee: num_overestimates += 1 else: num_correct += 1 return num_underestimates, num_correct, num_overestimates def calculate_monte_carlo_stats(scores, rating_accuracy): """ Assumes `scores` and `rating_counts` have stats for the same configurations. Collates the monte carlo stats for the simulation runs :param scores: :param rating_accuracy: :return: """ averages = [] for key, stats in scores.items(): average_score = sum(stats) / len(stats) average_underestimates = sum([stats[0] for stats in rating_accuracy[key]]) / len(stats) average_correct = sum([stats[1] for stats in rating_accuracy[key]]) / len(stats) average_overestimates = sum([stats[2] for stats in rating_accuracy[key]]) / len(stats) averages.append(list(key) + [average_score, average_underestimates, average_correct, average_overestimates]) return averages def _sample_labels_calculator(population_size, bins): """ Returns a function that gets and memoizes sample label mappings for a distribution specified by `bins` :param population_size: :param bins: :return: """ sample_labels = {} def get_sample_labels(sample_size): if sample_size not in sample_labels: sample_labels[sample_size] = _calculate_sample_labels_oversample( sample_size=min(sample_size, population_size), bins=bins, population_size=max(100000, population_size * 100)) return sample_labels[sample_size] return get_sample_labels def simulate_ratings(performance_bins, population_size, sample_sizes, rating_bins, payoffs, production, num_repetitions=1): """ Simulate all of the configurations specified in the arguments and return the aggregated states for the simulations :param performance_bins: :param population_size: :param sample_sizes: :param rating_bins: :param payoffs: :param production: :param num_repetitions: :return: """ rating_scores = defaultdict(list) rating_accuracy = defaultdict(list) # Precompute the distributions for the different sample sizes get_sample_labels = _sample_labels_calculator(population_size=population_size, bins=rating_bins) for sample_size in sample_sizes: get_sample_labels(sample_size=sample_size) # Repeat the simulation of each configuration `num_repetitions` times for _ in range(0, num_repetitions): # Random variable: the true distribution of ratings varies from run to run population = _generate_population(bins=performance_bins, population_size=population_size) # Now see how our stats are affected by rating this population using different sample sizes for sample_size in sample_sizes: ratings = _rate_population(population=population, sample_size=sample_size, get_sample_labels=get_sample_labels) # These stats don't change by payoff functions num_underestimates, num_correct, num_overestimates = _get_rating_accuracy_stats(population=population, ratings=ratings) # Score ratings using different payoff functions. Collate stats by simulation configuration for payoff in payoffs: run_configuration = tuple([sample_size] + list(payoff)) scores = \ _score_ratings(population, ratings, production=production, underestimate_score=payoff[0], over_estimate_score=payoff[2], correct_score=payoff[1]) rating_accuracy[run_configuration].append((num_underestimates, num_correct, num_overestimates)) rating_scores[run_configuration].append(sum(scores)) return rating_scores, rating_accuracy def print_simulation(f, scores): writer = csv.writer(f) for score in scores: writer.writerow(score) def main(args): if args.sample_sizes: sample_sizes = [int(s) for s in args.sample_sizes] else: sample_sizes = [5] while sample_sizes[-1] * 2 < int(args.population / 2): sample_sizes.append(sample_sizes[-1] * 2) # always include half the population and the entire population sample_sizes += [int(args.population / 2), args.population] # payoffs = [(-1, 1, .5), (0, 1, .5), (0, 0, 0), (-.5, 1, .5), (-.25, 1, .5), (-.25, .5, .25)] payoffs = [(.5, 1.2, 1)] rating_scores, rating_accuracy = simulate_ratings(performance_bins=args.performance_bins, population_size=args.population, sample_sizes=sample_sizes, rating_bins=args.rating_bins, payoffs=payoffs, production=args.production, num_repetitions=args.num_repetitions) results = calculate_monte_carlo_stats(scores=rating_scores, rating_accuracy=rating_accuracy) print_simulation(stdout, results) if __name__ == "__main__": parser = ArgumentParser( description="Demonstrates the effect of proper sample size usage in the context of a game with cost and payoff") parser.add_argument("--performance-bins", type=int, nargs='+', default=[5, 10, 50, 25, 10], help="The true distribution of the population's performance") parser.add_argument("--rating-bins", type=int, nargs='+', default=[5, 10, 50, 25, 10], help="The distribution the stack ranking policy assumes") parser.add_argument("--sample-sizes", type=int, nargs='+', help="The sizes of stack ranking groups to test") parser.add_argument("--population", type=int, default=200, help="The total size of the organization being stack ranked") parser.add_argument("--num-repetitions", type=int, default=100, help="The number of Monte Carlo runs to use") parser.add_argument("--production", type=int, nargs='+', default=[1.05, 1.1, 1.15, 1.2, 1.25], help="The true production of employees in each performance bin") args = parser.parse_args() main(args)