blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
51640e43dbe3038b807c52fb2d65462cad9e226b
ultimabugger/python_homework
/func_num.py
463
3.609375
4
def div(*args): try: arg_1 = float(input("Укажите число x: ")) arg_2 = float(input("Укажите число y: ")) res = arg_1 / arg_2 except ValueError: return "Что-то пошло не так :) Попробуйте еще раз" except ZeroDivisionError: return "На ноль делить нельзя!" return res print(f"Результат деления: {div()}")
6a1bd810422f098ca321fab3dfe9afa4a284e9a0
lukkwc-byte/CSReview
/Queues.py
894
3.84375
4
#Init of a Queue #Enqueue #Dequeing from LinkedLists import * class QueueLL(): def __init__(self): self.LL=LL() def __str__(self): return str(self.LL) def Enqueue(self, node): LL.AddTail(self.LL, node) return def Dequeue(self): ret=self.LL.head self.LL.RemoveHead() return ret class QueueArray(): def __init__(self): self.q=[] def __str__(self): ret="" for i in range(len(self.q)): ret+=str(self.q[i])+" " return ret def Enqueue(self, node): self.q.append(node) return def Dequeue(self): return self.q.pop(0) NodeD=LLNode("D") NodeC=LLNode("C") NodeB=LLNode("B") NodeA=LLNode("A") test=QueueArray() test.Enqueue(NodeA) test.Enqueue(NodeB) test.Enqueue(NodeC) test.Enqueue(NodeD) print(test.Dequeue()) print(test)
f308cd2e7a7c979ab741b91fdc859b338ec453c9
sency90/allCode
/acm/python/1850.py
157
3.515625
4
def gcd(b,s): if s==0: return int(b) else: return gcd(s,b%s) a,b = map(int, input().split()) g = gcd(a,b) i = 0 for i in range(g): print(1, end='')
721e5d6a05f065535b8fdec251e728310ecb9748
neeraj1909/100-days-of-challenge
/project_euler/problem-1.py
448
3.796875
4
#!/bin/python3 import sys def sum_factors_of_n_below_k(k, n): m = (k -1) //n return n *m *(m+1) //2 t = int(input().strip()) for a0 in range(t): n = int(input().strip()) total = 0 #for multiple of 3 total = total + sum_factors_of_n_below_k(n, 3) #for multiple of 5 total = total + sum_factors_of_n_below_k(n, 5) #for multiple of 15 total = total - sum_factors_of_n_below_k(n, 15) print("%s" % total)
02a7e4eafa99a2c99c8c54e45846ef23e6358522
konnomiya/algorithm021
/Week_02/589.N-ary_Tree_Preorder_Traversal.py
553
3.578125
4
class Solution: # iteration def preorder(self, root: 'Node') -> List[int]: stack, res = [root,], [] while stack: node = stack.pop() if node: res.append(node.val) stack.extend(node.children[::-1]) return res # recursive def preorder2(self, root: 'Node') -> List[int]: res = [] if not root: return res res.append(root.val) for child in root.children: res.extend(self.preorder(child)) return res
08e72c506ad7c81b8295b6e3a2d16ff46cb3236d
sayanm-10/py-modules
/main.py
3,660
3.5
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- __author__ = "Sayan Mukherjee" __version__ = "0.1.0" __license__ = "MIT" import unittest import os from datetime import datetime, timedelta from directory_analyzer import print_dir_summary, analyze_file def datetime_calculator(): ''' A helper to demonstrate the datetime module ''' start_date_1 = 'Feb 27, 2000' start_date_2 = 'Feb 27, 2017' start_date_1 = datetime.strptime(start_date_1, '%b %d, %Y') end_date_1 = start_date_1 + timedelta(days=3) print("The date three days after Feb 27, 2000 is", end_date_1.strftime('%b %d, %Y'), "\n") start_date_2 = datetime.strptime(start_date_2, '%b %d, %Y') end_date_2 = start_date_2 + timedelta(days=3) print("The date three days after Feb 27, 2017 is", end_date_2.strftime('%b %d, %Y'), "\n") date_diff_start = datetime.strptime('Jan 1, 2017', '%b %d, %Y') date_diff_end = datetime.strptime('Oct 31, 2017', '%b %d, %Y') date_diff = date_diff_end - date_diff_start print("{} days passed between Jan 1, 2017 and Oct 31, 2017".format(date_diff.days)) def file_reader(path, field_num, sep, header=False): ''' a generator function to read text files and return all of the values on a single line on each call to next() ''' try: fp = open(path, 'r') except FileNotFoundError: print("\n\nError while opening {} for reading".format(os.path.basename(path))) else: with fp: # skip the first line if header is true if header: next(fp) for line_num, line in enumerate(fp): fields = line.strip().split(sep) if (len(fields) < field_num): raise ValueError('\n\n {} has {} fields on line {} but expected {}'.format(os.path.basename(path), len(fields), line_num + 1, field_num)) else: # return fields from 0:field_num as tuple yield tuple(fields[:field_num]) class FileOpsTest(unittest.TestCase): ''' Includes all test cases for file operations ''' def test_file_reader(self): ''' test file_reader() ''' # test ValueError is raised if expected number # of fields exceeds the actual fields with self.assertRaises(ValueError) as context: for fields in file_reader('test_file_reader.txt', 6, '|', False): print(fields) self.assertTrue('Caught error' in str(context.exception)) # match the first returned tuple expected_result = ('John ', ' Doe ', ' 102000 ', ' Age: 36 ', ' NJ') self.assertEqual(next(file_reader('test_file_reader.txt', 5, '|', True)), expected_result) def test_print_dir_summary(self): ''' test individual o/p of print_dir_summary ''' try: fp = open('main.py', 'r') except FileNotFoundError: print('Unit test needs to run on main.py') else: classes, funcs, lines, chars = analyze_file(fp) self.assertEqual(classes, 1) self.assertEqual(funcs, 4) self.assertEqual(lines, 100) self.assertTrue(chars > 1) if __name__ == "__main__": ''' This is executed when run from the command line ''' print("\n\n************************* Problem 1 ******************************\n\n") datetime_calculator() print("\n\n************************* Problem 3 ******************************\n\n") print_dir_summary(os.getcwd()) print("\n\n************************* Unit Tests ******************************\n\n") unittest.main(exit=False, verbosity=2)
df11433519e87b3a52407745b274a6db005d767c
jtquisenberry/PythonExamples
/Interview_Cake/hashes/inflight_entertainment_deque.py
1,754
4.15625
4
import unittest from collections import deque # https://www.interviewcake.com/question/python/inflight-entertainment?section=hashing-and-hash-tables&course=fc1 # Use deque # Time = O(n) # Space = O(n) # As with the set-based solution, using a deque ensures that the second movie is not # the same as the current movie, even though both could have the same length. def can_two_movies_fill_flight(movie_lengths, flight_length): # Determine if two movie runtimes add up to the flight length # And do not show the same movie twice. lengths = deque(movie_lengths) while len(lengths) > 0: current_length = lengths.popleft() second_length = flight_length - current_length if second_length in lengths: return True return False # Tests class Test(unittest.TestCase): def test_short_flight(self): result = can_two_movies_fill_flight([2, 4], 1) self.assertFalse(result) def test_long_flight(self): result = can_two_movies_fill_flight([2, 4], 6) self.assertTrue(result) def test_one_movie_half_flight_length(self): result = can_two_movies_fill_flight([3, 8], 6) self.assertFalse(result) def test_two_movies_half_flight_length(self): result = can_two_movies_fill_flight([3, 8, 3], 6) self.assertTrue(result) def test_lots_of_possible_pairs(self): result = can_two_movies_fill_flight([1, 2, 3, 4, 5, 6], 7) self.assertTrue(result) def test_only_one_movie(self): result = can_two_movies_fill_flight([6], 6) self.assertFalse(result) def test_no_movies(self): result = can_two_movies_fill_flight([], 2) self.assertFalse(result) unittest.main(verbosity=2)
e7d72e428f84364bde9130e8bcecc818ee628a94
jtquisenberry/PythonExamples
/Interview_Cake/arrays/merge_meetings.py
2,921
4.09375
4
import unittest # https://www.interviewcake.com/question/python/merging-ranges?course=fc1&section=array-and-string-manipulation # Sort ranges of tuples # Time: O(n * lg(n)) because of the sorting step. # Space: O(n) -- 1n for sorted_meetings, 1n for merged_meetings. # First, we sort our input list of meetings by start time so any meetings that might # need to be merged are now next to each other. # Then we walk through our sorted meetings from left to right. At each step, either: # We can merge the current meeting with the previous one, so we do. # We can't merge the current meeting with the previous one, so we know the previous meeting can't be merged with any # future meetings and we throw the current meeting into merged_meetings. def merge_ranges(meetings): if len(meetings) < 1: return meetings # Sort by start time n*log(n) sorted_meetings = sorted(meetings) # Initialize merged_meetings with the earliest meeting # The for loop requires comparison with the latest meeting in the list, # so there needs to be a latest meeting in the list. merged_meetings = [sorted_meetings[0]] # Use this alternative for less space use # meetings.sort() for current_start, current_end in sorted_meetings[1:]: merged_start, merged_end = merged_meetings[-1] if current_start <= merged_end: # Overlapping meeting merged_meetings[-1] = (merged_start, max(merged_end, current_end)) else: # Non-overlapping meeting merged_meetings.append((current_start, current_end)) return merged_meetings # Tests class Test(unittest.TestCase): def test_meetings_overlap(self): actual = merge_ranges([(1, 3), (2, 4)]) expected = [(1, 4)] self.assertEqual(actual, expected) def test_meetings_touch(self): actual = merge_ranges([(5, 6), (6, 8)]) expected = [(5, 8)] self.assertEqual(actual, expected) def test_meeting_contains_other_meeting(self): actual = merge_ranges([(1, 8), (2, 5)]) expected = [(1, 8)] self.assertEqual(actual, expected) def test_meetings_stay_separate(self): actual = merge_ranges([(1, 3), (4, 8)]) expected = [(1, 3), (4, 8)] self.assertEqual(actual, expected) def test_multiple_merged_meetings(self): actual = merge_ranges([(1, 4), (2, 5), (5, 8)]) expected = [(1, 8)] self.assertEqual(actual, expected) def test_meetings_not_sorted(self): actual = merge_ranges([(5, 8), (1, 4), (6, 8)]) expected = [(1, 4), (5, 8)] self.assertEqual(actual, expected) def test_sample_input(self): actual = merge_ranges([(0, 1), (3, 5), (4, 8), (10, 12), (9, 10)]) expected = [(0, 1), (3, 8), (9, 12)] self.assertEqual(actual, expected) if __name__ == '__main__': unittest.main(verbosity=2)
8eeff2df65c400e2ae316070389736e46dc1fc2b
jtquisenberry/PythonExamples
/Jobs/bynder_isomorphic_strings.py
1,227
3.609375
4
import unittest def is_isomorphic(str1, str2): if len(str1) != len(str2): return False character_map = dict() seen_values = set() for i in range(len(str1)): if str1[i] in character_map: if str2[i] != character_map[str1[i]]: return False else: character_map[str1[i]] = str2[i] if str2[i] in seen_values: return False seen_values.add(str2[i]) return True class Test(unittest.TestCase): def setUp(self): pass def test_1(self): str1 = 'egg' str2 = 'app' result = is_isomorphic(str1, str2) self.assertTrue(result) def test_2(self): str1 = 'cow' str2 = 'app' result = is_isomorphic(str1, str2) self.assertFalse(result) def test_3(self): str1 = 'egs' str2 = 'add' result = is_isomorphic(str1, str2) self.assertFalse(result) def test_4(self): str1 = 'paper' str2 = 'title' result = is_isomorphic(str1, str2) self.assertTrue(result) if __name__ == '__main__': unittest.main()
dbfbd24fa14eeef9f495b3e6c08b428e8274159f
jtquisenberry/PythonExamples
/Simple_Samples/list_comprehension_multiple.py
104
3.578125
4
X = [['a','b','c'],['z','y','x'],['1','2','3']] aaa = [word for words in X for word in words] print(aaa)
e1c7953b7d1f52122d545583785a842e187a7bd7
jtquisenberry/PythonExamples
/Simple_Samples/array_to_tree.py
2,656
3.734375
4
import math from collections import deque class Node(): def __init__(self, value, left_child = None, right_child = None): self.value = value self.left = None self.right = None def __str__(self): return str(self.value) nodes = [1,2,3,4,5,6,7,8] current_index = 0 unlinked_nodes = [] max_power = math.log(len(nodes) + 1, 2) if max_power == int(max_power): # No change - already an integer. max_power = int(max_power) else: max_power = int(max_power) + 1 for power_of_two in range(0,max_power): items_to_place = 2 ** power_of_two items_placed = 0 current_list = [] while (items_placed < items_to_place) and (current_index < len(nodes)): current_list.append(Node(nodes[current_index])) items_placed += 1 current_index += 1 unlinked_nodes.append(current_list) print(current_list) for level in unlinked_nodes: print([l.value for l in level]) for level_number in range(0, len(unlinked_nodes)): #Start with the second-to-last level and work up. print('level', level_number) if level_number < len(unlinked_nodes) - 1: level = unlinked_nodes[level_number] child_index = 0 for node_number in range(0,len(level)): node = level[node_number] print('current_node_number', node_number) for child_node_number in [node_number * 2, node_number * 2 + 1]: print('child_node_number', child_node_number) #print(len(unlinked_nodes[level_number + 1])) if child_node_number < len(unlinked_nodes[level_number + 1]): if child_node_number % 2 == 0: print('even') node.left = unlinked_nodes[level_number + 1][child_node_number] else: print('odd') node.right = unlinked_nodes[level_number + 1][child_node_number] root = unlinked_nodes[0][0] print('root', root) print('root.left', root.left) print('root.right', root.right) print('root.left.left', root.left.left) print('root.left.right', root.left.right) print('root.right.left', root.right.left) print('root.right.right', root.right.right) print('root.left.left.left', root.left.left.left) # Print tree using bread-first search visited_nodes = deque() visited_nodes.append(root) while len(visited_nodes) > 0: current_node = visited_nodes.popleft() print(current_node) node = current_node.left if node is not None: visited_nodes.append(node) node = current_node.right if node is not None: visited_nodes.append(node)
5e5c7d41a7344b9eb94f9f9dbde5dbe48390b5f6
jtquisenberry/PythonExamples
/Interview_Cake/trees_and_graphs/graph_coloring.py
6,495
4.3125
4
import unittest # https://www.interviewcake.com/question/python/graph-coloring?section=trees-graphs&course=fc1 # We go through the nodes in one pass, assigning each node the first legal color we find. # How can we be sure we'll always have at least one legal color for every node? In a graph with maximum degree DDD, each node has at most DDD neighbors. That means there are at most DDD colors taken by a node's neighbors. And we have D+1D+1D+1 colors, so there's always at least one color left to use. # When we color each node, we're careful to stop iterating over colors as soon as we find a legal color. # Space = O(D), where D is the number of colors. The only data structure is `used_nodes`, which contains # at most D colors. # Time = O(N + M) N because we must look at each node in the list. M is the number of edges # because we must check the color of each neighbor. Each neighbor is at the end of an edge. # We add the color of each neighbor to used_colors. class GraphNode: def __init__(self, label): self.label = label self.neighbors = set() self.color = None def color_graph(graph, colors): # Create a valid coloring for the graph # Color one node at a time. # Handle each node in the list, rather than traversing # the graph. This avoids problems with nodes with no # edges and cycles other than loops. for node in graph: # Check whether there is a loop. If there is a loop, then # a single node is at both ends of an edge. Then, the node # cannot have the same color as itself. if node in node.neighbors: raise Exception('A loop was encountered') # Create a list of used nodes - nodes that have already # been allocated to neighbors. used_colors = set() for neighbor in node.neighbors: # Add the color of each neighbor to the set used_colors.add(neighbor.color) # Apply the first available color to the current node. for color in colors: if color not in used_colors: node.color = color break # Tests class Test(unittest.TestCase): def setUp(self): self.colors = frozenset([ 'red', 'green', 'blue', 'orange', 'yellow', 'white', ]) def assertGraphColoring(self, graph, colors): self.assertGraphHasColors(graph, colors) self.assertGraphColorLimit(graph) for node in graph: self.assertNodeUniqueColor(node) def assertGraphHasColors(self, graph, colors): for node in graph: msg = 'Node %r color %r not in %r' % (node.label, node.color, colors) self.assertIn(node.color, colors, msg=msg) def assertGraphColorLimit(self, graph): max_degree = 0 colors_found = set() for node in graph: degree = len(node.neighbors) max_degree = max(degree, max_degree) colors_found.add(node.color) max_colors = max_degree + 1 used_colors = len(colors_found) msg = 'Used %d colors and expected %d at most' % (used_colors, max_colors) self.assertLessEqual(used_colors, max_colors, msg=msg) def assertNodeUniqueColor(self, node): for adjacent in node.neighbors: msg = 'Adjacent nodes %r and %r have the same color %r' % ( node.label, adjacent.label, node.color, ) self.assertNotEqual(node.color, adjacent.color, msg=msg) def test_line_graph(self): node_a = GraphNode('a') node_b = GraphNode('b') node_c = GraphNode('c') node_d = GraphNode('d') node_a.neighbors.add(node_b) node_b.neighbors.add(node_a) node_b.neighbors.add(node_c) node_c.neighbors.add(node_b) node_c.neighbors.add(node_d) node_d.neighbors.add(node_c) graph = [node_a, node_b, node_c, node_d] tampered_colors = list(self.colors) color_graph(graph, tampered_colors) self.assertGraphColoring(graph, self.colors) def test_separate_graph(self): node_a = GraphNode('a') node_b = GraphNode('b') node_c = GraphNode('c') node_d = GraphNode('d') node_a.neighbors.add(node_b) node_b.neighbors.add(node_a) node_c.neighbors.add(node_d) node_d.neighbors.add(node_c) graph = [node_a, node_b, node_c, node_d] tampered_colors = list(self.colors) color_graph(graph, tampered_colors) self.assertGraphColoring(graph, self.colors) def test_triangle_graph(self): node_a = GraphNode('a') node_b = GraphNode('b') node_c = GraphNode('c') node_a.neighbors.add(node_b) node_a.neighbors.add(node_c) node_b.neighbors.add(node_a) node_b.neighbors.add(node_c) node_c.neighbors.add(node_a) node_c.neighbors.add(node_b) graph = [node_a, node_b, node_c] tampered_colors = list(self.colors) color_graph(graph, tampered_colors) self.assertGraphColoring(graph, self.colors) def test_envelope_graph(self): node_a = GraphNode('a') node_b = GraphNode('b') node_c = GraphNode('c') node_d = GraphNode('d') node_e = GraphNode('e') node_a.neighbors.add(node_b) node_a.neighbors.add(node_c) node_b.neighbors.add(node_a) node_b.neighbors.add(node_c) node_b.neighbors.add(node_d) node_b.neighbors.add(node_e) node_c.neighbors.add(node_a) node_c.neighbors.add(node_b) node_c.neighbors.add(node_d) node_c.neighbors.add(node_e) node_d.neighbors.add(node_b) node_d.neighbors.add(node_c) node_d.neighbors.add(node_e) node_e.neighbors.add(node_b) node_e.neighbors.add(node_c) node_e.neighbors.add(node_d) graph = [node_a, node_b, node_c, node_d, node_e] tampered_colors = list(self.colors) color_graph(graph, tampered_colors) self.assertGraphColoring(graph, self.colors) def test_loop_graph(self): node_a = GraphNode('a') node_a.neighbors.add(node_a) graph = [node_a] tampered_colors = list(self.colors) with self.assertRaises(Exception): color_graph(graph, tampered_colors) unittest.main(verbosity=2)
fcbb62045b3d953faf05dd2b741cd060376ec237
jtquisenberry/PythonExamples
/Jobs/maze_runner.py
2,104
4.1875
4
# Alternative solution at # https://www.geeksforgeeks.org/shortest-path-in-a-binary-maze/ # Maze Runner # 0 1 0 0 0 # 0 0 0 1 0 # 0 1 0 0 0 # 0 0 0 1 0 # 1 - is a wall # 0 - an empty cell # a robot - starts at (0,0) # robot's moves: 1 step up/down/left/right # exit at (N-1, M-1) (never 1) # length(of the shortest path from start to the exit), -1 when exit is not reachable # time: O(NM), N = columns, M = rows # space O(n), n = size of queue from collections import deque import numpy as np def run_maze(maze): rows = len(maze) cols = len(maze[0]) row = 0 col = 0 distance = 1 next_position = deque() next_position.append((row, col, distance)) # successful_routes = list() while len(next_position) > 0: array2 = np.array(maze) print(array2) print() current_row, current_column, current_distance = next_position.popleft() if current_row == rows - 1 and current_column == cols - 1: return current_distance # successful_routes.append(current_distance) maze[current_row][current_column] = 8 if current_row > 0: up = (current_row - 1, current_column, current_distance + 1) if maze[up[0]][up[1]] == 0: next_position.append(up) if current_row + 1 < rows: down = (current_row + 1, current_column, current_distance + 1) if maze[down[0]][down[1]] == 0: next_position.append(down) if current_column > 0: left = (current_row, current_column - 1, current_distance + 1) if maze[left[0]][left[1]] == 0: next_position.append(left) if current_column + 1 < cols: right = (current_row, current_column + 1, current_distance + 1) if maze[right[0]][right[1]] == 0: next_position.append(right) return -1 if __name__ == '__main__': maze = [ [0, 1, 0, 0, 0], [0, 0, 0, 0, 0], [0, 1, 0, 1, 0], [0, 0, 0, 1, 0]] length = run_maze(maze) print(length)
ba8395ab64f7ebb77cbfdb205d828aa552802505
jtquisenberry/PythonExamples
/Interview_Cake/arrays/reverse_words_in_list_deque.py
2,112
4.25
4
import unittest from collections import deque # https://www.interviewcake.com/question/python/reverse-words?section=array-and-string-manipulation&course=fc1 # Solution with deque def reverse_words(message): if len(message) < 1: return message final_message = deque() current_word = [] for i in range(0, len(message)): character = message[i] if character != ' ': current_word.append(character) if character == ' ' or i == len(message) - 1: # Use reversed otherwise extend puts characters in the wrong order. final_message.extendleft(reversed(current_word)) current_word = [] if i != len(message) - 1: final_message.extendleft(' ') for i in range(0, len(message)): message[i] = list(final_message)[i] return list(final_message) # Tests class Test(unittest.TestCase): def test_one_word(self): message = list('vault') reverse_words(message) expected = list('vault') self.assertEqual(message, expected) def test_two_words(self): message = list('thief cake') reverse_words(message) expected = list('cake thief') self.assertEqual(message, expected) def test_three_words(self): message = list('one another get') reverse_words(message) expected = list('get another one') self.assertEqual(message, expected) def test_multiple_words_same_length(self): message = list('rat the ate cat the') reverse_words(message) expected = list('the cat ate the rat') self.assertEqual(message, expected) def test_multiple_words_different_lengths(self): message = list('yummy is cake bundt chocolate') reverse_words(message) expected = list('chocolate bundt cake is yummy') self.assertEqual(message, expected) def test_empty_string(self): message = list('') reverse_words(message) expected = list('') self.assertEqual(message, expected) unittest.main(verbosity=2)
37506921175e5dfec216a7b8c0433d421e0cdbd1
jtquisenberry/PythonExamples
/numpy_examples/multiplication.py
365
3.703125
4
import numpy as np X = \ [ [3, 2, 8], [3, 3, 4], [7, 2, 5] ] Y = \ [ [2, 3], [4, 2], [5, 5] ] X = np.array(X) Y = np.array(Y) print("INPUT MATRICES") print("X") print(X) print("Y") print(Y) print() print("DOT PRODUCT") print(np.dot(X, Y)) print() print("CROSS PRODUCT") print(np.cross(X, Y))
8236247559f5951c95d1bd1a5074393c8feb8967
jtquisenberry/PythonExamples
/Leetcode/triangle4.py
488
3.640625
4
from functools import lru_cache triangle = [[2],[3,4],[6,5,7],[4,1,8,3]] class Solution: def minimumTotal(self, triangle): @lru_cache() def dfs(i, level): if level == len(triangle): return 0 left = triangle[level][i] + dfs(i, level + 1) right = triangle[level][i] + dfs(i + 1, level + 1) return min(left, right) return dfs(0, 0) solution = Solution() print(solution.minimumTotal(triangle))
6abe6859f0ce87b6a8d6cdd400a0c910246b0f0d
jtquisenberry/PythonExamples
/Leetcode/1342_number_of_steps_to_reduce_a_number_to_zero.py
408
3.71875
4
from typing import * class Solution: def numberOfSteps(self, num: int) -> int: steps = 0 while num > 0: # print(num, bin(num)) if num & 1: steps += 1 steps += 1 num = num >> 1 # print(steps) if steps - 1 > -1: return steps - 1 return 0 # Input #14 #8 #123 # Output #6 #4 #12
83cf3df4820c5d6a21118a51a2869080067a7870
jtquisenberry/PythonExamples
/Interview_Cake/combinatorics/find_duplicated_number_set.py
1,037
3.984375
4
import unittest # https://www.interviewcake.com/question/python/which-appears-twice?course=fc1&section=combinatorics-probability-math # Find the number that appears twice in a list. # This version is not the recommended version. This version uses a set. # Space O(n) # Time O(n) def find_repeat(numbers_list): # Find the number that appears twice number_set = set() for number in numbers_list: if number in number_set: return number else: number_set.add(number) return # Tests class Test(unittest.TestCase): def test_short_list(self): actual = find_repeat([1, 2, 1]) expected = 1 self.assertEqual(actual, expected) def test_medium_list(self): actual = find_repeat([4, 1, 3, 4, 2]) expected = 4 self.assertEqual(actual, expected) def test_long_list(self): actual = find_repeat([1, 5, 9, 7, 2, 6, 3, 8, 2, 4]) expected = 2 self.assertEqual(actual, expected) unittest.main(verbosity=2)
9adfabfbc83b97a11ee5b2f23cea5ec2eb357dd5
jtquisenberry/PythonExamples
/Interview_Cake/sorting/merge_sorted_lists3.py
1,941
4.21875
4
import unittest from collections import deque # https://www.interviewcake.com/question/python/merge-sorted-arrays?course=fc1&section=array-and-string-manipulation def merge_lists(my_list, alices_list): # Combine the sorted lists into one large sorted list if len(my_list) == 0 and len(alices_list) == 0: return my_list if len(my_list) > 0 and len(alices_list) == 0: return my_list if len(my_list) == 0 and len(alices_list) > 0: return alices_list merged_list = [] my_index = 0 alices_index = 0 while my_index < len(my_list) and alices_index < len(alices_list): if my_list[my_index] < alices_list[alices_index]: merged_list.append(my_list[my_index]) my_index += 1 else: merged_list.append(alices_list[alices_index]) alices_index += 1 if my_index < len(my_list): merged_list += my_list[my_index:] if alices_index < len(alices_list): merged_list += alices_list[alices_index:] return merged_list # Tests class Test(unittest.TestCase): def test_both_lists_are_empty(self): actual = merge_lists([], []) expected = [] self.assertEqual(actual, expected) def test_first_list_is_empty(self): actual = merge_lists([], [1, 2, 3]) expected = [1, 2, 3] self.assertEqual(actual, expected) def test_second_list_is_empty(self): actual = merge_lists([5, 6, 7], []) expected = [5, 6, 7] self.assertEqual(actual, expected) def test_both_lists_have_some_numbers(self): actual = merge_lists([2, 4, 6], [1, 3, 7]) expected = [1, 2, 3, 4, 6, 7] self.assertEqual(actual, expected) def test_lists_are_different_lengths(self): actual = merge_lists([2, 4, 6, 8], [1, 7]) expected = [1, 2, 4, 6, 7, 8] self.assertEqual(actual, expected) unittest.main(verbosity=2)
2950d12a2c1981f470e285bb6af54e51bdc6fa94
jtquisenberry/PythonExamples
/Pandas_Examples/groupby_unstack.py
1,464
3.890625
4
import pandas as pd import matplotlib.pyplot as plt # https://stackoverflow.com/questions/51163975/pandas-add-column-name-to-results-of-groupby # There are two ways to give a name to an aggregate column. # It may be necessary to unstack a compound DataFrame first. # Initial DataFrame d = {'timeIndex': [1, 1, 1, 9, 1, 1, 1, 2, 2, 2], 'isZero': [0, 0, 0, 1, 1, 1, 1, 0, 1, 0]} df = pd.DataFrame(data=d) print(df) print() # Group by one column # The sum aggregate function creates a series # notice that the sum does not have a column header df_agg = df.groupby('timeIndex', as_index=False)['isZero'].sum() print(type(df_agg)) print(df_agg) print() # Unstack OPTION 1, set as_index=False df_agg = df.groupby('timeIndex', as_index=False)['isZero'].sum() print(type(df_agg)) print(df_agg) print() data = { 'FirstName':['Tom', 'Tom', 'David', 'Alex', 'Alex', 'Tom'], 'LastName': ['Jones', 'Jones', 'Smith', 'Thompson', 'Thompson', 'Chuckles'], 'Number': [1,18,24,81,63,6] } df = pd.DataFrame(data) # This format creates a compound DataFrame df_agg = df.groupby(['FirstName']).agg({'Number': sum}) print(df_agg) print() # Unstack OPTION 1, set as_index=False df_agg = df.groupby(['FirstName'], as_index=False).agg({'Number': sum}) print(df_agg) print() # Unstack OPTION 2, use to_frame # The argument of to_frame is the name of the new field. df2 = df.groupby(['FirstName'])['Number'].sum().to_frame('Number_Sum').reset_index() print(df2)
e8d9dccc13de722b93bf91f8b33e5702a2a9b96b
jtquisenberry/PythonExamples
/Jobs/stellar/triangle2.py
557
3.84375
4
#https://leetcode.com/problems/triangle/ from copy import deepcopy triangle = [[2], [3, 4], [6, 5, 7], [4, 1, 8, 3]] def minimumTotal(triangle): print(triangle) #triangle2 = triangle.copy() # updates triangle and triangle2 #triangle2 = list(triangle) # updates triangle and triangle2 #triangle2 = triangle[:] # updates triangle and triangle2 triangle2 = deepcopy(triangle) # updates triangle only triangle2[0][0] = 99 print(triangle) print(triangle2) if __name__ == '__main__': minimumTotal(triangle=triangle)
148c6d9d37a9fd79e06e4371a30c65a5e36066b2
jtquisenberry/PythonExamples
/Jobs/multiply_large_numbers.py
2,748
4.25
4
import unittest def multiply(num1, num2): len1 = len(num1) len2 = len(num2) # Simulate Multiplication Like this # 1234 # 121 # ---- # 1234 # 2468 # 1234 # # Notice that the product is moved one space to the left each time a digit # of the top number is multiplied by the next digit from the right in the # bottom number. This is due to place value. # Create an array to hold the product of each digit of `num1` and each # digit of `num2`. Allocate enough space to move the product over one more # space to the left for each digit after the ones place in `num2`. products = [0] * (len1 + len2 - 1) # The index will be filled in from the right. For the ones place of `num` # that is the only adjustment to the index. products_index = len(products) - 1 products_index_offset = 0 # Get the digits of the first number from right to left. for i in range(len1 -1, -1, -1): factor1 = int(num1[i]) # Get the digits of the second number from right to left. for j in range(len2 - 1, -1, -1): factor2 = int(num2[j]) # Find the product current_product = factor1 * factor2 # Write the product to the correct position in the products array. products[products_index + products_index_offset] += current_product products_index -= 1 # Reset the index to the end of the array. products_index = len(products) -1; # Move the starting point one space to the left. products_index_offset -= 1; for i in range(len(products) - 1, -1, -1): # Get the ones digit keep = products[i] % 10 # Get everything higher than the ones digit carry = products[i] // 10 products[i] = keep # If index 0 is reached, there is no place to store a carried value. # Instead retain it at the current index. if i > 0: products[i-1] += carry else: products[i] += (10 * carry) # Convert the list of ints to a string. #print(products) output = ''.join(map(str,products)) return output class Test(unittest.TestCase): def setUp(self): pass def test_small_product(self): expected = "1078095" actual = multiply("8765", "123") self.assertEqual(expected, actual) def test_large_product(self): expected = "41549622603955309777243716069997997007620439937711509062916" actual = multiply("654154154151454545415415454", "63516561563156316545145146514654") self.assertEqual(expected, actual) def tearDown(self): pass if __name__ == '__main__': unittest.main()
d59ccfe23de3862992af4e1e16cd5d67c838ca21
jtquisenberry/PythonExamples
/Classes/getters_and_setters.py
1,094
3.609375
4
import unittest class Cat(): def __init__(self, name, hair_color): self._hair_color = hair_color # Use of a getter to return hair_color @property def hair_color(self): return self._hair_color # Setter has the name of the property # Use of a setter to throw AttributeError with a custom message. @hair_color.setter def hair_color(self, value): # raise AttributeError("Property hair_color is read-only.") self._hair_color = value class Test(unittest.TestCase): def setUp(self): self.cat = Cat('orange', 'Morris') self.cat._hair_color = 'black' def test_set_hair_color_field(self): expected = 'black' actual = self.cat._hair_color self.assertEqual(expected, actual, 'error at test_set_hair_color') def test_set_hair_color_property(self): expected = 'white' self.cat.hair_color = 'white' actual = self.cat.hair_color self.assertEqual(expected,actual,'error at test_set_hair_color_property') if __name__ == '__main__': unittest.main()
0812620e8371ba84710baa5a1eee9992804a3408
jtquisenberry/PythonExamples
/Simple_Samples/array_as_tree.py
609
3.75
4
# Calculate the sum of the left side and the right side tree = [1,2,3,4,0,0,7,8,9,10,11,12,13,14,15,16] # 1 # 2 3 # 4 5 6 7 # 8 9 10 11 12 13 14 15 # 16 left_side = 0 right_side = 0 power_of_two = 1 while len(tree) > 2**(power_of_two - 1): left_index = (2**power_of_two) -1 right_index = (2**(power_of_two + 1)-1 -1) if left_index < len(tree): left_side += tree[left_index] if right_index < len(tree): right_side += tree[right_index] power_of_two += 1 print('left_side', left_side) print('right_side', right_side)
b8b7d0a3067b776d6c712b2f229ef65448b9a4d9
jtquisenberry/PythonExamples
/Interview_Cake/arrays/reverse_words_in_list_lists.py
2,120
4.375
4
import unittest from collections import deque # https://www.interviewcake.com/question/python/reverse-words?section=array-and-string-manipulation&course=fc1 # Solution with lists only # Not in place def reverse_words(message): if len(message) < 1: return current_word = [] word_list = [] final_output = [] for i in range(0, len(message)): character = message[i] if character != ' ': current_word.append(character) if character == ' ' or i == len(message) - 1: word_list.append(current_word) current_word = [] # print(word_list) for j in range(len(word_list) - 1, -1, -1): final_output.extend(word_list[j]) if j > 0: final_output.extend(' ') # print(final_output) for k in range(0, len(message)): message[k] = final_output[k] return # Tests class Test(unittest.TestCase): def test_one_word(self): message = list('vault') reverse_words(message) expected = list('vault') self.assertEqual(message, expected) def test_two_words(self): message = list('thief cake') reverse_words(message) expected = list('cake thief') self.assertEqual(message, expected) def test_three_words(self): message = list('one another get') reverse_words(message) expected = list('get another one') self.assertEqual(message, expected) def test_multiple_words_same_length(self): message = list('rat the ate cat the') reverse_words(message) expected = list('the cat ate the rat') self.assertEqual(message, expected) def test_multiple_words_different_lengths(self): message = list('yummy is cake bundt chocolate') reverse_words(message) expected = list('chocolate bundt cake is yummy') self.assertEqual(message, expected) def test_empty_string(self): message = list('') reverse_words(message) expected = list('') self.assertEqual(message, expected) unittest.main(verbosity=2)
5ed8d9b76cd9a1443a8f0fa9a7ee46604b6e3dfd
mansigoel/GitHackeve
/project2.py
417
3.875
4
def factorial(number_for_factorial): # Add code here return #Factorial number def gcd(number_1, number_2): # Add code here return #gcd value def is_palindrome(string_to_check): # Add code here return #boolean response #Take input for fib in variable a print(fib(a)) #Take input for is_prime in variable b, c print(gcd(b, c)) #Take input for is_palindrome in variable d print(is_palindrome(d))
7aec878186d13b42ac12dd05d1580fc47662520e
devSantos16/pythonDice
/main.py
2,139
3.671875
4
from builtins import dict from Jogada import Jogada from Jogada import mostrarTodosOsDados from Jogada import deletar from Jogada import verificarDadoNulo # Modo usuario loop = True while loop: menu = int(input("SEJA BEM VINDO! \n" "Digite o modo de entrada\n" "1 - Modo Admin\n" "2 - Modo Usuário\n" "0 - Sair do Programa\n" "Digite a opção: ")) if menu == 0: exit(4) elif menu == 1: menuUsuario = int(input("MENU DO USUARIO\n" "1 - Mostrar dados e jogar\n" "2 - Adicionar Dado e jogar\n" "3 - Mostrar todas as jogadas\n" "4 - Deletar Tudo\n" "0 - SAIR\n" "Digite a opção desejada: ")) if menuUsuario == 0: print("SAINDO !!! ") exit(4) if menuUsuario == 1: f = mostrarTodosOsDados() verificarDadoNulo(f) print("Todos os dados inseridos: ") for c in range(len(f)): print(f[c]) resultado = int(input("Digite qual dado tu quer: ")) for c in range(len(f)): if f[c] == str(resultado): j = Jogada(resultado) print(j.retornarDado()) elif menuUsuario == 2: resultado = int(input("Digite um numero para o Dado: ")) j = Jogada(resultado) print(j.retornarDado()) elif menuUsuario == 3: mostrarTodosOsDados() elif menuUsuario == 4: print("Deletando tudo") deletar() else: print("ERRO, Digite novamente"); elif menu == 2: print("Ok!") exit(4) else: print("ERRO, tente novamente !") # resultado = int(input("Digite um numero para o Dado: ")) # # j = Jogada(resultado) # # print(j.retornarDado())
a274889dd5ea83c37dd31a7df6c5ea88d1f1f2bb
libp2p/py-libp2p
/libp2p/peer/addrbook_interface.py
1,673
3.5625
4
from abc import ABC, abstractmethod from typing import List, Sequence from multiaddr import Multiaddr from .id import ID class IAddrBook(ABC): @abstractmethod def add_addr(self, peer_id: ID, addr: Multiaddr, ttl: int) -> None: """ Calls add_addrs(peer_id, [addr], ttl) :param peer_id: the peer to add address for :param addr: multiaddress of the peer :param ttl: time-to-live for the address (after this time, address is no longer valid) """ @abstractmethod def add_addrs(self, peer_id: ID, addrs: Sequence[Multiaddr], ttl: int) -> None: """ Adds addresses for a given peer all with the same time-to-live. If one of the addresses already exists for the peer and has a longer TTL, no operation should take place. If one of the addresses exists with a shorter TTL, extend the TTL to equal param ttl. :param peer_id: the peer to add address for :param addr: multiaddresses of the peer :param ttl: time-to-live for the address (after this time, address is no longer valid """ @abstractmethod def addrs(self, peer_id: ID) -> List[Multiaddr]: """ :param peer_id: peer to get addresses of :return: all known (and valid) addresses for the given peer """ @abstractmethod def clear_addrs(self, peer_id: ID) -> None: """ Removes all previously stored addresses. :param peer_id: peer to remove addresses of """ @abstractmethod def peers_with_addrs(self) -> List[ID]: """ :return: all of the peer IDs stored with addresses """
5d730b83244e0a0d7773556652ff0332d0857ef8
Hananja/DQI19-Python
/01_Einfuehrung/prime_factors_simple.py
727
3.90625
4
# -*- coding: utf-8 -*- # Berechnung der Primfaktoren einer Zahl in einer Liste from typing import List loop = True while loop: # Eingabe input_number : int = int(input("Bitte Nummer eingeben: ")) number : int = input_number # Verarbeitung factors : List[int] = [] # Liste zum Sammeln der Faktoren divider : int = 2 while number > 1: while number % divider == 0: factors.append(divider) number //= divider # number = number // divider (integer division) divider = divider + 1 # Ausgabe print("{:s} = {:d}".format(" ⋅ ".join(map(str, factors)), input_number)) if input("Noch einmal ausführen (J/N)? ") not in "JjYy": loop = False
c53deedb3e49ee964abe0fd4b3a83f2a327a0a08
flofl-source/Pathfinding
/Maier_Flora_Td5.py
3,354
4.03125
4
# Advanced Data Structure and Algorithm # Parctical work number 5 # Exercice 2 #Graph 2 : Negative weight so we use the #Bellman-Ford algorithm #Graph 1 : #Number of edges : 13 #Number of nodes : 8 #Complexity of the dijkstra algorithm : 64 #Complexity of the Bellman-Ford algorithm : 104 #Complexity of the Floyd-Warshall algorithm : 512 #We will use Dijkstra algorithm #Graph 3 : #Number of edges : 13 #Number of nodes : 7 #Complexity of the dijkstra algorithm : 49 #Complexity of the Bellman-Ford algorithm : 91 #Complexity of the Floyd-Warshall algorithm : 343 #We will use Dijkstra algorithm from queue import Queue class vertex : def __init__(self,name,adjacent): self.name=name self.adjacent = adjacent self.d=None self.parent=None def __str__(self): res = str(self.name)+"-->" if (self.adjacent==None): res=res+" "+str(None) else: for elt in self.adjacent.keys(): res=res+" "+elt.name return res def setd(self,k): self.d=k def showQ(Q): for q_item in Q.queue: print (q_item) def showS(S): for (obtained,init) in S.items(): print(obtained+" is obtained by "+init) def showPath(path): res="" for vert in path: res=res+"-->"+vert print(res) def min_d(Q): min_v=None min_d=99999 for vert_n in Q.queue: if min_d>vert_n.d: min_v=vert_n min_d=vert_n.d return(min_v) def modifyQ(Q,vert): print("Q is modyfied :") temp=Queue() for q_vertex in Q.queue: if (q_vertex!=vert): temp.put(q_vertex) return temp def findPath(S,start,end): Res=[end.name] current=end.name while current!=start.name: Res=Res+[S[current]] current=S[current] Res.reverse() return Res def dijkstra(start,end,graph): Q=Queue() for vert in graph: vert.setd(99999) start.setd(0) for vert in graph: Q.put(vert) print("Queue initialization as follow :") showQ(Q) S={} #dictionnary {vertex obtaines by : ..., } #while Q.empty()==False: for q_vertex in Q.queue: min_d_vertex=min_d(Q) print("\nWe work on the vertex :") print(min_d_vertex) if (q_vertex!=end): for v,length in min_d_vertex.adjacent.items(): #(vertex,length) if (length+min_d_vertex.d<v.d): S[v.name]=min_d_vertex.name v.d=min(length+min_d_vertex.d,v.d) Q=modifyQ(Q,min_d_vertex) showQ(Q) print("\nSmallest weight :"+str(end.d)) print("\nAll the movements :") showS(S) print("\nThe shortest path is :") print(findPath(S,start,end)) vert_H=vertex('H',None) vert_G=vertex('G',{vert_H:2}) vert_E=vertex('E',{vert_H:4}) vert_D=vertex('D',{vert_G:2, vert_E:4}) vert_F=vertex('F',{vert_H:7,vert_G:4,vert_D:1}) vert_C=vertex('C',{vert_D:3}) vert_B=vertex('B',{vert_F:4,vert_C:2}) vert_A=vertex('A',{vert_B:2,vert_C:5}) graph=[vert_A,vert_B,vert_C,vert_D,vert_E,vert_F,vert_G,vert_H] dijkstra(vert_A,vert_H,graph)
1aa6ba8516a4e996c07028bc798bdb13064add85
jaeyun95/Algorithm
/code/day05.py
431
4.1875
4
#(5) day05 재귀를 사용한 리스트의 합 def recursive(numbers): print("===================") print('receive : ',numbers) if len(numbers)<2: print('end!!') return numbers.pop() else: pop_num = numbers.pop() print('pop num is : ',pop_num) print('rest list is : ',numbers) sum = pop_num + recursive(numbers) print('sum is : ',sum) return sum
a76ed6a1b76c2f0771acb387e63bcafb86b73b96
jaeyun95/Algorithm
/code/day06.py
398
3.640625
4
#(6) day06 가장 많이 등장하는 알파벳 개수 구하기 def counter(word): counter_dic = {} for alphabet in word: if counter_dic.get(alphabet) == None: counter_dic[alphabet] = 1 else: counter_dic[alphabet] += 1 max = -1 for key in counter_dic: if counter_dic[key] > max: max = counter_dic[key] return max
1786d5bd32505970f897ff9691259f3a1cc785a7
phypm/Pedro_Motta
/Ex8_maiornota.py
791
3.765625
4
import sys i=0 nota=0 boletim=[] while True: try: a = int (raw_input("Digite a nota do Aluno ")) while a >= 0: boletim.append(a) i += 1 nota = a + nota print "Nota total e: ", nota a = int (raw_input("Digite a nota do Aluno ")) else: media = nota/i maior=0 j=0 print "O boletim e: ",boletim for x in boletim: if x>j: j=x print "A maior nota e :", j print print "O valor da media e: ", media break except: print "Nao foi um numero valido" #Nota: 0.8 #Comentario: media eh um valor float e nao um inteiro. Para que serve a variavel "maior?"
4b8c656ea711a2274df26c044ec6a7d7ce7b33bc
bojanuljarevic/Algorithms
/BST/bin_tree/bst.py
1,621
4.15625
4
# Zadatak 1 : ručno formiranje binarnog stabla pretrage class Node: """ Tree node: left child, right child and data """ def __init__(self, p = None, l = None, r = None, d = None): """ Node constructor @param A node data object """ self.parent = p self.left = l self.right = r self.data = d def addLeft(self, data): child = Node(self, None, None, data) self.left = child return child def addRight(self, data): child = Node(self, None, None, data) self.right = child return child def printNode(self): print(self.data.a1, self.data.a2) '''if(self.left != None): print("Has left child") else: print("Does not have left child") if (self.right != None): print("Has right child") else: print("Does not have right child")''' class Data: """ Tree data: Any object which is used as a tree node data """ def __init__(self, val1, val2): """ Data constructor @param A list of values assigned to object's attributes """ self.a1 = val1 self.a2 = val2 if __name__ == "__main__": root_data = Data(48, chr(48)) left_data = Data(49, chr(49)) right_data = Data(50, chr(50)) root = Node(None, None, None, root_data) left_child = root.addLeft(left_data) right_child = root.addRight(right_data) root.printNode() left_child.printNode() right_child.printNode() left_child.parent.printNode()
99421729232987d7fe4d317883032134d21d07b3
bojanuljarevic/Algorithms
/sorting/quicksort.py
1,342
3.75
4
#!/usr/bin/python import random import time def random_list (min, max, elements): list = random.sample(range(min, max), elements) return list def partition(A, p, r): x = A[r] i = p - 1 for j in range(p, r): if A[j] <= x: i = i + 1 A[i], A[j] = A[j], A[i] A[i+1], A[r] = A[r], A[i+1] return i+1 def randomized_partition(A, p, r): i = random.randint(p, r) A[r], A[i] = A[i], A[r] return partition(A, p, r) def randomized_quicksort(A, p, r): if p < r: q = randomized_partition(A, p, r) randomized_quicksort(A, p, q-1) randomized_quicksort(A, q+1, r) l = random_list(0, 100, 100) t1 = time.clock() randomized_quicksort(l, 0, len(l)-1) t2 = time.clock() print("QUICK(100): ", t2 - t1) l = random_list(0, 1000, 1000) t1 = time.clock() randomized_quicksort(l, 0, len(l)-1) t2 = time.clock() print("QUICK(1K): ", t2 - t1) l = random_list(0, 10000, 10000) t1 = time.clock() randomized_quicksort(l, 0, len(l)-1) t2 = time.clock() print("QUICK(10K): ", t2 - t1) l = random_list(0, 100000, 100000) t1 = time.clock() randomized_quicksort(l, 0, len(l)-1) t2 = time.clock() print("QUICK(100K): ", t2 - t1) l = random_list(0, 1000000, 1000000) t1 = time.clock() randomized_quicksort(l, 0, len(l)-1) t2 = time.clock() print("QUICK(1M): ", t2 - t1)
6157e34614e49830e4899261da0db857eac845f2
ZhaoHuiXin/MachineLearningFolder
/Part 2 - Regression/Section 4 - Simple Linear Regression/simple_linear_regression_practice2.py
764
3.53125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jun 12 17:29:51 2019 @author: zhx """ import pandas as pd import numpy as np import matplotlib.pyplot as plt dataset = pd.read_csv('Salary_Data.csv') X = dataset.iloc[:,0:1].values y = dataset.iloc[:,1].values from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0) from sklearn.linear_model import LinearRegression regressor = LinearRegression() regressor.fit(X_train, y_train) y_pred = regressor.predict(X_test) # plot plt.scatter(X_test, y_test, color='red') plt.plot(X_test, regressor.predict(X_test), color='green') plt.title('SimpleLinearRegression') plt.xlabel('age') plt.ylabel('salary') plt.show()
9956ac773c8fc68668abb55eb445a6be2b3aea4f
kalewford/Python-
/Bank/main(submission).py
2,516
4
4
# Dependencies import csv import os # Files to Load file_to_load = "Bank/budget_data.csv" file_to_output = "Bank/budget_analysis.txt" # Variables to Track total_months = 0 total_revenue = 0 prev_revenue = 0 revenue_change = 0 great_date = "" great_increase = 0 bad_date = "" worst_decrease = 0 revenue_changes = [] # Read Files with open(file_to_load) as budget_data: reader = csv.DictReader(budget_data) # Loop through all the rows of data we collect for row in reader: # Calculate the totals total_months = total_months + 1 total_revenue = total_revenue + int(row[1]) # print(row) # Keep track of changes revenue_change = int(row[1]) - prev_revenue # print(revenue_change) # Reset the value of prev_revenue to the row I completed my analysis prev_revenue = int(row[1]) # print(prev_revenue) # Determine the greatest increase if (int(row[1]) > great_increase): great_increase = int(row[1]) great_date = row[0] if (int(row[1]) < worst_decrease): worst_decrease = int(row[1]) bad_date = row[0] # Add to the revenue_changes list revenue_changes.append(int(row[1])) # Set the Revenue average revenue_avg = sum(revenue_changes) / len(revenue_changes) # Show Output print() print() print() print("Financial Analysis") print("-------------------------") print("Total Months: " + str(total_months)) print("Total Revenue: " + "$" + str(total_revenue)) print("Average Change: " + "$" + str(round(sum(revenue_changes) / len(revenue_changes),2))) print("Greatest Increase: " + str(great_date) + " ($" + str(great_increase) + ")") print("Greatest Decrease: " + str(bad_date) + " ($" + str(worst_decrease) + ")") # Output Files with open(file_to_output, "w") as txt_file: txt_file.write("Total Months: " + str(total_months)) txt_file.write("\n") txt_file.write("Total Revenue: " + "$" + str(total_revenue)) txt_file.write("\n") txt_file.write("Average Change: " + "$" + str(round(sum(revenue_changes) / len(revenue_changes),2))) txt_file.write("\n") txt_file.write("Greatest Increase: " + str(great_date) + " ($" + str(great_increase) + ")") txt_file.write("\n") txt_file.write("Greatest Decrease: " + str(bad_date) + " ($" + str(worst_decrease) + ")")
5f5e0b19e8b1b6d0b0142eb63621070a50227142
steven-liu/snippets
/generate_word_variations.py
1,109
4.125
4
import itertools def generate_variations(template_str, replace_with_chars): """Generate variations of a string with certain characters substituted. All instances of the '*' character in the template_str parameter are substituted by characters from the replace_with_chars string. This function generates the entire set of possible permutations.""" count = template_str.count('*') _template_str = template_str.replace('*', '{}') variations = [] for element in itertools.product(*itertools.repeat(list(replace_with_chars), count)): variations.append(_template_str.format(*element)) return variations if __name__ == '__main__': # use this set to test REPLACE_CHARS = '!@#$%^&*' # excuse the bad language... a = generate_variations('sh*t', REPLACE_CHARS) b = generate_variations('s**t', REPLACE_CHARS) c = generate_variations('s***', REPLACE_CHARS) d = generate_variations('f*ck', REPLACE_CHARS) e = generate_variations('f**k', REPLACE_CHARS) f = generate_variations('f***', REPLACE_CHARS) print list(set(a+b+c+d+e+f))
14deebd3730600c4c34d2ef5ae3cd3f110dcaf0c
SharanSMenon/Sharan-Main
/guessTheNumber.py
484
3.828125
4
import random while True: n = random.randint(0,100) count = 0 while True: guess = int(input('Guess a number between 1 and 100:')) if guess == n: print("You win") count += 1 print("You tried "+str(count)+" times.") play_again = input('Do you want to play again?') if play_again == 'no': print('Bye') quit() else: break elif guess > n: print('Try a smaller number') count += 1 elif guess < n: print('Try a larger number') count += 1
f84682bb7f6a6df4644cff27e69d48cf0b1a6fc2
cdanh-aptech/Python-Learning
/PTB2.py
787
3.5
4
import math def main(): print("Giai Phuong Trinh Bac 2 (ax2 + bx + c = 0)") hs_a = int(input("Nhap he so a: ")) hs_b = int(input("Nhap he so b: ")) hs_c = int(input("Nhap he so c: ")) giaiPT(hs_a, hs_b, hs_c) def giaiPT(a, b, c): if a == 0: print(f"La phuong trinh bac 1, x = {-c/b}") else: delta = b*b - (4 * a * c) if delta < 0: print("Phuong trinh vo nghiem") elif delta == 0: x = -b / 2*a print(f"Phuong trinh co nghiem kep x1 = x2 = {x}") else: x1 = -b + math.sqrt(delta) x2 = -b - math.sqrt(delta) print("Phuong trinh co 2 nghiem") print(f"x1 = {x1}") print(f"x2 = {x2}") if __name__ == "__main__": main()
dbc393cb1fe09bc5cb54992be1294e154cf023a1
KuleshovaY/Python_GB
/Lesson_3/task_3.5.py
1,594
3.875
4
# Программа запрашивает у пользователя строку чисел, разделенных пробелом. # При нажатии Enter должна выводиться сумма чисел. # Пользователь может продолжить ввод чисел, разделенных пробелом и снова нажать Enter. # Сумма вновь введенных чисел будет добавляться к уже подсчитанной сумме. # Но если вместо числа вводится специальный символ, выполнение программы завершается. # Если специальный символ введен после нескольких чисел, # то вначале нужно добавить сумму этих чисел к полученной ранее сумме и после этого завершить программу. def str_numbers(): sum_result = 0 ex = False while ex == False: numbers = (input('Введите несколько чисел через пробел или E для выхода: ')).split() result = 0 for el in range(len(numbers)): if numbers[el] == 'E': ex = True break else: result = result +int(numbers[el]) sum_result = sum_result + result print(f'Текущий результат {sum_result}') print(f'Финальный результат {sum_result}') str_numbers() str_numbers()
c1bdaf6db92db9e09dce8e58127041436842b4ce
KuleshovaY/Python_GB
/Lesson_2/task _2.6.py
951
3.6875
4
i = 1 goods = [] n = int(input('Сколько товаров хотите ввести? ')) for _ in range(n): name = input('Введите название товара ') price = int(input('Введите цену ')) quantity = int(input('Введите колличество ')) measure = input('введите единицы измерения ') goods.append((i, {'название': name, 'цена': price, 'количество': quantity, 'ед': measure})) i += 1 print(goods) goods_dict = {'название': [], 'цена': [], 'количество': [], 'ед': []} for good in goods: goods_dict['название'].append(good[1]['название']) goods_dict['цена'].append(good[1]['цена']) goods_dict['количество'].append(good[1]['количество']) if good[1]['ед'] not in goods_dict['ед']: goods_dict['ед'].append(good[1]['ед']) print(goods_dict)
a0e648ea664458c9752d4013b8b91b6cee690dfa
jackjyq/COMP9021_Python
/ass01/highest_scoring_words/highest_scoring_words.py
5,438
3.859375
4
# Author: Jack (z5129432) for COMP9021 Assignment 1 # Date: 25/08/2017 # Description: Qustion 3 from itertools import permutations from collections import defaultdict import sys # Function: CombineLetters # Dependency: itertools.permutations # Input: a list such as ['a', 'b', 'c'] # Output: a set such as {'ab', 'bac', 'b', 'c', 'acb', 'ca', 'bc', 'cb', 'cba', 'ba', 'bca', 'ac', 'cab', 'abc', 'a'} # Description: def CombineLetters(letters, word_dictionary): letters_combination = set() for word_length in range (1, len(letters) + 1): # generate different word length letters_combination |= set(''.join(e) for e in permutations(letters, word_length)) & word_dictionary # union all permutation() return(letters_combination) # Function: FindHighestScoreWords # Dependency: ScoreWord # Input: an unsorted dictionary contains words, such as {8: [['oui'], ['iou']], 2: [['a'], ['ie']], 7: [['eau']], 3: [['ai']]} # Output: search in the input set. return an integer (highest score), such as 8 # followed by a list (highest score words) orderd alphabetaly, such as [['iou'], ['oui']] # Description: def FindHighestScoreWords(scored_word_set): if len(scored_word_set) != 0: highest_score = sorted(scored_word_set.keys())[len(scored_word_set) - 1] highest_score_words = sorted(scored_word_set[highest_score]) else: highest_score = 0 highest_score_words = [] return highest_score, highest_score_words # Function: GenerateDict.py # Dependency: # Input: a string such as "wordsEn.txt" # Output: a set of the words in the dictionary such as {'backup', 'way', 'rink'} # Description: def GenerateDict(file_name): word_dictionary = set() with open("wordsEn.txt") as book: for line in book: word_dictionary.add(line.strip()) return(word_dictionary) # Function: ScoreLetter # Dependency: # Input: a letter 'i' # Output: an integer(score of letter) # Description: def ScoreLetter(letter): magic_book = { 'a': 2, 'b': 5, 'c': 4, 'd': 4, 'e': 1, 'f': 6, \ 'g': 5, 'h': 5, 'i': 1, 'j': 7, 'k': 6, 'l': 3, \ 'm': 5, 'n': 2, 'o': 3, 'p': 5, 'q': 7, 'r': 2, \ 's': 1, 't': 2, 'u': 4, 'v': 6, 'w': 6, 'x': 7, \ 'y': 5, 'z': 7 } return(magic_book[letter]) # Function: ScoreWord # Dependency: ScoreLetter # Input: a string 'iou' # Output: an integer (score) such as 8 for 'iou' # Description: def ScoreWord(word): score = int(0) for letter in word: score += ScoreLetter(letter) return(score) # Function: ScoreWordSet # Dependency: ScoreWord, collections.defaultdict # Input: a set contains words, such as {'eau', 'iou', 'a', 'oui', 'ie', 'ai'} # Output: an unsorted dictionary contains words, such as {8: [['oui'], ['iou']], 2: [['a'], ['ie']], 7: [['eau']], 3: [['ai']]} # Description: def ScoreWordSet(word_set): scored_word_set = defaultdict(list) word_set = list(word_set) for word in word_set: scored_word_set[ScoreWord(word)].append([word]) return(scored_word_set) # Function: UserInput Version: 01 # Dependency: sys.exit # Input: 3 ~ 10 lowercase letters from user # Output: a list ['a', 'e', 'i', 'o', 'u'] # Description: def UserInput(): converted_letters = [] try: input_letters = input('Enter between 3 and 10 lowercase letters: ').replace(" ", "") if len(input_letters) < 3 or len(input_letters) > 10: raise ValueError for e in input_letters: if e.islower(): converted_letters.append(e) else: raise ValueError except ValueError: print('Incorrect input, giving up...') sys.exit() return(converted_letters) # Function: UserOutput Version: 01 # Dependency: sys.exit # Input: an integer (highest score), such as 8 # followed by a list (highest score words) orderd alphabetaly, such as [['iou'], ['oui']] # Output: print # Description: def UserOutput(highest_score, highest_score_words): if len(highest_score_words) == 0: print('No word is built from some of those letters.') elif len(highest_score_words) == 1: print(f'The highest score is {highest_score}.') print(f'The highest scoring word is {highest_score_words[0][0]}') else: print(f'The highest score is {highest_score}.') print('The highest scoring words are, in alphabetical order:') for the_words in highest_score_words: print(f' {the_words[0]}') return ##### main function debug_mode = 0 # toggle debug_mode, print output of every functions input_letters = UserInput() if debug_mode == 1: print('input_letters =', input_letters) word_dictionary = GenerateDict("wordsEn.txt") if debug_mode == 3: print('word_dictionary =', word_dictionary) letters_combination = CombineLetters(input_letters, word_dictionary) if debug_mode == 2: print('letters_combination =', letters_combination) scored_word_set = ScoreWordSet(letters_combination) if debug_mode == 5: print('scored_word_set =', scored_word_set) highest_score, highest_score_words = FindHighestScoreWords(scored_word_set) if debug_mode == 6: print('scored_word_set =', scored_word_set) print(highest_score) print(highest_score_words) UserOutput(highest_score, highest_score_words)
7b8489895a95d9870f1caff4edf870e1e496da11
jackjyq/COMP9021_Python
/ass01/highest_scoring_words/Permutations.py
406
3.765625
4
# Function: Permutations # Dependency: # Input: list such as ['e', 'a', 'e', 'o', 'r', 't', 's', 'm', 'n', 'z'], and a integer such as 10 # Output: set of permutations of your input # Description: def Permutations(input_list, number): return # Test Codes if __name__ == "__main__": Letters = ['e', 'a', 'e', 'o', 'r', 't', 's', 'm', 'n', 'z'] number = 10 Permutations(Letters, number)
54f286be437cb160aa7c49f4e9630d1a5072a8ce
jackjyq/COMP9021_Python
/quiz04/sort_ratio.py
1,049
3.546875
4
from get_valid_data import get_valid_data from get_ratio import get_ratio from get_top_n_countries import get_top_n_countries def sort_ratio(courtry_with_ratio): """ sort_ratio Arguements: an unsorted list[(ratio1, country1), (ratio2, country2), (ratio3, country3) ...] Returns: A list sorted by ratio. If two countries have same ratio, then sort by countries' name. Such as: [[ratio1, country1], [ratio2, country2], [ratio3, country3] ...] """ counry_sorted_by_ratio = sorted(courtry_with_ratio, key=lambda tup: (-tup[0], tup[1])) return counry_sorted_by_ratio # Test Codes if __name__ == "__main__": agricultural_land_filename = 'API_AG.LND.AGRI.K2_DS2_en_csv_v2.csv' forest_filename = 'API_AG.LND.FRST.K2_DS2_en_csv_v2.csv' year_1 = 1992 year_2 = 1999 agricultural = get_valid_data(agricultural_land_filename, year_1, year_2) forest = get_valid_data(forest_filename, year_1, year_2) country_with_ratio = get_ratio(agricultural, forest) print(sort_ratio(country_with_ratio))
2514877d40f20ee981d6cb981cdf0b0dd92b263d
jackjyq/COMP9021_Python
/ass01/pivoting_die/pivoting_die.py
2,703
3.984375
4
# Author: Jack (z5129432) for COMP9021 Assignment 1 # Date: 23/08/2017 # Description: ''' ''' import sys # function: move # input: null # output: die[] after moved def move_right(): die_copy = die[:] die[3] = die_copy[2] # right become bottom die[2] = die_copy[0] # top become right die[0] = die_copy[5] # left become top die[5] = die_copy[3] # bottom become left return def move_left(): die_copy = die[:] die[0] = die_copy[2] # right become top die[5] = die_copy[0] # top become left die[3] = die_copy[5] # left become bottom die[2] = die_copy[3] # bottom become right return def move_forewards(): die_copy = die[:] die[1] = die_copy[0] # top become front die[3] = die_copy[1] # front become bottom die[4] = die_copy[3] # bottom become back die[0] = die_copy[4] # back become top return def move_backwards(): die_copy = die[:] die[4] = die_copy[0] # top become back die[0] = die_copy[1] # front become top die[1] = die_copy[3] # bottom become front die[3] = die_copy[4] # back become bottom return # user interface: input part while True: try: cell = int(input('Enter the desired goal cell number: ')) if cell <= 0: raise ValueError break except ValueError: print('Incorrect value, try again') # initialize die[] # top front right bottom back left # 0 1 2 3 4 5 die = [3, 2, 1, 4, 5, 6] # initialize moving step in one direction step = 1 # initialize counter i = cell # simulate moving die # function: move # input: null # output: die[] after moved while(i > 1): for _ in range(0, step): # moving right for "step" steps move_right() i -= 1 if i <= 1: break if i <= 1: break for _ in range(0, step): # moving forewards for "step" steps move_forewards() i -= 1 if i <= 1: break if i <= 1: break step += 1 # increase step by 1 for _ in range(0, step): # moving left for "step" steps move_left() i -= 1 if i <= 1: break if i <= 1: break for _ in range(0, step): # moving backwards for "step" steps move_backwards() i -= 1 if i <= 1: break step += 1 # increase step by 1 # user interface: output part print(f'On cell {cell}, {die[0]} is at the top, {die[1]} at the front, and {die[2]} on the right.')
a4d065a288fb455ede7cf37fc3e4b4d3eabf6c9f
jackjyq/COMP9021_Python
/ass01/poker_dice/roll_dice.py
571
4.03125
4
from random import randint from random import seed def roll_dice(kept_dice=[]): """ function Use to generate randonly roll, presented by digits. Arguements: a list of kept_dice, such as [1, 2] default argument if [] Returns: a list of ordered roll, such as [1, 2, 3, 4, 5]. Dependency: random.randint """ roll = [randint(0, 5) for _ in range(5 - len(kept_dice))] roll.extend(kept_dice) roll.sort() return roll # Test Codes if __name__ == "__main__": kept_dice = [1, 2] seed() print(roll_dice(kept_dice))
cc3a1d58b9a459e87baba1db1667b8c3eafaed7a
jackjyq/COMP9021_Python
/ass01/poker_dice/hand_rank.py
1,577
4.21875
4
def hand_rank(roll): """ hand_rank Arguements: a list of roll, such as [1, 2, 3, 4, 5] Returns: a string, such as 'Straight' """ number_of_a_kind = [roll.count(_) for _ in range(6)] number_of_a_kind.sort() if number_of_a_kind == [0, 0, 0, 0, 0, 5]: roll_hand = 'Five of a kind' elif number_of_a_kind == [0, 0, 0, 0, 1, 4]: roll_hand = 'Four of a kind' elif number_of_a_kind == [0, 0, 0, 0, 2, 3]: roll_hand = 'Full house' elif number_of_a_kind == [0, 0, 0, 1, 1, 3]: roll_hand = 'Three of a kind' elif number_of_a_kind == [0, 0, 0, 1, 2, 2]: roll_hand = 'Two pair' elif number_of_a_kind == [0, 0, 1, 1, 1, 2]: roll_hand = 'One pair' elif number_of_a_kind == [0, 1, 1, 1, 1, 1]: if (roll == [0, 2, 3, 4, 5] or roll == [0, 1, 3, 4, 5] or roll == [0, 1, 2, 4, 5] or roll == [0, 1, 2, 3, 5]): # According to https://en.wikipedia.org/wiki/Poker_dice, # there are only four possible Bust hands roll_hand = 'Bust' else: roll_hand = 'Straight' return roll_hand # Test Codes if __name__ == "__main__": roll = [1, 1, 1, 1, 1] print(hand_rank(roll)) roll = [1, 1, 1, 1, 2] print(hand_rank(roll)) roll = [1, 1, 1, 3, 3] print(hand_rank(roll)) roll = [1, 1, 1, 2, 3] print(hand_rank(roll)) roll = [1, 1, 2, 2, 3] print(hand_rank(roll)) roll = [0, 2, 3, 4, 5] print(hand_rank(roll)) roll = [1, 2, 3, 4, 5] print(hand_rank(roll))
c889b0c75a22a5de5204de652db5adc535c8d190
eunic/bootcamp-final-files
/wordcount.py
495
3.65625
4
def words(stringofwords): dict_of_words = {} list_of_words = stringofwords.split() for word in list_of_words: if word in dict_of_words: if word.isdigit(): dict_of_words[int(word)] += 1 else: dict_of_words[word] += 1 else: if word.isdigit(): dict_of_words[int(word)] = 1 else: dict_of_words[word] = 1 return dict_of_words
dd79781c62f4547d9d74d2ac395464642b02ec89
mtasende/usd-uyu-dashboard
/src/data/world_bank.py
3,125
4.0625
4
""" Functions to access the World Bank Data API. """ import requests from collections import defaultdict import pandas as pd def download_index(country_code, index_code, start_date=1960, end_date=2018): """ Get a JSON response for the index data of one country. Args: country_code(str): The two letter code for the World Bank webpage index_code(str): The code for the index to retreive start_date(int): The initial year to retreive end_date(int): The final year to retreive Returns: str: a JSON string with the raw data """ payload = {'format': 'json', 'per_page': '500', 'date': '{}:{}'.format(str(start_date), str(end_date)) } r = requests.get( 'http://api.worldbank.org/v2/countries/{}/indicators/{}'.format( country_code, index_code), params=payload) return r.json() def format_response(raw_res): """ Formats a raw JSON string, returned from the World Bank API into a pandas DataFrame. """ result = defaultdict(dict) for record in raw_res[1]: result[record['country']['value']].update( {int(record['date']): record['value']}) return pd.DataFrame(result) def download_cpi(country_code, **kwargs): """ Downloads the Consumer Price Index for one country, and returns the data as a pandas DataFrame. Args: country_code(str): The two letter code for the World Bank webpage **kwargs: Arguments for 'download_index', for example: start_date(int): The initial year to retreive end_date(int): The final year to retreive """ cpi_code = 'FP.CPI.TOTL' raw_res = download_index(country_code, cpi_code, **kwargs) return format_response(raw_res) def download_cpis(country_codes, **kwargs): """ Download many countries CPIs and store them in a pandas DataFrame. Args: country_codes(list(str)): A list with the two letter country codes **kwargs: Other keyword arguments, such as: start_date(int): The initial year to retreive end_date(int): The final year to retreive Returns: pd.DataFrame: A dataframe with the CPIs for all the countries in the input list. """ cpi_list = [download_cpi(code, **kwargs) for code in country_codes] return pd.concat(cpi_list, axis=1) def download_exchange_rate(country_code, **kwargs): """ Downloads the Exchange for one country, with respect to USD, and returns the data as a pandas DataFrame. Args: country_code(str): The two letter code for the World Bank webpage **kwargs: Arguments for 'download_index', for example: start_date(int): The initial year to retreive end_date(int): The final year to retreive Returns: pd.DataFrame: The values for the exchange rates in a dataframe. """ cpi_code = 'PA.NUS.FCRF' raw_res = download_index(country_code, cpi_code, **kwargs) return format_response(raw_res)
00fd9d33ece481fe3d2e98eaca624aeb2e595b1c
YuvalHelman/adventofcode2020
/adventOfCode/day2.py
1,368
3.5625
4
from pathlib import Path from typing import Callable from itertools import filterfalse import re FILE_PATTERN = re.compile(r"(?P<min>[0-9]+)-(?P<max>[0-9]+)\s*(?P<letter_rule>[A-Za-z]):\s*(?P<password>[A-Za-z]+)") INPUT_PATH = Path("inputs/day2_1.txt") def is_count_of_char_in_sentence(char: str, sentence: str, min: int, max: int) -> bool: counter = len(list(filterfalse(lambda x: x is not char, sentence))) return min <= counter <= max def day2(checker: Callable[..., bool]) -> int: counter = 0 with open(INPUT_PATH) as fp: for line in fp: line = line.strip("\n") m = re.search(FILE_PATTERN, line) if m: if checker(m.group("letter_rule"), m.group("password"), int(m.group("min")), int(m.group("max"))): counter += 1 print(line) print(len(m.group("password"))) return counter def are_positions_valid(char: str, sentence: str, min: int, max: int) -> bool: counter = 0 if len(sentence) >= min and sentence[min - 1] == char: counter += 1 if len(sentence) >= max and sentence[max - 1] == char: counter += 1 return counter == 1 if __name__ == "__main__": print("ex1 res: ", day2(is_count_of_char_in_sentence)) print("ex2 res: ", day2(are_positions_valid))
c758312e57e9cbab57c6a448cb7cfb90331ebbad
tskkst51/lplTrade
/PTP/trading_platform_shell/string_parsers.py
2,493
3.59375
4
# # # def string_to_value(s): s = s.strip().lower() if s[-1] == 'k': try: value = float(s[:-1]) return value * 1000.0 except ValueError: return None try: value = float(s) return value except ValueError: pass try: return float(eval(s)) except Exception: pass return None # # # def string_to_price(s): s = s.strip() if s == '' or s == 'm': return 'MEAN_PRICE' if s == 'M': return 'MARKET_PRICE' if s.upper() == 'MARKET_PRICE': return 'MARKET_PRICE' try: num = float(s) return round(num, 2) except ValueError: return None # # # def string_to_relative(s): if s[-1] != '%': return None try: margin = float(s[:-1]) except ValueError: return None return margin / 100.0 # # # def string_to_price_relative(s, symbol, trade, condition='negative'): price = string_to_price(s) if price is not None: return price margin = string_to_relative(s) if margin is None: return None if condition == 'negative': if margin >= 0: print('% must be negative') return None if condition == 'positive': if margin <= 0: print('% must be positive') return None try: price = trade.get_current_price(symbol) except ValueError as e: print(str(e)) return None return round(price * (1.0 + margin), 2) # # # def string_to_int(s): try: num = int(float(s)) return num except ValueError: return None # # # def string_to_session(s): s = s.strip() if s == '' or s == 'R': return 'REGULAR' if s == 'E': return 'EXTENDED' return None # # # def string_to_price_or_quote_price(s, trade): s = s.strip().lower() try: value = float(s) return value, False except ValueError: pass try: return float(eval(s)), False except Exception as _: pass if s[-1] == '%': return None, False try: value = trade.get_current_price(s) return value, True except ValueError as e: print('quote request for ' + s.upper() + ': ' + str(e)) pass return None, False
903ba4783c8c4e7af8d4087dfab2759cd3579919
mailtsjp/FinPy
/Filetoticker.py
1,825
3.5625
4
import pandas_datareader.data as web import datetime #read ticker symbols from a file to python symbol list symbol = [] with open('tickers.txt') as f: for line in f: symbol.append(line.strip()) f.close #datetime is a Python module #datetime.datetime is a data type within the datetime module #which allows access to Gregorian dates and today function #datetime.date is another data type within the datetime module #which permits arithmetic with Gregorian date components #definition of end with datetime.datetime type must precede #definition of start with datetime.date type #the start expression collects data that are up to five years old end = datetime.datetime.today() start = datetime.date(end.year-5,1,1) #set path for csv file path_out = 'c:/python_programs_output/' #loop through 50 tickers in symbol list with i values of 0 through 49 #if no historical data returned on any pass, try to get the ticker data again #for first ticker symbol write a fresh copy of csv file for historical data #on remaining ticker symbols append historical data to the file written for #the first ticker symbol and do not include a header row i=0 while i<len(symbol): try: df = web.DataReader(symbol[i], 'yahoo', start, end) df.insert(0,'Symbol',symbol[i]) df = df.drop(['Adj Close'], axis=1) if i == 0: df.to_csv(path_out+'yahoo_prices_volumes_for_ST_50_to_csv_demo.csv') print (i, symbol[i],'has data stored to csv file') else: df.to_csv(path_out+'yahoo_prices_volumes_for_ST_50_to_csv_demo.csv',mode = 'a',header=False) print (i, symbol[i],'has data stored to csv file') except: print("No information for ticker # and symbol:") print (i,symbol[i]) continue i=i+1
0cadee6937b8b5954877cfd8de03660fa983407f
Miguel-21904220/pw_python_03
/pw-python-03/Exercisio 1/analisa_ficheiro/acessorio.py
369
3.625
4
import os def pede_nome(): while True: try: nome_ficheiro = input("Introduza o numero do ficheiro: ") with open('analisa_ficheiro/' + nome_ficheiro, 'r') as file: return nome_ficheiro except: print("Nao existe") def gera_nome(x): return os.path.splitext(x)[0] + ".json"
007ef0564c214ab11f0b9ef081cb08c0b2315029
cassiano-r/Spark
/MapReduceSparkHadoopProject/gastos-cliente.py
787
3.65625
4
from pyspark import SparkConf, SparkContext # Define o Spark Context, pois o job será executado via linha de comando com o spark-submit conf = SparkConf().setMaster("local").setAppName("GastosPorCliente") sc = SparkContext(conf = conf) # Função de mapeamento que separa cada um dos campos no dataset def MapCliente(line): campos = line.split(',') return (int(campos[0]), float(campos[2])) # Leitura do dataset a partir do HDFS input = sc.textFile("hdfs://clientes/gastos-cliente.csv") mappedInput = input.map(MapCliente) # Operação de redução por chave para calcular o total gasto por cliente totalPorCliente = mappedInput.reduceByKey(lambda x, y: x + y) # Imprime o resultado resultados = totalPorCliente.collect(); for resultado in resultados: print(resultado)
cb7c7e5bdfd3b741a4b3a77d7264736ec61e184f
joker507/exercise
/UA.py
1,229
3.71875
4
#用于求大学物理实验中的A类不确定度和平均值,今后将考虑自动取好不确定度的有效数字和求解b类不确定度并取相应的有效数字并计算总不确定度,但现实践有限,不做实现 #physics average,求平均值 def phsaver(a): m = len(a) aver = [] for i in range(m): sum = 0 for num in a[i]: sum = sum + num aver.append(sum/len(a[i])) return aver #physics undecided 求A类不确定度 def phsunde(a): m = len(a) ud = [] for i in range(m): ud.append(0) for j in range(m): ave = phsaver(a)[j] sum = 0 dim = len(a[j]) for num in a[j]: sum = sum + (num - ave)**2 unde = (sum/(dim*(dim - 1)))**0.5 print ("第",j+1,"行的平均值为:",ave) print ("第",j+1,"行的A类不确定度为:",unde) return ud if __name__ == "__main__": try: while 1: a = input('请输入要计算的表格,同行用,(英文逗号)分隔,换行用;(英文分号)分隔:\n') a = a.split(";") s = len(a) for i in range(s): a[i] = a[i].split(',') n = len(a[i]) for j in range(n): a[i][j] = eval(a[i][j]) phsunde(a) key = input("是否继续计算(y/n)") if key == 'n': break except: print("输入错误")
e0408bdb6b3251bf3472b3a3836ad7ec8ec0ed4d
madhurigorthi/sdet-1
/python/Activity3.py
537
3.859375
4
input1=input("Enter player1 input :").lower() input2=input("Enter player2 input :").lower() if input1 == input2: print("Its tie !!") elif input1 == 'rock': if input2 == 'scissors': print("player 1 wins") else: print("player 2 wins") elif input1 == 'scissors': if input2 == 'rock': print("player 1 wins") else: print("player 2 wins") elif input1 == 'paper': if input2 == 'scissors': print("player 2 wins") else: print("player 1 wins")
54893e3be825167355e17ed579f00053945d924a
madhurigorthi/sdet-1
/python/Acitvity1.py
161
3.921875
4
name=input("Enter your name ") age=int(input("Enter your age ")) year=str((2020-age)+100) print(name + " you will become 100 years old in the year " + year)
ddc9a3d2c6c1933dc8a404084ee9afc146a3cfae
wojciechuszko/random_Fibonacci_sequence
/random_fibonacci_sequence.py
769
3.546875
4
import numpy as np import matplotlib.pyplot as plt n = int(input("Enter a positive integer n: ")) vector = np.zeros(n) vector[0] = 1 vector[1] = 1 for i in range(2,n): rand = np.random.rand() if rand < 0.5: sign = -1 else: sign = 1 vector[i] = vector[i-1] + sign * vector[i-2] x = np.linspace(1,n,n) v = 1.132*np.ones(n) plt.figure() plt.subplot(1, 2, 1) plt.plot(x, np.absolute(vector), 'k-', label='|random f_n|') plt.plot(x, 1.132**x, 'k--', label='1.132^n') plt.yscale("log") plt.xlabel("n") plt.legend(loc='upper left') plt.subplot(1, 2, 2) plt.plot(x, np.absolute(vector)**(1/x), 'k-', label='|random f_n| ^ 1/n') plt.plot(x, v, 'k--', label='1.132') plt.ylim(1,1.3) plt.xlabel("n") plt.legend(loc='upper left') plt.show()
7947bfed24a33be65cecd3bca43eba6d76adf3eb
dkout/6.006
/pset3/code_template_and_latex_template/search_template.py
3,381
3.875
4
################################### ########## PROBLEM 3-4 ########### ################################### from rolling_hash import rolling_hash def roll_forward(rolling_hash_obj, next_letter): """ "Roll the hash forward" by discarding the oldest input character and appending next_letter to the input. Return the new hash, and save it in rolling_hash_obj.hash_val as well Parameters ---------- rolling_hash_obj : rolling_hash Instance of rolling_hash next_letter : char New letter to append to input. Returns ------- hsh : int Hash of updated input. """ #print('Next Letter: ', next_letter) #print (rolling_hash_obj.alphabet_map) # Pop a letter from the left and get the mapped value of the popped letter # YOUR CODE HERE last_char=rolling_hash_obj.sliding_window.popleft() popval=rolling_hash_obj.alphabet_map[last_char] #print ('last character: ', rolling_hash_obj.sliding_window.popleft()) #print ('last char value: ', popval) #print('old hash value = ', rolling_hash_obj.hash_val) # Push a letter to the right. # YOUR CODE HERE rolling_hash_obj.sliding_window.append(next_letter) # Set the hash_val in the rolling hash object # Hint: rolling_hash_obj.a_to_k_minus_1 may be useful rolling_hash_obj.hash_val = ((rolling_hash_obj.hash_val-popval*rolling_hash_obj.a_to_k_minus_1)*rolling_hash_obj.a + rolling_hash_obj.alphabet_map[next_letter]) % rolling_hash_obj.m #print ('new hash value = ', rolling_hash_obj.hash_val) rolling_hash_obj.roll_history.append(next_letter) # Return. return rolling_hash_obj def exact_search(rolling_hash_obj, pattern, document): """ Search for string pattern in document. Return the position of the first match, or None if no match. Parameters ---------- rolling_hash_obj : rolling_hash Instance of rolling_hash, with parameters guaranteed to be already filled in based on the inputs we will test: the hash length (k) and alphabet (alphabet) are already set You will need to create atleast one additional instance of rolling_hash_obj pattern : str String to search in document. document : str Document to search. Returns ------- pos : int or None (zero-indexed) Position of first approximate match of S in T, or None if no match. """ print (rolling_hash_obj.sliding_window) # may be helpful for you n = len(document) k = len(pattern) ## DO NOT MODIFY ## rolling_hash_obj.set_roll_forward_fn(roll_forward) rolling_hash_obj.init_hash(document[:k]) ## END OF DO NOT MODIFY ## ph=rolling_hash(k,rolling_hash_obj.alphabet) ph.init_hash(pattern) #print ('PATTERN, ', pattern) #print ('DOCUMENT, ', document) for i in range(n-k): #print('pattern hash value, window hash value ', ph.hash_val, rolling_hash_obj.hash_val) #print ("current window ", ''.join(rolling_hash_obj.sliding_window)) nl=document[i+k] #print ("next letter = ", nl) if ph.hash_val==rolling_hash_obj.hash_val: #print('***SAME HASH VALUE***') if pattern==document[i:i+k]: #print("*******MATCHING STRING FOUND******** ", i) return i roll_forward(rolling_hash_obj, nl) return None
30a9dcb344404f005a6f62031701c9b5c856d0fa
Blasius7/Python-homeworks
/guess.py
1,274
3.6875
4
import random attempts = 0 end_num = [5,15,50] while True: difficulty = input("Milyen nehézségi fokon játszanád a játékot? \n (Könnyű, közepes vagy nehéz): \n") if difficulty == "könnyű": end_num = 5 break elif difficulty == "közepes": end_num = 15 break elif difficulty == "nehéz": end_num = 50 break else: print("Nem jó, adj meg egy nehézségi fokozatot!") secret = random.randint(1, end_num) with open("score.txt", "r") as score_file: best_score = int(score_file.read()) print("Top score: " + str(best_score)) while True: guess = int(input("Találd ki a titkos számot 1 és " + str(end_num) + "között ")) attempts += 1 if guess == secret: print("Gratulálok, kitaláltad! Ez a szám: " + str(secret)) print("Kísérletek száma: " + str(attempts)) if best_score > attempts: with open("score.txt", "w") as score_file: score_file.write(str(attempts)) break elif guess > secret: print("Próbáld kisebbel") print("Kísérletek száma: " + str(attempts)) elif guess < secret: print("Próbáld nagyobbal") print("Kísérletek száma: " + str(attempts))
8960e2ef84431879e95ccdaa62d78c55e8b30311
michelle-chiu/Python
/Gauss.py
246
3.984375
4
#Add the numbers from 1 to 100 #Think about what happens to the variables as we go through the loop. total = 0 #will be final total for i in range(101): #i will be 0, 1, 2, 3, 4, 5, etc total = total + i #change total by i print(total)
2e199b2cde6f32ac5008f72558d50c717657146e
hilaryweller0/talks2013
/SS/HilaryNotes/pythonExamples_HW/GaussQuad.py
951
3.59375
4
# Calculate the approximate integral of sin(x) between a and b # using 1-point Gaussiaun quadrature using N intervals # First import all functions from the Numerical Python library import numpy as np # Set integration limits and number of intervals a = 0.0 # a is real, not integer, so dont write a = 0 b = np.pi # pi is from numpy library so prefix with np. N = 40 # N is an integer # from these calculate the interval length dx = (b - a)/N # since a and b are real, dx is real # Initialise the integral I = 0.0 # Sum contribution from each interval (end of loop at end of indentation) for i in xrange(0,N): # : at the beginning of a loop x = a + (i+0.5)*dx I += np.sin(x) # sin is in the numpy library so prefix with np. I *= dx print 'Gaussian quadrature integral = ', I, \ '\nExact integral = ', -np.cos(b)+np.cos(a), \ ' dx = ', dx, ', error = ', I + np.cos(b)-np.cos(a)
805a3bf16a9afccf42a465d3968bb3e2e7365abe
jgkr95/CSPP1
/Practice/M5/p2/square_root.py
348
3.875
4
'''Write a python program to find the square root of the given number using approximation method''' def main(): '''This is main method''' s_r = int(input()) ep_n = 0.01 g_s = 0.0 i_n = 0.1 while abs(g_s**2 - s_r) >= ep_n and g_s <= s_r: g_s += i_n print(g_s) if __name__ == "__main__": main()
0e9d74abf1c2592ec74bdfef35ed89f4cb480f7c
jgkr95/CSPP1
/Practice/M3/compare_AB.py
243
4.03125
4
varA=input("Enter a stirng: ") varB=input("Enter second string: ") if isinstance(varA,str) or isinstance(varB,str): print("Strings involved") elif varA>varB: print("bigger") elif varA==varB: print("equal") elif varA<varB: print("smaller")
05736db1424292838f160b8ca66ea94d911a752e
jgkr95/CSPP1
/Practice/M3/iterate_even.py
139
4.0625
4
count = 0 n=input() print(n) for letter in 'Snow!': print('Letter # ' + str(3)+ ' is ' + letter) count += 1 break print(count)
8dbfcde0a480f44ea8f04d113a5214d7ddb9d290
jgkr95/CSPP1
/Practice/M6/p1/fizz_buzz.py
722
4.46875
4
'''Write a short program that prints each number from 1 to num on a new line. For each multiple of 3, print "Fizz" instead of the number. For each multiple of 5, print "Buzz" instead of the number. For numbers which are multiples of both 3 and 5, print "FizzBuzz" instead of the number. ''' def main(): '''Read number from the input, store it in variable num.''' num_r = int(input()) i_i = 1 while i_i <= num_r: if (i_i%3 == 0 and i_i%5 == 0): print("Fizz") print("Buzz") elif i_i%3 == 0: print("Fizz") elif i_i%5 == 0: print("Buzz") else: print(str(i_i)) i_i = i_i+1 if __name__ == "__main__": main()
86c07784b9a2a69756a3390e8ff70b2a4af78652
Ashishrsoni15/Python-Assignments
/Question2.py
391
4.21875
4
# What is the type of print function? Also write a program to find its type # Print Funtion: The print()function prints the specified message to the screen, or other #standard output device. The message can be a string,or any other object,the object will #be converted into a string before written to the screen. print("Python is fun.") a=5 print("a=",a) b=a print('a=',a,'=b')
6575bbd5e4d495bc5f8b5eee9789183819761452
Ashishrsoni15/Python-Assignments
/Question1.py
650
4.375
4
#Write a program to find type of input function. value1 = input("Please enter first integer:\n") value2 = input("Please enter second integer:\n") v1 = int(value1) v2 = int(value2) choice = input("Enter 1 for addition.\nEnter 2 for subtraction.\nEnter 3 for multiplication:\n") choice = int(choice) if choice ==1: print(f'you entered {v1} and {v2} and their addition is {v1+ v2}') elif choice ==2: print(f'you entered {v1} and {v2} and their subtraction is {v1 - v2}') elif choice ==3: print(f'you entered {v1} and {v2} and their multiplication is {v1 * v2}') else: print("Wrong Choice, terminating the program.")
a745d249dcd6eaf6bbd7c4b08bf1f8a9998291df
LeoM98/Nomina-industrial
/Explosiones.py
3,338
3.796875
4
def caso_explosion(): #definimos el algoritmo mezclas=int(input("digite el numero de mezclas "))#pedimos al usuario que introduzca un valor nombre_o=[raw_input("ingrese el nombre del operario " + str (a+1)+ ": ")for a in range(5)]# establecemos los nombres de los operarios en la lista explosion=[[0 for a in range(mezclas)] for a in range(5)]#establecemos la matriz en cuanto a la explosion de 5 listas for a in range(5):#creamos un ciclo que itere 5 veces for l in range(mezclas):#dentro del ciclo volvemos a poner otro ciclo que itere (mezclas)veces explosion[a][l]=float(input("digite la fuerza de la mezcla " + str (l+1)+ ": "))#pedimos al usuario que ingrese valor while explosion[a][l]<=0:#condicionamos dentro del ciclo, no debe ser menor o igual a 0 de lo contrario se pedira otra vez explosion[a][l]= float(input("digite la fuerza de la mezcla " + str (l+1)+ ": ")) sumador=[0 for i in range(5)]#establecemos un sumador for j in range(5):#creamos un ciclo que itere 5 veces for i in range(0, mezclas):#dentro del ciclo volvemos a crear otro ciclo que itere (mezclas) veces sumador[j]+=explosion[j][i]#le vamos sumando al sumador prom=[sumador[i]/mezclas for i in range(5)]#identificamos la operacion para hallar el promedio for i in range(1,len(prom)):#creamos otro ciclo for l in range(len(prom)-i):#creamos un ciclo dentro de otro ciclo para iterar if prom[l]>prom[l+1]:# condicionamos el algoritmo para establecer valores menores y mayores, utilizando la tecnica de la burbuja var=prom[l] var2=nombre_o[l] var3=explosion[l] prom[l]=prom[l+1] nombre_o[l]=nombre_o[l+1] explosion[l]=explosion[l+1] prom[l+1]=var nombre_o[l+1]=var2 explosion[l+1]=var3 posicion=3# se establece un contador for r in range(2):#se crea un contador for o in range(1,mezclas):#creamos otro ciclo que itere desde uno hasta (mezclas) veces for a in range(mezclas-o):#creamos otro ciclo que itere desde (mezclas) y a ese le restamos el valor de o if explosion[posicion][a]>explosion[posicion][a+1]:#condicionamos siempre y cuando los valores de la lista sea unos mayores que otros. utilizando la tecnica de la burbuja var4=explosion[posicion][a] explosion[posicion][a]=explosion[posicion][a+1] explosion[posicion][a+1]=var4 posicion+=1# se le aumente uno en valor al contador #en todo esto se imprimen los mensajes mostrandole al usuario los datos de promedio, operarios,explosion y el orden print "los promedios fueron", prom print "operariso en orden", nombre_o print "explosiones en orden",explosion print nombre_o[3],"la menor fuerza de la mezcla fue ", explosion[3][0],"_ su fuerza mayor fue ", explosion[3][mezclas-1],">>>", nombre_o[4], " la fuerza menor fue de ", explosion[4][0], "_ y su fuerza mayor fue de ", explosion[4][mezclas-1] caso_explosion()#cerramos el algoritmo para poder ejecutarlo
ea4c7aaefa309e8f0db99f4f43867ebd1bd52282
Shahriar2018/Data-Structures-and-Algorithms
/Task4.py
1,884
4.15625
4
""" Read file into texts and calls. It's ok if you don't understand how to read files. """ import csv with open('texts.csv', 'r') as f: reader = csv.reader(f) texts = list(reader) with open('calls.csv', 'r') as f: reader = csv.reader(f) calls = list(reader) """ TASK 4: The telephone company want to identify numbers that might be doing telephone marketing. Create a set of possible telemarketers: these are numbers that make outgoing calls but never send texts, receive texts or receive incoming calls. Print a message: "These numbers could be telemarketers: " <list of numbers> The list of numbers should be print out one per line in lexicographic order with no duplicates. """ print("These numbers could be telemarketers: ") calling_140=set() receving_140=set() text_sending=set() text_receiving=set() telemarketers=set() def telemarketers_list(calls,texts): global calling_140,receving_140,text_sending,text_receiving,telemarketers m=len(calls) n=len(texts) # making a list of calling/reciving numbers for row in range(m): if '140'in calls[row][0][:4]: calling_140.add(calls[row][0]) if '140'in calls[row][1][:4]: receving_140.add(calls[row][1]) # making a list of sending/receiving texts for row in range(n): if '140'in texts[row][0][:4]: text_sending.add(calls[row][0]) if '140'in texts[row][1][:4]: text_receiving.add(calls[row][1]) #Getting rid of unnecessary numbers telemarketers=calling_140-receving_140-text_sending-text_receiving telemarketers=sorted(list(telemarketers)) # Printing all the numbers for i in range(len(telemarketers)): print(telemarketers[i]) return "" telemarketers_list(calls,texts)
be6417755aa43edf9a4eab63392fe474a08c561d
killercatfish/AdventCode
/2018/Advent2018/Tree.py
2,945
3.828125
4
# http://openbookproject.net/thinkcs/python/english2e/ch21.html class Tree: def __init__(self, cargo, left=None, right=None): self.cargo = cargo self.left = left self.right = right def __str__(self): return str(self.cargo) def total(tree): if tree == None: return 0 return total(tree.left) + total(tree.right) + tree.cargo def print_tree(tree): if tree == None: return print(tree.cargo,end='') print_tree(tree.left) print_tree(tree.right) def print_tree_postorder(tree): if tree == None: return print_tree_postorder(tree.left) print_tree_postorder(tree.right) print(tree.cargo,end='') def print_tree_inorder(tree): if tree == None: return print_tree_inorder(tree.left) print(tree.cargo,end='') print_tree_inorder(tree.right) def print_tree_indented(tree, level=0): if tree == None: return print_tree_indented(tree.right, level+1) print(' ' * level + str(tree.cargo)) print_tree_indented(tree.left, level+1) # Check if a character is an int def RepresentsInt(s): try: int(s) return True except ValueError: return False def parse_expression(exp): exp = exp.replace(' ','') exp = list(exp) for i in range(len(exp)): if RepresentsInt(exp[i]): exp[i] = int(exp[i]) exp.append('end') # print(exp) return exp def get_token(token_list, expected): if token_list[0] == expected: del token_list[0] return True return False def get_number(token_list): x = token_list[0] if type(x) != type(0): return None del token_list[0] return Tree(x, None, None) def get_product(token_list): a = get_number(token_list) if get_token(token_list, '*'): b = get_product(token_list) return Tree('*',a,b) else: return a def get_sum(token_list): a = get_product(token_list) if get_token(token_list,'+'): b = get_sum(token_list) return Tree('+',a,b) else: return a # left = Tree(2) # right = Tree(3) # tree = Tree(1, left, right) # # print(total(tree)) # tree = Tree('+', Tree(1), Tree('*', Tree(2), Tree(3))) # print_tree(tree) # print('') # print_tree_postorder(tree) # print('') # print_tree_inorder(tree) # print('') # print_tree_indented(tree) # expression = '(3 + 7) * 9' # token_list = parse_expression(expression) # print(token_list) # token_list = [9, 11, 'end'] # x = get_number(token_list) # print_tree_postorder(x) # print('') # print(token_list) # token_list = [9,'*',11,'end'] # tree = get_product(token_list) # print_tree_postorder(tree) # token_list = [9,'+',11,'end'] # tree = get_product(token_list) # print_tree_postorder(tree) # token_list = [2,'*',3,'*',5,'*',7,'end'] # tree = get_product(token_list) # print_tree_postorder(tree) token_list = [9, '*', 11, '+', 5, '*', 7, 'end'] tree = get_sum(token_list) print_tree_postorder(tree)
15ded2b85a743b4c14f7c816f6284a5496f0a2bf
killercatfish/AdventCode
/2018/Advent2018/Day2/day2_part1.py
829
4.03125
4
''' Advent of code 2018 1) How do you import from a file a) Did you create a file for input? 2) What format would you like the input to be in? a) Ideally, what type of value would the input have been? 3) What data structure could you use to organize your input? 4) What is the question asking? a) How should you compute it? 5) Wrong answer? ''' two = 0 three = 0 def parse_entry(cur): letter_count = {} for i in cur: if i in letter_count: letter_count[i] = letter_count[i] + 1 else: letter_count[i] = 1 return letter_count with open("../input/inputday2.txt") as f: for line in f: l = line.strip() cur = parse_entry(l) if 2 in cur.values(): two += 1 if 3 in cur.values(): three += 1 print(two * three)
8e32b2bb8de4fff23664083acc690e27e145447a
killercatfish/AdventCode
/2018/Advent2018/Day7/day7_try2.py
4,027
3.828125
4
''' In order to copy an inner list not by reference: https://stackoverflow.com/questions/8744113/python-list-by-value-not-by-reference ''' from copy import deepcopy input_list = [] ''' step_time: list of letter values printable: heading for printing second_list: [workers current job, seconds remaining], done list ''' ''' Test input ''' # with open("test.txt") as f:#Test File # for line in f: # l = line.strip().split(" ") # print(l) # j = [l[1],l[7]] # input_list.append(j) # step_time = {chr(64+i):i for i in range(1,27)} # printable = "%-*s%-*s%-*s%-*s" % (12,'Second',12,'Worker 1', 12,'Worker 2', 12,'Done') # second_list = [[[],[],[]]] ''' Real input ''' with open("../input/inputday7.txt") as f:#Input File for line in f: l = line.strip().split(" ") print(l) j = [l[1],l[7]] input_list.append(j) step_time = {chr(64+i):60+i for i in range(1,27)} printable = "%-*s%-*s%-*s%-*s%-*s%-*s%-*s" % (12,'Second',12,'Worker 1', 12,'Worker 2',12,'Worker 3', 12,'Worker 4',12,'Worker 5', 12,'Done') second_list = [[[],[],[],[],[],[]]] # print(input_list) # print(step_time) # print(printable) # Dictionary containing the letter key, and a list of what letter needs to come first. order = {} ''' order dictionary: list of what needs to come before a letter ''' for i in input_list: if i[0] not in order.keys(): order[i[0]] = [] if i[1] not in order.keys(): order[i[1]] = [] for i in input_list: order[i[1]].append(i[0]) # # for i in order: # print(i,":",order[i]) final_size = len(order.keys()) # print(len(second_list[len(second_list)-1])) #len(second_list[len(second_list)-1]) #get length of finished list ''' find any parts that no longer have to wait ''' def find_available_parts(): found = [] for i in order: if order[i] == []: found.append(i) return sorted(found) # available = find_available_parts() # print(available) # remove a completed project from list def remove_from_values(val): # print("val in remove from values:",val) for i in order: if val in order[i]: # print("removing:",val) order[i].remove(val) #check if there are workers available and a part ready. def update_second_workers(next): ready = find_available_parts() for i in range(0, len(next) - 1): if next[i] == []: # print(second_list[0][i]) if len(ready) > 0: r = ready.pop(0) time = step_time[r] next[i] = [r, time] del order[r] return next #Create next second list entry def decrease_times(cur): #goes through and decreases any current work times by 1 second and returns list. #moves to finished list if at 0 for i in range(len(cur)-1): next = cur # print("i:",i, "next[i]", next[i]) if next[i] != []: next[i][1]-=1 if next[i][1] == 0: next[len(next)-1].append(next[i][0]) needs_removal = next[i][0] next[i] = [] # print("i:",i) remove_from_values(needs_removal) next = update_second_workers(next) #add any available parts to any available worker. return next #update another second def update_second_list(): current_index = len(second_list)-1 # print(current_index) cur = deepcopy(second_list[current_index]) second_list.append(decrease_times(cur)) #method to update available, check if its in the done list too. #update what workers are doing #Initialize seconds list update_second_workers(second_list[0]) # print(second_list) #while the done lists length is less than the total letters needing completion while len(second_list[len(second_list)-1][len(second_list[len(second_list)-1])-1]) <final_size: update_second_list() #print(len(second_list[len(second_list)-1][len(second_list[len(second_list)-1])-1])) for i in range(len(second_list)): print(i,second_list[i])
0ba5f660e4518f026991b66f02b793d5aa836199
kiner-shah/CompetitiveProgramming
/Hackerrank/Pythonist 2/find_angle_mbc.py
254
3.765625
4
# Enter your code here. Read input from STDIN. Print output to STDOUT import math x=int(raw_input()) y=int(raw_input()) h=math.hypot(x,y) v=math.asin(x/h)*180/math.pi if v<math.floor(v)+0.5: print int(math.floor(v)) else: print int(math.ceil(v))
586d1398fa085b65390f464ae8a6d23b3f4cdef9
kiner-shah/CompetitiveProgramming
/Hackerrank/Pythonist 2/swap_case.py
269
3.640625
4
# Enter your code here. Read input from STDIN. Print output to STDOUT x=raw_input() l=list(x) for i in range(0,len(l)): if l[i]>='a' and l[i]<='z': l[i]=chr(ord(l[i])-32) elif l[i]>='A' and l[i]<='Z': l[i]=chr(ord(l[i])+32) p="".join(l) print p
75f8fb51306ab728df6ea35bf73fc6a04f88bfba
jpalat/AdventOfCode-2020
/day5/day51.py
1,279
3.53125
4
import struct import math def seatDecoder(passid): print('passid:', passid) instructions = list(passid) row_instructions = instructions[:7] col_instructions = instructions[-3:] row = parseRow(row_instructions) col = parseCol(col_instructions) seat = (row * 8) + col # print(row_instructions, seat_instructions) return (row, col, seat) def parseRow(instructions): row = 0 for index, r in enumerate(reversed(instructions)): if r == 'B': row = (2**index) + row return row def parseCol(instructions): column = 0 for index,c in enumerate(reversed(instructions)): if c == 'R': column = (2**index) + column return column if __name__ == "__main__": f = open('input.txt') l = list(f) l.sort() bigseat = 0 seats = [] for index, seat in enumerate(l): row, col, seat = seatDecoder(seat.strip()) print (index, ': ',row, col, seat, bigseat) if seat > bigseat: bigseat = seat seats.append(seat) seats.sort() seats_total = sum(seats) seats_possible = sum(range(seats[0], seats[-1]+1)) my_seat = seats_possible - seats_total print("Highest Seat ID:", bigseat) print("My seat", my_seat)
e5f5ccdcada9074dbc77cda74ff0af195394ec11
uva-slpl/nlp2
/resources/project_neuralibm-2019/vocabulary.py
3,647
3.53125
4
#!/usr/bin/env python3 from collections import Counter, OrderedDict import numpy as np class OrderedCounter(Counter, OrderedDict): """A Counter that remembers the order in which items were added.""" pass class Vocabulary: """A simple vocabulary class to map words to IDs.""" def __init__(self, corpus=None, special_tokens=('<PAD>', '<UNK>', '<S>', '</S>', '<NULL>'), max_tokens=0): """Initialize and optionally add tokens in corpus.""" self.counter = OrderedCounter() self.t2i = OrderedDict() self.i2t = [] self.special_tokens = [t for t in special_tokens] if corpus is not None: for tokens in corpus: self.counter.update(tokens) if max_tokens > 0: self.trim(max_tokens) else: self.update_dicts() def __contains__(self, token): """Checks if a token is in the vocabulary.""" return token in self.counter def __len__(self): """Returns number of items in vocabulary.""" return len(self.t2i) def get_token_id(self, token): """Returns the ID for token, if we know it, otherwise the ID for <UNK>.""" if token in self.t2i: return self.t2i[token] else: return self.t2i['<UNK>'] def tokens2ids(self, tokens): """Converts a sequence of tokens to a sequence of IDs.""" return [self.get_token_id(t) for t in tokens] def get_token(self, i): """Returns the token for ID i.""" if i < len(self.i2t): return self.i2t[i] else: raise IndexError("We do not have a token with that ID!") def add_token(self, token): """Add a single token.""" self.counter.add(token) def add_tokens(self, tokens): """Add a list of tokens.""" self.counter.update(tokens) def update_dicts(self): """After adding tokens or trimming, this updates the dictionaries.""" self.t2i = OrderedDict() self.i2t = list(self.special_tokens) # add special tokens self.i2t = [t for t in self.special_tokens] for i, token in enumerate(self.special_tokens): self.t2i[token] = i # add tokens for i, token in enumerate(self.counter, len(self.special_tokens)): self.t2i[token] = i self.i2t.append(token) def trim(self, max_tokens): """ Trim the vocabulary based on frequency. WARNING: This changes all token IDs. """ tokens_to_keep = self.counter.most_common(max_tokens) self.counter = OrderedCounter(OrderedDict(tokens_to_keep)) self.update_dicts() def batch2tensor(self, batch, add_null=True, add_end_symbol=True): """ Returns a tensor (to be fed to a TensorFlow placeholder) from a batch of sentences. The batch input is assumed to consist of tokens, not IDs. They will be converted to IDs inside this function. """ # first we find out the shape of the tensor we return batch_size = len(batch) max_timesteps = max([len(x) for x in batch]) if add_end_symbol: max_timesteps += 1 if add_null: max_timesteps += 1 # then we create an empty tensor, consisting of zeros everywhere tensor = np.zeros([batch_size, max_timesteps], dtype='int64') # now we fill the tensor with the sequences of IDs for each sentence for i, sequence in enumerate(batch): start = 1 if add_null else 0 tensor[i, start:len(sequence)+start] = self.tokens2ids(sequence) if add_null: tensor[i, 0] = self.get_token_id("<NULL>") if add_end_symbol: tensor[i, -1] = self.get_token_id("</S>") # end symbol return tensor
3e019a6dda73376db4bcc04bb99f07c9fdf214bc
jucariasar/Proyecto_POO_UNAL_2017-1_Python
/ingenierotecnico.py
1,385
3.6875
4
from empleado import Empleado class IngenieroTecnico(Empleado): MAX_IT = 4 # Constante de clase para controlar el numero máximo de elementos que puede prestar #un IngenieroTecnico areas = {'1':'Mantenimiento', '2':'Produccion', '3':'Calidad'} def __init__(self, ident=0, nombre="", apellido="", numElementPrest=0, roll="", email="", area=""): super().__init__(ident, nombre, apellido, numElementPrest, roll, email) self._areaEncargada = area # Los tipos definidos en el diccionario estatico de areas def getArea(self): return self._areaEncargada def setArea(self, area): self._areaEncargada = area @staticmethod def registrarEmpleado(listEmpleados): empleado = IngenieroTecnico() empleado.setIdent(int(input("Ingrese el id del ingeniero:"))) empleado.setNombre(str(input("Ingrese el nombre del ingeniero:"))) empleado.setApellido(str(input("Ingrese el apellido del ingeniero:"))) empleado.setEmail(str(input("Ingrese el correo del ingeniero:"))) empleado.setRoll(Empleado().tiposEmpleado['3']) empleado.setArea(str(input("Establezca area del Ingeniero:"))) listEmpleados.append(empleado) def __str__(self): return (super().__str__() + "\nArea Encargada: " + self.getArea())
b440521c3f550e35b63bfb7687f6a94d3d0d61a0
arnizamani/Networks
/AdditionEnv.py
1,984
3.90625
4
# -*- coding: utf-8 -*- """ Created 17 Feb 2016 @author: Abdul Rahim Nizamani """ from network import Network import random class AdditionEnv(object): """Environment feeds activation to the sensors in the network""" def __init__(self,network): print("Initializing Environment...") self.network = network self.sensors = network.sensors self.history = [] # history of activated sensors self.score = 0 # total correct answers self.examples = 0 # total examples def Begin(self,count=0): """Start feeding activation to the sensors. Activate a single sensor randomly.""" if(not self.sensors): raise SyntaxError if(count<=0): count=1000 reward = 0.0 active = random.choice(sorted(list(self.sensors))) while(count>0): result = filter(lambda x:x!="",self.network.result) self.network.Tick({active},reward) reward = 0.0 if not self.history: reward = 0.0 else: if list(reversed(self.history))[0:3] == list(reversed(["3","+","4"])): self.examples += 1 #print(list(reversed(self.history))[0]) if(result==["7"]): if list(reversed(self.history))[0:3] == list(reversed(["3","+","4"])): reward = 100.0 self.score += 1 else: reward = -10.0 else: if list(reversed(self.history))[0:3] == list(reversed(["3","+","4"])): reward = -100.0 else: reward = 0.0 if result==["7"] and list(reversed(self.history))[0:3] == list(reversed(["3","+","4"])): active = "7" else: #active = random.choice(sorted(list(self.sensors))) active = random.choice(["3","+","4"]) count -= 1 self.history.append(active)
67354d9d9ffdbe84f8348ecf1efa127c56ec33c5
dickersonsteam/CircuitPython_ToneOnA0
/main.py
2,451
3.796875
4
# This example program will make a single sound play out # of the selected pin. # # The following are the default parameters for which pin # the sound will come out of, sample rate, note pitch/frequency, # and note duration in seconds. # # audio_pin = board.A0 # sample_rate = 8000 # note_pitch = 440 # note_length = 1 # # This example makes use of print messages to help debug # errors. As you make changes and then run your code, watch # these messages to understand what is happening (or not happening). # When you add features, add messages to help you debug your own # code. Ultimately, these print messages do slow things down a bit, # but they will make you life easier in the long run. import audioio import board import array import time import math # record current time start_time_pgm = time.monotonic() # for Feather M0 use A0 only # for Feather M4 either A0 or A1 work audio_pin = board.A0 # Sample rate roughly determines the quality of the sound. # A larger number may sound better, but will take # more processing time and memory. sample_rate = 8000 # Set the pitch for the note you would like to play. # http://pages.mtu.edu/~suits/notefreqs.html note_pitch = 440 # Set how many seconds the note will last. # Try 0.1 - 1.0 or any number. note_length = 1 # Now you must "draw" the sound wave in memory. # This will take more or less time depending on the # frequency and sample_rate that you selected. print("Generate sound wave.") start_time_gen = time.monotonic() length = sample_rate // note_pitch sine_wave = array.array("h", [0] * length) for i in range(length): sine_wave[i] = int(math.sin(math.pi * 2 * i / 18) * (2 ** 15)) time_to_completion = time.monotonic() - start_time_gen print("Generating the sound wave took " + str(time_to_completion) + " seconds.") # Now initialize you DAC (aka speaker pin) print("Initialize DAC.") dac = audioio.AudioOut(audio_pin) # Convert the sine wave you generated earlier into a # sample that can be used with the dac. print("Converting to RawSample.") sine_wave = audioio.RawSample(sine_wave) # Play the sine wave on the dac and loop it for however # many seconds you set with note_length. print("Playing sound.") dac.play(sine_wave, loop=True) time.sleep(note_length) dac.stop() # Print program execution time print("Program completed execution.") time_to_completion = time.monotonic() - start_time_pgm print("Execution took " + str(time_to_completion) + " seconds.")
3842e494b165c2442a0205ea752e0f3aeafb5c12
WillGreen98/Project-Euler
/Tasks 1-99/Task 15/Task-15.py
641
3.75
4
# Task 15 - Python # Lattice Paths import time from functools import reduce binomial = lambda grid_size: reduce(lambda hoz, vert: hoz * vert, range(1, grid_size + 1), 1) def path_route_finder(grid_size_to_check): # As size is perfect cube - I have limited calculations instead of n & m size = grid_size_to_check if grid_size_to_check == 0: return 1 return binomial(2*size) // binomial(size) // binomial(size) def main(): time_start = time.time() route_num = path_route_finder(20) print("Answer: {0} => Calculated in: {1}".format(route_num, (time.time() - time_start))) if __name__ == '__main__': main()
50f0cbdf511231ae28bff1dbe993b9a57befc6f5
WillGreen98/Project-Euler
/Tasks 1-99/Task 10/Task-10.py
898
4.03125
4
# Task 10 - Python # Summations Of Primes import math import time is_prime = lambda num_to_check: all(num_to_check % i for i in range(3, int(math.sqrt(num_to_check)) + 1, 2)) def sum_of_primes(upper_bound): fp_c = 2 summation = 0 eratosthenes_sieve = ((upper_bound + 1) * [True]) while math.pow(fp_c, 2) < upper_bound: if is_prime(eratosthenes_sieve[fp_c]): multiple = fp_c * 2 while multiple < upper_bound: eratosthenes_sieve[multiple] = False multiple += fp_c fp_c += 1 for i in range(fp_c, upper_bound + 1): if eratosthenes_sieve[i]: summation += 1 return summation def main(): time_start = time.time() prime_sum = sum_of_primes(11) print("Answer: {0} => Calculated in: {1}".format(prime_sum, (time.time() - time_start))) if __name__ == '__main__': main()
74083ac38b480e5c26bf58cd405728e1f2999e9d
AJSterner/UnifyID
/atmosphere_random.py
2,851
3.703125
4
import urllib2 from urllib import urlencode from ctypes import c_int64 def random_ints(num=1, min_val=-1e9, max_val=1e9): """ get random integers from random.org arguments --------- num (int): number of integers to get min_val (int): min int value max_val (int): max int value timeout (int): timeout in seconds (should be long as random.org may ban) """ num = int(num) min_val = int(min_val) max_val = int(max_val) assert 1 <= num, "num must be positive" assert min_val < max_val, "min must be less than max" rand_ints = [] while num > 0: to_get = min(num, 1E4) rand_ints.extend(random_ints_helper(to_get, min_val, max_val)) num -= to_get return rand_ints def random_ints_helper(num=1, min_val=-1e9, max_val=1e9): """ get random integers from random.org (not to be called directly) arguments --------- num (int): number of integers to get min_val (int): min int value max_val (int): max int value timeout (int): timeout in seconds (should be long as random.org may ban) """ num = int(num) min_val = int(min_val) max_val = int(max_val) assert 1 <= num <= 1E4, "num invalid (if too great use many_random_ints)" assert min_val < max_val, "min must be less than max" req = urllib2.Request(random_request_url(num, min_val, max_val)) try: response = urllib2.urlopen(req).read() except urllib2.HTTPError as e: print('Request could\'t be filled by the server') print('Error code: ' + e.code) except urllib2.URLError as e: print('Connection error') print('Reason: ' + e.reason) return [int_from_hexstr(line) for line in response.splitlines()] def random_request_url(num, min_val, max_val): """ return GET random request URL (see https://www.random.org/clients/http/) """ assert isinstance(num, int) and isinstance(min_val, int) and isinstance(max_val, int) req_data = dict(num=num, min=min_val, max=max_val, col=1, base=16, format='plain', rnd='new') return "https://www.random.org/integers/?" + urlencode(req_data) def int_from_hexstr(hexstr): """ returns a python integer from a string that represents a twos complement integer in hex """ uint = int(hexstr, base=16) # python assumes positive int from string return c_int64(uint).value
fae39f809f9202288cfe12ab7de8e63a05fd6341
Rayban63/Coffee-Machine
/Problems/Calculator/task.py
583
4
4
first_num = float(input()) second_num = float(input()) operation = input() no = ["mod", "div", "/"] if second_num == (0.0 or 0) and operation in no: print("Division by 0!") elif operation == "mod": print(first_num % second_num) elif operation == "pow": print(first_num ** second_num) elif operation == "*": print(first_num * second_num) elif operation == "div": print(first_num // second_num) elif operation == "/": print(first_num / second_num) elif operation == "+": print(first_num + second_num) elif operation == "-": print(first_num - second_num)
d54a81b17a5d535737681a88420bbc1c87fdad97
mattikus/advent2017
/day_1/1.py
307
3.640625
4
#!/usr/bin/env python3 import sys def inverse_captcha(captcha): arr = list(map(int, captcha)) return sum(i for idx, i in enumerate(arr) if i == (arr[0] if idx == (len(arr) - 1) else arr[idx+1])) if __name__ == "__main__": problem_input = sys.argv[1] print(inverse_captcha(problem_input))
cc50953b5b3fb569c4ee7b792b2b4ef02ddaa182
MatiasLeon1/MCOC2020-P0
/MIMATMUL.py
615
3.5625
4
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ import numpy as np def mimatmul(A,B): f=len(A) c=len(B) result=np.zeros([f,c]) #Creamos una matriz de puros ceros for i in range(len(A)): #Itera las filas de la matriz A for j in range(len(B[0])): #Itera las columnas de B for k in range(len(B)): #Itera las filas de B # Utilizamos la formula de calculo de matrices ordenando # el calculo entre dilas y columnas respectivas result[i][j] += A[i][k]*B[k][j] return result
9e8b97dfce807ab9655b0d7c32c344f875c4fdec
SiddharthaPramanik/Assessment-VisualBI
/music_app/songs/models.py
1,061
3.5625
4
from music_app import db class Songs(db.Model): """ A class to map the songs table using SQLAlchemy ... Attributes ------- song_id : Integer database column Holds the id of the song song_title : String databse column Holds the song name seconds : String databse column Holds the duration in seconds thumbnail_url: String databse column Holds the thumbnail url for song album_id : Integer database column Holds the foreign key for albums table Methods ------- __repr__() Method to represent the class object """ song_id = db.Column(db.Integer, primary_key=True) song_title = db.Column(db.String(60), nullable=False) seconds = db.Column(db.Integer, nullable=False) thumbnail_url = db.Column(db.String(200), default='thumbnail.png') album_id = db.Column(db.Integer, db.ForeignKey('albums.album_id'), nullable=False) def __repr__(self): return f"Songs('{self.song_title}', '{self.seconds}', {self.album_id})"
9d8a9f005a7261d963be2c06d7281563deddf157
PowersYang/houseSpider
/houseSpider/test.py
1,772
3.703125
4
# -*- coding: utf-8 -*- import time, datetime kHr = 0 # index for hour kMin = 1 # index for minute kSec = 2 # index for second kPeriod1 = 0 # 时间段,这里定义了两个代码执行的时间段 kPeriod2 = 1 starttime = [[9, 30, 0], [13, 0, 0]] # 两个时间段的起始时间,hour, minute 和 second endtime = [[11, 30, 0], [15, 0, 0]] # 两个时间段的终止时间 sleeptime = 5 # 扫描间隔时间,s def DoYourWork(): # 你的工作函数 print('Now it\'s the time to work!') def RestYourSelf(): # 你的休息函数 print('Now it\'s the time to take a rest!') def T1LaterThanT2(time1, time2): # 根据给定时分秒的两个时间,比较其先后关系 # t1 < t2, false, t1 >= t2, true if len(time1) != 3 or len(time2) != 3: raise Exception('# Error: time format error!') T1 = time1[kHr] * 3600 + time1[kMin] * 60 + time1[kSec] # s T2 = time2[kHr] * 3600 + time2[kMin] * 60 + time2[kSec] # s if T1 < T2: return False else: return True def RunNow(): # 判断现在是否工作 mytime = datetime.datetime.now() currtime = [mytime.hour, mytime.minute, mytime.second] if (T1LaterThanT2(currtime, starttime[kPeriod1]) and (not T1LaterThanT2(currtime, endtime[kPeriod1]))) or ( T1LaterThanT2(currtime, starttime[kPeriod2]) and (not T1LaterThanT2(currtime, endtime[kPeriod2]))): return True else: return False if __name__ == "__main__": if len(starttime) != len(endtime): raise Exception('# Error: the run time format is not correct!') else: while True: if RunNow(): DoYourWork() else: RestYourSelf() time.sleep(sleeptime) # sleep for 5 s
f24a10c953482e69f0131e4acf6e13d83fc36cdd
sushrao1996/DSA
/Recursion/Factorial.py
276
4
4
def myFact(n): if n==1: return 1 else: return n*myFact(n-1) num=int(input("Enter a number: ")) if num<0: print("No negative numbers") elif(num==0): print("Factorial of 0 is 1") else: print("Factorial of",num,"is",myFact(num))
22ad07d51d6377717ab69018e34652e03140f837
sushrao1996/DSA
/Queue/CircularQueue.py
1,868
3.953125
4
class CircularQueue: def __init__(self,size): self.size=size self.queue=[None for i in range(size)] self.front=self.rear=-1 def enqueue(self,data): if ((self.rear+1)%self.size==self.front): print("Queue is full") return elif (self.front==-1): self.front=0 self.rear=0 self.queue[self.rear]=data else: self.rear=(self.rear+1)%self.size self.queue[self.rear]=data def dequeue(self): if (self.front==-1): print("Queue is already empty") elif (self.front==self.rear): popvalue=self.queue[self.front] self.front=-1 self.rear=-1 return popvalue else: popvalue=self.queue[self.front] self.front=(self.front+1)%self.size return popvalue def display(self): if(self.front==-1): print("Queue is empty") elif(self.rear>=self.front): print("Elements in the circular queue are: ") for i in range(self.front,self.rear+1): print(self.queue[i],end=" ") print() else: print("Elements in the circular queue are: ") for i in range(self.front,self.size): print(self.queue[i],end=" ") for i in range(0,self.rear+1): print(self.queue[i],end=" ") print() if((self.rear+1)%self.size==self.front): print("Queue is full") ob = CircularQueue(5) ob.enqueue(14) ob.enqueue(22) ob.enqueue(13) ob.enqueue(-6) ob.display() print ("Deleted value = ", ob.dequeue()) print ("Deleted value = ", ob.dequeue()) ob.display() ob.enqueue(9) ob.enqueue(20) ob.enqueue(5) ob.display()
7add6d6db4a6824b60f4ee5d5ea150e55f0cb69c
amites/davinci_2017_spring
/codewars/carry_over.py
852
3.625
4
# https://www.codewars.com/kata/simple-fun-number-132-number-of-carries/train/python def number_of_carries(a, b): y = [int(n) for n in list(str(a))] x = [int(n) for n in list(str(b))] # reverse order so beginning with smallest # and going to biggest y.reverse() x.reverse() # figure out which list contains more digits if a > b: longer = y shorter = x else: longer = x shorter = y # define starting values carry = 0 count = 0 for i in range(0, len(longer)): # skip adding from a column that does not exist if i < len(shorter): num = longer[i] + shorter[i] + carry else: num = longer[i] + carry if num > 9: count += 1 carry = 1 else: carry = 0 return count
d9177b87da9f04a0d1c4406abf65d2996449fc11
v-lubomski/python_start
/old_lessons/func_with_param.py
134
4.125
4
def printMax(a, b): if a > b: print(a, 'is max') elif a == b: print(a, 'equal', b) else: print(b, 'is max') printMax(5, 8)
41f729db17f24ba77f849434e75b4519ea93c9af
kordaniel/AoC
/2020/day8/main.py
2,212
3.671875
4
import sys sys.path.insert(0, '..') from helpers import filemap # Part1 def walk(code): ''' Executes the instructions, stops when reach infinite loop and returns the value''' idx, accumulator = 0, 0 visited = set() while True: if idx in visited: break visited.add(idx) instruction, arg = code[idx] if instruction == 'jmp': idx += arg continue if instruction == 'acc': accumulator += arg idx += 1 return accumulator # Part2 def walk_fix(code): ''' Executes the instructions and tries to fix the code so that it won't end up in an infinite loop''' idx, end_idx = 0, len(code) end_reached = False while not end_reached and idx < end_idx: code_arg = code[idx] if code_arg[0] == 'acc': idx += 1 continue elif code_arg[0] == 'jmp': code[idx] = ('nop', code_arg[0]) elif code_arg[0] == 'nop': code[idx] = ('jmp', code_arg[1]) end_reached = can_reach_end(code) if not end_reached: code[idx] = code_arg else: return end_reached idx += 1 raise Exception('ERRORRORORROROROROR') def can_reach_end(code): end_idx = len(code) idx, accumulator = 0, 0 visited = set() while True: if idx == end_idx: return True, accumulator if idx in visited: return False visited.add(idx) instruction, arg = code[idx] if instruction == 'jmp': idx += arg continue if instruction == 'acc': accumulator += arg idx += 1 return accumulator def main(): # Test data data = [ ('nop', 0), ('acc', 1), ('jmp', 4), ('acc', 3), ('jmp', -3), ('acc', -99), ('acc', 1), ('jmp', -4), ('acc', 6) ] data = filemap('input.txt', lambda s: s.split()) data = list(map(lambda l: (l[0], int(l[1])), data)) #print(data) # Part 1 print('Part1:', walk(data)) # Part 2 print('Part2:', walk_fix(data)) if __name__ == '__main__': main()
95a68ebdcb01557a83900a8f34f3c57417a0c60f
abnormalmakers/object-oriented
/super.py
378
3.53125
4
class A(): def fn(self): print("A被调用") def run(self): print('A run') class B(A): def fn(self): print("B被调用") def run(self): super(B,self).run() super(__class__,self).run() super().run() a = A() a.fn() b = B() b.fn() b.__class__.__base__.fn(b) print('aaaa') super(B,b).fn() print('aaaa') b.run()
cd44060db334e79d426b1cd69aa2f5e798a9a1cb
thaynnara007/ATAL_listas
/lista02/questao03.py
1,368
3.71875
4
PESO = 0 VALOR = 1 def mochilaBinaria( valorAtual, capacidadeAtual, i, conjuntoAtual): global capacidadeMochila global itens global qntdItens global conjunto global maiorValor if i <= qntdItens: if capacidadeAtual <= capacidadeMochila: if valorAtual > maiorValor: maiorValor = valorAtual conjunto = conjuntoAtual for iten in xrange(i, qntdItens): # Parte abaixo necessária pois em python, não é passado listas como parámetros, mas sim a referência para a lista, implicitamente, #o que ocaciona da lista continuar modificada por chamadas recursivas a frente, mesmo depois de ter voltado na recursão #gerando um comportamento inesperado tendo em vista a teoria da recursão. conjuntoAtual2 = conjuntoAtual[:] conjuntoAtual2.append(itens[iten]) mochilaBinaria( itens[iten][VALOR] + valorAtual, capacidadeAtual + itens[iten][PESO], iten + 1, conjuntoAtual2) capacidadeMochila = int(raw_input()) qntdItens = int(raw_input()) itens = [] maiorValor = 0 conjunto = [] for iten in xrange(qntdItens): peso, valor = map(int, raw_input().split()) itens.append((peso, valor)) itens.sort() mochilaBinaria(0,0,0,[]) print maiorValor print conjunto
d218fc784ea19385eb5aff0517529af3c6a513f0
LucHighwalker/CaptainRainbowSpaceMan
/spaceman.py
3,855
3.5
4
import random import os secret_word = '' blanks = list() guessed = list() attempts_left = 7 game_won = False game_lost = False help_prompt = False running = True def load_word(): global secret_word f = open('words.txt', 'r') words_list = f.readlines() f.close() words_list = words_list[0].split(' ') secret_word = random.choice(words_list) def gen_blanks(): global secret_word global blanks blanks = list('-' * len(secret_word)) def initialize(): global secret_word global blanks global guessed global attempts_left global game_won global game_lost global help_prompt secret_word = '' blanks = list() guessed = list() attempts_left = 7 game_won = False game_lost = False help_prompt = False load_word() gen_blanks() def draw_spaceman(): global attempts_left if attempts_left == 7: return '\n\n' elif attempts_left == 6: return ' o \n\n' elif attempts_left == 5: return ' o \n | \n' elif attempts_left == 4: return ' o \n/| \n' elif attempts_left == 3: return ' o \n/|\\\n' elif attempts_left == 2: return ' o \n/|\\\n/ ' elif attempts_left == 1: return ' o \n/|\\\n/ \\' def render_screen(): global blanks global guessed global attempts_left global help_prompt global game_won global game_lost os.system('cls' if os.name == 'nt' else 'clear') if game_won: print('CONGRATS!!! You survive another day! :D\n\n' + 'The word was: ' + secret_word + '\n') elif game_lost: print('RIP! You got shot into space. GG :\'(\n\n' + 'The word was: ' + secret_word + '\n') else: blank_lines = '' guesses = '' for i in blanks: blank_lines = blank_lines + i for i in guessed: guesses = guesses + i + ' ' print(blank_lines) print('\n\nGuessed: ' + guesses + '\n') print(draw_spaceman()) print('\n') if help_prompt: print('Enter a single letter or \'quit\' to exit the program.\n') help_prompt = False def user_input(prompt): try: user_input = input(prompt) return user_input except EOFError: return '' def check_guess(guess): global secret_word global blanks global guessed global attempts_left correct_letter = False letter_index = 0 for i in secret_word: if i == guess: blanks[letter_index] = guess correct_letter = True letter_index += 1 if not correct_letter: for i in guessed: if i == guess: return attempts_left -= 1 guessed.append(guess) def process_input(inp): global help_prompt global running if inp == 'quit': running = False elif len(inp) == 1 and inp.isalpha(): check_guess(inp.lower()) render_screen() else: help_prompt = True render_screen() def check_win(): global blanks global attempts_left global game_won global game_lost if attempts_left <= 0: game_lost = True return found_blank = False for i in blanks: if i == '-': found_blank = True break if not found_blank: game_won = True return initialize() render_screen() while running: if not game_won and not game_lost: inp = user_input('Enter guess: ') process_input(inp) check_win() else: render_screen() inp = user_input('Press enter to replay or enter \'quit\' to exit: ') if inp == 'quit' or inp == 'q': running = False elif not inp: initialize() render_screen()
e29240d2ac37a9fdeedfd1795ed92bc4d5c59359
MagdaM91/Python
/GUI.py
573
3.609375
4
from tkinter import * root = Tk() #thLable = Label(root, text="This is to easy") #thLable.pack() '' topFrame = Frame(root) topFrame.pack() bottomFram = Frame(root) bottomFram.pack(side=BOTTOM) Firstbutton = Button(topFrame, text="FirstButton",fg="red") Secondbutton = Button(topFrame, text="SecondButton",fg="blue") Thirdbutton = Button(topFrame, text="ThirdButton",fg="green") Fourbutton = Button(topFrame, text="ThirdButton",fg="yellow") Firstbutton.pack(side=LEFT) Secondbutton.pack(side=LEFT) Thirdbutton.pack(side=LEFT) Fourbutton.pack(side=BOTTOM) root.mainloop()
f728bb9426eeb04961d39186b2bd98532e02a167
TaiCobo/practice
/checkio/to_encrypt.py
819
3.796875
4
def to_encrypt(text, delta): #replace this for solution alphabet = "abcdefghijklmnopqrstuvwxyz" ret = "" for word in range(len(text)): if text[word] == " ": ret += " " else: ret += alphabet[(alphabet.index(text[word]) + delta) % 26] return ret if __name__ == '__main__': print("Example:") print(to_encrypt('abc', 10)) #These "asserts" using only for self-checking and not necessary for auto-testing print(to_encrypt("a b c", 3))# == "d e f" print(to_encrypt("a b c", -3))# == "x y z" print(to_encrypt("simple text", 16))# == "iycfbu junj" print(to_encrypt("important text", 10))# == "swzybdkxd dohd" print(to_encrypt("state secret", -13))# == "fgngr frperg" print("Coding complete? Click 'Check' to earn cool rewards!")
f5a72e136b367e877afd5632cadb843e5944d8db
TaiCobo/practice
/checkio/left_right.py
1,049
3.765625
4
def left_join(phrases): """ Join strings and replace "right" to "left" """ ret = "" return ",".join(phrases).replace("right", "left") def checkio(number: int) -> int: nnn = str(number) ret = 1 for i, val in enumerate(range(0, len(nnn))): if nnn[i] == "0": continue ret = ret * int(nnn[i]) return ret if __name__ == '__main__': #These "asserts" using only for self-checking and not necessary for auto-testing # print(left_join(("left", "right", "left", "stop")))# == "left,left,left,stop", "All to left" # print(left_join(("bright aright", "ok")))# == "bleft aleft,ok", "Bright Left" # print(left_join(("brightness wright",)))# == "bleftness wleft", "One phrase" # print(left_join(("enough", "jokes")))# == "enough,jokes", "Nothing to replace" # print("Coding complete? Click 'Check' to review your tests and earn cool rewards!") print(checkio(123405)) print(checkio(999))# == 729 print(checkio(1000))# == 1 print(checkio(1111))# == 1