blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
fc2a45554495e4cbbb142b9951261f6170801ad8
jh-lau/leetcode_in_python
/01-数据结构/栈/225.用队列实现栈.py
1,312
3.90625
4
""" @Author : liujianhan @Date : 2020/3/30 上午10:07 @Project : leetcode_in_python @FileName : 225.用队列实现栈.py @Description : 使用队列实现栈的下列操作: push(x) -- 元素 x 入栈 pop() -- 移除栈顶元素 top() -- 获取栈顶元素 empty() -- 返回栈是否为空 你只能使用队列的基本操作-- 也就是 push to back, peek/pop from front, size, 和 is empty 这些操作是合法的。 你所使用的语言也许不支持队列。 你可以使用 list 或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。 你可以假设所有操作都是有效的(例如, 对一个空的栈不会调用 pop 或者 top 操作)。 """ from collections import deque # 36ms, 13.8MB class MyStack: def __init__(self): self.stack = deque() def push(self, x: int) -> None: self.stack.appendleft(x) def pop(self) -> int: if self.stack: return self.stack.popleft() def top(self) -> int: if self.stack: return self.stack[0] def empty(self) -> bool: return not bool(self.stack) if __name__ == '__main__': obj = MyStack() obj.push(1) obj.push(2) print(obj.top()) print(obj.pop()) print(obj.empty())
4d6ba6687f4ac587f210ca67ef1aeec041dd621d
duschado/module_32
/min323.py
493
3.65625
4
#!/usr/bin/python3 import random N = input('Enter the number of items in the list N, N < 50\n > ') N = int(N) lst_N = random.sample(range(1, 50), N) M = input('Enter the number of items in the list M, M < 50\n > ') M = int(M) lst_M = random.sample(range(1, 50), M) print(lst_N) print(lst_M) lst_new = list() for i in range(N): for j in range(M): if lst_N[i] == lst_M[j]: lst_new.append(lst_M[j]) if lst_new == []: print("These lists don't have generic numbers") else: print(lst_new)
8585598dd63a8e580332f2de15bd4f06626b02a3
BEPCTA/Coding_Games
/more_pour_problem.py
3,323
3.875
4
# ----------------- # User Instructions # # In this problem, you will solve the pouring problem for an arbitrary # number of glasses. Write a function, more_pour_problem, that takes # as input capacities, goal, and (optionally) start. This function should # return a path of states and actions. # # Capacities is a tuple of numbers, where each number represents the # volume of a glass. # # Goal is the desired volume and start is a tuple of the starting levels # in each glass. Start defaults to None (all glasses empty). # # The returned path should look like [state, action, state, action, ... ] # where state is a tuple of volumes and action is one of ('fill', i), # ('empty', i), ('pour', i, j) where i and j are indices indicating the # glass number. def more_pour_problem(capacities, goal, start=None): """The first argument is a tuple of capacities (numbers) of glasses; the goal is a number which we must achieve in some glass. start is a tuple of starting levels for each glass; if None, that means 0 for all. Start at start state and follow successors until we reach the goal. Keep track of frontier and previously explored; fail when no frontier. On success return a path: a [state, action, state2, ...] list, where an action is one of ('fill', i), ('empty', i), ('pour', i, j), where i and j are indices indicating the glass number.""" # your code here def _is_goal(state): return goal in state def _successors(state): def __fill(i): new_state = list(state) new_state[i] = capacities[i] return tuple(new_state) def __empty(i): new_state = list(state) new_state[i] = 0 return tuple(new_state) def __pour(i, k): new_state = list(state) trans_amount = min(state[i], capacities[k] - state[k]) new_state[i] -= trans_amount new_state[k] += trans_amount return tuple(new_state) indices = range(len(state)) fill_set = {__fill(i): ("fill", i) for i in indices} empty_set = {__empty(i): ("empty", i) for i in indices} pour_set = {__pour(i, k): ("pour", i, k) for i in indices for k in indices} return dict(list(fill_set.items()) + list(empty_set.items()) + list(pour_set.items())) if start is None: start = (0,)*len(capacities) return shortest_path_search(start, _successors, _is_goal) def shortest_path_search(start, successors, is_goal): """Find the shortest path from start state to a state such that is_goal(state) is true.""" if is_goal(start): return [start] explored = set() frontier = [ [start] ] while frontier: path = frontier.pop(0) s = path[-1] for (state, action) in successors(s).items(): if state not in explored: explored.add(state) path2 = path + [action, state] if is_goal(state): return path2 else: frontier.append(path2) return Fail Fail = [] def test_more_pour(): assert more_pour_problem((1, 2, 4, 8), 4) == [ (0, 0, 0, 0), ('fill', 2), (0, 0, 4, 0)] assert more_pour_problem((1, 2, 4), 3) == [ (0, 0, 0), ('fill', 2), (0, 0, 4), ('pour', 2, 0), (1, 0, 3)] starbucks = (8, 12, 16, 20, 24) assert not any(more_pour_problem(starbucks, odd) for odd in (3, 5, 7, 9)) assert all(more_pour_problem((1, 3, 9, 27), n) for n in range(28)) assert more_pour_problem((1, 3, 9, 27), 28) == [] return 'test_more_pour passes' if __name__ == '__main__': print test_more_pour()
03396163f3e13d9c30684caebcf8fc02f799fdd5
zhuzhu18/leetcode
/100相同的树.py
642
3.84375
4
# Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def isSameTree(p: TreeNode, q: TreeNode) -> bool: if p == None and q != None: return False elif p != None and q == None: return False elif p == None and q == None: return True return p.val == q.val and isSameTree(p.left, q.left) and isSameTree(p.right, q.right) p = TreeNode(10) p.left = TreeNode(5) p.right = TreeNode(15) q = TreeNode(10) q.left = TreeNode(5) q.left.right = TreeNode(15) a = isSameTree(p, q) print(a)
ff5ddb66d2b637439e9fe28c4059fe40aab9d76d
erezshi/code-examples-python3
/betterpython.py
746
3.71875
4
#ternary condition condition = True x = 1 if condition else 0 #Large numbers # ternary condition n1 = 10_000_000_000 n2 = 100_000_000 total = n1+n2 print(f'{total:,}') 10,100,000,000 #enumerate - display the position of the value in the list names = ['David', 'Fisher', 'Davidson', 'Yoda'] for index, name in enumerate(names, start=1): print(index, name) 1 David 2 Fisher 3 Davidson 4 Yoda # unpacking multiple lists # python unpack multiple lists together titles = ['Mr', 'Ms', 'Mrs', 'Mr'] names = ['David', 'Diana', 'Mor', 'Joe'] for name, title in zip(names, titles): print(f'Hey {title} {name} nice to meet you') Hey Mr David nice to meet you Hey Ms Diana nice to meet you Hey Mrs Mor nice to meet you Hey Mr Joe nice to meet you
e31dc123bf7f693e29e4437cb4d03ac5e914058e
thisalmadu/Python-Training-HR-
/string_format_output.py
290
3.984375
4
def print_formatted(number): for i in range(1,int(number+1)): binn = bin(i) n = int(len(binn[2:])) octn = oct(i) hexn = hex(i) print(i,octn[1:],hexn[2:].upper(),binn[2:]) # format the output later n = int(raw_input()) print_formatted(n)
79250c345769c5221e200cf4fb5421fd69655501
AndreisSirlene/Python-Exercises-Curso-em-Video-World-1-2-and-3
/World 2/Challenge050.py
186
3.8125
4
s = 0 count = 0 for c in range (1,7): n = int(input('Type a number: ')) if n % 2 == 0: s += n count += 1 print('The sum of {} ODD numbers is {}'.format(count, s))
b95c1afb589b4437ffaa32cea052d5e73e3954eb
pooja89299/function
/fun5.py
653
3.671875
4
#add_numbers_list naam ka function likhiye jo do integers ki 2 # lists leta ho aur fir same position wale integers ka sum print karta ho. # Same position waale 2 integers ka sum karne ke liye Part 1 mein di gayi add_numbers waale function ka use karo. # # Jaise agar hum iss function ko [50, 60, 10] aur [10, 20, 13] denge ko woh yeh print karega # def add_numbers_list(): # list1=[50,60,10] # list2=[10,20,13] # i=0 # s=0 # while i<len(list1): # s=list1[i]+list2[i] # i+=1 # print(s) # add_numbers_list() # def add_number(a,b): # c=a+b # print(c) # add_number(12,56)
66146e7c2d36a4fb5126cc51668d3d1c6ca9cef2
devclassio/200-interview-algorithm-questions
/arrays/questions/squareOfSortedArrays.py
613
3.59375
4
''' https://leetcode.com/problems/squares-of-a-sorted-array/discuss/310865/Python%3A-A-comparison-of-lots-of-approaches!-Sorting-two-pointers-deque-iterator-generator REVIEW!!! Why is this considered O(1) aux space? See and understand iterator solution Given an array of integers A sorted in non-decreasing order, return an array of the squares of each number, also in sorted non-decreasing order. Example 1: Input: [-4,-1,0,3,10] Output: [0,1,9,16,100] Example 2: Input: [-7,-3,2,3,11] Output: [4,9,9,49,121] Note: 1 <= A.length <= 10000 -10000 <= A[i] <= 10000 A is sorted in non-decreasing order. '''
2b8f01dcf4ef5bbbff48f4fd5b002bd04a9ba5ab
WesRoach/coursera
/specialization-intro-discrete-math-computer-science/mathematical-thinking-for-computer-science/week3/hanoi.py
953
3.96875
4
def hanoi(num): """ Return steps to solve hanoi tower of `num` height. """ # Create disks; Larger number == larger disk # list.pop() will return the top disk discs = [x for x in range(num, 0, -1)] towers = [discs, [], []] rounds = [] rounds.append(towers) print_rounds(rounds) cnt = 0 def solve_toh(n, source, destination, auxiliary): global cnt if n == 1: print(f"Move disk 1 from source {source} to destination {destination}") cnt += 1 return solve_toh(n - 1, source, auxiliary, destination) print(f"Move disk {n} from source {source} to destination {destination}") cnt += 1 solve_toh(n - 1, auxiliary, destination, source) def print_rounds(rounds): """Prints supplied list of lists""" for idx, rnd in enumerate(rounds): print(f"## Round {idx + 1} ##") for tower in rnd: print(tower) solve_toh(6, 1, 3, 2) print(cnt)
97681fa12ebec3d3aa544fcd7dc3d9102a8007cb
danielsenhwong/adventofcode
/2015/day09/day09.py
2,743
4.28125
4
""" --- Day 9: All in a Single Night --- Every year, Santa manages to deliver all of his presents in a single night. This year, however, he has some new locations to visit; his elves have provided him the distances between every pair of locations. He can start and end at any two (different) locations he wants, but he must visit each location exactly once. What is the shortest distance he can travel to achieve this? For example, given the following distances: London to Dublin = 464 London to Belfast = 518 Dublin to Belfast = 141 The possible routes are therefore: Dublin -> London -> Belfast = 982 London -> Dublin -> Belfast = 605 London -> Belfast -> Dublin = 659 Dublin -> Belfast -> London = 659 Belfast -> Dublin -> London = 605 Belfast -> London -> Dublin = 982 The shortest of these is London -> Dublin -> Belfast = 605, and so the answer is 605 in this example. What is the distance of the shortest route? """ import re import sys from itertools import permutations data = [] places = set() distances = dict() for line in open('2015/day09/day09_input.txt'): data.append([x.rstrip() for x in re.split(' to | = ', line)]) # solution from elsewhere, very interesting way of importing data # i've never used the set datatype before (source, _, dest, _, distance) = line.split() places.add(source) places.add(dest) # also never used setdefault before to set up a dictionary # super interesting, sets up a nested dict off the top # each location is searched in the distances dict, and if it doesn't exist, a nested dict is created with that location as the key # then within the nested dict, the name of another location and the distance to it are the key, value pair distances.setdefault(source, dict())[dest] = int(distance) distances.setdefault(dest, dict())[source] = int(distance) # solution from elsewhere # return the largest positive integer supported by the platform shortest = sys.maxsize # initialize longest = 0 # iterate through the list of permutations of places (all the different orders you could go) # set up a temporary variable dist to figure out the distance with a lambda function, which has two variables x and y in a function to look up the distance in the distances dict, items[:-1] and items[1:] are the values passed to x and y. these are everything except the last location, and everything but the first location to come up with source-dest pairs to look up distances # min max to find shortest and longest for items in permutations(places): dist = sum(map(lambda x, y: distances[x][y], items[:-1], items[1:])) shortest = min(shortest, dist) longest = max(longest, dist) print("shortest: %d" % (shortest)) print("longest: %d" % (longest))
5372c31a3873eb2d05312817a937f4fc902f8bbd
acmachado14/ListasCCF110
/Lista09/08.py
1,192
3.890625
4
#8. Crie um algoritmo que leia e armazene os elementos de uma matriz inteira #M[10x10] e escrevê-la. Troque, na ordem a seguir: # ● A segunda linha pela oitava linha; # ● A quarta coluna pela décima coluna; # ● A diagonal principal pela diagonal secundária; matriz = [[0 for j in range(10)] for i in range(10)] for i in range(len(matriz)): for j in range(len(matriz[i])): matriz[i][j] = int(input(f"Digite o valor para o índice ({i},{j}): ")) for j in range(len(matriz[0])): aux = matriz[1][j] matriz[1][j] = matriz[7][j] matriz[7][j] = aux for i in range(len(matriz[0])): aux = matriz[i][3] matriz[i][3] = matriz[i][9] matriz[i][9] = aux princ = [] second = [] for i in range(len(matriz)): for j in range(len(matriz[0])): if i == j: princ.append(matriz[i][j]) elif i + j == len(matriz)-1: second.append(matriz[i][j]) cont1 = 0 cont2 = 0 for i in range(len(matriz)): for j in range(len(matriz[i])): if i == j: matriz[i][j] = princ[cont1] cont1 += 1 elif i + j == len(matriz)-1: matriz[i][j] = second[cont2] cont2 += 1
f231bcdd55a6ca5d880cd9bd02293e8c35d965c1
Wangpeihu1/python---
/scatter_squares.py
527
3.625
4
import matplotlib.pyplot as plt x_value = list(range(1,5000)) y_value = [x**3 for x in x_value] plt.scatter(x_value,y_value,c = y_value,cmap = plt.cm.Reds,edgecolor = 'none',s=20) #设置图表标题给坐标加参数 plt.title('squares numbers',fontsize = 24) plt.xlabel('value',fontsize = 14) plt.ylabel('squares of value',fontsize = 14) #设置刻度标记的大小 plt.tick_params(axis = 'both',which = 'major',labelsize = 14) # plt.axis([0,1100,0,1100000]) # plt.savefig('squares_plot.png',bbox_inches='tight') plt.show()
cc48501c5605c2035ef7f1401543d93fe3d55763
ashu20031994/HackerRank-Python
/Day-6 Closures and Generators/1.decorator.py
912
4.40625
4
''' The given mobile numbers may have , or written before the actual digit number. Alternatively, there may not be any prefix at all. Input Format The first line of input contains an integer , the number of mobile phone numbers. lines follow each containing a mobile number. Output Format Print mobile numbers on separate lines in the required format. Sample Input 3 07895462130 919875641230 9195969878 Sample Output +91 78954 62130 +91 91959 69878 +91 98756 41230 ''' import re def wrapper(f): def fun(l): # complete the function rules = (("^91", '+91'), ("^0", "+91")) for i in range(len(l)): item = l[i] if len(item) == 10: l[i] = "+91 " + item[0:5] + " " + item[5:10] else: l[i] = "+91 " + item[len(item)-10:len(item)-5] + " " + item[len(item)-5:] return f(l) return fun
82194e94a0a28ce49e34b007e3a0b52e66091160
TylerLangtry/Sandbox
/oddName.py
105
3.828125
4
"""Tyler Langtry""" name = input("Name?") while len(name) == 0: name = input("Name?") print(name[1::2])
d73c26c2671b15d787a2b602882bcb37e68bc9fc
manu07yad/PYTHON
/reverse multiplicative table.py
136
3.921875
4
num = int(input("Enter the number ")) for i in range (10,0,-1): print( str(num) + "X" + str(i) + "=" +str(num*i) )
f28785ec8ddb069edbc366c5ab8dee90f3e63f1a
erjan/coding_exercises
/make_two_arrays_equal_by_reversing_subarrays.py
1,169
4.09375
4
''' Given two integer arrays of equal length target and arr. In one step, you can select any non-empty sub-array of arr and reverse it. You are allowed to make any number of steps. Return True if you can make arr equal to target, or False otherwise. ''' #DUMB SOLUTION - CHEATING.. class Solution: def canBeEqual(self, target: List[int], arr: List[int]) -> bool: return sorted(target) == sorted(arr) #SOLUTION I LOOKED UP using dictionaries or collections counter #this is just counting how many times each digit appears - another condition of equality def f( target, arr): d1={} d2={} for i in target: if i in d1: d1[i]+=1 else: d1[i]=1 print('d1 after filling') print(d1) for i in arr: if i in d2: d2[i]+=1 else: d2[i]=1 print('d2 after filing') print(d2) return (d1==d2) target = [1,2,3,4] arr = [2,4,1,3] f(target,arr) #same with counter from collections import Counter def f( target, arr): c_target = Counter(target) c_arr = Counter(arr) result = c_target == c_arr print(result)
8cd912a1b20ec50626fdbccb9c9a3ea138f35204
savva-kotov/coursera-python-basics
/Ряд - 2.py
884
3.671875
4
""" Даны два целых числа A и В. Выведите все числа от A до B включительно, в порядке возрастания,если A < B, или в порядке убывания в противном случае. Формат ввода Вводятся два целых числа. Формат вывода Выведите ответ на задачу. Тест 1 Входные данные: 1 10 Вывод программы: 1 2 3 4 5 6 7 8 9 10 Тест 2 Входные данные: 10 1 Вывод программы: 10 9 8 7 6 5 4 3 2 1 Тест 3 Входные данные: 179 179 Вывод программы: 179 """ # 09.09.19 a, b = int(input()), int(input()) if a < b: res = [i for i in range(a, b + 1)] else: a, b = b, a res = [i for i in range(a, b + 1)][::-1] print(' '.join(map(str, res)))
c3b4bad5226defbe46ef2f46a1796de7f84764ed
kuzmichevdima/coding
/implementations/to_stress_1/gen_py.py
581
3.5
4
import sys, random args = sys.argv n = int(args[1]) m = int(args[2]) con = int(args[3]) print(str(n) + " " + str(m)) start = [] for i in range(n): start.append(random.randint(0, con)) for elem in start: print(elem, end = ' ') print() for i in range(m): typ = random.randint(1, 2) if typ == 1: pos = random.randint(1, n) newVal = random.randint(0, con) print("1 " + str(pos) + " " + str(newVal)) else: s = random.randint(1, n) f = random.randint(s, n) print("2 " + str(s) + " " + str(f))
7cd8755968d7a2c18bf3ad43d13d2426ce20cf2a
AlexbjUPS/ejercicios-Python
/Taller_sumanotas.py
768
3.609375
4
# -*- coding: utf-8 -*- """ Created on Thu Jun 25 14:25:06 2020 @author: Yolanda """ nota_1=int(input("Ingrese la nota de la evaluacion 1: ")) nota_2=int(input("Ingrese la nota de la evaluacion 2: ")) nota_3=int(input("Ingrese la nota de la evaluacion 3: ")) if nota_1>nota_2 and nota_2>nota_3: suma_total1= nota_1+nota_2 print("Su nota total es: ", suma_total1) else: if nota_2>nota_1 and nota_2>nota_3: suma_total2= nota_1+nota_2 print("Su nota total es: ", suma_total2) else: if nota_1>nota_2 and nota_3>nota_2: suma_total3= nota_1+nota_3 print("Su nota total es: ", suma_total3) else: suma_total4= nota_2+nota_3 print("Su nota total es: ", suma_total4) # Alexis Bajaña
c26ca1827d04c1f7da5be8ae6ada40f6aff0604d
remnv/python-vending-machine
/mdcoin/test.py
3,907
3.6875
4
import unittest from .controller import Coin class UnitTestCoin(unittest.TestCase): def test_is_valid_coin_true(self): coin_obj = Coin() inserted_coin = 500 expected = True self.assertEqual(expected, coin_obj.is_valid_coin(inserted_coin)) def test_is_valid_coin_false(self): coin_obj = Coin() inserted_coin = 20 expected = False self.assertEqual(expected, coin_obj.is_valid_coin(inserted_coin)) def test_is_coin_usable_true(self): coin_obj = Coin() coin_list = {"10": 3, "100": 2} inserted_coin = 50 expected = True self.assertEqual(expected, coin_obj.is_coin_usable( inserted_coin, coin_list)) def test_is_coin_usable_false(self): coin_obj = Coin() coin_list = {"10": 0, "100": 2} inserted_coin = 50 expected = False self.assertEqual(expected, coin_obj.is_coin_usable( inserted_coin, coin_list)) def test_is_change_possible_true(self): coin_obj = Coin() coin_list = { "10": 21, "50": 5, "100": 16, "500": 10, } inserted_coin = 500 expected = True self.assertEqual(expected, coin_obj.is_change_possible( inserted_coin, coin_list)) def test_is_change_possible_true(self): coin_obj = Coin() coin_list = { "10": 21, "50": 5, "100": 3, "500": 10, } inserted_coin = 500 expected = False self.assertEqual(expected, coin_obj.is_change_possible( inserted_coin, coin_list)) def test_is_coin_check_true(self): coin_obj = Coin() coin_list = { "10": 21, "50": 5, "100": 16, "500": 10, } inserted_coin = 500 expected = True self.assertEqual(expected, coin_obj.is_coin_check( inserted_coin, coin_list)) def test_is_coin_check_false(self): coin_obj = Coin() coin_list = { "10": 21, "50": 5, "100": 3, "500": 10, } inserted_coin = 500 expected = False self.assertEqual(expected, coin_obj.is_coin_check( inserted_coin, coin_list)) def test_change_coin_is_check_true(self): coin_obj = Coin() last_gate = {} coin_list = { "10": 21, "50": 5, "100": 6, "500": 10, } leftover_coin = 380 expected = { "100": 3, "10": 8 } self.assertEqual(expected, coin_obj.change_coin(leftover_coin, coin_list, last_gate)) def test_change_coin_is_check_true(self): coin_obj = Coin() last_gate = { "500": 3 } coin_list = { "10": 21, "50": 5, "100": 6, "500": 10, } leftover_coin = 380 expected = { "100": 3, "10": 8, "500": 3, } self.assertEqual(expected, coin_obj.change_coin(leftover_coin, coin_list, last_gate)) def test_return_gate_empty_gate(self): coin_obj = Coin() last_gate = {} inserted_coin = 500 expected = { "500": 1, } self.assertEqual(expected, coin_obj.return_gate(inserted_coin, last_gate)) def test_return_gate_fill_gate(self): coin_obj = Coin() last_gate = { "500": 3 } inserted_coin = 40 expected = { "500": 3, "40": 1, } self.assertEqual(expected, coin_obj.return_gate(inserted_coin, last_gate))
7c0b452fb46205ef6ecdcfd595f30f43679e5c7d
YZ775/Vernam-cipher
/encrypt.py
2,522
3.734375
4
# -*- coding: utf-8 -*- import random message = raw_input("Enter a messege >>>") message_list = list(message) message_ascii = [""]*len(message) message_bit = [""]*len(message) for i in range (0,len(message)): #入力された文字をASCIIコード化し,さらにそれを2進数に変換してリストに格納する message_ascii[i] = ord(message_list[i]) #10進数のACSIIコード化 message_bit[i] = format(message_ascii[i],'08b') #2進数に変換 message_bit_temp = "".join(message_bit) #入力された文字の2進数リストを結合する bit_number = "0" + str(len(message)*8) +"b" #入力された文字のビット数の取得(0b{n}の形) key = random.randint(0, 2**(len(message)*8)) #復号のための鍵は入力された文字数分のビットの最大値以下でランダムに生成される key_bit = format (key,bit_number) #鍵を二進数に変換 message_temp = int(message_bit_temp,2) #結合した2進数表記の文字列を10進数に変換する print "Your encrypted message is[" + format (message_temp ^ key,bit_number) + "]" print "Your key is [" +key_bit + "]" print "Your message is " + str(len(message)*8) + "bits" encrypted_message = int(format (message_temp ^ key,bit_number),2) #入力された文字を排他的論理和によって暗号化する. 復号のために10進数の整数型に直しておく print "Your encrypted message is[" + format (message_temp ^ key,bit_number) + "]" ##表示(2進数) print "Your key is [" +key_bit + "]" print "Your message is " + str(len(message)*8) + "bits" decrypted_message = format(encrypted_message ^ key,bit_number) #復号 decrypted_message_list_bit = [decrypted_message[i: i+8] for i in range(0, len(decrypted_message), 8)] #復号された文字は2進数表記なので8ビットごとに分けてリストに格納する. decrypted_message_list = [""]*len(message) decrypted_message_list_ascii = [""]*len(message) #リストの定義 for i in range (0,len(message)): ##復号された2進数表記のリストをASCII文字に直す decrypted_message_list[i] = int(decrypted_message_list_bit[i],2) decrypted_message_list_ascii[i] = chr(decrypted_message_list[i]) ans = "".join(decrypted_message_list_ascii) ##リストを結合する print "." +"\n" print "Decrypting..." +"\n" print "." +"\n" print "Your decrypted message is["+ ans + "]"
01fa30e2693968a5ff91e7cd435bfa35949f7fff
LangdalP/EulerCode
/Problem1-24/Problem019/peder.py
1,332
4.28125
4
MONTH_DAYS = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] # Weekdays are 1 - 7 (monday - sunday) def is_leap_year(year): is_century = year % 100 == 0 return year % 400 == 0 if is_century else year % 4 == 0 def count_sundays_on_first(from_date, to_date, starting_weekday): current_year = from_date[0] current_month = from_date[1] current_day = from_date[2] current_weekday = starting_weekday sunday_count = 0 while (current_year, current_month, current_day) != to_date: # print("{yr}-{mn}-{da} // {wda}".format(yr=current_year, mn=current_month, da=current_day, wda=current_weekday)) if current_weekday == 7 and current_day == 1: sunday_count += 1 # Change day current_weekday = current_weekday % 7 + 1 days_in_month = MONTH_DAYS[current_month - 1] if is_leap_year(current_year) and current_month == 2: days_in_month = 29 current_day += 1 if current_day > days_in_month: current_day = 1 current_month += 1 if current_month > 12: current_month = 1 current_year += 1 return sunday_count if __name__ == "__main__": start = (1901, 1, 1) end = (2001, 1, 1) num_sundays = count_sundays_on_first(start, end, 2) print(num_sundays)
2d1bc38d4b70e91accbdbebe7cf8f57dedf1d95e
wasimblogs/PhotoFilter
/ImageStitching.py
5,122
3.5
4
""" This module takes two images and stitches them to create panorama Stitching Algorithm First place the right shifted image on empty canvas Then place the left image down. """ import cv2 import numpy as np def drawMatches(image1, point1, image2, point2): "Connects two matching keypoints by a line" output = np.hstack((image1, image2)) row, col = image1.shape[:2] x, y = point2 x = x + col cv2.line(output, point1, (x, y), (255, 0, 255), 5) cv2.imshow("OUTPUT", output) cv2.waitKey(10) pass # Goodness bias should matter more than recent bias def findHomography(image1, image2, Match=0.6): """Finds the matrix which relates two images. H = [R|T]""" # FLANN parameters for matching features # Calcuate keypoints in an image sift = cv2.SIFT(2000) kp1, des1 = sift.detectAndCompute(image1, None) kp2, des2 = sift.detectAndCompute(image2, None) kp1.sort() # Define a matcher to match keypoints in image pairs FLANN_INDEX_KDTREE = 0 index_params = dict(algorithm=FLANN_INDEX_KDTREE, trees=5) search_params = dict(checks=50) flann = cv2.FlannBasedMatcher(index_params, search_params) matches = flann.knnMatch(des1, des2, k=2) points1 = [] points2 = [] # ratio test as per Lowe's paper # 0.8 is default for i, (m, n) in enumerate(matches): if m.distance < 0.6 * n.distance: mm = m.distance / n.distance # Keep a list of good points from both images to compute homography # Points1 = Matrix * Points2 points1.append(kp1[m.queryIdx].pt) points2.append(kp2[m.trainIdx].pt) # Location of keypoints point1 = (int(kp1[m.queryIdx].pt[0]), int(kp1[m.queryIdx].pt[1])) point2 = (int(kp2[m.trainIdx].pt[0]), int(kp2[m.trainIdx].pt[1])) # useful only for debugging drawMatches(image1, point1, image2, point2) else: # Bad match pass # Data type conversion points1 = np.float32(points1) points2 = np.float32(points2) # Are two images touching? isAdjacentImage = False # Two images are touching if they have common keypoints / regions if len(points1) and len(points2): H, mask = cv2.findHomography(points1, points2, cv2.FM_RANSAC, 10) isAdjacentImage = True return isAdjacentImage, H else: return isAdjacentImage, None def stitch(imageL, imageR, result): row, col = imageR.shape[:2] # temp1 = result.copy() # temp2 = result.copy() print "RESULT : ", result.shape result[0:row, 0:col] = imageR row, col = imageL.shape[:2] result[0:row, 0:col] = imageL # result = cv2.addWeighted(temp2,0.5,temp1,0.5,0) # cv2.imshow("TEMP1", temp1) # cv2.imshow("TEMP2", temp2) cv2.imshow("RES", result) cv2.imwrite("G:/Result.jpg", result) cv2.waitKey(0) return result def findOrderAndStitch(retval, image1, image2): translate_X, translate_Y = int(retval[0][2]), int(retval[1][2]) # width = image1.shape[1]+image2.shape[1]-translate_X # height = image1.shape[0]+ image2.shape[0]-translate_Y row = np.max((image1.shape[0], image2.shape[0])) + abs(translate_Y) col = np.max((image1.shape[1], image2.shape[1])) + abs(translate_X) result = np.zeros((row, col, 3), np.uint8) print("Image1 shape : {}").format(image1.shape) print("Image2 shape : {}").format(image2.shape) print("Result shape : {}").format(result.shape) print("Translate Y, X {} {}").format(translate_Y, translate_X) # If left image is in left and right image at is in right if translate_X >= 0: row, col = image1.shape[:2] M = np.float32([[1, 0, translate_X], [0, 1, translate_Y]]) r, c = row + abs(translate_Y), col + abs(translate_X) image1 = cv2.warpAffine(image1, M, (c, r)) print "After affine image1 :", image1.shape imageR = image1 imageL = image2 else: row, col = image2.shape[:2] M = np.float32([[1, 0, -translate_X], [0, 1, -translate_Y]]) r, c = row + abs(translate_Y), col + abs(translate_X) image2 = cv2.warpAffine(image2, M, (c, r)) print "After affine image2 :", image2.shape imageR = image2 imageL = image1 result = stitch(imageL, imageR, result) cv2.imshow('INPUT 1', image1) cv2.imshow('INPUT 2', image2) cv2.imshow('RESULT', result) cv2.waitKey(0) def stitchImage(image1, image2): """Stitches two images if they have common regions""" ret, H = findHomography(image1, image2) if ret: res = findOrderAndStitch(H, image1, image2) else: print("Only images with common area can be stitched!") if __name__ == "__main__": image1 = cv2.imread("G:/Filters/Stitch/a1.jpg") image2 = cv2.imread("G:/Filters/Stitch/a3.jpg") stitchImage(image1, image2) help(drawMatches)
b0189f307dce4391c024f307901cc6fe0ccd2929
yosiyoshi/Go_Julia_and_Python
/super.py
389
3.734375
4
# coding: utf-8 # Your code here! class MyClass: def __init__(self, name): self.name=name def say(self): print(self.name) class UltraClass(MyClass): def __init__(self, name, year): super(UltraClass, self).__init__(name) self.year=year def say(self): print(self.name, "was born in", self.year) uc=UltraClass("John", 1990) uc.say()
ef28ba254b7a47d7a248f53382b4ec77c6f3bed2
mdenko/University-of-Washington-Certificates
/PYTHON 220/lesson08/lesson08_assignment.py
2,296
3.625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """importing functions""" import functools import pandas as pd def create_invoice(): """function to create_invoice""" invoice_file = pd.DataFrame(list()) invoice_file.to_csv('invoice_file.csv') return invoice_file def create_rental_items(invoice_file): """function to create_rental_items""" rental_items = pd.DataFrame() if not invoice_file.empty: rental_items.append(invoice_file) return rental_items def add_furniture(invoice_file, customer_name, item_code, item_description, item_monthly_price): """function will create invoice file (if it doesn't exist) or append to new line if does""" customer_name_list = list() item_code_list = list() item_description_list = list() item_monthly_price_list = list() customer_name_list.append(customer_name) item_code_list.append(item_code) item_description_list.append(item_description) item_monthly_price_list.append(item_monthly_price) if not invoice_file.empty: data_frame = pd.DataFrame() data_frame['customer_name'] = customer_name_list data_frame['item_code'] = item_code_list data_frame['item_description'] = item_description_list data_frame['item_monthly_price'] = item_monthly_price_list invoice_file.append(data_frame) else: invoice_file = pd.DataFrame() invoice_file['customer_name'] = customer_name_list invoice_file['item_code'] = item_code_list invoice_file['item_description'] = item_description_list invoice_file['item_monthly_price'] = item_monthly_price_list return invoice_file def return_single_customer(rental_items): """function to be called by single_customer""" return print(rental_items['customer_name']) def single_customer(customer_name, invoice_file): """returns a function that takes one parameter, rental_items""" rental_items = pd.DataFrame() rental_items = invoice_file.loc[invoice_file['customer_name'] == customer_name] functools.partial(return_single_customer, rental_items) if __name__ == "__main__": INVOICE_FILE = create_invoice() INVOICE_FILE = add_furniture(INVOICE_FILE, "Matt", "A346", "Baseball", 10.50) single_customer("Matt", INVOICE_FILE)
5fcf3076fabcd7f3b8bce724d4d547d20fe0290c
ulink-college/code-dump
/Riddle_Task/riddles_task3_MrF.py
527
3.984375
4
time = 0 answer = "" while answer != "Mississippi": print("What has 4 eyes but cannot see? ") print("Please entre the answer here:") answer = input() time+=1 if answer == "Mississippi": if time <= 3: print("Well done, you solved my riddle within three guesses!Number of total times: %d times"%(time)) else: print("Well down!You solve this riddle!Number of total times: %d times"%(time)) else: print("Number of %s times: %d times"%('error',time))
ba78405f4ccd12c548e0f8bdd08c0d293b2b4801
lypeng29/python-learning
/function.py
1,485
3.625
4
# def s(r): # return 3.14*pow(r,2) # print(s(2)) # n1 = 255 # n2 = 1000 # print(hex(n1),hex(n2),hex(n2),hex(n2),hex(n2),hex(n2)) import math def quadratic(a,b,c): # if not isinstance(a, (int, float)): # raise TypeError('bad data type') if a==0: return 'a不能等于0' dt=pow(b,2)-4*a*c if dt>0: x=(-b+math.sqrt(dt))/(2*a) y=(-b-math.sqrt(dt))/(2*a) return ('方程组有两个解,分别为:x1=%.1f,x2=%.1f' %(x,y)) elif dt==0: x=(-b+math.sqrt(dt))/(2*a) return ('方程组有一个解:x1=x2=%.1f' % x) else: return '方程组无解' a=float(input('请输入a:')) b=float(input('请输入b:')) c=float(input('请输入c:')) x=quadratic(a,b,c) # if isinstance(x, (float, int)): # print('x1=x2=',x) # elif isinstance(x, tuple): # print('x1=',x.x) # print('x2=',x.y) # else isinstance(x, str): print(x) # def power(x,n): # s=1 # while n>0: # s=s*x # n-=1 # return s # print(power(2,3)) ''' # *表示参数个数任意 def calc(*numbers): sum = 0 for n in numbers: sum = sum + n * n return sum print(calc(1,2,3,4)) ''' ''' def fact(n): if n==1: return 1 return n * fact(n - 1) print(len(str(fact(1000)))) ''' ''' def fact(n): return fact_iter(n, 1) def fact_iter(num, product): if num == 1: return product return fact_iter(num - 1, num * product) print(len(str(fact(100)))) '''
32814ce669290ce850a0320cf0d37802970d7b76
kanghuawu/Python
/python-cookbook/12-Concurrency/12-1-starting-and-stopping-threads.py
780
3.71875
4
import time def countdown(n): while n > 0: print('T-minus', n) n -= 1 time.sleep(1) from threading import Thread t = Thread(target=countdown, args=(5,), daemon=True) t.start() while True: print("running") if t.is_alive(): print("Still alive") else: print("Dead") break time.sleep(1) class CountDownTask: def __init__(self): self._running = True def terminate(self): self._running = False def run(self, n): while self._running and n > 0: print('T-minus', n) n -= 1 time.sleep(1) c = CountDownTask() t = Thread(target=c.run, args=(5,)) t.start() # c.terminate() t.join() if t.is_alive(): print("Still alive") else: print("Dead")
b93baff132f444127c3f3a724ed6d0e6700493db
GianRathgeb/m226B
/vehicles/vehicleClasses.py
1,055
3.6875
4
class Vehicle: def __init__(self, clean, number, wheels): self.__speed = 0 self.clean = clean self.number = number self.wheels = wheels def print_speedometer(self): print(f"{self.__speed}km/h") def accelerate_up(self, value): if value > 30: print("Cannot accelerate more than 30") elif value < 0: pass else: self.__speed += value if self.__speed > 250: self.__speed = 250 def slow_down(self, value): if value < 0: pass else: self.__speed -= value if self.__speed < 0: self.__speed = 0 class PW(Vehicle): def __init__(self, clean, number, wheels, countdoors, type): super().__init__(clean, number, wheels) self.countdoors = countdoors self.type = type class LKW(Vehicle): def __init__(self, clean, number, wheels, payload): super().__init__(clean, number, wheels) self.payload = payload
842df324828956a66f57bfd3facc3cc8e0b0b5d4
xxoellie/growth_recording
/Algorithm/backjoon/bronze/구구단.py
115
3.859375
4
a = int(input()) for i in range(1,10): print("{0} * {1} = {2}".format(a,i,a*i)) print(f"{a} * {i} = {a*i}")
791eb993af56cf5aec4afabde7268016b06c5b20
raviputtar/pycharm_repo
/random.py
236
3.84375
4
def myfunct(a,b,c): if c=="sum": return(a+b) elif c=="mul": if a < 0 or b < 0: raise ValueError("a or b should be greater than 0") else: return(a*b) else: return(a-b)
18d377100abf4614493f53971fb60661ff1f079f
Kalyan-Amarthi/100-days-python
/6.py
611
3.875
4
'''import math #n=int(input("enter")) #i=2 while i<=abs(int(math.sqrt(n))): if n%i==0: print(n,'is not a prime') break i+=1 else: print(n,"is a prime")''' '''a,b,c=map(int,input("enter the number").split()) print(a+b+c)''' '''s=int(input()) r=int(input()) n=int(input()) if s<r: for i in range(s,r+1): print(n,'*',i,'=',n*i) else: for i in range(s,r-1,-1): print(n,'*',i,'=',n*i)''' a=int(input("first number")) b=int(input("second number")) temp=0 print("before swapping",a,b) temp=a a=b b=temp print("after swapping",a,b)
9da3f26a6cf08dd0d4ff9bed51803b357ef0b8b1
mahdibz97/holbertonschool-higher_level_programming
/0x0B-python-input_output/1-number_of_lines.py
259
3.859375
4
#!/usr/bin/python3 """Define class""" def number_of_lines(filename=""): """returns the number of lines of a text file""" with open(filename, mode='r', encoding='UTF8') as f: num = 0 for line in f: num += 1 return num
d507d6b502f84ea583655ad3ca0ae9549359a344
Dzhevizov/SoftUni-Python-Fundamentals-course
/Programming Fundamentals Final Exam - 14 August 2021/03. Problem.py
1,482
3.90625
4
battlefield = {} command = input() while not command == "Results": command = command.split(":") action = command[0] if action == "Add": person = command[1] health = int(command[2]) energy = int(command[3]) if person not in battlefield: battlefield[person] = {} battlefield[person] = {'health': health, 'energy': energy} else: battlefield[person]['health'] += health elif action == "Attack": attacker = command[1] defender = command[2] damage = int(command[3]) if attacker in battlefield and defender in battlefield: battlefield[attacker]['energy'] -= 1 battlefield[defender]['health'] -= damage if battlefield[defender]['health'] <= 0: battlefield.pop(defender) print(f"{defender} was disqualified!") if battlefield[attacker]['energy'] <= 0: battlefield.pop(attacker) print(f"{attacker} was disqualified!") elif action == "Delete": person = command[1] if person == "All": battlefield = {} else: if person in battlefield: battlefield.pop(person) command = input() print(f"People count: {len(battlefield)}") for person, data in sorted(battlefield.items(), key= lambda x: (-x[1]['health'], x[0])): print(f"{person} - {data['health']} - {data['energy']}")
d74a29be975823f18cfc4ae2d49c4c077cba4663
huangyingw/submissions
/130/130.surrounded-regions.233262937.Accepted.leetcode.py
902
3.5
4
class Solution(object): def solve(self, board): if not board or not board[0]: return rows, cols = len(board), len(board[0]) to_expand = [] for row in range(rows): to_expand += [(row, 0), (row, cols - 1)] for col in range(1, cols - 1): to_expand += [(0, col), (rows - 1, col)] while to_expand: row, col = to_expand.pop() if 0 <= row < rows and 0 <= col < cols and board[row][col] == 'O': board[row][col] = 'T' for dr, dc in [(1, 0), (0, 1), (-1, 0), (0, -1)]: to_expand.append((row + dr, col + dc)) for row in range(rows): for col in range(cols): if board[row][col] == 'O': board[row][col] = 'X' elif board[row][col] == 'T': board[row][col] = 'O'
1455cbec0091f5b05171a5c71beae28becd47ff6
KokosTech/Python-Classwork
/15-01-21/class.py
2,663
3.875
4
# Exercise 1 print("Exercise 1:\n") class Triangle: a = 0 b = 0 c = 0 def __init__(self, a, b, c): self.a = a self.b = b self.c = c def p(self): print(f"The perimeter of the triangle is: {self.a + self.b + self.c}") obj = Triangle(int(input("Enter a: ")), int(input("Enter b: ")), int(input("Enter c: "))) obj.p() # Exercise 2 print("Exercise 2:\n") import os # Core Game Functions class Table: table = [] def __init__(self): i = 1 for row in range(3): self.table.append([]) for _ in range(3): self.table[row].append(i) i += 1 def print_table(self): clear() print("-------------") print(f"| {self.table[0][0]} | {self.table[0][1]} | {self.table[0][2]} |") print("----+---+----") print(f"| {self.table[1][0]} | {self.table[1][1]} | {self.table[1][2]} |") print("----+---+----") print(f"| {self.table[2][0]} | {self.table[2][1]} | {self.table[2][2]} |") print("-------------\n") def get_turn(self, player_name, symbol): num = int(input(f"{player_name}, choose a number: ")) for row in range(3): for col in range(3): if self.table[row][col] == num: self.table[row][col] = symbol return def win_check(self): if self.table[0][0] == self.table[0][1] == self.table[0][2] or \ self.table[1][0] == self.table[1][1] == self.table[1][2] or \ self.table[2][0] == self.table[2][1] == self.table[2][2] or \ self.table[0][0] == self.table[1][0] == self.table[2][0] or \ self.table[0][1] == self.table[1][1] == self.table[2][1] or \ self.table[0][2] == self.table[1][2] == self.table[2][2] or \ self.table[0][0] == self.table[1][1] == self.table[2][2] or \ self.table[0][2] == self.table[1][1] == self.table[2][0]: return True return False def clear(): os.system('cls' if os.name == 'nt' else 'clear') # Main Game count = 0 names = [] symbols = { 1: "X", 2: "O" } table = Table() names.append(input("Enter player one's name: ")) names.append(input("Enter player two's name: ")) while True: player_number = count % 2 table.print_table() table.get_turn(names[player_number], symbols[player_number+1]) if table.win_check(): clear() print(f"{names[player_number]} has won!") break if count == 8: clear() print("Tie...") break count += 1
7bb9285a34b3380de21167428d86e312eea45d72
poorna20/Task2
/Task2B.py
368
3.78125
4
def add(a,s): for i in range(s[0]-1,s[1]): a[i]+=s[2] return a n=int(input("Enter number of elements: ")) a=[i for i in range(1,n+1)] q=int(input("Enter number of queries: ")) for i in range(0,q): s=[int(s) for s in input("Enter indices and value to add: ").split()] a=add(a,s) print ("Max element: ",max(a))
b4cef7f5855a65dfa93cde69d99c64c4ba9fea5b
koffy1/DSA
/Python/linked-list.py
1,805
4.15625
4
# Implementation of linked list in python class Node: def __init__(self, val=None): self.val = val self.next = None class LinkedList: def __init__(self, head=None): self.head = head def printList(self): if self.head is None: return "No node to print" printList = self.head while printList is not None: print(printList.val) printList = printList.next return "End" def insertBeginning(self, node): if self.head is None: self.head = node else: node.next = self.head self.head = node def insertEnd(self, node): if self.head is None: self.head = node else: prevNode = self.head while prevNode.next is not None: prevNode = prevNode.next prevNode.next = node def delete(self, key): if self.head is None: return 'No node to delete' if self.head.val == key: self.head = self.head.next return 'Removed Head Node' loopList = self.head.next prev = self.head while loopList is not None: if loopList.val == key: prev.next = loopList.next return 'Removed key', key prev = loopList loopList = loopList.next return 'Could not find key in the linkedList' myList = LinkedList() firstNode = Node(1) myList.head = firstNode myList.insertBeginning(Node(0)) myList.insertEnd(Node(2)) myList.insertEnd(Node(3)) myList.insertEnd(Node(4)) myList.insertEnd(Node(5)) print(myList.delete(0)) print(myList.printList())
92937277992c122c26f8c4964fa1b820a811c7a7
christodragnev/unit3
/favorites.py
165
3.890625
4
#Christo Dragnev #2/14/18 #favorites.py word = input('Enter your favorite word: ') num = int(input('Enter your favorite number: ')) for i in range(0,num): print(word)
105ee360a50d5133c07fd1224fc9872fd1f4e243
shelcia/InterviewQuestionPython
/amazon/PreorderToBST.py
2,143
4.0625
4
# Construct BST from given preorder traversal # Given preorder traversal of a binary search tree, construct the BST. # For example, if the given traversal is {10, 5, 1, 7, 40, 50}, then the output should be # the root of the following tree. # 10 # / \ # 5 40 # / \ \ # 1 7 50 # A O(n) program for construction of BST from preorder traversal INT_MIN = float("-infinity") INT_MAX = float("infinity") # A Binary tree node class Node: # Constructor to created a new node def __init__(self, value, left=None, right=None): self.value = value self.left = left self.right = right # Methods to get and set the value of static variable # constructTreeUtil.preIndex for function construcTreeUtil() class BinaryTree: def __init__(self, root=None): self.root = root def _insertNode(self, node, value): if value < node.value: if node.left is None: node.left = Node(value) else: self._insertNode(node.left, value) elif value > node.value: if node.right is None: node.right = Node(value) else: self._insertNode(node.right, value) def insertNode(self, value): node = Node(value) if(self.root is None): self.root = node else: self._insertNode(self.root, value) def _inorderTraversal(self, currentNode): if currentNode is None: return [] return (self._inorderTraversal(currentNode.left) + [currentNode.value] + self._inorderTraversal(currentNode.right)) def inorderTraversal(self): if self.root is None: return [] return self._inorderTraversal(self.root) if __name__ == "__main__": instance = BinaryTree() print('print') print(instance.inorderTraversal()) # instance.constructTree([10, 5, 1, 7, 40, 50]) preorder = [10, 5, 1, 7, 40, 50] for i in range(len(preorder)): instance.insertNode(preorder[i]) print('print') print(instance.inorderTraversal())
38c8a88b42549a60cd10ac0c85e578a3f67872ad
namyangil/edu
/Python/codeup/codeup_1635.py
124
3.671875
4
n=int(input()) n_list=[] for i in range(n): n_list.append(input()) n_list.sort() for i in range(n): print(n_list[i])
88e488611a5380ddc3e04037cc9870922cdf5071
MrWormsy/Graphs
/TP1/main.py
1,782
3.515625
4
from RTree import RTree def main(): #We first create a RTree where rt0 is the root rt5 = RTree('n5') rt11 = RTree('n11') rt10 = RTree('n10', [rt11]) rt4 = RTree('n4') rt3 = RTree('n3') rt2 = RTree('n2') rt7 = RTree('n7', [rt10]) rt9 = RTree('n9') rt6 = RTree('n6', [rt7]) rt8 = RTree('n8', [rt6]) rt1 = RTree('n1', [rt4, rt5, rt8, rt9]) rt0 = RTree('n0', [rt1, rt2, rt3]) #Display the Depth print("\nDisplay through Depth") rt0.displayDepth() #Display the Width print("\nDisplay through Width") rt0.displayWidth() #Get the childrens print("\nGet the childrens") for children in rt0.getChildrens(): print(children.getContent()) #Get the father print("\nGet the father") print(rt0.getFather(rt1).getContent()) #Get the descendents (childs, grand childs ect) print("\nGet the descendents") #Filter the RTree that are in more than once listToPrint = [] for children in rt0.getDescending(): if(children not in listToPrint): listToPrint.append(children) print(children.getContent()) #Get the ascendents (father, grand father) print("\nGet the Ascendents") for fathers in rt0.getAscending(rt0.getRoot(), rt11): print(fathers.getContent()) #Check if a RTree is a leaf or not print("\nKnow if this is a leaf") print(rt0.isLeaf()) print(rt2.isLeaf()) #Get the degree of a RTree print("\nGet the degree of the RTree") print(rt0.getDegree()) """ print("\nGet the Depth of the RTree") print(rt0.getDepth()) """ if __name__ == "__main__": main()
88cff0d789044c512fd713649b830a2e7d91735a
BLaurenB/daily-practice
/sum_digits.py
748
4.40625
4
""" In this kata, you must create a digital root function. A digital root is the recursive sum of all the digits in a number. Given n, take the sum of the digits of n. If that value has two digits, continue reducing in this way until a single-digit number is produced. This is only applicable to the natural numbers. Ex: digital_root(132189) => 1 + 3 + 2 + 1 + 8 + 9 => 24 ... => 2 + 4 => 6 """ # My solution def digital_root(n): while (len(str(n)) > 1): n = sum([int(num) for num in str(n)]) return n # Other options after looking at other answers... # def digital_root(n): # while (n > 9): # n = sum(map(int,str(n))) # return n print(digital_root(123)) print(digital_root(123456)) print(digital_root(1234561122))
bb50f63005000493a70c9a2cd65cd2c0453e56ae
Wangyibao/PythonLearning
/python-learn.py
1,305
4.25
4
# -*_ coding: utf-8 -*- # day01 # 输出 print('hello world'); print('hello','world','hello','python'); print(300); print(100+300); print('100+200= ',100+200); # 输入 # name=input(); # 输入任意字符,按回车完成输入 # print('name= ',name); # name=input('please enter your name:') # print('name= ',name); # -------------------------------------------------- # day02 # 变量 # 变量不需要指定数据类型 a = 1 str = 'hello' answer = True print(a,str,answer) # 常量 NAME="wangyi" print(NAME) # 字符串 str=b'abc' # bytes类型的数据用b作为前缀 # 编码 print('abc'.encode('ascii')) print('你好'.encode('utf-8')) # 解码 print(b'abc'.decode('ascii')) print(b'efg'.decode('utf-8')) print('你好'.encode('utf-8').decode('utf-8')) # 计算字符串长度 print(len(b'abc')) print(len('你好'.encode('utf-8'))) # 格式化输出字符串 print('hello, %s'%'world') print('hello, %s, welcome to %s' %('李四','北京')) print('you have %d money' %10000) # 输出指定长度 print('%5d' %5) # 补零 print('%05d' %4) # 指定小数位数 print('%.2f' %3.1415926) # format()函数,使用传入参数替换字符串内的占位符{0},{1}……. print('hello,{0}, 成绩提升了{1:.1f}%'.format('李四',15.155)) # --------------------------------------------------
3585f06c0c3c0a3bdfa9422321f6c54c8a6362d5
santhosh-kumar/AlgorithmsAndDataStructures
/python/problems/hashing/two_sum.py
1,794
3.859375
4
""" Two Sum Given an array of integers, find two numbers such that they add up to a specific target number. The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based. You may assume that each input would have exactly one solution. """ from common.problem import Problem class TwoSum(Problem): """ Two Sum """ PROBLEM_NAME = "TwoSum" def __init__(self, input_list, target_sum): """Two Sum Args: input_list: Contains a list of integers target_sum: Target sum for which the indices need to be returned Returns: None Raises: None """ assert (len(input_list) > 0) assert (target_sum > 0) super().__init__(self.PROBLEM_NAME) self.input_list = input_list self.target_sum = target_sum def solve(self): """Solve the problem Note: The O(n) runtime uses the commutative property of addition. (target_sum-x) is searched for in the given map. However, it takes O(n) extra space for the dictionary. Comparatively, O(n^2) brute-force solution adds each element with every other element. Args: Returns: tuple Raises: None """ print("Solving {} problem ...".format(self.PROBLEM_NAME)) input_dict = {} for i in range(0, len(self.input_list)): x = self.input_list[i] if (self.target_sum - x) in input_dict: return input_dict[self.target_sum - x] + 1, i + 1 input_dict[x] = i assert (False, "InvalidArguments")
1c9e4cb35a997a7656a02b2e3a0c2a4a33a26b5d
LuHanUp/lean-python
/python入门/Alex大王的Python开发96天0基础到大神课程/day1/运算符.py
393
4.0625
4
# 常见的运算符 # 算术运算符 普通的+ - * / % 就不介绍了 # 幂算术操作符 ** print(2 ** 8) # 表示为2的8次方 # 取整除,返回商的整数部分 print(9 // 2) # 比较运算符 略 参考Java中的比较运算符 # 赋值运算符 = += -= *= /= 就不介绍了 num = 10 b = 2 num //= b print(num) num = 20 num **= 3 print(num) num = 20 num %= 5 print(num)
7d06b01b7ed9c13fde7e7cbd1be85db09518005e
dhairyajoshi/Enigma-Learning-Series
/Chopsticks.py
6,585
3.59375
4
import time from os import system, name class player: def __init__(self) -> None: self.left=1 self.right=1 def clear(): # for windows if name == 'nt': _ = system('cls') # for mac and linux(here, os.name is 'posix') else: _ = system('clear') def game(): current=0 run=True p1=player() p2=player() print("Current Status: ") print(f'player 1- {p1.left} {p1.right}') print(f'player 2- {p2.left} {p2.right}') while(run): if(current==0): move=input('Enter move for player 1: ') if((p1.right==0 and p1.left==1 or p1.left==0 and p1.right==1) and move=='S'): print("You can only attack in this turn") move='A' if(move=='A'): invalid=True while(invalid): inp=input('Enter Move combination for player 1: ').split() if(inp[0]=='R' and inp[1]=='R'): if(p1.right!=0 and p2.right!=0): p2.right+=(p1.right) p2.right=p2.right%5 invalid=False else: print("Invalid move!") continue elif(inp[0]=='R' and inp[1]=='L'): if(p1.right!=0 and p2.left!=0): p2.left+=(p1.right) p2.left=p2.left%5 invalid=False else: print("Invalid move!") continue elif(inp[0]=='L' and inp[1]=='L'): if(p1.left!=0 and p2.left!=0): p2.left+=(p1.left) p2.left=p2.left%5 invalid=False else: print("Invalid move!") continue elif(inp[0]=='L' and inp[1]=='R'): if(p1.left!=0 and p2.right!=0): p2.right+=(p1.left) p2.right=p2.right%5 invalid=False else: print("Invalid move!") continue elif(move=='S'): invalid=True while(invalid): inp=input('Enter move combination for player 1: ').split() lef=int(inp[1]) rig=int(inp[2]) if(lef+rig==p1.right+p1.left): if(lef!=p1.left and rig!=p1.right) and (lef!=p1.right and rig!=p1.left): invalid=False p1.right=rig%5 p1.left=lef%5 else: print("Invalid move!") continue else: print("Invalid move") continue current=1-current elif(current==1): move=input('Enter move for player 2: ') if((p2.right==0 and p2.left==1 or p2.left==0 and p2.right==1) and move=='S'): print("You can only attack in this turn") move='A' if(move=='A'): invalid=True while(invalid): inp=input('Enter Move combination for player 2: ').split() if(inp[0]=='R' and inp[1]=='R'): if(p2.right!=0 and p1.right!=0): p1.right+=(p2.right) p1.right=p1.right%5 invalid=False else: print("Invalid move!") continue elif(inp[0]=='R' and inp[1]=='L'): if(p2.right!=0 and p1.left!=0): p1.left+=(p2.right) p1.left=p1.left%5 invalid=False else: print("Invalid move!") continue elif(inp[0]=='L' and inp[1]=='L'): if(p2.left!=0 and p1.left!=0): p1.left+=(p2.left) p1.left=p1.left%5 invalid=False else: print("Invalid move!") continue elif(inp[0]=='L' and inp[1]=='R'): if(p2.left!=0 and p1.right!=0): p1.right+=(p2.left) p1.right=p1.right%5 invalid=False else: print("Invalid move!") continue elif(move=='S'): invalid=True while(invalid): inp=input('Enter move combination for player 2: ').split() lef=int(inp[1]) rig=int(inp[2]) if(lef+rig==p2.right+p2.left): if(lef!=p2.left and rig!=p2.right) and (lef!=p2.right and rig!=p2.left): invalid=False p2.right=rig%5 p2.left=lef%5 else: print("Invalid move!") continue else: print("Invalid move") continue current=1-current print("Current Status: ") print(f'player 1- {p1.left} {p1.right}') print(f'player 2- {p2.left} {p2.right}') if(p1.right==0 and p1.left==0): print("Player 2 has won!") run=False if(p2.right==0 and p2.left==0): print("Player 1 has won!") run=False play=True while(play): game() print('New game in',end=' ') time.sleep(1) print(5,end=' ') time.sleep(1) print(4,end=' ') time.sleep(1) print(3,end=' ') time.sleep(1) print(2,end=' ') time.sleep(1) print(1,end=' ') time.sleep(1) clear()
70a1842f98e5bd2d60442ddbf4b8b78f3b8ecab6
Karnyshov/Codeacademy
/LogicTask.py
128
4.125
4
if not True: print(True) elif 8 % 3 < 2: print(False) elif False and True: print("None") else: print("Nothing")
178923d220f5efa882a2d9bf549dd2a69fe1ae8b
XUEMANoba/python-jichu
/13-day/2自己练习名片系统.py
354
3.578125
4
print("名片管理系统".center(30,"*")) print("1.添加名片".center(30," ")) print("2.查找名片".center(30," ")) print("3.修改名片".center(30," ")) print("4.删除名片".center(30," ")) print("5.退出系统".center(30," ")) list[] while True: fun_number = int(input("请选择功能")) if fun_number == 1: print("新增") flag = 0
ce52bedad32b48cf6f7f67d2c5f27351c6e0ae5d
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/allergies/7ec0bcde6ed14b0d86e0add56ccb7d5e.py
832
3.765625
4
from collections import OrderedDict class Allergies: "Inputs: Allergy score" def __init__(self, score): self.score = score self._allergydictionary = { 'eggs': 1, 'peanuts': 1<<1, 'shellfish': 1<<2, 'strawberries': 1<<3, 'tomatoes': 1<<4, 'chocolate': 1<<5, 'pollen': 1<<6, 'cats': 1<<7 } self.ordereddictionary = OrderedDict(sorted (self._allergydictionary.items(), key=lambda t: t[1])) self.list = [x for x in self.ordereddictionary if self.is_allergic_to(x)] def is_allergic_to(self, thing): return self.score & self._allergydictionary[thing] != 0
dc0e2ed3141b18cd51e0e9b5d698cba4aab87ada
stockenberg/PyPy
/Python: Getting Started/Statements and other goodies/functions_local.py
338
3.671875
4
store = [] def sort_by_last_letter(strings): def last_letter(s): return s[-1] store.append(last_letter) print(last_letter) return sorted(strings, key=last_letter) ''' Local functions can be returned from functions ''' def outer(): def inner(): print("inner") return inner i = outer() i()
3193a85cd9a9025092cb4b38116aff72c7ac6654
gohst9/cp_library
/shakutori.py
928
3.515625
4
class Shakutori: def __init__(self,lst,mono=0,limit=0): self.lst = lst self.mono = mono self.limit = limit self.answer = self.mono def calc(self): l = 0 r = 1 while l <= len(self.lst) and r < len(self.lst)+1: if self.judge(self.lst[l:r]): self.answer_update() print(self.lst[l:r]) #rを+1したとき条件に合うか判定。合えばr+=1 合わない、合わないならl+=1 if (r <= len(self.lst)+1 and self.judge(self.lst[l:r+1])) or l >= r-1: r += 1 else: l += 1 return self.answer def judge(self,lst): if sum(lst) <= self.limit: return True else: return False def answer_update(self): self.answer += 1 lst = [1,2,3,4,5,6,7,2,3] s = Shakutori(lst,0,5) print(s.calc())
ab36649c982810f0bdd80dd0cfc16e00fb369c4b
sirrah23/HyperLogLog
/hll.py
3,736
3.546875
4
""" Contains an implementation of the HyperLogLog algorithm. """ import hashlib from collections import defaultdict def hash_string(s): """ Return the SHA-1 hash for a given string. """ return hashlib.sha1(str.encode(s)).hexdigest() def hexstring_to_int(s): """ Convert a hexadecimal number to a base 10 integer. """ return int(s, 16) def get_hll_register_num(hs): """ Designates the first three elements of a hexadecimal number as the HyperLogLog register. """ return hs[:3] def get_hll_hash(hs): """ Designates the last 14 elements of a hexadecimal number as the HyperLogLog hash. """ return hs[-14:] def int_to_bin(i): """ Convert an integer to a binary number. """ return bin(i) def first_nonzero_bit(bs): """ Return the one-based array index of the first non-zero bit (from the left) for a given binary string. """ bs = bs[2:] #return len(bs) - bs.index('1') return bs[::-1].index('1') def element_to_register_nonzero(elem): """ Given an element, return it's register # and the index of first-non-zero bit of its HyperLogLog hash. """ elem_hash = hash_string(elem) register = hexstring_to_int(get_hll_register_num(elem_hash)) hll_hash = get_hll_hash(elem_hash) fnz_bit = first_nonzero_bit(int_to_bin(hexstring_to_int(hll_hash))) return (register, fnz_bit) def cardinality_estimate(maxbits): """ Given the the first non-zero indices for a register, perform a cardinality estimate using the HyperLogLog formula. """ tot_regs = len(maxbits) two_inv_sum = sum(map(lambda m: pow(2, -1*m), maxbits)) return 0.7213/(1 + 1.079/tot_regs) * pow(tot_regs,2) * 1/two_inv_sum def HLL(items): """ Given a list of (dimension, element) pairs, get a probabilistic, distinct element count for each value of dimension using the HyperLogLog algorithm. """ # For each item in the list # 1. Add the dimension to dictionary # 2. Get the register #, and first non-zero for the associated element # 3. Add the (register #, first non-zero) to the dimension's dictionary if the # first non-zero value for the register is greater than the current one # 4. Perform the cardinality estimate for each dimension dim_reg_maxbit = defaultdict(lambda: defaultdict(int)) for item in items: i_dim, i_elem = item i_reg, i_fnz_bit = element_to_register_nonzero(i_elem) dim_reg_maxbit[i_dim][i_reg] = max(dim_reg_maxbit[i_dim][i_reg], i_fnz_bit) estimates = [] for dim in dim_reg_maxbit: maxbits = [v for _, v in dim_reg_maxbit[dim].items()] estimates.append((dim, cardinality_estimate(maxbits))) return estimates def count(items): """ Given a list of (dimension, element) pairs, compute the number of distinct elements for each dimension. Can be used to compare results of the HyperLogLog implementation. """ res = defaultdict(lambda: set([])) for dim, elem in items: res[dim].add(elem) return [(k, len(v)) for k, v in res.items()] def print_cmp(estimates, actuals): width = 30 print("{: <{width}}\t{: <{width}}\t{: <{width}}".format("date", "estimate", "actual", width=width)) for i, j in zip(estimates, actuals): print("{: <{width}}\t{: <{width}}\t{: <{width}}".format(i[0], i[1], j[1], width=width)) if __name__ == "__main__": fname = input("Name of file with input data? ") with open(fname) as f: items = [r.split(',') for r in f.read().splitlines()] items = items[1:] # drop header hll_counts = HLL(items) actual_counts = count(items) print_cmp(hll_counts, actual_counts)
7f8b312fde53ac974ffdc02c4ada807de6f8c17b
moni310/List_questions
/without_len_count.py
72
3.8125
4
list=[3,5,8,9,1,7] count=0 for i in list: count=count+1 print(count)
1fd91edaa0c599b714dd030574bbf11fdeaa1bcd
pytoday/pycode
/data_visualization/random_walk.py
2,116
3.5
4
#!/usr/bin/env python3 # coding=utf-8 # title :random_walk.py # description : # author :JackieTsui # organization :pytoday.org # date :2017/8/20 下午5:09 # email :jackietsui72@gmail.com # notes : # ================================================== # Import the module needed to run the script from random import choice import matplotlib.pyplot as plt class Randomwalk: """a class of random walk""" def __init__(self, num_points=5000): self.num_points = num_points # random start at (0, 0) self.x_values = [0] self.y_values = [0] def fill_walk(self): """walk all point""" while len(self.x_values) < self.num_points: x_direction = choice([1, -1]) x_distance = choice([1, 2, 3, 4]) x_step = x_direction * x_distance y_direction = choice([1, -1]) y_distance = choice([1, 2, 3, 4]) y_step = y_direction * y_distance if x_step==0 and y_step==0: continue next_x = self.x_values[-1] + x_step next_y = self.y_values[-1] + y_step self.x_values.append(next_x) self.y_values.append(next_y) while True: rw = Randomwalk() rw.fill_walk() # plt.scatter(rw.x_values, rw.y_values, s=15) point_numbers = list(range(rw.num_points)) plt.scatter(rw.x_values, rw.y_values, c=point_numbers, cmap=plt.cm.Reds, edgecolors='none', s=15) # set start and end point plt.scatter(0, 0, c='green', edgecolors='none', s=100) plt.scatter(rw.x_values[-1], rw.y_values[-1], c='blue', edgecolors='none', s=100) # hidden label plt.axes().get_xaxis().set_visible(False) plt.axes().get_yaxis().set_visible(False) # set windows size # plt.figure(dpi=128, figsize=(10, 6)) plt.show() keep_running = input("Make another walk?(y/n)") if keep_running == 'n' or keep_running == 'N': break rw1 = Randomwalk() rw1.fill_walk() point_numbers1 = list(range(rw1.num_points)) plt.plot(rw1.x_values, rw1.y_values, linewidth=8) plt.show()
47bf317162d6f9c76db1d2a8fc69344b76fdedce
calvinshalim/BINUSIAN-2023
/Functions/function.py
676
4.0625
4
# Introduction to function #%% # Simple calculator firstNum = input("Enter your first number: ") secNum = input("Enter your second number: ") def addition(num_1, num_2): return int(num_1) + int(num_2) print ("addition is:",addition(firstNum,secNum)) # Task - create the remaining functions for substraction, multiplication and division def substract(num_1, num_2): return int(num_1) - int(num_2) print("substract is:",substract(firstNum,secNum)) def multiply(num_1, num_2): return int(num_1) * int(num_2) print("multiply is:",multiply(firstNum,secNum)) def divide(num_1,num_2): return int(num_1) / int(num_2) print("divide is:",divide(firstNum,secNum))
25010ab485356a2f8969e5f611830f9922b3d8dd
moazsholook/Performance_Task_1
/main.py
10,888
4.375
4
#importing tkinter to add simple widgets from tkinter import * root = Tk() #outer while loop to make sure that the game can be repeated even when #one of the storylines has been completed. while True: #a loop to make the code repeat if the input to the first decision is invalid while True: #Game created by Moaz and Thomas, this choice game is a satire game where #unexpected choices bring forth unexpected outcomes. this may not be funny to most, #but it was funny to us. #displaying the title and storing the players' name print("BORING SATURDAY") #empty print statements to space out the console a bit print() #entry field player_name = Entry(root) #retrieves name from input field player_name.pack() player_name.get() print() print("Man, I'm bored today. I need something to do.") print("1.Go to the kitchen") print("2.Go on a walk") #loop and try/except to make sure a player cannot proceed without #entering a proper input. these smaller loops are repeated everytime there is #a new input. keeping inputs simple with numbers instead of words while True: try: print() decision = int(input("What do you choose to do: ")) break except ValueError: print() print("That is not a valid option. Try Again") #branching off different possible story paths. if decision == 1: print() print("You go down to the kitchen... there are some rummaging noises when all of a sudden you see a raccoon and a bush-like creature raiding your fridge. what do you choose to do?") print("1.Escape") print("2.Chase them") #branching off within branches while True: try: print() decision_2 = int(input("What do you choose to do: ")) break except ValueError: print() print("That is not a valid option. Try Again") if decision_2 == 1: #f string for efficiency in calling upon variables in print statements print() print(f"The invader realizes {player_name.get()} is a beta and they beat {player_name.get()} to death for being a wuss") print() print("GAME OVER") #this break statement is repeated after most if statements in this #program so that it doesnt automatically loop once the if statement #is completed break #repeat all of the elements accordingly for all the other story paths elif decision_2 == 2: print() print(f"{player_name.get()} chases them outside where they split up. which one will you chase? ") print() print("1.Bush creature") print("2.Raccoon") decision_3 = int(input("What do you choose to do: ")) if decision_3 == 1: print() print(f"{player_name.get()} chases the creature into the woods where it gathers with a child-sized ferret and a statue of George Washington. They're discussing something about a coup. {player_name.get()} can't believe it.") print() print("1.Take a photo") print("2.Escape") print("3.Join them") while True: try: print() decision_4 = int(input("What do you choose to do: ")) break except ValueError: print() print("That is not a valid option. Try Again") if decision_4 == 1: print() print(f"{player_name.get()} takes a photo. but they saw the flash so you were caught and beat to death. it's 1pm. what do you have flash on for? you deserved that, you dirty snitch.") print() print("GAME OVER") break elif decision_4 == 2: print() print(f"{player_name.get()} attempts to escape but snaps a stick on the way out. look where you're going next time genius lol. you obviously get beat to death.") print() print("GAME OVER") break elif decision_4 == 3: print() print(f"{player_name.get()} accepts defeat due to incompetence and join the mysterious gang. {player_name.get()} is accepted into the group.") print() print("YOU WIN!") break #else statements used to stop players from entering undesired inputs else: print() print("invalid option") #continue statements used to automatically repeat the immediate #loop so that players cannot advance without the proper inputs continue if decision_3 == 2: print() print(f"{player_name.get()} chases the raccoon a few houses down where it ends in a standoff. What will they do?") print() print("1.Throw something at it") print("2.Let it be") print("3.Grab it") while True: try: print() decision_5 = int(input("What do you choose to do: ")) break except ValueError: print() print("That is not a valid option. Try Again") if decision_5 == 1: print() print(f"{player_name.get()} threw a stick at the raccoon.") print(f"the raccoon hit it back at {player_name.get()} with the force of 1000 suns. {player_name.get()} incinerates and dies instantly.") print() print("GAME OVER") break elif decision_5 == 2: print() print(f"John Quiñones, host of What Would You Do appears. 'Congratulations, {player_name.get()}. I'm John Quiñones,host of What Would You Do, and this raccoon is a paid actor. You did well.'") print() print("YOU WIN!") break elif decision_5 == 3: print() print(f"{player_name.get()} tries to grab the raccoon, but is bitten by it. {player_name.get()} transforms into a were-raccoon and wreaks havoc on everyone in town.") print() print("YOU WIN!") break else: print() print("invalid option") continue #the 'go to kitchen' potential storylines end here #this is what happens if the player chooses to go on a walk elif decision == 2: print() print(f"{player_name.get()} is out on the street when they spot a statue of George Washington head into the forest. What will they do?") print() print("1.Ignore and continue walking.") print("2.Follow the statue.") while True: try: print() decision_6 = int(input("What do you choose to do: ")) break except ValueError: print() print("That is not a valid option. Try Again") if decision_6 == 1: print() print(f"{player_name.get()} continued walking.") elif decision_6 == 2: print() print(f"{player_name.get()} was spotted and caught a mean right hook from the statue. {player_name.get()} is out cold") print() print("GAME OVER") break else: print() print("Invalid option") continue print() print(f"{player_name.get()} reaches a crossroads. Which way will they go?") print() print("1.right") print("2.straight") print("3.left") while True: try: print() decision_i=int(input("Which way do you choose: ")) break except ValueError: print() print("That is not a valid option. Try Again") if decision_i == 1: print() print(f"{player_name.get()} stumbles across a vampire and a T-rex having a dance off in the middle of the street. What will you do?") print() print("1.Join in") print("2.Ignore them") while True: try: print() int_right=int(input("What will you do")) break except ValueError: print() print("That is not a valid option. Try Again") if int_right==1: print() print(f"{player_name.get()} decides to show them why they call you the modern Micheal Jackson. They are thouroughly impressed and decide to become your buddies") print() print("YOU WIN") break elif int_right==2: print() print(f"{player_name.get()} decided to ignore them. Unfortunately they caught you before you could leave. They decided to give you the beats because you wanted to be a lame") print() print("GAME OVER") break elif decision_i == 2: print() print(f"{player_name.get()} decided to be foolish and went straight. You were obviously trampled by a marching band of elephants") print() print("GAME OVER") break elif decision_i == 3: print() print(f"{player_name.get()} heads left and you are met with 2 old ladies arguing about a shared yard. What will you do?") print() print("1.Try to act as a mediator") print() print("2.Ignore them") while True: try: print() int_left=int(input("What will you do: ")) break except ValueError: print() print("That is not a valid option. Try Again") if int_left==1: print() print(f"{player_name.get()} chooses to try to help them but end up getting yourself and the other lady shot because you couldn't just mind your business") print() print("GAME OVER") break elif int_left==2: print() print(f"{player_name.get()} decides to mind your business(as you should) and you make it home safely") print() print("YOU WIN") break else: print() print("Invalid option") continue else: print() print("Invalid option") else: print() print("invalid option") #placed inside the outermost while loop, this allows players to decide whether or #not they would like to repeat print() play_again = input("Would you like to play again (yes/no): ") if play_again.lower() == "yes": print() print() print() print() continue elif play_again.lower() == "no": print() print("Thank you for playing.") break root.mainloop()
7a83c5d8fb7958c3f2e739bddb7d20b2a3b25025
leilalu/algorithm
/剑指offer/第一遍/tree/18-1.二叉树的深度.py
1,570
4.15625
4
""" 题目一:二叉树的深度 输入一棵二叉树的根结点,求该树的深度。 从根结点到叶结点一次经过的结点(含根、叶结点)形成的一条路径,最长路径的长度为树的深度 """ class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution1: def TreeDepth(self, pRoot): """ 这是在间接考察遍历一棵树 :param pRoot: :return: """ class Solution2: def TreeDepth(self, pRoot): """ 递归法更加简洁 从另外一个角度理解树的深度,不要一味纠结面试官给出的深度的定义 如果一棵树只有一个结点, 那么它的深度为1 (左子树深度等于右子树深度) 如果一棵树只有左子树没有右子树,那么它的深度为其左子树深度+1 (左子树深度 大于 右子树深度) 如果一棵树只有右子树没有左子树,那么它的深度为其右子树深度+1 (右子树深度 大于 左子树深度) 如果一棵树既有右子树又有左子树,那么它的深度为左、右子树深度的较大值+1 :param pRoot: :return: """ depth = 0 if not pRoot: return depth left = self.TreeDepth(pRoot.left) right = self.TreeDepth(pRoot.right) if left > right: depth = left + 1 else: depth = right + 1 return depth
13d4180d75757b046b8fc1332aaf0b4be458a49a
ThyagoHiggins/LP-Phython
/Aulas e Exercicios/Exercicios/Lista 5/Questão 9.py
110
3.609375
4
def inverso(x): return str(x[::-1]) num = str(input('Qual número:')).strip() print(f'{inverso(num)}')
af3d70229accfda5bf61e2517e7ca9bce2dff535
SheetanshKumar/smart-interviews-problems
/InterviewBit/Dynamic Programming/Edit Distance.py
1,370
3.96875
4
''' https://www.interviewbit.com/problems/edit-distance/ Given two strings A and B, find the minimum number of steps required to convert A to B. (each operation is counted as 1 step.) You have the following 3 operations permitted on a word: Insert a character Delete a character Replace a character Input Format: The first argument of input contains a string, A. The second argument of input contains a string, B. Output Format: Return an integer, representing the minimum number of steps required. Constraints: 1 <= length(A), length(B) <= 450 Examples: Input 1: A = "abad" B = "abac" Output 1: 1 Explanation 1: Operation 1: Replace d with c. Input 2: A = "Anshuman" B = "Antihuman" Output 2: 2 Explanation 2: => Operation 1: Replace s with t. => Operation 2: Insert i. ''' def minDistance(self, A, B): dp = [[0 for i in range(len(A) + 1)] for j in range(len(B) + 1)] for i in range(len(A) + 1): dp[0][i] = i for i in range(len(B) + 1): dp[i][0] = i for i in range(1, len(B) + 1): for j in range(1, len(A) + 1): if B[i - 1] == A[j - 1]: dp[i][j] = dp[i - 1][j - 1] else: dp[i][j] = min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]) + 1 # for i in dp: # print(*i) return dp[len(B)][len(A)]
dd946321e3b3584442ddf934b39890428490a0ac
LeandrOS1/Ejercicios
/Ejercicios 17.06 DICCIONARIOS.py
1,756
4.25
4
""" 1.- Dadas 2 tuplas crear un diccionario donde la primera tupla sean las claves y la segunda los valores. """ def dicc(): Lista1=[] Lista2=[] print("Para detener ingrese 'Alto'") while True: x=input("Ingrese llave: ") if x=="Alto" or x=="alto": break if x not in Lista1: y=input("Ingrese valor: ") Lista1.append(x) Lista2.append(y) else: print("Usuario repetido, Ingrese nuevamente.") llave=tuple(Lista1) valor=tuple(Lista2) dicc=dict(zip(llave,valor)) print(dicc) #dicc() #2.- Escribir una funcion que reciba una cadena y devuelva un diccionario con la cantidad de apariciones de cada palabra". def cadena(): cadena=str(input("Ingrese oracion: ")) a="" Lista1=[] Lista2=[] Lista3=[] for i in cadena: if i != " ": a=a+i elif i== " ": Lista1.append(a) a="" Lista1.append(a) for j in Lista1: b=Lista1.count(j) if j not in Lista3: Lista3.append(j) Lista2.append(b) dicc=dict(zip(Lista3,Lista2)) print(dicc) #cadena() #3.- Lo mismo pero para cada cantidad de caracter. def cadenaC(): cadena=str(input("Ingrese oracion: ")) a="" Lista1=[] Lista2=[] Lista3=[] for i in cadena: if i != "": a=a+i elif i== "": Lista1.append(a) a="" Lista1.append(a) for j in Lista1: b=Lista1.count(j) if j not in Lista3: Lista3.append(j) Lista2.append(b) dicc=dict(zip(Lista3,Lista2)) print(dicc) cadenaC()
49073ef49f8038871e50cd939fd8fd2e2bdf9011
payalmandulkar17/python
/factorial.py
220
4.15625
4
num =5 fact=1 if num<0: print("factorial cant find") elif num==0: print("factorial is 1") else: for i in range(1,num+1): fact=fact*i print("factorial of",num,"is",fact)
8e3ef7571adb887a363bc8759cf5574eb9d72eb9
beginner-codes/beginnerpy-pypi
/beginnerpy/challenges/daily/c40_sum_of_nth.py
2,795
4.0625
4
import unittest from typing import List def sum_every_nth(numbers: List[int], nth: int) -> int: return sum(numbers[nth-1::nth]) def sum_every_nth(inList, n): outInt = 0 print(inList, n) for i in range(0,len(inList),n): outInt += inList[i] print(outInt) return outInt class TestSumEveryNth(unittest.TestCase): def test_1(self): self.assertEqual(sum_every_nth([2, 5, 3, 9, 5, 7, 10, 7, 3, 3, 3], 9), 3) def test_2(self): self.assertEqual(sum_every_nth([10, 9, 2, 5, 9, 6, 4, 6, 7, 10, 9, 9, 9, 9, 2, 1, 2], 7), 13) def test_3(self): self.assertEqual(sum_every_nth([4, 5, 8, 7, 8, 1, 7, 9, 7, 4, 6, 2, 8, 8, 9, 9, 1, 7, 4], 6), 10) def test_4(self): self.assertEqual(sum_every_nth([8, 3, 5, 2, 6, 1, 5, 4, 3, 6, 6, 8, 5, 10, 7, 3, 7, 3, 5], 11), 6) def test_5(self): self.assertEqual(sum_every_nth([8, 9, 4, 8, 7, 5, 2, 9, 1, 8, 3, 8, 4, 9, 9, 6], 11), 3) def test_6(self): self.assertEqual(sum_every_nth([8, 2, 2, 7, 10, 6, 3, 5, 4, 4], 12), 0) def test_7(self): self.assertEqual(sum_every_nth([7, 4, 4, 10, 2, 6, 1, 9, 5, 10, 6, 4, 6, 6, 5, 9, 4, 10, 9], 8), 18) def test_8(self): self.assertEqual(sum_every_nth([5, 10, 10, 9, 10, 3, 5, 6, 6, 2, 10, 2, 9, 6, 8, 9, 10, 9, 4], 16), 9) def test_9(self): self.assertEqual(sum_every_nth([10, 4, 8, 4, 3, 9, 1, 1, 10, 7, 1, 4, 5, 5, 6, 1, 9], 6), 13) def test_10(self): self.assertEqual(sum_every_nth([2, 6, 3, 10, 6, 5, 4, 7, 9, 4, 1, 8, 9, 10, 8, 7, 2, 3, 6], 8), 14) def test_11(self): self.assertEqual(sum_every_nth([10, 9, 7, 8, 5, 7, 9, 5, 3, 3, 1], 7), 9) def test_12(self): self.assertEqual(sum_every_nth([7, 2, 9, 6, 1, 8, 8, 10, 2, 5, 5, 7, 3, 10, 1], 2), 48) def test_13(self): self.assertEqual(sum_every_nth([3, 10, 3, 8, 10, 9, 1, 3, 7, 2], 2), 32) def test_14(self): self.assertEqual(sum_every_nth([6, 5, 7, 9, 4, 2, 2, 9, 8, 10, 5, 2, 8], 7), 2) def test_15(self): self.assertEqual(sum_every_nth([9, 3, 7, 10, 3, 10, 2, 8, 8, 7, 1], 11), 1) def test_16(self): self.assertEqual(sum_every_nth([4, 6, 10, 8, 4, 7, 10, 10, 4, 4, 9, 2, 1, 9, 9, 8, 6, 6, 10], 7), 19) def test_17(self): self.assertEqual(sum_every_nth([3, 3, 2, 6, 4, 4, 10, 2, 10, 5, 5, 8, 6], 1), 68) def test_18(self): self.assertEqual(sum_every_nth([10, 1, 10, 8, 3, 2, 10, 8, 2, 3, 8, 7, 6, 4, 8], 6), 9) def test_19(self): self.assertEqual(sum_every_nth([5, 1, 4, 7, 3, 9, 4, 5, 9, 6, 1, 6, 9, 6, 7, 6, 8, 1], 14), 6) def test_20(self): self.assertEqual(sum_every_nth([2, 1, 7, 4, 2, 6, 2, 4, 6, 1, 2, 2, 10, 10], 2), 28) if __name__ == "__main__": unittest.main()
abcd938ffe2f35b683044741613881c455ece84d
andrenaq/Python
/Python_Classes/Weeks/w4/dict5.py
147
3.78125
4
#adding items to a dictionary dict ={} dict['key1']='val1' dict[44.09]='temp' dict['key3']=('1','2') dict ['key4']= ['x','y','z'] print(dict)
8a0a838ebfe646cf8dea793d3ebe8916f3513276
ashinsukumaran/pythonprograms
/works/prime number.py
156
4.125
4
print("prime number program") n = int(input("enter a number")) for i in range(1,10): if n%n==0: print(n) else: print("not prime")
8b6d025fbf43b0da3c2cad6f2b5afc48675a35e5
MFG38/PySnippets
/battleship/battleship.py
1,234
4.0625
4
# A simple game of Battleship. 'Nuff said. # Written in Notepad++, tested with Python 2.7.16 running # through the Windows command line. # Santtu "MFG38" Pesonen, 2019-12-28 from random import randint board = [] for i in range(8): board.append(['O'] * 8) def print_board(board): for row in board: print " ".join(row) def random_row(board): return randint(0,len(board) - 1) def random_col(board): return randint(0,len(board[0]) - 1) ship_row = random_row(board) ship_col = random_col(board) for turn in range(10): print "Turn", turn + 1 print_board(board) guess_row = int(raw_input("Guess row: ")) guess_col = int(raw_input("Guess column: ")) if guess_row == ship_row and guess_col == ship_col: print "AAAAAAAAA I'M DROWNING gg you found my ship." break else: if guess_row not in range(0,8) or guess_col not in range(0,8): print "ERROR: Guess out of bounds!" elif board[guess_row][guess_col] == "X": print "ERROR: Nothing already found there!" else: print "Hah, nope! Not over there!" board[guess_row][guess_col] = "X" if turn == 9: print "GAME OVER"
622c05e53726a24cbb6de34ce92fe953e56c6164
RuidongZ/LeetCode
/code/241.py
1,382
4.03125
4
# -*- Encoding:UTF-8 -*- # 241. Different Ways to Add Parentheses # Given a string of numbers and operators, # return all possible results from computing all the different possible ways to group numbers and operators. # The valid operators are +, - and *. # # # Example 1 # Input: "2-1-1". # # ((2-1)-1) = 0 # (2-(1-1)) = 2 # Output: [0, 2] # # # Example 2 # Input: "2*3-4*5" # # (2*(3-(4*5))) = -34 # ((2*3)-(4*5)) = -14 # ((2*(3-4))*5) = -10 # (2*((3-4)*5)) = -10 # (((2*3)-4)*5) = 10 # Output: [-34, -14, -10, -10, 10] class Solution(object): global hm hm = {} def diffWaysToCompute(self, input): """ :type input: str :rtype: List[int] """ if input in hm: return hm[input] ans = [] for i, s in enumerate(input): if s == '+' or s == '-' or s == '*': for l in self.diffWaysToCompute(input[:i]): l = int(l) for r in self.diffWaysToCompute(input[i+1:]): r = int(r) if s == '+': ans.append(l+r) elif s == '-': ans.append(l-r) else: ans.append(l*r) if len(ans) == 0: ans.append(int(input)) hm[input] = ans return ans
d2176d5c18d41f0b388864736aefcd4527bf7910
jawad1505/SoftwareEngineering
/Lists/fast_list_append.py
374
3.859375
4
def method1(): l = [] for n in range(10): l = l + [n] print(l) return(l) def method2(): l = [] for n in range(10): l.append(n) print(l) return(l) def method3(): l = [n for n in range(10)] def method4(): l = range(10) # Python 3: list(range(10000)) print("Lists: ",method1()) print("Lists: ",method2())
0232844eeeef27d83aab73dd77969c3ff2fce562
intisarhaque/Learning-Python
/baseconverter/baseconverter.py
222
4.21875
4
powers=[] for power in range(15,-1,-1): powers.append(2**power) print(powers) x = int(input("Please enter a number: ")) for power in powers: print(x, end = ' ') print(x // power, end=' ') x %= power
2d0308e0d3c401873b31354050f8ffe3dd5b3eba
JcbBrtn/Evolution-Algorithm
/NeuralNetwork.py
7,204
3.75
4
import random import math import numpy as np """ Neural network class: TODO List: Add biases into each neuron before sent into activation function [X] Add back prop [X] Play around with mutating learning rate [X] """ class neuralNetwork: #2 layer neural network, 10 neurons per layer #Initilized with the number of inputs to be expecting and the number of outputs to be expecting def __init__(self, inp, out): self.inp = inp self.out = out #masses are the multipliers of each neuron layer self.masses = [] self.biases = [] #weights are the multiplied and summed inputs along each layer self.primers = [] self.weights = [] #Activation of each neuron #Learning rate in this case is the highest percentage a mass can change during mutation #This will remain constant through families self.learningRate = 0.2 self.delta = [] """ Masses are to be initilized as such: M_x_y_z where, x = the neuron layer you are in y = the neuron number you are going to z = the neuron number you are coming from Masses are going to filled randomly with numbers between -1 and 1 2 to start No biases are added between layers No sigmoid functions just a bare bone neural network. """ self.fillBiases() for x in range(3): self.fillMasses(x) def fillMasses(self, layer): #Fills the masses array with random values between -1 and 1. #Place Holder/Starter for optimization if layer == 0: comeFrom = self.inp goTo = 3 elif layer == 1: comeFrom = goTo = 3 else: comeFrom = 3 goTo = self.out massGoTo = [] for y in range(goTo): massCome = [] for z in range(comeFrom): massCome.append(random.uniform(-1,1)) massGoTo.append(massCome) self.masses.append(massGoTo) def fillBiases(self): for layers in range(2): biases = [] for bias in range(3): biases.append(random.uniform(-1,1)) self.biases.append(biases) biases = [] for i in range(self.out): biases.append(random.uniform(-1,1)) self.biases.append(biases) def run(self, inpArr): #Sums product of weights and masses through the Neural Network self.weights = [] self.primers = [] self.weights.append(inpArr) for x in range(len(self.masses)): weight = [] primer = [] for my, by in zip(self.masses[x], self.biases[x]): total = by for mz, wy in zip(my, self.weights[x]): total += (mz*wy) primer.append(total) weight.append(self.sigmoid(total)) self.primers.append(primer) self.weights.append(weight) def sigmoid(self, x): return (1/(1+ np.exp(-1*x))) def sigmoidPrime(self, x): return self.sigmoid(x) * (1 - self.sigmoid(x)) def costDerivative(self, outA, desired): return (outA - desired) def getCost(self, desiredArr): cost = [] total = 0 for y, yPrime in zip(desiredArr, self.getOutput()): cost.append(0.5*(y - yPrime)**2) for c in cost: total += c return total def getOutput(self): return self.weights[-1] def toString(self): print('\nPrimers') print(self.primers) print('\nweights') print(self.weights) print('\nBiases') print(self.biases) print('\n') """ Now are the Optimization Functions. First is mutation which is mainly used int he evolutionary arena. Second is BackPropagation which is used when controlling the fighters This is so they learn from your actions. """ def mutate(self): #Create a child for the Neural Network and bump masses around child = neuralNetwork(self.inp, self.out) child.masses = self.masses child.learningRate = self.learningRate child.biases = self.biases #for each mass, bump it up or down determined by the learning rate #TODO, play around with mutating the learning Rate for mx in range(len(child.masses)): for my in range(len(child.masses[mx])): for mz in range(len(child.masses[mx][my])): mutationRate = random.uniform(-1* child.learningRate, child.learningRate) child.masses[mx][my][mz] += mutationRate for bx in range(len(child.biases)): for by in range(len(child.biases[bx])): mutationRate = random.uniform(-1* child.learningRate, child.learningRate) child.biases[bx][by] += mutationRate return child def getMassTotal(self, layer, goTo): massTotal = 0 for m in self.masses[layer - 1][goTo]: massTotal += m return massTotal def getError(self, error, x, comeFrom): errorTotal = 0 massT = np.transpose(self.masses[-x + 1]) massTotal = 0 for goTo in range(len(error[-x + 1])): massTotal = 0 #for each neuron connected to the one we're looking at: #calc massTotal connected to that neuron for z in range(len(self.masses[-x + 1][goTo])): massTotal += self.masses[-x + 1][goTo][z] #then add error proportional to the mass percentage by the error errorTotal += ((massT[comeFrom][goTo] * error[-x+1][z]) / float(massTotal)) return errorTotal def backprop(self, desiredArr): #uses the desired output array to apply gradient descent to the masses and biases error = [] for x in range(len(self.biases)): errorx = [] for y in range(len(self.biases[x])): errorx.append(0) error.append(errorx) #find error for the first layer for y in range(len(error[-1])): error[-1][y] = desiredArr[y] - self.weights[-1][y] #Find error for all the other layers for x in range(2, len(error) + 1): for y in range(len(error)): error[-x][y] = self.getError(error, x, y) #Update all masses for x in range(len(self.masses)): for y in range(len(self.masses[x])): for z in range(len(self.masses[x][y])): self.masses[x][y][z] += error[x][z] * self.learningRate / self.getMassTotal(y, z) #Update all Biases self.biases[x][y] += error[x][y] * self.learningRate return #End of Backprop() myNN = neuralNetwork(2, 4) myNN.run([0.5,0.33333]) print('Cost, Output') print(myNN.getCost([0.25, 0.5, 0.75, 1.0]), myNN.getOutput()) for i in range(10000): myNN.run([0.5, 0.33333]) myNN.backprop([0.25, 0.5, 0.75, 1.0]) print('Cost, Output') print( myNN.getCost([0.25,0.5,0.75, 1.0]), myNN.getOutput())
89e08480dbf080ad64439c5bcceadc25c23185a1
ramyasutraye/Python-13
/Beginner level/addNumbers.py
79
3.609375
4
def add(x,y): z=x+y print z n1=int(input()) n2=int(input()) add(n1,n2)
8013571a7ef5b1fc4cb2ae3045956a1fe581f352
skyvltu/pythonWorks
/ch02/p35.py
287
3.71875
4
""" 날짜 : 2021/02/18 이름 : 이승환 내용 : 교재 p35 - 변수와 메모리 주소 예 """ var1 = "Hello Python" print("var1") print( id(var1) ) var1 = 100 print(var1) print( id(var1) ) var2 = 150.25 print(var2) print( id(var2) ) var3 = True print(var3) print( id(var3) )
9e754903370bda7ad8a871197ee4d4adcf9078e3
kanhaichun/ICS4U
/hhh/Mike/assignment5.py
1,271
4.0625
4
# -*- coding: utf-8 -*- """ Name: Xu, Yingjie (Mike) Date: 2018-01-16 Program Title: assignment5 Purpose: (1) Make a short quiz program that uses a dictionary for its questions and answers. (1a) Create a dictionary with at least five key:value pairs to store the questions and answers. (1b) In a loop, ask questions based on the key values. (1c) Allow the user to input the answers. (1d) Keep track of the score and, when all of the questions have been asked, tell print the final quiz score. Variable names: dirt1, score """ dict1 = {'When did the Beijing Olympics held?':'2008', 'What is the answer of 1+1 ?': '2', 'What is the area of a square with the side length of 4':'16','Which city is the Capital of China':'beijing','Who wrote the book \'The hunger games\' ?':'Suzanne Collins'} score = 0 print('Welcome to this quiz!') print('Each question worth 1 mark in the quiz.') for i in range (0,len(dict1.keys())): print('Question number '+str(i + 1)+' :') print(list(dict1.keys())[i]) answer = input('Please write your answer here: ') if answer == list(dict1.values())[i]: print('correct!!!') score = score + 1 else: print('wrong!!!') print('Your current score is: '+str(score)) print ('Your final score is: '+str(score))
e1fba1ac4ff7e82ad325d6bfc9e87a1436b49bf7
davll/practical-algorithms
/LeetCode/236-lowest_common_ancestor_of_a_binary_tree.py
1,156
3.6875
4
# https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/description/ # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # returns (ancestor, status) # # status = 0b00 : nothing found # status = 0b01 : found p # status = 0b10 : found q # status = 0b11 : both found # def bt_lca(root, p, q): if not root: return (None, 0b00) status = 0 if root.val == p.val: status |= 0b01 if root.val == q.val: status |= 0b10 left_a, left_st = bt_lca(root.left, p, q) right_a, right_st = bt_lca(root.right, p, q) status |= left_st | right_st if left_st == 0b11: return (left_a, 0b11) elif right_st == 0b11: return (right_a, 0b11) elif status == 0b11: return (root, 0b11) else: return (None, status) class Solution: def lowestCommonAncestor(self, root, p, q): """ :type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode """ x, _ = bt_lca(root, p, q) return x
42c5a481910fe6df32fbd0fc74769ad0264ac613
siddharth23052006/Class-98
/countWords.py
274
4.3125
4
def countWordsFromFile(): filePath = input("Enter the path to your file") readFile = open(filePath, 'r') noOfWords = 0 for line in readFile: words = line.split() noOfWords = noOfWords + len(words) print("Number of words: ", noOfWords) countWordsFromFile()
812c01e50530cf061a3ae4cd5a7af60dc2e6b0fb
thaReal/MasterChef
/codeforces/ed_round_90/donut.py
480
3.8125
4
#!/usr/bin/python3 # Codeforces - Educational Round 90 # Author: frostD # Problem A - Donut Shop def read_int(): n = int(input()) return n def read_ints(): ints = [int(x) for x in input().split(" ")] return ints #--- def solve(a, b, c): if c <= a: shop1 = -1 else: shop1 = 1 shop2 = b if a*b > c else -1 return (str(shop1), str(shop2)) # Main t = read_int() for case in range(t): a, b, c = read_ints() sol = solve(a, b, c) print (' '.join(sol))
f8646ca51bd3f70bdad63bc2b5619f3b2a6d51ee
jasonzz123/GCD-another-way
/2gcd.py
569
3.921875
4
#divide and conquer gcd # /2 def gcd(a,b): #must a>b if a < b : return gcd(b,a) if a==0 or b==0:#exit condition return a+b if a ==b: #exit condition return a if (a%2==0) and (b%2==0): return 2*gcd(a//2, b//2) if a%2==0: return gcd(a//2, b) elif b%2==0: return gcd(a, b//2) else: #both odd return gcd((a-b)//2, b) print(gcd(21,36)) print(gcd(17,7)) a =int(input('pls input num1:')) b = int(input('pls input num2:')) print('re:', gcd(a,b))
4c83a924767dcacd086b269b60b956f427b9e4e6
tmdenddl/Python
/Sort/insertion_sort.py
1,041
3.859375
4
# 삽입 정렬 def insertion_sort(my_list): for i in range(len(my_list)): key = my_list[i] # i - 1부터 시작해서 왼쪽으로 하나씩 확인 # 왼쪽 끝까지(0번 인덱스) 다 봤거나 # key가 들어갈 자리를 찾으면 끝냄 j = i - 1 while j >= 0 and my_list[j] > key: my_list[j + 1] = my_list[j] j = j - 1 # key가 들어갈 자리에 삽입 # 왼쪽 끝까지 가서 j가 -1이면 0번 인덱스에 key를 삽입 my_list[j + 1] = key some_list = [11, 3, 6, 4, 12, 1, 2] insertion_sort(some_list) print(some_list) # 삽입 정렬 def insertion_sort_2(my_list): # 코드를 입력하세요. for i in range(len(my_list)): for j in range(0, i): if my_list[i] < my_list[j]: temp = my_list[i] my_list[i] = my_list[j] my_list[j] = temp return my_list some_list_2 = [11, 3, 6, 4, 12, 1, 2] insertion_sort_2(some_list_2) print(some_list_2)
1b42b02404f9f9e0558a183f330451d3278d990b
thestrawberryqueen/python
/1_beginner/chapter4/solutions/hours.py
890
4.3125
4
# Hours # Write a program that asks the user # how many hours they spend on the internet # per day, and print if they’re addicted # or not based on the hours. (5 or more hours # is addicted, less is not). # prompt user for hours spent on internet hours = int(input("How many hours/day do you spend on the internet? ")) # display whether or not the user is addicted if hours >= 5: print("You are addicted to the internet.") else: print("You aren't addicted to the internet.") # See if you can write the same program, # except that the user is addicted to the internet # if the number of hours they spend on the internet # is greater than 2 times the remainder of hours / 7 hours = int(input("How many hours/day do you spend on the internet? ")) if hours > 2 * (hours % 7): print("You are addicted to the internet.") else: print("You aren't addicted to the internet.")
804a87c014567ee0b99115f01c03e590bfb9af99
sanketwadekar3/Machine-Learning
/Ball Predictor/Ball_Predictor.py
1,331
3.671875
4
from sklearn import tree from sklearn import preprocessing from sklearn.model_selection import train_test_split import pandas as pd def Ball_Predictor(weight,surface): dataset = pd.read_csv('Balls.csv') print(dataset) label_encoder = preprocessing.LabelEncoder() dataset['Pattern'] = label_encoder.fit_transform(dataset['Pattern']) dataset['Label'] = label_encoder.fit_transform(dataset['Label']) print(dataset['Pattern'].unique()) print(dataset['Label'].unique()) X = dataset[['Weight','Pattern']] Y = dataset[['Label']] X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.2, random_state = 0) clf = tree.DecisionTreeClassifier() clf = clf.fit(X,Y) result = clf.predict([[weight,surface]]) if result == 1: print("Your object looks like Tennis ball") elif result == 0: print("Your object looks like Cricket ball") def main(): print("------ Ball Predictor Case Study ------") weight = input('Enter weight of object') surface = input("What is the surface type of your object : Rough or Smooth ?") if surface.lower() == "rough": surface = 1 elif surface.lower() == "smooth": surface = 0 else: print("Error : Wrong input") exit() Ball_Predictor(weight,surface) if __name__ == "__main__": main()
ba3a7142338e1af83dc6018a55176a5adcbf1428
calebbelmont/class-examples
/04 - db/db.py
5,442
3.546875
4
import sqlite3 from flask import g from application import app import os ##### Database Utilities ######################################## DATABASE = 'test-db.sqlite' # Connect to the database. def connect_db(db_path): if db_path is None: db_path = os.path.join(os.getcwd(), DATABASE) if not os.path.isfile(db_path): raise RuntimeError("Can't find database file '{}'".format(db_path)) connection = sqlite3.connect(db_path) connection.row_factory = sqlite3.Row return connection # Open a database connection and hang on to it in the global object. def open_db_connection(db_path=None): """Open a connection to the database. Open a connection to the SQLite database at `db_path`. Store the resulting connection in the `g.db` global object. """ g.db = connect_db(db_path) # If the database is open, close it. def close_db_connection(): db = getattr(g, 'db', None) if db is not None: db.close() # Convert the 'row' retrieved with 'cursor' to a dictionary # whose keys are column names and whose values are column values. def row_to_dictionary(cursor, row): dictionary = {} for idx, col in enumerate(cursor.description): dictionary[col[0]] = row[idx] return dictionary ##### Users and Comments ######################################## # Create a new user. def create_user(email, first_name, last_name, password): query = ''' INSERT INTO user (email, first_name, last_name, password) VALUES (:email, :first, :last, :pass) ''' cursor = g.db.execute(query, {'email': email, 'first': first_name, 'last': last_name, 'pass': password}) g.db.commit(); return cursor.rowcount # List all users. def all_users(): cursor = g.db.execute('select * from user order by email') return cursor.fetchall() # List all comments in the database. def all_comments(): query = ''' SELECT first_name, last_name, email, body FROM user INNER JOIN comment ON user.email = comment.user ORDER BY last_name ASC, first_name ASC''' return g.db.execute(query).fetchall() # Look up a single user def find_user(email): return g.db.execute('SELECT * FROM user WHERE email = ?', (email,)).fetchone() # Retrieve comments for a user with the given e-mail address. def comments_by_user(email): cursor = g.db.execute('SELECT * FROM comment WHERE user = ?', (email,)) return cursor.fetchall() # Update a user's profile (first and last name) def update_user(email, first_name, last_name, password): query =''' UPDATE user SET first_name = :first, last_name = :last, password = :pass WHERE email = :email''' cursor = g.db.execute(query, {'first': first_name, 'last': last_name, 'email': email, 'pass': password}) g.db.commit() return cursor.rowcount ##### Accounts ######################################## # Return all data in the account table. def all_accounts(): return g.db.execute('SELECT * FROM account').fetchall() # Return the balance for the account with id 'account_id'. def find_account(account_id): return g.db.execute('SELECT * FROM account WHERE id=:id', {'id': account_id}).fetchone() # Get the balance for an account. def read_balance(account_id): cursor = g.db.execute('SELECT balance FROM account WHERE id=:id', {'id': account_id}) row = cursor.fetchone() return row['balance'] # Set the balance in account 'account_id' to 'new_balance'. Note that this # function does not commit to the database so that we can illustrate commit # and rollback behavior in the transfer_funds function. def update_balance(account_id, new_balance): cursor = g.db.execute('UPDATE account SET balance = :balance WHERE id=:id', {'id': account_id, 'balance': new_balance}) if cursor.rowcount != 1: raise RuntimeError("Failed to update account {}".format(account_id)) # Transfer funds def transfer_funds(from_account_id, to_account_id, transfer_amount, cause_rollback): # Get the balance of the source account. from_balance = read_balance(from_account_id) # Ensure sufficient funds; we've already checked this in the controller, # but it doesn't hurt to make sure a transfer is valid. if from_balance < transfer_amount: raise RuntimeError('Insufficient funds') # Get the balance of the destination account. to_balance = read_balance(to_account_id) # Transfer funds! update_balance(from_account_id, from_balance - transfer_amount) update_balance(to_account_id, to_balance + transfer_amount) # Either roll back or commit the current transaction. if cause_rollback: # Roll back. To demonstrate that database updates are reversed # during a rollback, create a message containing the current # account balances. pending_from_balance = read_balance(from_account_id) pending_to_balance = read_balance(to_account_id) message = "Rolled back transaction: from was {:.2f}, to was {:.2f}".format(pending_from_balance, pending_to_balance) # Roll back the transaction and return the message g.db.rollback() return message else: # Commit the transaction. The user can see that the database updates are # persistent by viewing the current account balances. g.db.commit() return "Committed transaction"
53c4cc631f91291f2e57daae25ce88f07fa0a344
Rajeshinu/bitrm11
/21.DictSort.py
388
4.4375
4
"""Print a list of the values of the given dictionary: d={3:'c', 1: 'a', 5:'e', 4:'d', 2:'b'} in a sorted format""" d={3:'c', 1: 'a', 5:'e', 4:'d', 2:'b'} print("Dictionary items are: ",d) list1=d.keys() print(list1) list2=list(list1) list2.sort() print("sorted list is ",list2) print("Dictionary Keys and values in sorted are: ",end="") for i in list2: print(i,":",d[i],end=",")
19c5051155c99c2a5ad16e3f6e538d320acbe2d5
Long-yuyao/python-trailing
/data_structure/stack/decode-string.py
1,924
3.6875
4
""" input:s = "3[a]2[bc]" output:"aaabcbc" """ # class Solution: # def decodestring(self, s: str) -> str: # """ # # :type s: object # """ # list_s = [[1, ""]] # for letter in s: # if letter.isdigit(): # if len(list_s[-1]) == 1: # list_s[-1][0] = int(letter) + list_s[-1][0] * 10 # else: # list_s.append([int(letter)]) # elif letter == '[': # list_s[-1].append("") # elif letter == ']': # a = (list_s[-1][0]) * list_s[-1][1] # list_s.pop() # k = list_s[-1][1] + a # list_s[-1].pop() # list_s[-1].append(k) # else: # k = list_s[-1][1] + letter # list_s[-1].pop() # list_s[-1].append(k) # return list_s[0][1] class Solution: def decodestring(self, s: str) -> str: stack = [] for a in s: if a == ']': word = '' while stack[-1] != '[': word = stack[-1] + word stack.pop() stack.pop() word = int(stack[-1]) * word stack.pop() stack.append(word) elif stack and a.isnumeric() and stack[-1].isnumeric(): stack[-1] = stack[-1] + a else: stack.append(a) word = '' for s in stack: word = word + s return word if __name__ == '__main__': assert Solution().decodestring("3[a]2[bc]") == "aaabcbc" assert Solution().decodestring("abc3[cd]xyz") == "abccdcdcdxyz" assert Solution().decodestring("3[a2[c]]") == "accaccacc" assert Solution().decodestring("adbcdf") == "adbcdf" assert Solution().decodestring("100[leetcode]") == 100 * "leetcode"
c6d4d4498718f030868e724d76979b3fbda86875
jihye1996/Algorithm
/programmers/소수만들기.py
397
3.625
4
from itertools import combinations def solution(nums): answer = 0 List = list(combinations(nums,3)) for i in List: flag = check(sum(i)) if flag == True: answer+=1 return answer def check(num): if num % 2 == 0: return False for i in range(3, num, 2): if num % i == 0: return False return True
94246949175394facfdb5a6de6a29a5bc31048a9
ayesh99747/Python-Programming-Udemy-Course-Theory-and-Hands-on
/src/Tutorial4/Q3.py
645
4.28125
4
# Exercise 3 # • Write a program that will allow a user to enter a number of scores until -9 is entered. # • When -9 is entered, print the average of the scores entered. Use a while loop. # • Ensure that at least one score has been entered before calculating the average # (division by zero would produce an error). total = 0 count = 0 entered_num = 0 while entered_num != -9: entered_num = int(input("Please enter a number : ")) if entered_num != -9: total = total + entered_num count = count + 1 if count != 0: average = total / count print(average) else: print("No values were entered!")
a0121e7ee46e7964b083b8f05d0d6007c272248a
jhyang12345/algorithm-problems
/problems/reverse_letters_in_string.py
212
4.09375
4
def reverse_letters(sentence): words = sentence.split() words = ["".join(list(word)[::-1]) for word in words] return " ".join(words) print(reverse_letters("The cat in the hat")) # ehT tac ni eht tah
85f6aa866c40a3a468c86d091bc42dd166a6d2e6
ricardoZhao/AtOffer
/16.py
561
3.90625
4
#!/usr/bin/env python # coding=utf-8 """ 实现函数def power(base, exp), 求base的exp次方, 不得使用库函数,同时不需要考虑大数问题 """ class Solution(object): def power(self, base, exp): if exp == 0: return 1 if exp == 1: return base result = self.power(base, exp>>1) result *= result if exp & 0x1 == 1: result *= base return result if __name__ == '__main__': solution = Solution() result = solution.power(2, 3) print(result)
21d882ba1ef6424ce6be5034c694929465248f8d
parth-github/rock-paper-scissors-end
/main_v2.py
1,097
4.03125
4
import random, os, time rps_dict = { 1: "rock", 2: "paper", 3: "scissors", } score = { "your_score": 0, "computer_score": 0, } for i in range(1, 6): print(f"Round:{i}") computer_choice = random.randint(1,3) your_choice = int(input("Enter your choice:\n 1-> rock \n 2 -> paper \n 3 -> scissors \n")) print("*******************") print(f"Computer has choosen:{rps_dict[computer_choice]}") print(f"You have choosen:{rps_dict[your_choice]}") if your_choice == computer_choice: print("Draw") score["your_score"] += 1 score["computer_score"] += 1 elif your_choice == 1 and computer_choice == 3: print("You won") score["your_score"] += 2 elif your_choice == 3 and computer_choice == 1: print("You lost") score["computer_score"] += 2 elif your_choice > computer_choice: print("You won") score["your_score"] += 2 else: print("You lost") score["computer_score"] += 2 time.sleep(5) os.system("clear") print(f''' Final score board: ****************** Your score\t|Computer score --------------------------- {score["your_score"]}\t|{score["computer_score"]} ''')
1299c431c13f53a8cb8a1af7644b8200b7533f26
hsh814/Baekjoon-algorithm
/competition/b.py
536
3.546875
4
def count(s: str, c: str) -> int: n = 0 for temp in s: if temp == c: n += 1 return n def thanos(s: str) -> str: zero = count(s, '0') one = count(s, '1') result = list() zn = 0 on = 0 for i in range(len(s)): if s[i] == '0': if zn < zero // 2: #print("zero", i) result.append(s[i]) zn += 1 else: if on >= one // 2: #print("one", i) result.append(s[i]) on += 1 return "".join(result) def main(): s: str = input() print(thanos(s)) main()
a14d32fc9c32210fc4fe159daa795a6173d55ca0
manasir66/leetcode_30day
/Day14/test.py
788
3.671875
4
#shift= [[1,1],[1,1],[0,2],[1,3]] #for direction, amount in shift: #print("Direction : ", direction, end= " | ") #print("Amount : ", amount) #s = "thisisalongstring" #s_list = [] #for c in s: # s_list.append(c) #print("".join(s_list)) s = "abc" shift = [[0,1],[1,2]] s_list = [] for char in s: s_list.append(char) print(s_list) temp = 0 for direction, amount in shift: print("1st pass ", direction, " ", amount) if direction == 1: temp = s_list.pop(-1) print(s_list) if amount == 1: s_list.insert(0, temp) else: s_list.insert(amount-1,temp) else: temp = s_list.pop(0) print(s_list) if amount == 1: s_list.append(temp) else: s_list.insert(-amount+1,temp) print(s_list) ans = "".join(s_list) print(ans)
ab458ade82fe6a7cd13f839a78f4040e8ee38875
iascending/pay_slip
/src/PaySlip.py
4,051
3.8125
4
import calendar from math import inf from datetime import datetime class PaySlip: """ This is a class for employee's payslip operations. Class attributes: tax_rate: an array of tuples represent current tax table. Instance attributes: first_name: a string for employee's first name. last_name: a string for employee's last name. annual_salary: an interger for employee's annual salary. super_rate: a deciaml for employee's super rate [0 -0.5] inclusive. pay_start_date: a string represent of employee's payment start date. pay_end_date: calculated employee's monthly payment end date. work_days_frac: calculated percentage of days employee worked in the month. """ tax_rate_2017 = [ (0, 18200, 0, 0), (18201, 37000, 0, 0.19), (37001, 87000, 3572, 0.325), (87001, 180000, 19822, 0.37), (180001,inf, 54232, 0.45) ] tax_rate_2019 = [ (0, 18200, 0, 0), (18201, 37000, 0, 0.19), (37001, 90000, 3572, 0.325), (87001, 180000, 20797, 0.37), (180001,inf, 54232, 0.45) ] tax_rate = {2017: tax_rate_2017, 2019: tax_rate_2019} def __init__(self, first_name, last_name, annual_salary, super_rate, pay_start_date): """ The constructor of PaySlip Class. """ if not isinstance(first_name, str): raise TypeError("first_name must be a string") self.first_name = first_name if not isinstance(last_name, str): raise TypeError("last_name must be a string") self.last_name = last_name if not isinstance(annual_salary, int): raise TypeError("annual_salary must be an integer") if annual_salary <= 0: raise ValueError("annual_salary must be positive") self.annual_salary = annual_salary if not isinstance(super_rate, float): raise TypeError("super_rate must be a decimal") if super_rate < 0 or super_rate > 0.5: raise ValueError("super_rate: {}. It must be between (0, 0.5) inclusive".format(super_rate)) self.super_rate = super_rate if not isinstance(pay_start_date, str): raise TypeError("pay_start_date must be a date represented by the string of ""%Y-%m-%d") try: self.pay_start_date = datetime.strptime(pay_start_date, "%Y-%m-%d").date() year = self.pay_start_date.year self.tax_rate_year = year month = self.pay_start_date.month _, num_days = calendar.monthrange(year, month) self.pay_end_date = datetime(year, month, num_days).date() work_days = (self.pay_end_date - self.pay_start_date).days + 1 self.work_days_frac = work_days/float(num_days) except ValueError: raise ValueError("Please use the date format %Y-%m-%d") def __str__(self): return "<PaySlip> object: {} {}".format(self.first_name, self.last_name) def get_pay_period(self): """Return a string of payment period based on pay_start_date.""" start = self.pay_start_date.strftime("%d %b") end = self.pay_end_date.strftime("%d %b") return "{} - {}".format(start, end) def get_gross_income(self): """Return gross income of the month.""" return round(self.annual_salary/12.0*self.work_days_frac) def get_income_tax(self): """Return income tax of the month.""" tax_rgn = [r for r in self.tax_rate[self.tax_rate_year] if r[0] <= self.annual_salary <= r[1]][0] return round((tax_rgn[2] + tax_rgn[3] * (self.annual_salary - tax_rgn[0]))/12.0*self.work_days_frac) def get_net_income(self): """Return net income of the month.""" return self.get_gross_income() - self.get_income_tax() def get_monthly_super(self): """Return super paid for the month.""" return round(self.get_gross_income()*self.super_rate)
2d69cecd169ee25d233cb3582e47f47312212d2a
litded/lessons
/Py2-Lec1-2/Lec14/main1.py
637
4.25
4
class B: b = 10 def print_me(self): print("b from B:", self.b) class C: c = 20 def print_me(self): print("c from C:", self.c) class D: c = 40 class A(D, C, B): a = 30 def print_me(self): super().print_me() # Обращение к первому родителю, который имеет даннное поле в распоряжении B.print_me(self) # Явное обращение к другому классу print("a from A:", self.a) obj_a = A() print("obj_a.a:", obj_a.a) print("obj_a.b:", obj_a.b) print("obj_a.c:", obj_a.c) obj_a.print_me()
d4d8cc775b2b51f4d90335dcd65bc287a36ffbcf
stungkit/Leetcode-Data-Structures-Algorithms
/14 Sliding Window/480. Sliding Window Median.py
956
3.6875
4
# Method 1: brute force: sorting # class Solution(object): # def medianSlidingWindow(self, nums, k): # # (0) edge case # if not nums: # return # # (1) initialize two pointers and result # res = [] # l = 0 # # (2) traverse the nums and get each sorted window # while l+k <= len(nums): # sort = sorted(nums[l:(l+k)]) # if k % 2 == 1: # (2.1) k is odd # median = sort[k//2] # else: # (2.2) k is even # median = (sort[(k-1)//2] + sort[k//2]) / 2 # res.append(median) # l += 1 # # (3) return result # return res # Time: O((n-k+1)·k·logk): O(n-k) for traverse the nums and O(klogk) for sorting # Space: O(n−k+1) extra linear space for the window container.
7233aef761a7806024b8411ac29a26d1bb285b9e
young-geng/leet_code
/problems/102_binary-tree-level-order-traversal/main.py
832
3.859375
4
# https://leetcode.com/problems/binary-tree-level-order-traversal/ # 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 levelOrder(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ if not root: return [] q = [] out = [] q.append(root) while len(q) > 0: num_level_elements = len(q) lst = [] for i in xrange(num_level_elements): node = q.pop(0) if node.left: q.append(node.left) if node.right: q.append(node.right) lst.append(node.val) out.append(lst) return out
c9ee8c40c4d83a5011e9ebf2aefe5c3a30029f53
hanxuema/LeetCodePython
/Problems/Eazy/0680.valid-palindrome-ii.py
892
3.59375
4
# # @lc app=leetcode id=680 lang=python # # [680] Valid Palindrome II # # @lc code=start import unittest class Solution(object): def validPalindrome(self, s): left, right = 0, len(s) -1 while left <= right: if s[left] == s[right]: left += 1 right -= 1 else: return self.helper(self, s, left +1 ,right) or self.helper(self, s, left, right-1) return True def helper(self, s, left, right): while left <= right: if s[left] == s[right]: left += 1 right -= 1 else: return False return True # @lc code=end class testClass(unittest.TestCase): def test1and2(self): s = Solution() self.assertEqual(s.validPalindrome("aba"), True) if __name__ == "__main__": unittest.main()
a62802afa8842cb4098fb00a49cb336f47b97c0a
zalogarciam/CrackingTheCodeInterview
/Chapter 1/OneAway.py
704
3.546875
4
def one_away(a, b): letters = {} for i in a: if i not in letters: letters[i] = 1 else: letters[i] += 1 for i in b: if i not in letters: letters[i] = -1 else: letters[i] -= 1 count = 0 for letter in letters: if letters[letter] > 0: count += 1 if letters[letter] < 0: count += 1 if count > 2: return False return True print(one_away("pale", "ple")) print(one_away("pales", "pale")) print(one_away("pale", "bale")) print(one_away("pale", "bale")) print(one_away("pale", "bake")) print(one_away("pale", "bakes"))
b0b3d1f37ef3c63b235fad3e86202ddfaf87dc59
GuzelPro/practice
/strings/task_06.py
448
3.5625
4
''' Запросить имя пользователя. После того, как пользователь ввел имя, поприветствовать его с указанием имени. Если имя введено с маленькой буквы - сделать большой. Пример: ввод - дима вывод - Привет, Дима! ''' def name(name): return ('Привет, ' + name.capitalize() + ('!'))
7c587e821c3ee0460e9bfdfa1fce08ccbec76016
dquinnfrank/Sensor_Filtering_Fusion
/Project2_Consensus/consensus_filter_field.py
27,333
3.5
4
# Project 2: Consensus Filter # David Frank # For getting commandline arguments #import argparse import sys # For numerical operations import numpy as np # For statistical analysis import scipy # For getting distances from scipy.spatial import distance # For plotting results import matplotlib.pyplot as plt # Working 2D space right now R_space = 2 # Target reading is 1D right now T_space = 1 # A single node in the sensor network # R_space is the number of dimensions being worked in class Node: # Implementations of fusing sensor readings # Max Degree # Each neighbor gets weight 1 / total_nodes def max_degree(self): # Go through each neighbor reading and accumulate the reading acc_reading = np.zeros(T_space) for neighbor_name in self.neighbor_readings: # Get the value of the neighbor reading neighbor_value = self.neighbor_readings[neighbor_name] # Set the weight for the reading weight = 1.0 / self.network.total_nodes() # Add the reading based on the weight acc_reading += weight * neighbor_value # Set the weight of this node so that the weights all sum to 1 self_weight = 1 - (self.get_degree() / float(self.network.total_nodes())) # Add the weight of this node acc_reading += self_weight * self.get_sensor_reading() return acc_reading # Metropolis def metropolis(self): # Go through each neighbor reading and accumulate the reading acc_reading = np.zeros(T_space) acc_weight = np.zeros(T_space) for neighbor_name in self.neighbor_readings: # Get the value of the neighbor reading neighbor_value = self.neighbor_readings[neighbor_name] # Set the weight of this neighbor weight = 1.0 / (1.0 + max(self.get_degree(), self.network.get_node_degree(neighbor_name))) # Track the weights acc_weight += weight # Add the reading based on the weight acc_reading += weight * neighbor_value # Set the weight of this node so that all weights sum to 1 self_weight = 1.0 - acc_weight # Add the reading of this node acc_reading += self_weight * self.get_sensor_reading() return acc_reading # Weight design 1 from Lecture 10 # Choosing the midpoint of possible values # All nodes have the same range sweet spot, so the simplified version can be used def design1(self): # Set the design factor as a fraction of the highest possible value # TODO: make this changable by using kwargs design_factor = .5 # Go through each cell for x_index in range(25): for y_index in range(25): cell_index = (x_index, y_index) """ # Make sure this cell is sensed if not np.isnan(self.this_field_prediction[cell_index]): # Get all neighbors that also sense the cell neighbor_input = [] for neighbor_name in self.neighbor_readings: for item_name in self.neighbor_readings[neighbor_name]: #neighbor_input[item_name] = [] if item_name in self.readings.keys(): #if self.name == "0": #print self.neighbor_readings neighbor_input.append(self.neighbor_readings[neighbor_name][item_name]) if len(neighbor_input): # The weight to apply to all neighbor readings weight = (design_factor * 2 * self.reading_noise) / ((self.range_s ** 2) * len(neighbor_input)) acc_weight = weight * len(neighbor_input) acc_reading = 0 for reading in neighbor_input: acc_reading += weight * reading else: acc_weight = 0 acc_reading = 0 # self weight self_weight = 1.0 - acc_weight # Set the cell value self.unstable_field_prediction[cell_index] = self_weight * self.this_field_prediction[cell_index] + acc_reading """ self.unstable_field_prediction[cell_index] = self.this_field_prediction[cell_index] """ # Go through each neighbor reading and accumulate the reading acc_reading = np.zeros(T_space) acc_weight = np.zeros(T_space) for neighbor_name in self.neighbor_readings: # Get the value of the neighbor reading neighbor_value = self.neighbor_readings[neighbor_name] # Set the weight of this neighbor weight = (design_factor * 2 * self.reading_noise) / ((self.range_s ** 2) * self.get_degree()) # Track the weights acc_weight += weight # Add the reading based on the weight acc_reading += weight * neighbor_value # Set the weight of this node so that all weights sum to 1 self_weight = 1.0 - acc_weight # Add the reading of this node acc_reading += self_weight * self.get_sensor_reading() """ #return acc_reading # Weight design 2 from Lecture 10 # Choosing midpoint of possible values def design2(self): # Set the design factor as a fraction of the highest possible value # TODO: make this changable by using kwargs design_factor = .5 # Get the variance of the node variance = (np.linalg.norm(self.get_position() - self.network.get_network_average_position()) ** 2 + self.reading_noise) / (self.range_s ** 2) # Set the self weight of the node self_weight = ((design_factor * self.reading_noise) / self.range_s ** 2) / variance # Go through each neighbor reading and accumulate the reading acc_reading = self_weight * self.get_sensor_reading() for neighbor_name in self.neighbor_readings: # Get the value of the neighbor reading neighbor_value = self.neighbor_readings[neighbor_name] # Set the weight of this neighbor weight = (1 - self_weight) / (self.get_degree()) # Add the reading based on the weight acc_reading += weight * neighbor_value return acc_reading # The methods for fusing neighbor readings consensus_methods = { "Weight Design 1" : design1, "Weight Design 2" : design2, "Max Degree" : max_degree, "Metropolis" : metropolis } # Class members # # neighbors : list # Holds the names of all neighboring nodes # # stable_reading : np.array : shape(T_space) # The reading from the last update, needed to avoid race conditions # # unstable_reading : np.array : shape(T_space) # The reading after running the consensus for this node, while other nodes are still updating # Constructor # # environment : Environment() # Object that the node will use to find information about the environment # # network : Network() # This node is a member of the network # Used to find information about the network # # name : string # A unique name for this node # # reading_noise : float # the noise of the reading as defined by cv in the project description # # range_s : float # optimal sensing range # # consensus_method : string # The name of the method to use to fuse readings from neighbors def __init__(self, environment, network, name, reading_noise=.01, range_s=1.6, consensus_method = "Max Degree"): # Save the environment and network self.environment = environment self.network = network # Save the name of this node self.name = name # Save the reading parameters self.reading_noise = reading_noise self.range_s = range_s # This holds the neighbors of this node self.neighbors = [] # Holds the readings of every neighbor self.neighbor_readings = {} # Each node has an internal field map, unknown cells are set to NaN self.stable_field_prediction = np.full((25,25), np.nan) self.unstable_field_prediction = np.full((25,25), np.nan) # The last reading that is valid, to avoid race conditions among node reports # Use a noisy intial estimate of the target without any fusion initial_readings = self.environment.get_cell_readings(self.name) # Add noise to the readings and update the field for cell_name in initial_readings: index = np.array(cell_name.split()).astype(np.uint8) self.unstable_field_prediction[index[0], index[1]] = initial_readings[cell_name] #if self.name == "0": # print self.unstable_field_prediction # The value storing the consensus while the other nodes are updating #self.unstable_reading = None # Set which consensus method to use self.fuse_readings = self.consensus_methods[consensus_method] # Sets the unstable reading for this node, and returns it # Output is based on the consensus method choosen for the node def reading(self): # Update the neighbor readings self.acquire_neighbor_readings() # Get the reading from this node self.get_sensor_reading() # Use the set consensus method to get the reading self.unstable_reading = self.fuse_readings(self) # Return the reading return self.unstable_reading # Once the network is done updating, the unstable reading becomes the new stable reading def stabilize(self): self.stable_field_prediction = self.unstable_field_prediction # Gets the postion # # return : numpy array : shape (R_space,) def get_position(self): return self.environment.get_node_position(self.name) # Gets the sensor reading of this node def get_sensor_reading(self): self.this_field_prediction = np.full((25,25), np.nan) # Get the readings of every cell in range self.readings = self.environment.get_cell_readings(self.name) # Get the deviation for the noise term sigma = np.sqrt((np.linalg.norm(self.get_position() - self.network.get_network_average_position()) ** 2 + self.reading_noise) / (self.range_s ** 2)) # Get the noise #noise = np.random.normal(scale=sigma, size=(T_space,)) # Add every reading to the unstable matrix for cell_name in self.readings: index = np.array(cell_name.split()).astype(np.uint8) noise = np.random.normal(scale=sigma, size=(T_space,)) self.this_field_prediction[index[0], index[1]] = self.readings[cell_name] + noise self.readings[cell_name] += noise cp = np.nan_to_num(self.this_field_prediction) #fig, ax = plt.subplots() #heatmap = ax.pcolor(cp, cmap=plt.cm.Blues) #plt.show() # Get the measurement from the environment and add the noise #self.unstable_reading[self.unstable_reading] + noise #return measurement # Acquires the neighbors of this node def acquire_neighbors(self): self.neighbors = self.environment.get_node_neighbors(self.name) # Gets the degree of this node # Does not update before checking def get_degree(self): return len(self.neighbors) # Gets the readings from every neighbor def acquire_neighbor_readings(self): # Clear current readings self.neighbor_readings = {} # Update the neighbors self.acquire_neighbors() # Go through each neighbor and get the reading for node in self.neighbors: #self.neighbor_readings[node] = self.network.get_node_reading(node) self.neighbor_readings[node] = self.environment.get_cell_readings(node) # The environment that the nodes are in # Nodes interact with this class to find their positions and sensor readings class Environment: # Class members # # nodes : dictionary : (node_name : position) # Holds information about nodes # position : numpy array : shape (R_space,) # # target_function : function(numeric time_step) # Gives the true position of the target as a function of time # # time_step : numeric # The current time to evalutate # Constructor # # target_position : function(numeric time_step) # Needs to give the position of the target being tracked as a function of time # # target_reading : function(numeric time_step) # Needs to give the reading of the target being tracked as a function of time # # communication_radius : float # Determines how far a node can communicate # Defaults to None, means that the node can communicate with every other node in network # # max_neighbors : int # The maximum number of neighbors to accept, nodes closer have priority # Defaults to None, means that every node in the communication_radius will be a neighbor def __init__(self, field_name = "field.txt", communication_radius = None, sensing_max = 8.0, max_neighbors = None): # Create the node dictionary self.nodes = {} # Load the file with open(field_name, 'r') as field_file: # Get the entire contents of the file file_contents = field_file.read() # Get a numpy array # TODO: make reshaping more general self.field = np.array(file_contents.strip("\n ").split()).astype(np.float32).reshape((25,25)) # Set the node communication parameters self.communication_radius = communication_radius self.max_neighbors = max_neighbors self.sensing_max = sensing_max # Set the initial time to 0 self.time_step = 0 # Moves the environment ahead by the set amount def advance(self, increment = 1): self.time_step += increment # Adds a node to the nework at the specified postion # # node_name : string # The unique name of the node # # node_position : numpy array : shape (R_space,) # The location of the node in the environment def add_node(self, node_name, node_position): self.nodes[node_name] = node_position # Returns the position of a node # # node_name : string # The name of the node to get the postion of # # return : numpy array : shape (R_space) # The position of the specified node def get_node_position(self, node_name): return self.nodes[node_name] # Returns the true position of the target # # return : numpy array : shape (R_space,) #def get_target_position(self): # return self.get_target_position_at(self.time_step) # Returns the true reading of the target # # return : numpy array : shape (T_space,) #def get_target_reading(self): # return self.get_target_reading_at(self.time_step) # Evaluates the position function at the specified time step # # return : numpy array : shape (R_space,) #def get_target_position_at(self, time_step): # return self.target_position(time_step) # Evaluates the reading function at the specified time step # # return : numpy array : shape (T_space,) #def get_target_reading_at(self, time_step): # return self.target_reading(time_step) # Returns the reading of all cells within the range of the node def get_cell_readings(self, node_name): node_position = self.nodes[node_name] # Get a list of cells in range # TODO: make this more efficient cells = {} for x_index in range(25): for y_index in range(25): if distance.euclidean(node_position, np.array([x_index, y_index])) <= self.sensing_max: cells[str(x_index) + " " + str(y_index)] = self.field[x_index, y_index] return cells # Returns the neighbors of the node # # Returns : list[strings] # The nodes that are the neighbors of the specified node def get_node_neighbors(self, node_name): # Get the location of the interest node node_position = self.nodes[node_name] # Get the distances to every other node in the network names = [] distances = [] for name in self.nodes: # Get the position position = self.nodes[name] # Ignore if the node is the interest node if node_name != name: # Get the distance between the nodes dist = distance.euclidean(node_position, position) # If the communication_radius is None, add the node if self.communication_radius is None: # Add the node to the name list names.append(name) # Add the distance distances.append(dist) # If communication_radius is sent and distance is within range, add the node to the lists elif dist <= self.communication_radius: # Add the node to the name list names.append(name) # Add the distance distances.append(dist) # Sort the name list by the distances closest = [n for (d,n) in sorted(zip(distances, names))] # If max_neighbors is sent, remove all items after the max if self.max_neighbors is not None: closest = closest[:self.max_neighbors] return closest # A network of sensor nodes class Network: # Class members # nodes : dictionary : (node_name, node_object) # The node objects # # edges : list : "first_name-second_name" sorted lexigraphically # Represents an undirected graph of neighbors # # max_node : string # The name of the node with the most neighbors # # min_node : string # The name of the node with the fewest neighbors # Constructor def __init__(self): # Create the node dictionary self.nodes = {} # Holds the edges in the network self.edges = [] # Interest nodes self.max_node = "0" self.min_node = "0" # Runs the network to get the reading of the nodes # TODO: Return mean and variance of the network def update_all_readings(self): # Update the readings of all nodes for node_name in self.nodes: # Updates the value in unstable_reading self.nodes[node_name].reading() # Once all nodes have updated, they can be stabilized for node_name in self.nodes: self.nodes[node_name].stabilize() # Uses the readings from all nodes to report the mean and standard deviation of all nodes # # return : average, std def get_network_reading(self): # Update the readings for all nodes self.update_all_readings() # Get the current readings from all nodes node_readings = [] for node_name in self.nodes: node_readings.append(self.nodes[node_name].stable_field_prediction) #node_readings = np.array(node_readings) network_map = np.full((25,25), 0) network_confidence = np.zeros((25,25)) # Go through each cell and get values from node predictions for x_index in range(25): for y_index in range(25): cell_vals = [] index = (x_index, y_index) for plane in node_readings: # Get the value val = plane[index] if not np.isnan(val): cell_vals.append(val) #if x_index == 13 and y_index == 13: # print cell_vals if not np.isnan(scipy.average(np.array(cell_vals))): network_map[index] = scipy.average(np.array(cell_vals)) network_confidence[index] = scipy.std(np.array(cell_vals)) else: network_map[index] = 0 network_confidence[index] = 0 # Get the average #network_avg = scipy.average(node_readings) # Get the standard deviation #network_std = scipy.std(node_readings) return network_map, network_confidence # Adds a node to the nework # # node_name : string # The unique name of the node def add_node(self, node_name, node_object): # Add the node self.nodes[node_name] = node_object # Generator that returns the names of all nodes in the network # # yield : string def node_names(self): for node_name in self.nodes.keys(): yield node_name # Gets average position of all nodes in the network # # return : numpy array : shape (R_space,) def get_network_average_position(self): # The total number of nodes in the network num_nodes = self.total_nodes() # Get the location of all nodes all_nodes = np.empty((num_nodes, R_space)) for index, item in enumerate(self.nodes.values()): all_nodes[index] = item.get_position() # Get the sum of all of the positions along space dim and divide by the number of nodes average_position = np.sum(all_nodes, axis=0) / num_nodes return average_position # Gets the stable reading of a node def get_node_reading(self, node_name): return self.nodes[node_name].stable_field_prediction # Gets the degree of a node def get_node_degree(self, node_name): return self.nodes[node_name].get_degree() # Updates the neighbors of every node def update_neighbors(self): # The nodes are all stored in the values for node in self.nodes.values(): # Update node.acquire_neighbors() # Makes an undirected graph from the nodes and their neighbors # # Returns a list of all edges def make_graph(self): # Update the neighbors in the graph self.update_neighbors() # Go through each node and get their neighbors self.edges = [] for node_name in self.nodes: # Get the neighbors node_neighbors = self.nodes[node_name].neighbors # Go through neighbors for neighbor_name in node_neighbors: # Make the edge key edge_key = "-".join(sorted([node_name, neighbor_name])) # Add it to the edge list if it is not already present if edge_key not in self.edges: self.edges.append(edge_key) return self.edges # Checks to make sure that the network is connected # # update : bool # If true, neighbors will be updated before checking # # Return Bool def check_connected(self, update=True): # Update if needed if update: self.update_neighbors() # Go through each node checking that each degree is greater than 0 for node in self.nodes: # Only one node needs to be disconnnected to fail if len(self.nodes[node].neighbors) < 1: return False return True # Gives the total number of nodes in the network def total_nodes(self): return len(self.nodes) # Gets the nodes with the lowest and highest number of neighbors # # return : string, string # names of the lowest, highest def get_interest_nodes(self): # Go through each node in the network to find the min and max degrees max_value = 0 min_value = len(self.nodes) for name in self.nodes: # Check for new max if self.nodes[name].get_degree() >= max_value: max_value = self.nodes[name].get_degree() self.max_node = name # Check for new min elif self.nodes[name].get_degree() <= min_value: min_value = self.nodes[name].get_degree() self.min_node = name return self.max_node, self.min_node # Target position implementations # Stationary at the center of the field #def stationary_center(time_step, max_range): # return np.empty((R_space,)).fill(max_range / 2.0) # Dictionary of target position functions #target_position_functions = { # "Stationary Center" : stationary_center # } # Target reading implementations # Always returns 50 #def constant_50(time_step): # return np.empty((T_space,)).fill(50.0) # Dictionary of target reading functions #target_reading_functions = { # "Constant 50" : constant_50 # } # Runs the entire consensus filter and visualizes results class Simulate: # Class members # # environment : Environment() # Object that handles the environment where the nodes are # # network : Network() # This node is a member of the network # Used to find information about the network # # info : list # [target_reading, target_location, network_average, network_std, max_node_reading, min_node_reading] # Information about the network at each timestep # # default_consensus_method : string # Constructor # # Area will be square, target will be in the center # # max_range : numeric # The boundary of the environment # # num_nodes : int # How many nodes to put into the network # # default_consensus_method : string def __init__(self, max_range, num_nodes = 30, communication_radius = 10, default_consensus_method = "Max Degree", field_name="field.txt"): # Nodes will use this as their consensus method unless another is specified at creation time self.default_consensus_method = default_consensus_method # Create the environment # Use a constant position and reading for the target self.environment = Environment(field_name = field_name, communication_radius = communication_radius) # Make a network self.make_network(max_range, num_nodes = num_nodes) # Get the nodes to track self.max_node, self.min_node = self.network.get_interest_nodes() # Holds the network average and standard deviation at each time step self.info = [] # Makes a network, ensuring that it is connected # # retry_max : int # The maximum number of times to create a new network if they keep ending up disconnected # Throws exception after too many failures def make_network(self, max_range, retry_max = 10, num_nodes = 10): # Redo if the network is disconnected retry_count = 0 network_connected = False while retry_count < retry_max and not network_connected: # Create the network self.network = Network() # Randomly generate nodes with positions around the target random_nodes = (np.random.rand(num_nodes, R_space) * max_range).astype(np.uint8) # Place the nodes into the environment and network for node_index, node_position in enumerate(random_nodes): # Name is just the index as a string node_name = str(node_index) # Add to environment self.environment.add_node(node_name, node_position) # Create the node, use default values new_node = Node(self.environment, self.network, node_name, range_s = 100.0 ,consensus_method = self.default_consensus_method) # Add to the network self.network.add_node(node_name, new_node) # Get the connected flag network_connected = self.network.check_connected() # Increment counter retry_count += 1 # Throw exception #if not network_connected: # raise RuntimeError # Runs the network and environment for the specified number of iterations # TODO: make convergence a condition def run(self, iterations = 1000): for time_step in range(iterations): # Have the network update all of the readings #avg, std = self.network.get_network_reading() self.last_avg, self.last_std = self.network.get_network_reading() print "Completed iteration: ", time_step # Advance the environment self.environment.advance() # Shows information about the network through matplotlib # Shows positions of nodes and location of the object being sensed def visualize(self): # Figure 1 will be the locations of nodes and the tracked object plt.figure(1) # Set the title plt.title("Node Positions") # Set the x and y axis names plt.xlabel("X location") plt.ylabel("Y location") # Plot the neighbors of each node edges = self.network.make_graph() # Make a line for each neighbor for edge in edges: # Unpack the node names first_node, second_node = edge.split("-") # Get the coordinates of each node first_coordinates = self.environment.get_node_position(first_node) second_coordinates = self.environment.get_node_position(second_node) # Make a line plt.plot([first_coordinates[0], second_coordinates[0]], [first_coordinates[1], second_coordinates[1]], 'bs-', markersize=0.0) # Add the locations of every node in the graph # Uses the true positions in the environment node_positions_x = [] node_positions_y = [] for node_name in self.network.node_names(): # Get the position of the node node_position = self.environment.get_node_position(node_name) # Add it to the list node_positions_x.append(node_position[0]) node_positions_y.append(node_position[1]) # Plot points plt.plot(node_positions_x, node_positions_y, 'ko', label="Nodes") # Set the legend plt.legend(loc="best") # The network prediction fig, ax = plt.subplots() plt.title("Network Prediction") heatmap = ax.pcolor(self.last_avg, cmap=plt.cm.RdBu) # The actual field fig, ax = plt.subplots() plt.title("True Field") heatmap = ax.pcolor(self.environment.field, cmap=plt.cm.RdBu) # The error between the prediction and the true field fig, ax = plt.subplots() plt.title("Mean Squared Error") heatmap = ax.pcolor(np.power(self.environment.field - self.last_avg, 2), cmap=plt.cm.Reds) # Confidence at each location fig, ax = plt.subplots() plt.title("Confidence") heatmap = ax.pcolor(self.last_std, cmap=plt.cm.Reds) # Show the figures plt.show() if __name__ == "__main__": # Get the fusion method #consensus_method = sys.argv[1] # Seed the random function for reproducability np.random.seed(50) sim = Simulate(25, default_consensus_method = "Weight Design 1") sim.run(10) sim.visualize()
5b74990960e46eafbb6506b4fc50a7389c222099
ohio-university-cs3560-spring-2019/homework-3-pkennedy1999
/hw4/hw4_py2.py
103
3.6875
4
x = 0 for i in range (1, 1000): if(i % 5) == 0 or (i % 3) == 0: x += i print (x)