blob_id
stringlengths
40
40
repo_name
stringlengths
6
108
path
stringlengths
3
244
length_bytes
int64
36
870k
score
float64
3.5
5.16
int_score
int64
4
5
text
stringlengths
36
870k
238722d288633262934c91dd279c4a31b7a99e44
EmmaNunoMares/Practice_Python_withAlgorithms
/SmallestDifference.py
2,033
3.515625
4
""" Sample input: [-1,5,10,20,28,3],[26,134,135,15,17] Sample output: [28,26] tiemp: O(nlog(n) + mlog(m)) space: O(1) """ import sys """ my version def smallestDifference(arrayOne, arrayTwo): out =[] arrayOne.sort() arrayTwo.sort() holdValue = sys.maxsize leftOnePointer = 0 leftTwoPointer = 0 print("array 1: "+str(arrayOne)+" array 2: "+str(arrayTwo)) while(leftOnePointer < len(arrayOne) and leftTwoPointer < len(arrayTwo)): computeSmallestD = arrayOne[leftOnePointer] - arrayTwo[leftTwoPointer] print("operation: "+str(computeSmallestD)) if abs(computeSmallestD) < holdValue: holdValue = abs(computeSmallestD) out = [arrayOne[leftOnePointer], arrayTwo[leftTwoPointer]] print("hold value: "+str(holdValue)) if leftOnePointer < len(arrayOne)-1 and arrayOne[leftOnePointer] < arrayTwo[leftTwoPointer]: leftOnePointer += 1 if leftTwoPointer < len(arrayTwo)-1 and arrayOne[leftOnePointer] > arrayTwo[leftTwoPointer]: leftTwoPointer += 1 return out """ def smallestDifference(arrayOne, arrayTwo): out = [] arrayOne.sort() arrayTwo.sort() idxone = 0 idxtwo = 0 smallest = sys.maxsize current = 0 while(idxone < len(arrayOne) and idxtwo < len(arrayTwo)): firstNum = arrayOne[idxone] secondNum = arrayTwo[idxtwo] if firstNum < secondNum: current = secondNum - firstNum idxone += 1 elif secondNum < firstNum: current = firstNum - secondNum idxtwo += 1 else: return [firstNum, secondNum] #print("smallest "+str(smallest)+" current "+str(current)) if smallest > current: smallest = current out = [firstNum, secondNum] return out array_One = [-1,5,10,20,28,3] array_Two = [26,134,135,15,17] result = smallestDifference(array_One, array_Two) print(result)
117e7902f17adb03cc9505e6845fecda4dd239ff
code-runner-2017/python-snippets
/multiprocessing-example.py
457
3.578125
4
import multiprocessing # Here we create separate processes, with different heaps # You can also create threads, that share the same heap. # See 'multithreading.py' # More examples here: https://pymotw.com/3/multiprocessing/basics.html def worker(): """worker function""" print('Worker') if __name__ == '__main__': jobs = [] for i in range(5): p = multiprocessing.Process(target=worker) jobs.append(p) p.start()
404debd7472e6215d748b8932f7a0f75766e0e31
TouchySarun/comarchProject62
/Assembler/my_utils.py
945
3.625
4
import string avaiable_character = string.ascii_letters + "1234567890" def check_allowed_label(label): illegal_character = [] for character in label: if character not in avaiable_character: illegal_character.append(character) return illegal_character def to_binary_str(number, mask): binary_str = "" while mask > 0: current_bit = number & 1 binary_str = str(current_bit) + binary_str number >>= 1 mask -= 1 return binary_str def binary_str_to_decimal(binary): decimal = 0 i = len(binary) - 1 for bit in binary: decimal += int(bit) * (2 ** i) i -= 1 return decimal def check_offset_field(num): if num < -32768 or num > 32767: raise Exception(f"error {num} offset overflow") return True def check_isregister(num): if num < 0 or num > 7: raise Exception(f"error {num} not register") return True
933b7ff7774c70de17422265ad8d6cc2a56bb7dc
BeaLove/RLlab
/PycharmProjects/minimax/player2.py
5,493
3.5
4
import random from fishing_game_core.game_tree import Node from fishing_game_core.player_utils import PlayerController from fishing_game_core.shared import ACTION_TO_STR class PlayerControllerHuman(PlayerController): def player_loop(self): """ Function that generates the loop of the game. In each iteration the human plays through the keyboard and send this to the game through the sender. Then it receives an update of the game through receiver, with this it computes the next movement. :return: """ while True: # send message to game that you are ready msg = self.receiver() if msg["game_over"]: return class PlayerControllerMinimax(PlayerController): def __init__(self): super(PlayerControllerMinimax, self).__init__() def player_loop(self): """ Main loop for the minimax next move search. :return: """ # Generate game tree object first_msg = self.receiver() # Initialize your minimax model #model = self.initialize_model(initial_data=first_msg) while True: msg = self.receiver() # Create the root node of the game tree node = Node(message=msg, player=0) ##first node is created # Possible next moves: "stay", "left", "right", "up", "down" best_move = self.search_best_next_move( initial_tree_node=node) ##send that root node to search_best_next_move() # Execute next action self.sender({"action": best_move, "search_time": None}) def initialize_model(self, initial_data): """ Initialize your minimax model :param initial_data: Game data for initializing minimax model :type initial_data: dict :return: Minimax model :rtype: object Sample initial data: { 'fish0': {'score': 11, 'type': 3}, 'fish1': {'score': 2, 'type': 1}, ... 'fish5': {'score': -10, 'type': 4}, 'game_over': False } Please note that the number of fishes and their types is not fixed between test cases. """ # EDIT THIS METHOD TO RETURN A MINIMAX MODEL ### return None def search_best_next_move(self, initial_tree_node): """ Use your minimax model to find best possible next move for player 0 (green boat) :param model: Minimax model :type model: object :param initial_tree_node: Initial game tree node :type initial_tree_node: game_tree.Node (see the Node class in game_tree.py for more information!) :return: either "stay", "left", "right", "up" or "down" :rtype: str """ # EDIT THIS METHOD TO RETURN BEST NEXT POSSIBLE MODE FROM MINIMAX MODEL ### # NOTE: Don't forget to initialize the children of the current node # with its compute_and_get_children() method! ## initialize alpha, beta deoth etc with starting values alpha = float('-inf') beta = float('inf') depth = 3 player = 0 ##send root node and these parameters to minimax best_value, best_move = self.minimax(initial_tree_node, player, depth) print(best_move) return ACTION_TO_STR[best_move] def minimax(self, node, player, depth): children = node.compute_and_get_children() if len(children) == 0 or depth == 0: move = node.move print("move after state eval:", move) return self.evaluate_state(node.state), move else: if player == 0: best_value = float("-inf") player1 = 1 for child in children: state_value, max_move = self.minimax(child, player1, depth-1) print("state value in max clause", state_value) if state_value > best_value: best_value = state_value best_move = child.move print("best max move:", best_move) print("determined best max value", best_value) return best_value, best_move if player == 1: best_min_value = float("inf") player0 = 0 for child in children: min_value, min_move = self.minimax(child, player0, depth-1) if min_value < best_min_value: best_min_value = min_value best_min_move = child.move return best_min_value, best_min_move def evaluate_state2(self, state): #get difference between player scores scores = state.get_player_scores() player0_score = scores[0] #Max score player1_score = scores[1] #Min score return player0_score - player1_score def compute_distance(self, state): fish = state.get_fish_positions() players = state.get_hook_positions() sum_diff_distance = 0 for fish in list(fish.values()): distance_player_max = abs(fish[0]-players[0][0]) + abs(fish[1]-players[0][1]) distance_player_min = abs(fish[0] - players[1][0]) + abs(fish[1] - players[1][1]) diff_distance = distance_player_max - distance_player_min sum_diff_distance += abs(diff_distance) return sum_diff_distance
756fa601346f2d53c6a88a560bb94b2bbc4366d1
AlexaAndreas99/Faculty
/ArtificialIntelligence/HillClimb.py
4,439
3.53125
4
# -*- coding: utf-8 -*- """ Created on Sun Mar 8 14:21:16 2020 @author: Andreas-PC """ import copy as cp import qtpy as qt class State: def __init__(self,n): self.__board=[] self.__N=n self.__currentn=0 for i in range(n): self.__board.append(0) def __str__(self): return self.__board.__str__() def setValues(self,values): self.__board=values[:] def getSize(self): return self.__N def getValues(self): return self.__board[:] def isGoal(self): if self.__currentn==self.__N: return True else: return False def isSafe(self,clm): for i in range(0,self.__currentn): if self.__board[i]==clm or abs(clm-self.__board[i]) == self.__currentn-i: return False return True def place(self, clm): if clm>=0 and clm < self.__N: self.__board[self.__currentn]=clm self.__currentn+=1 def unPlace(self): if(self.__currentn>0): self.__currentn-=1 class Problem: def __init__(self,n): self.__state=State(n) def getRoot(self): return self.__state class Controller: def __init__(self,problem): self.__problem=problem def dfs(self, problem): if problem.getRoot().isGoal() == True: return problem.getRoot() else: for i in range(problem.getRoot().getSize()): if problem.getRoot().isSafe(i): problem.getRoot().place(i) res=self.dfs(problem) if res != None: return res problem.getRoot().unPlace() return None def greedy(self,Problem): n=self.__problem.getRoot().getSize() r=[0 for i in range(n)] board=[cp.deepcopy(r) for i in range(n)] for i in range(n): for j in range(n): if board[i][j]==0: for k in range(0,j): board[i][k]=-1 for k in range(j+1,n): board[i][k]=-1 for k in range(0,i): board[k][j]=-1 for k in range(i+1,n): board[k][j]=-1 o=cp.deepcopy(i) p=cp.deepcopy(j) while o>0 and p>0: board[o][p]=-1 o-=1 p-=1 o=cp.deepcopy(i) p=cp.deepcopy(j) while o<n and p<n: board[o][p]=-1 o+=1 p+=1 o=cp.deepcopy(i) p=cp.deepcopy(j) while o>0 and p<n: board[o][p]=-1 o-=1 p+=1 o=cp.deepcopy(i) p=cp.deepcopy(j) while o<n and p>0: board[o][p]=-1 o+=1 p-=1 board[i][j]=1 for i in range(n): for j in range(n): if board[i][j]==-1: board[i][j]=0 return board class UI: def __init__(self,n): self.__problem=Problem(n) self.__ctrl=Controller(self.__problem) def mainMenu(): pass def printDFS(self): print(self.__ctrl.dfs(self.__problem),'\n') n=self.__problem.getRoot().getSize() board = self.__problem.getRoot().getValues() r=[0 for i in range(n)] m=[cp.deepcopy(r) for i in range(n)] for i in range(n): m[i][board[i]]=1 for i in m: print (i) def printGreedy(self): for i in self.__ctrl.greedy(self.__problem): print (i) def main(): while True: print("0.Exit\n1.DFS\n2.Greedy") i=int(input()) n=int(input("Size: ")) ui=UI(n) if i==1: ui.printDFS() elif i==2: ui.printGreedy() else: return main() print("Hello World!")
43bac6c967c915f8841151ed13853272875621e0
IsmaTerluk/Progamacion_Orientada_Objetos
/ProbandoListaPorProgramador/Principal.py
785
3.578125
4
from ClasePersona import Persona from ClaseLista import Lista if __name__ == '__main__': lista=Lista() persona1=Persona('Ismael',21) persona2=Persona('Juan',28) persona3=Persona('Cluadio',22) persona4=Persona('Joaquin',30) lista.insertarVehiculoPorCola(persona1) lista.insertarVehiculoPorCola(persona2) lista.insertarVehiculoAlFinal(persona3) pos=int(input("Posicion en la que desea insetar el vehiculo: ")) lista.insertarVehiculoAdentro(persona4,pos) pos=int(input("Posicion en la que desea insetar el vehiculo: ")) lista.encontrarObjeto(pos-1) lista.listarDatosProfesores() lista.eliminarPorEdad(22) print("Eliminado\n") lista.listarDatosProfesores() print("s+++++++++++\n") lista.prueba()
458216d4dbb5e10cf96d54e84402bcd888f4bbc1
Billshimmer/blogs
/algorithm_problem/merge_intervals.py
948
3.84375
4
#!/usr/bin/python # -*- coding: latin-1 -*- # leetcode 56 # Definition for an interval. class Interval(object): def __init__(self, s=0, e=0): self.start = s self.end = e def to_list(self): print(self.start, self.end) class Solution(object): def merge(self, Intervals): Intervals = sorted(Intervals, key=lambda d:d.start) pre, cur = 0, 1 while cur < len(Intervals): preItem = Intervals[pre] curItem = Intervals[cur] if preItem.end >= curItem.start: Intervals.pop(cur) preItem.end = curItem.end if preItem.end <= curItem.end else preItem.end else: pre += 1 cur += 1 return Intervals if __name__ == "__main__": print(Solution().merge([ Interval(1,3), Interval(2,6), Interval(8,10), Interval(10,18), Interval(19,25) ]))
da86f2c7c4083a0cb7be29898368781dcb3df1a8
FabriceSalvaire/mamba-image
/test/basics/testLabelb.py
6,356
3.53125
4
""" Test cases for the image labelling function. The function only works with binary image as input and 32-bit image as output. For every set of pixels in the input image (pixels set to True that are connected), the output image is computed to give the entire pixels set a value (its label) that is unique inside the image. The result depends on grid and edge configurations. Python function: label C functions: MB_Labelb Test cases for the MB_Labelb function """ from __future__ import division from mamba import * import unittest class TestLabelb(unittest.TestCase): def setUp(self): # Creating two images for each possible depth self.im1_1 = imageMb(1) self.im1_2 = imageMb(1) self.im1_3 = imageMb(1) self.im8_1 = imageMb(8) self.im8_2 = imageMb(8) self.im32_1 = imageMb(32) self.im32_2 = imageMb(32) self.im32_3 = imageMb(32) self.im1s2_1 = imageMb(128,128,1) self.im32s2_1 = imageMb(128,128,32) def tearDown(self): del(self.im1_1) del(self.im1_2) del(self.im1_3) del(self.im8_1) del(self.im8_2) del(self.im32_1) del(self.im32_2) del(self.im32_3) del(self.im1s2_1) del(self.im32s2_1) if getImageCounter()!=0: print("ERROR : Mamba image are not all deleted !") def testDepthAcceptation(self): """Tests that incorrect depth raises an exception""" self.assertRaises(MambaError, label, self.im1_1, self.im1_2) self.assertRaises(MambaError, label, self.im1_1, self.im8_2) #self.assertRaises(MambaError, label, self.im1_1, self.im32_2) self.assertRaises(MambaError, label, self.im8_1, self.im1_2) self.assertRaises(MambaError, label, self.im8_1, self.im8_2) self.assertRaises(MambaError, label, self.im8_1, self.im32_2) self.assertRaises(MambaError, label, self.im32_1, self.im1_2) self.assertRaises(MambaError, label, self.im32_1, self.im8_2) self.assertRaises(MambaError, label, self.im32_1, self.im32_2) def testSizeCheck(self): """Tests that different sizes raise an exception""" self.assertRaises(MambaError, label, self.im1s2_1, self.im32_1) self.assertRaises(MambaError, label, self.im1_1, self.im32s2_1) def testParameterRange(self): """Verifies that an incorrect parameter raises an exception""" for i in range(257, 1000): self.assertRaises(MambaError, label, self.im32_1, self.im1_2, 0, i) self.assertRaises(MambaError, label, self.im32_1, self.im1_2, 255, 254) def testComputationUniqueLabel(self): """Labelling only one complex object""" (w,h) = self.im1_1.getSize() self.im1_1.reset() for x in range(1,w-3,4): for hi in range(1,h-1): self.im1_1.setPixel(1, (x, hi)) self.im1_1.setPixel(1, (x+1, hi)) for hi in range(h-2,0,-1): self.im1_1.setPixel(1, (x+2, hi)) self.im1_1.setPixel(1, (x+3, 1)) n = label(self.im1_1, self.im32_1, grid=SQUARE) self.assertTrue(n==1) n = label(self.im1_1, self.im32_1, grid=HEXAGONAL) self.assertTrue(n==1) def testComputationMultipleLabel(self): """Labelling numerous simple objects""" (w,h) = self.im1_1.getSize() self.im1_1.reset() n_exp = 0 vol_exp = 0 for wi in range(0,w-2,2): for hi in range(0,h-2,2): self.im1_1.setPixel(1, (wi,hi)) n_exp=n_exp+1 vol_exp = vol_exp+n_exp+(n_exp-1)//255 n = label(self.im1_1, self.im32_1, grid=SQUARE) self.assertTrue(n==n_exp) vol = computeVolume(self.im32_1) self.assertTrue(vol==vol_exp) n = label(self.im1_1, self.im32_1, grid=HEXAGONAL) self.assertTrue(n==n_exp) vol = computeVolume(self.im32_1) self.assertTrue(vol==vol_exp) def testComputationGridEffect(self): """Verifies grid configuration on labelling""" self.im1_1.reset() # first 'object' self.im1_1.setPixel(1, (6,3)) self.im1_1.setPixel(1, (5,4)) self.im1_1.setPixel(1, (6,5)) # second 'object' self.im1_1.setPixel(1, (4,8)) self.im1_1.setPixel(1, (5,9)) self.im1_1.setPixel(1, (4,10)) n = label(self.im1_1, self.im32_1, grid=SQUARE) self.assertTrue(n==2) n = label(self.im1_1, self.im32_1, grid=HEXAGONAL) self.assertTrue(n==6) def testComputationEdge(self): """Verifies that objects touching the edge are correctly labelled""" (w,h) = self.im1_1.getSize() self.im1_1.reset() self.im1_1.setPixel(1, (0,0)) self.im1_1.setPixel(1, (w-1,0)) self.im1_1.setPixel(1, (0,h-1)) self.im1_1.setPixel(1, (w-1,h-1)) n = label(self.im1_1, self.im32_1, grid=SQUARE) self.assertTrue(n==4) n = label(self.im1_1, self.im32_1, grid=HEXAGONAL) self.assertTrue(n==4) def testComputationRange(self): """Labelling in the lower byte according to range specified""" (w,h) = self.im1_1.getSize() self.im1_1.reset() for wi in range(0,w-2,2): for hi in range(0,h-2,2): self.im1_1.setPixel(1, (wi,hi)) n = label(self.im1_1, self.im32_1, 10, 230, grid=SQUARE) copyBytePlane(self.im32_1, 0, self.im8_1) l = list(range(256)) l[0] = 10 lookup(self.im8_1, self.im8_1, l) mi, ma = computeRange(self.im8_1) self.assertTrue(mi==10) self.assertTrue(ma==229) n = label(self.im1_1, self.im32_1, 10, 230, grid=HEXAGONAL) copyBytePlane(self.im32_1, 0, self.im8_1) l = list(range(256)) l[0] = 10 lookup(self.im8_1, self.im8_1, l) mi, ma = computeRange(self.im8_1) self.assertTrue(mi==10) self.assertTrue(ma==229) def getSuite(): return unittest.TestLoader().loadTestsFromTestCase(TestLabelb) if __name__ == '__main__': unittest.main()
de6b8049ebd59c50d04f20bd946af1828245ebf3
JoaoPauloAntunes/learning
/SQLite/basic_cmd/crud/update.py
1,419
3.734375
4
import sqlite3 from read_one import retrieve_single_product def update_produto(): code = input("Codigo: ") product = retrieve_single_product(code) user_want_to_update = False if product: description = product[1] price = product[2] description_buffer = input( "Descriรงรฃo atual: " + description + ", para manter digite ENTER --> " ) if description_buffer != "": description = description_buffer user_want_to_update = True price_buffer = input( "Preรงo atual: " + str(price) + ", para manter digite ENTER --> " ) if price_buffer != "": price = float(price_buffer) user_want_to_update = True if user_want_to_update: try: connection = sqlite3.connect("shop.db") # cria e/ou conecta cursor = connection.cursor() sql = "update products set description = ?, price = ? where code = ?" cursor.execute(sql, (description, price, code)) connection.commit() print("Produto " + description + " alterado com sucesso!") except Exception as error: print("ErrorUpdating: " + str(error), code) finally: cursor.close() connection.close() if __name__ == "__main__": update_produto()
0aee6e1417fc356dade15917ae958a329414ede4
targueriano/neuroIFC
/neuro-ifc_1.0.16_amd64/usr/local/lib/python2.7/dist-packages/neurolab/__init__.py
1,764
3.5625
4
๏ปฟ# -*- coding: utf-8 -*- """ Neurolab is a simple and powerful Neural Network Library for Python. Contains based neural networks, train algorithms and flexible framework to create and explore other neural network types. :Features: - Pure python + numpy - API like Neural Network Toolbox (NNT) from MATLAB - Interface to use train algorithms form scipy.optimize - Flexible network configurations and learning algorithms. You may change: train, error, initialization and activation functions - Unlimited number of neural layers and number of neurons in layers - Variety of supported types of Artificial Neural Network and learning algorithms :Example: >>> import numpy as np >>> import neurolab as nl >>> # Create train samples >>> input = np.random.uniform(-0.5, 0.5, (10, 2)) >>> target = (input[:, 0] + input[:, 1]).reshape(10, 1) >>> # Create network with 2 inputs, 5 neurons in input layer and 1 in output layer >>> net = nl.net.newff([[-0.5, 0.5], [-0.5, 0.5]], [5, 1]) >>> # Train process >>> err = net.train(input, target, show=15) Epoch: 15; Error: 0.150308402918; Epoch: 30; Error: 0.072265865089; Epoch: 45; Error: 0.016931355131; The goal of learning is reached >>> # Test >>> net.sim([[0.2, 0.1]]) # 0.2 + 0.1 array([[ 0.28757596]]) :Links: - `Home Page <http://code.google.com/p/neurolab/>`_ - `PyPI Page <http://pypi.python.org/pypi/neurolab>`_ - `Documentation <http://packages.python.org/neurolab/>`_ - `Examples <http://packages.python.org/neurolab/example.html>`_ """ __version__ = '0.3.5' # Development Status :: 1 - Planning, 2 - Pre-Alpha, 3 - Alpha, # 4 - Beta, 5 - Production/Stable __status__ = '3 - Alpha' from .tool import load from . import net
687ad0cc29a78af39d58209855b0b68bbf665f17
juhideshpande/LeetCode
/AsteroidCollision.py
621
3.546875
4
class Solution(object): def asteroidCollision(self, asteroids): """ :type asteroids: List[int] :rtype: List[int] """ result=[] for i in range(len(asteroids)): while result and asteroids[i]<0<result[-1]: if result[-1]<-asteroids[i]: result.pop() continue elif result[-1]==-asteroids[i]: result.pop() break else: result.append(asteroids[i]) return result
b1f2fb75fae04236bb24e6219848da0caf633111
daviddwlee84/LeetCode
/Python3/BinaryTree/BalancedBinaryTree/Naive110.py
978
3.765625
4
from ..TreeNodeModule import TreeNode class Solution: def isBalanced(self, root: TreeNode) -> bool: if not root: return True if not root.left and not root.right: return True return self._checkBalanced(root) and self.isBalanced(root.left) and self.isBalanced(root.right) def _checkBalanced(self, node: TreeNode) -> bool: if not node: return True ldepth = self._getDepth(node.left) rdepth = self._getDepth(node.right) if abs(ldepth - rdepth) > 1: return False else: return True def _getDepth(self, node: TreeNode) -> int: if not node: return 0 return 1 + max(self._getDepth(node.left), self._getDepth(node.right)) # Runtime: 60 ms, faster than 55.93% of Python3 online submissions for Balanced Binary Tree. # Memory Usage: 16.2 MB, less than 100.00% of Python3 online submissions for Balanced Binary Tree.
57085c65eaa49c7e26da412032736836deeda718
EH2007/veritas_fal2018
/Veritas/Hackerrank/scratch.py
177
3.5625
4
score_list = [] for i in range(int(input())): name = input() score = float(input()) in_list = [name, score] score_list.append(score_list) print(score_list)
f5c84557b9c10395148713394cb9b04bd2464290
0xRUDRA/Simplified-Advanced-Encryption-Standard
/src/rsa.py
6,409
3.75
4
""" author: RUDRA @description: --RSA Class module -- module(created) - func rsa class for encryption, decryptiona and key generation parameters: Key Generation Paramters (p,q,r) variables: p,q,e (key generation parameters) n (p*q) phi prKey (private Key) pubKey (public key) plaintext (message to be encrypted) ciphertext (encrypted message) f (flag for key parameters validation) methods: Constructor: initialises key parameters, validates them and generates key if key parameters valid genkey(): generates public key and private upon validation else assigns f = 1 validate(): checks the validity of key generation parameters encrypt(): encrypts the passes plaintext with the private key using rsa algorithm principles decrypt(): decrypts the passes ciphertext with the public key using rsa algorithn principles """ from src.func import ConvertToInt, ConvertToStr, gcd, is_coprime, isPrime, is_coprime, ConvertToInt, ConvertToStr, modInverse # importing methods from func module class rsa: # constructor to assign key parameters, validate key parameter and generate private key def __init__(self, p, q, e): self.p = p self.q = q self.e = e self.n = self.p * self.q self.phi = (self.p - 1) * (self.q - 1) self.prKey = None # = genKey(self) self.pubKey = None self.plaintext = None self.ciphertext = None # self.validate() self.f = 0 self.genKey() def validate(self): flag = True # flage for validity TRUE assuming valid at start # check p if (self.p == self.q) or (self.q == self.e): print("Enter distinct values for p,q,e") flag = False if self.p != int(self.p): print('{} is not an integer. Please enter a valid value for p'.format( self.p)) flag = False # return False if not isPrime(self.p): print('{} is not prime. Please enter a valid value for p'.format( self.p)) flag = False # return False # check q if self.q != int(self.q): print('{} is not an integer. Please enter a valid value for q'.format( self.q)) flag = False # return False if not isPrime(self.q): print('{} is not prime. Please enter a valid value for q'.format( self.q)) flag = False # return False # check e if self.e != int(self.e): print('{} is not an integer. Please enter a valid value for e'.format( self.e)) flag = False # return False if self.e >= self.phi or self.e <= 1: print('{} is greater than or equal to phi or less than 2'.format(self.e)) flag = False if is_coprime(self.e, self.phi) == False: print('{} is a factor of phi. Enter a valid value for e'.format( self.e)) flag = False # return False if flag == False: return False self.pubKey = self.e # when valid assign public key to pubKey return True def genKey(self): if self.validate() == True: # generate key when valid key parameters # finding the modular inverse d = modInverse(self.pubKey, self.phi) self.prKey = d return d self.f = 1 def encrypt(self, plaintext): # encrypting self.plaintext = plaintext # converting plaintext to digits using convertToInt() for encryption plaintext = ConvertToInt(plaintext) cipher_arr = [] while plaintext: rem = plaintext % 10 # rsa encryption formula encrypting each number corresponding to each character encrypt_digit = (rem**self.pubKey) % (self.n) cipher_arr.insert(0, encrypt_digit) plaintext = plaintext//10 # genCipherText() assigns ciphertext to the class variable in string form self.getCiphertext(cipher_arr) return cipher_arr # returns list def decrypt(self, ciphertext): plaintext = 0 for i in ciphertext: # decrypting each digit in the ciphertext decrypt_digit = (i**self.prKey) % (self.n) plaintext = plaintext * 10 + decrypt_digit # finally converting the ciphertext (int) into string plaintext = ConvertToStr(plaintext) return plaintext def getCiphertext(self, ciphertextarr): # converting list to string ciphertextarr = ' '.join(map(str, ciphertextarr)) self.ciphertext = ciphertextarr def encrypt(plaintext, n, e): # equivalent to def encrypt(self, plaintext): for encryption with any key without instantiating a class plaintext = ConvertToInt(plaintext) cipher_arr = [] while plaintext: rem = plaintext % 10 encrypt_digit = (rem**e) % n cipher_arr.insert(0, encrypt_digit) plaintext = plaintext//10 getCiphertext(cipher_arr) return cipher_arr # # equivalent to def getCiphertext(self, ciphertextarr): for encryption with any key without instantiating a class def getCiphertext(ciphertextarr): ciphertextarr = ''.join(map(str, ciphertextarr)) return ciphertextarr # equivalent to def decrypt(self, ciphertext): for decryption with any key without instantiating a class def decrypt(ciphertext, n, privateKey): plaintext = 0 for i in ciphertext: decrypt_digit = (i**privateKey) % (n) plaintext = plaintext * 10 + decrypt_digit plaintext = ConvertToStr(plaintext) return plaintext # a = rsa(23, 43, 19) # en = a.encrypt('00000') # n = a.n # e = a.pubKey # d = a.prKey # print('d: ', d) # print('e: ', e) # print('phi: ', a.phi) # print(en) # print(a.ciphertext) # en2 = a.decrypt(en) # print(en2)
522ce42319ab526d430d7f099f20e6d5ddbc3640
fedeMorlan/semin_python_2021
/practico2/eje6.py
1,185
3.9375
4
""" 6. Dada una frase donde las palabras pueden estar repetidas e indistintamente en mayรบsculas y minรบsculas, imprimir una lista con todas las palabras sin repetir y en letra minรบscula. """ frase = """ Si trabajรกs mucho CON computadoras, eventualmente encontrarรกs que te gustarรญa automatizar alguna tarea. Por ejemplo, podrรญas desear realizar una bรบsqueda y reemplazo en un gran nรบmero DE archivos de texto, o renombrar y reorganizar un montรณn de archivos con fotos de una manera compleja. Tal vez quieras escribir alguna pequeรฑa base de datos personalizada, o una aplicaciรณn especializada con interfaz grรกfica, o UN juego simple. """ # RESUELTO CON LISTA porque todavรญa no se vio en clase el set. for caracter in frase: # recorre toda la frase eliminando simbolos que no sean letras if not caracter.isalpha(): frase = frase.replace(caracter, ' ') lista_frase = frase.lower().split() # ya bajo a minusculas porque el resultado se imprimira en minuscula lista_compacta = [] for x in lista_frase: if x not in lista_compacta: lista_compacta.append(x) # solo crea entradas nuevas en el diccionario si la clave no existรญa print(lista_compacta)
26c11ebd8994ef897d10a21e5adaafed80f7a3e1
DhruviV/LeetCode
/string_to_int.py
73
3.578125
4
s="dhruvi" ans="" for char in s: ans=ans + str(ord(char)) print(ans)
91a84bbe9d6b4fc403544e004b7bfb81fb80c483
hvijaycse/Data-Structures-and-Algorithms-Coursera
/Algorithmic Toolbox/week2/8_fibonacci_sum_squares.py
827
3.90625
4
# Uses python3 def get_fibonacci_huge_naive(): m = 10 previous = 0 current = 1 sequense = [0, 1] while True: previous, current = current, previous + current s = current % m if s == 0: previous, current = current, previous + current s2 = current % m if s2 == 1: break else: sequense.append( s) sequense.append( s2) continue else: sequense.append(s) return sequense def fibonacci_sum_squares_naive(n): series = get_fibonacci_huge_naive() length = len(series) a = series[ n % length] b = series[ (n + 1) % length] return (a*b) % 10 if __name__ == '__main__': n = int(input()) print(fibonacci_sum_squares_naive(n))
f1f488fdc2967c7f2c1a3497e5170976b94a120f
ARSimmons/IntroToPython
/Students/michel/session02/fizzBuzz.py
411
4.1875
4
# -*- coding: utf-8 -*- """ Created on Tue Oct 07 20:33:17 2014 @author: Michel """ for number in range(100): if not number % 3 == 0 and not number % 5 == 0: print number elif number % 3 == 0 and not number % 5 == 0: print 'Fizz' elif not number % 3 == 0 and number % 5 == 0: print 'Buzz' else: print 'FizzBuzz'
37da1de5cb511b8f0930dde207d551fb777220ef
mortiz96/Learning-Scripts
/Primeros cursos/palindromo.py
415
3.90625
4
def palindromo(palabra): palabra=palabra.replace(' ','') palabra=palabra.lower() palabra_inv=palabra[::-1] if palabra==palabra_inv: return True else: return False def run(): palabra=input('Escribe una palabra: ') es_palindromo=palindromo(palabra) if es_palindromo==True: print('Es palรญndromo') else: print('No es palรญndromo') if __name__ == '__main__': run()
04bdf3627f8329aca025c7effdc22adba7f1606b
aldst/redes_neuronales
/adaline.py
3,985
3.578125
4
import random import math import numpy as np import matplotlib.pyplot as plt class ConjuntoEntrenamiento: def __init__(self, x1, x2,x3, esperado): self.x1 = x1 self.x2 = x2 self.x3 = x3 self.esperado = esperado class Etapa: def __init__(self, conjunto): self.w1 = 0 self.w2 = 0 self.w3 = 0 self.error = 0 self.conjunto = conjunto def inicializar_pesos(self, w1, w2, w3): self.w1 = w1 self.w2 = w2 self.w3 = w3 def salida_red(self): return round(self.w1 * self.conjunto.x1 + self.w2 * self.conjunto.x2 + self.w3 * self.conjunto.x3,3) def hallar_error(self, y): self.error = round(self.conjunto.esperado - y,3) def modifica_pesos(self,alpha): self.w1 = round( self.w1 + alpha * self.error * self.conjunto.x1 , 3 ) self.w2 = round( self.w2 + alpha * self.error * self.conjunto.x2 , 3 ) self.w3 = round( self.w3 + alpha * self.error * self.conjunto.x3 , 3 ) def algoritmo(conjuntos_entrenamiento): # se crea valores aletoria paraa los pesos y lumbral w1 = 0.84 #random.randint(0,100) / 100 w2 = 0.394 #random.randint(0,100) / 100 w3 = 0.783 #random.randint(0,100) / 100 alpha = 0.3 parada = True while parada: pesos_etapa = [] for conjunto in conjuntos_entrenamiento: #selecciona un valor de x1,x2 y umbral etapa = Etapa(conjunto) etapa.inicializar_pesos(w1,w2,w3) # se calcula la red de salida y = f(x1w1 + w2x2 + ... + w3x3) y = etapa.salida_red() etapa.hallar_error(y) etapa.modifica_pesos(alpha) w1 = etapa.w1 w2 = etapa.w2 w3 = etapa.w3 pesos_etapa.append(etapa.error) parada = verificar_parada(pesos_etapa) return w1,w2,w3 def encontrar_valores(conjuntos_entrenamiento, w1, w2, w3): total_pesos = [] for conjunto in conjuntos_entrenamiento: resultado = w1 * conjunto.x1 + w2 * conjunto.x2 + w3 * conjunto.x3 pesos = np.array(['{}, {}, {}'.format(conjunto.x1,conjunto.x2,conjunto.x3),resultado]) total_pesos.append(pesos) total_pesos = np.array(total_pesos) return total_pesos def graficar(valores): #entrada = ['0,0,1','0,1,0','0,1,1','1,0,0','1,0,1','1,1,0','1,1,1'] entrada = valores[:,0] deseado = valores[:,1] plt.figure(figsize=(20,10)) plt.plot(entrada,deseado, marker="o") plt.yticks(deseado, rotation='vertical') plt.xticks(entrada) plt.title("Entradas vs. Esperados") plt.xlabel('Entradas') plt.ylabel('Esperadas') plt.show() def convertir_2_decimales(peso): dec, unid = math.modf(peso) dec = (math.floor(dec * 10 **2))/10**2 return round(unid + dec , 2) def verificar_parada(pesos_etapas): suma = 0 for peso in pesos_etapas: suma += peso suma /= 2 if suma < 0: return False else: return True def inicializar_input(): conjuntos_entrenamiento = [] conjuntos_entrenamiento.append(ConjuntoEntrenamiento(0,0,1,1)) conjuntos_entrenamiento.append(ConjuntoEntrenamiento(0,1,0,2)) conjuntos_entrenamiento.append(ConjuntoEntrenamiento(0,1,1,3)) conjuntos_entrenamiento.append(ConjuntoEntrenamiento(1,0,0,4)) conjuntos_entrenamiento.append(ConjuntoEntrenamiento(1,0,1,5)) conjuntos_entrenamiento.append(ConjuntoEntrenamiento(1,1,0,6)) conjuntos_entrenamiento.append(ConjuntoEntrenamiento(1,1,1,7)) return conjuntos_entrenamiento def main(): conjuntos_entrenamiento = inicializar_input() w1, w2, w3 = algoritmo(conjuntos_entrenamiento) w1 = convertir_2_decimales(w1) w2 = convertir_2_decimales(w2) w3 = convertir_2_decimales(w3) entradas = encontrar_valores(conjuntos_entrenamiento,w1, w2, w3) graficar(entradas) if __name__ == "__main__": main()
f0406ea2b5c70a340116a6d891edf08e61ea6463
fernandadreis/Duel-52
/duel52.py
2,137
3.546875
4
from time import sleep from lanes import game_board from deck import make_deck, pick_a_card, show_cards from actions import draw_card deck = make_deck() # the deck of this game # preparing to the start of the game # flag to alert the end-game end_game = False # dealing cards face_down = deck[0:6] # 1 face_down card in each lane for each player # each player starts with 5 cards on hand hand_player1 = deck[6:11] hand_player2 = deck[11:16] draw_pile = deck[16:42] # 10 cards are removed from the deck, so the draw_pile has 26 cards # "put the face_down cards on the board" / give a variable to the cards on the game_board a01 = deck[0] a02 = deck[1] a03 = deck[2] b01 = deck[3] b02 = deck[4] b03 = deck[5] # leave the other spaces of the board empty a11 = ' ' a12 = ' ' a13 = ' ' a21 = ' ' a22 = ' ' a23 = ' ' a31 = ' ' a32 = ' ' a33 = ' ' b11 = ' ' b12 = ' ' b13 = ' ' b21 = ' ' b22 = ' ' b23 = ' ' b31 = ' ' b32 = ' ' b33 = ' ' # STAR OF THE GAME # presenting the game print('Welcome to Duel 52\n') sleep(0.5) print('This game was created by Judd Madden and Nina Riddell.\n') sleep(0.3) print("And I'm trying to make their game on Python :D\n") sleep(0.3) print('Enjoy\n') sleep(0.5) print('.') print('.') print('.\n') # show game board to the players print("I'm going to display your face down cards for you.\n") sleep(0.5) # '??' represents the face_down cards game_board(a01='??',a02='??',a03='??',a11=' ',a12=' ',a13=' ',a21=' ',a22=' ',a23=' ',a31=' ',a32=' ',a33=' ', b01='??',b02='??',b03='??',b11=' ',b12=' ',b13=' ',b21=' ',b22=' ',b23=' ',b31=' ',b32=' ',b33=' ') sleep(0.5) # show player1 hand print('Player 1 starts the game.\n') sleep(0.3) print('This is Player 1 hand:') print(show_cards(hand_player1)) print('Draw a card') # draw a card when the turn starts draw_pile, card, end_game = draw_card(draw_pile,end_game) hand_player1 = hand_player1 + [card] print(show_cards(hand_player1)) # give the options to the player print('You can use three actions. What do you want to do?')
59c52a46f2fed91aa5c0e80e6b9578fe917fd9b1
mhernandez2/Python
/sumatorianp.py
201
3.75
4
n = int(raw_input("ingrese n numeros ")) i = int(raw_input("ingrese limite de suma ")) suma=0 if n>i : print "no se efectuara suma n debe ser < que i" else : while n<=i : suma+=n n+=1 print suma
f5d14dd96ef3dbebfec3873666e46ee707af1189
monty123456789/coding_one_submission
/Week3_PigLatin.py
860
4.03125
4
vowels = ('a', 'e', 'i', 'o', 'u', 'y') consonants = ('b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'z') word1 = input('enter a word: ') def pig_latin(word): if word[0] in vowels: print(word + 'yay') elif word[0] in consonants and word[1] in vowels: first_letters = word[0:1] word_w_first = word[1:] new_word = word_w_first + first_letters + 'ay' print(new_word) elif word[0:1] in consonants and word[2] in vowels: first_letters = word[0:2] word_w_first = word[2:] new_word = word_w_first + first_letters + 'ay' print(new_word) elif word[1:2] in consonants: first_letters = word[0:3] word_w_first = word[3:] new_word = word_w_first + first_letters + 'ay' print(new_word) pig_latin(word1)
4a21fc0672c7c34b0f5ca996efac54cd60a7082c
mmiah00/Sudoku
/clique.py
307
3.5
4
class clique: def __init__(self): self.group = [] #one clique is 9 numbers in either a row, column, or square def check_group (list): uniqueNums = set (group) i = 1 while (i < 10): if !(i in uniqueNums): return False return True
d082272f859ab1fbfc7c0620769e889692aea563
Damon0626/Leetcode-
/069-Sqrt(x).py
737
3.578125
4
# -*-coding:utf-8-*- # @Author: Damon0626 # @Time : 18-11-4 ไธ‹ๅˆ10:53 # @Email : [email protected] # @Software: PyCharm class Solution: def mySqrt(self, x): """ :type x: int :rtype: int """ """ if x < 0: return 0 else: return int(x**0.5) """ if x < 2: return x else: # ไบŒๅˆ†ๆŸฅๆ‰พ low = 0 high = x while(low<high): mid = (low + high)//2 if x/mid >= mid: low = mid + 1 else: high = mid return low-1 if __name__ == "__main__": test = Solution() print(test.mySqrt(8))
6c4381f77a400d43ab1a9228e73dbbed19c7ad83
sakshimadan20/Python-Projects
/fundamentals/chapter4/4_example_string_reverse.py
167
4.28125
4
#to print the string in reverse order myString = "Programming" #print(len(myString)) for count in range(1, len(myString)+1): print(myString[-count], end="")
a2da8463d7327887b8220fec6ffbf4e295cead39
ktel1218/skills2
/skillstest2.py
1,525
4.09375
4
# Write a function that takes an iterable (something you can loop through, ie: string, list, or tuple) and produces a dictionary with all distinct elements as the keys, and the number of each element as the value def count_unique(some_iterable): d = {} while some_iterable != []: key = some_iterable.pop() d[key] = d.get(key, 0) + 1 print d # Given two lists, (without using the keyword 'in' or the method 'index') return a list of all common items shared between both lists def common_items(list1, list2): list_mash = [] temp1 = list1[:] while temp1 != []: i = temp1.pop() temp2 = list2[:] while temp2 != []: j = temp2.pop() if i == j: list_mash.append(i) print list_mash # Given two lists, (without using the keyword 'in' or the method 'index') return a list of all common items shared between both lists. This time, use a dictionary as part of your solution. def common_items2(list1, list2): d = {} list_mash = [] temp1 = list1[:] temp2 = list2[:] while temp1 != []: i = temp1.pop() d[i] = d.get(i, True) while temp2 != []: j = temp2.pop() d[j] = d.get(j) if d[j] == True: list_mash.append(j) print list_mash first_list = ["hug", 'bug', 'tug', 'glug', 'a', 'e', 'f'] second_list = ['a', 'b', 'c', 'd', 'tug', 'glug', 'e', 'f'] count_unique(["dog", "dog", "cat", "rat", "Pat", "dog"]) common_items2(first_list, second_list)
0a89014452834708e697c9da1c38a4f1107e217c
ankurgokhale05/LeetCode
/Amazon/Trees/124-Binary_Tree_Max_Path_Sum.py
845
3.78125
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None ''' See Most Voted 2nd solution ''' class Solution: def maxPathSum(self, root: TreeNode) -> int: max_path_sum = float('-inf') def get_max_gain(node: TreeNode): nonlocal max_path_sum if not node: return 0 max_left_gain = max(get_max_gain(node.left),0) max_right_gain = max(get_max_gain(node.right),0) current_max_path = node.val + max_left_gain + max_right_gain max_path_sum = max(max_path_sum, current_max_path) return node.val + max(max_left_gain,max_right_gain) get_max_gain(root) return max_path_sum
fef474436fa23697a0539df0fe47ed146f3b3b78
jsinoimeri/Gr12-Python
/Task 2/hash_table.py
6,278
3.875
4
from linked_list import * from hashing import * from contacts import * class HashTable(object): def __init__(self, size): '''H(size) creates a hash table with the desired size''' self.__buckets = [] for num in range(size): self.__list = SortedList() self.__buckets.append(self.__list) def __str__(self): '''H.__str__() or H --> str Returns the string representations of a hash table.''' table = "" for num in range(len(self.__buckets)): table += "{%3i}%s\n" %(self.__buckets[num].size(), str(self.__buckets[num])) return table def insert(self, value): '''H.insert(value) --> None Inserts the value into the appropriate bucket postition determined by the hash code.''' code = int(hash_code(value)) pos = int(code % len(self.__buckets)) self.__buckets[pos].insert(value) def is_empty(self): '''H.is_empty() --> Boolean Returns whether or not the hash table is empty.''' for i in range(len(self.__buckets)): if self.__list.is_empty(): boolean = True else: boolean = False break return boolean def retrieve(self, value): '''H.retrieve(value) --> object Return a reference to the Contact from the table or None if it is not present.''' code = int(hash_code(value)) pos = int(code % len(self.__buckets)) current = self.__buckets[pos].get_first() if current != None: data = current.get_data() previous = current for i in range(len(str(self.__buckets[pos]))): if current != None: previous = current current = current.get_next() data = previous.get_data() if value == data: return self.__buckets[pos].retrieve(value) def delete(self, value): '''H.delete(value) --> None: Deletes the Contact form the table''' code = int(hash_code(value)) pos = int(code % len(self.__buckets)) current = self.__buckets[pos].get_first() data = current.get_data() previous = current for i in range(len(str(self.__buckets[pos]))): if current != None: previous = current current = current.get_next() data = previous.get_data() if value == data: self.__buckets[pos].delete(value) class SortedList(LinkedList): def __init__(self): LinkedList.__init__(self) def insert(self, value): '''S.insert(value) --> None Inserts the value in the correct sorted place within the list.''' if self.get_first() == None: self.set_first(ListNode(value, None)) else: current = self.get_first() data = current.get_data() previous = current while current != None and data < value: previous = current current = current.get_next() if current != None: data = current.get_data() if current != None and previous.get_data() < value and current.get_data() > value: previous.set_next(ListNode(value, ListNode(current.get_data(), current.get_next()))) elif data < value and current == None: previous.set_next(ListNode(value, None)) elif value < previous.get_data() and current != None: self.set_first(ListNode(value, ListNode(data, current.get_next()))) def delete(self, value): '''S.delete(value) --> None Deletes the value inside the sorted linked list. If the value is not in the position that it should be it will not go any further to look for it.''' current = self.get_first() data = current.get_data() if data == value and current == self.get_first(): self.set_first(current.get_next()) while current.get_next() != None: previous = current current = current.get_next() if current != None and current.get_data() == value and current.get_next() == None: if current.get_data() == value: previous.set_next(None) elif current != None and current.get_next() != None: data = current.get_data() if data == value: previous.set_next(ListNode(current.get_next().get_data(), current.get_next().get_next())) def retrieve(self, value): '''S.retrieve(value) --> object Return the first occurence of the value in the sorted linked list. If the value is not in its rightful place, it will stop searching and return None.''' current = self.get_first() data = current.get_data() if current == self.get_first() and data == value: return data while current != None and data <= value: previous = current current = current.get_next() if current != None and current.get_next() != None: data = current.get_data() if data == value: return data elif current == None: data = previous.get_data() if data < value and previous.get_next().get_data() == value: return previous.get_next().get_data()
1c9d085c55bdf5a2f7898cf97e55c4ddc364b7f0
Huchengxi/Programming-Exericises
/python_event/thread_test.py
1,057
3.8125
4
# -*- coding:utf-8 -*- import time from collections import deque from random import Random import threading class Example(): def __init__(self): self.r = Random(time.time()) def worker_run(self, name, q): while True: if q: print("%s pop number: %s, %s numbers left" % (name, q.pop(), len(q))) time.sleep(0.001) def manager_run(self, worker_num): queue_list = [deque() for i in range(worker_num)] worker_list = [threading.Thread(target=self.worker_run, args=["Thread-%s" % i, queue_list[i]]) for i in range(worker_num)] for worker in worker_list: worker.start() while True: i = 0 while i < self.r.randint(0, 20): queue_list[self.r.randint(0, worker_num - 1)].appendleft( self.r.randint(1, 100) ) i += 1 time.sleep(self.r.random() / 100) if __name__ == '__main__': Example().manager_run(3)
a7778c0bce559da27d608c7c3b37cda51845eba3
ranxx/map-house
/unique.py
504
3.625
4
import csv def unqiue(filename): # ่ฏปๅ–csvๆ•ฐๆฎ w = open(filename,"r") # w.readline() ret = w.readlines() # print(ret[:3]) # return print(len(ret)) # ๅŽป้‡ ret = set(ret) print(len(ret)) # ้‡ๅ†™ uw = open("unique"+filename, "a+") uw.writelines(ret) # csv_writer = csv.writer(uw, delimiter=",") # csv_writer.writerows(ret) uw.close() w.close() pass if __name__ == "__main__": filename = "kunming.csv" unqiue(filename)
645ba6eea58f471748c3f7f66f5b42140e4a4ce9
Hhn202/APweofingwoi
/AP1/util/generate_expressions.py
1,677
3.890625
4
#!/usr/bin/python # This is just the very beginning of a script that can be used to process # arithmetic expressions. At the moment it just defines a few classes # and prints a couple example expressions. # Possible additions include methods to evaluate expressions and generate # some random expressions. # Stolen from: http://stackoverflow.com/questions/6881170/is-there-a-way-to-autogenerate-valid-arithmetic-expressions from random import random, randint, choice, seed import sys class Expression: pass class Number(Expression): def __init__(self, num): self.num = num def __str__(self): return str(self.num) class BinaryExpression(Expression): def __init__(self, left, op, right): self.left = left self.op = op self.right = right def __str__(self): return str(self.left) + " " + self.op + " " + str(self.right) class ParenthesizedExpression(Expression): def __init__(self, exp): self.exp = exp def __str__(self): return "( " + str(self.exp) + " )" def randomExpression(prob): p = random() if p > prob: return Number(randint(1, 100)) elif randint(0, 1) == 0: return ParenthesizedExpression(randomExpression(prob / 1.2)) else: left = randomExpression(prob / 1.2) op = choice(["+", "-", "*", "/"]) right = randomExpression(prob / 1.2) return BinaryExpression(left, op, right) if __name__ == "__main__": ITERATIONS = 10 if len(sys.argv) > 1: ITERATIONS = int(sys.argv[1]) if len(sys.argv) > 2: seed(sys.argv[2]) for i in range(ITERATIONS): print(randomExpression(1))
4dca4cf87bc9e595af6fd407939eefe9812ee401
anitrajpurohit28/PythonPractice
/python_practice/List_programs/9_count_occurance_of_element.py
991
4.1875
4
# 9 Python | Count occurrences of an element in a list input_list = [15, 6, 7, 10, 12, 20, 10, 28, 10] key = 10 print("------- for loop-------") count = 0 for element in input_list: if element == key: count += 1 print(f"Element {key} occurred {count} times") print("-------builtin count()-------") count = 0 count = input_list.count(key) print(f"Element {key} occurred {count} times") print("-------counter from collections-------") import collections counter_list = collections.Counter(input_list) count = counter_list[key] print(counter_list) print(f"Element {key} occurred {count} times") print("-------item counter--------") # Letโ€™s say we want to count each element in a list and store in another list or say dictionary. lst = ['Cat', 'Bat', 'Sat', 'Cat', 'Mat', 'Cat', 'Sat'] item_counter_list = [[item, lst.count(item)] for item in set(lst)] print(item_counter_list) item_counter_dict = [{item: lst.count(item)} for item in set(lst)] print(item_counter_dict)
c1905ab495050522d54f2d5391d3c19f9d98f108
kryman0/school
/python/analyzer/analyzer.py
3,500
4.03125
4
""" Module for text analyzing. """ import re, string filename = None def check_file_exists(filename): """ Check if file exists. """ file_not_found = True try: open(filename, "r") return not file_not_found except: print("Kunde ej hitta filen.\n") return file_not_found def file(filename, mode="r"): """ Get the file, e.g. "phil.txt". """ return open(filename, mode) def lines(filename): """ Analyze the number of non-empty lines. """ get_file = file(filename) non_empty_lines = 0 with get_file as fh: lst_from_file = fh.read().split("\n") for item in lst_from_file: if item == "": continue else: non_empty_lines += 1 if filename: print("Antalet icke-tomma rader:", non_empty_lines) return non_empty_lines def words(filename): """ Analyze number of words. """ get_file = file(filename) words = 0 with get_file as fh: lst_from_file = fh.read().split() for word in lst_from_file: words += 1 if filename: print("Antalet ord:", words) return words def letters(filename): """ Analyze number of characters. """ get_file = file(filename) with get_file as fh: lst_from_file = fh.read().split("\n") chars = 0 for item in lst_from_file: for letter in item: chars += 1 get_file = file(filename) with get_file as fh: all_letters = re.findall("[a-z]", fh.read(), re.IGNORECASE) if filename: print( "Alla tecken fรถrutom rader:", chars, "\n" "Antal bokstรคver:", len(all_letters) ) return chars, len(all_letters) def word_frequency(filename): """ Analyze top seven words frequency. """ get_file = file(filename) with get_file as fh: lst_from_file = fh.read().lower().translate( str.maketrans("", "", string.punctuation) ).split() sorted(lst_from_file) words_dict = {} for item in lst_from_file: words_dict[item] = lst_from_file.count(item) result_list = [] for key, value in words_dict.items(): result_list.append((value, key)) result_list.sort(reverse=True) if filename: print("Sju hรถgsta fรถrekommande orden:") for value, key in result_list[:7]: print( key, round(value / len(lst_from_file) * 100, 2), "%" ) return result_list, len(lst_from_file) def letter_frequency(filename): """ Analyze top seven letters frequency. """ get_file = file(filename) with get_file as fh: lst_from_file = fh.read().lower().translate( str.maketrans("", "", string.punctuation) ).split() lst_from_file.sort() letters_list = [] for item in lst_from_file: for letter in item: letters_list.append(letter) letters_list.sort() letters_dict = {} for letter in letters_list: letters_dict[letter] = letters_list.count(letter) result_list = [] for key, value in letters_dict.items(): result_list.append((value, key)) result_list.sort(reverse=True) if filename: print("Sju hรถgsta fรถrekommande bokstรคverna:") for value, key in result_list[:7]: print( key, round(value / len(letters_list) * 100, 2), "%" ) return result_list, len(letters_list)
a5db68ddd93fb42c9a675324ac1a4a934dae090a
PhamNguyen18/PHY403
/hw/hw2/dart_class.py
7,518
4.125
4
""" Author: Pham Nguyen Last Updated: 02-05-20 """ import argparse import numpy as np import matplotlib.pyplot as plt from tqdm import tqdm class DartGame: """ Class to play dart game. Rules: 1. A dart is throw randomly at a board. One point is given even if the first throw is a miss. 2. If the dart lands in the circle, add one point to the score. 3. Update the radius of the circle. The new radius is determined by a chord that is perpendicular to the line joining the center and the position of the dart. The chord's midpoint is defined by the dart position. 4. Repeat steps 1-3 until a miss occurs then end the game """ def __init__(self, radius=1): self.radius = radius self.game_result = () @staticmethod def new_radius(x, y, r): """ Calculates one-half the length of a chord to set as the new radius for the next circle. Paramters --------- x, y: float (x, y) coordinates of dart r: float The radius of the circle Returns ------- radius: float New radius of the circle """ h = np.sqrt(x**2 + y**2) radius = np.sqrt(r**2 - h**2) return radius def play_round(self, cartesian=True): """ Play a around of darts. A random x and y coordinate pair is selected by default. If cartesian is set to FALSE, a random r and angle pair is selected instead. """ win = True r = self.radius score = 1 round_list = [] while win is True: if cartesian: x_rand = np.random.uniform(-self.radius, self.radius) y_rand = np.random.uniform(-self.radius, self.radius) else: r_rand = np.random.uniform(0, self.radius) theta_rand = np.random.uniform(0, 2*np.pi) x_rand = r_rand * np.cos(theta_rand) y_rand = r_rand * np.sin(theta_rand) if x_rand**2 + y_rand**2 <= r**2: score += 1 round_list.append((score, x_rand, y_rand, r)) r = self.new_radius(x_rand, y_rand, r) else: win = False if score > 1: self.game_result = round_list else: self.game_result = [(1, x_rand, y_rand, self.radius)] return None class DartSimulation: """ Class to run a simulation of many dart throwing games. Also includes some plotting methods. """ def __init__(self, num_games=1000, radius=1, cartesian=True): """ Class constructor for dart game simulations. num_games: int Total number of games to simulate radius: float Radius of all board games (does not change!) game_list: dict{int: tuple} Dictionary containing the results of each game. {game #: (score, x position, y position, radius)} game_count: int Labels games from 1 to num_games """ self.num_games = num_games self.radius = radius self.cartesian = cartesian self.games_list = {} self.game_count = 0 def simulate(self): """ Play N number of games as given by the num_games variable. """ game = DartGame(self.radius) for i in tqdm(range(self.num_games)): self.game_count += 1 game.play_round(self.cartesian) self.games_list[self.game_count] = game.game_result return None def clear_board(self): # Clear all board games from class self.games_list.clear() return None def hist_games(self, save=False): """ Plots a histogram of game final scores. Option to save histogram as well. """ scores = [s[-1][0] for s in self.games_list.values()] high_score = np.max(scores) fig = plt.hist(scores, bins=range(high_score), ec="white", alpha=0.9) plt.grid(axis="y", color="whitesmoke") plt.gca().set_facecolor("whitesmoke") plt.gca().tick_params(direction="in", axis="both") plt.xlim(0, high_score) plt.xlabel("Score") plt.ylabel("Frequency") print("Mean: {:0.3f}".format(np.mean(scores))) print("Std: {:0.3f}".format(np.std(scores))) plt.show() if save: plt.savefig("histogram_{}.png".format(self.num_games), dpi=150) return fig def scatter_games(self, save=False): """ Make scatter plot of all throws for all games. Option to save image. """ x = [] y = [] for single_game in self.games_list.values(): for data in single_game: x.append(data[1]) y.append(data[2]) fig = plt.scatter(x, y, s=10, alpha=0.75) plt.tight_layout() plt.gca().set_aspect('equal') plt.xlim(-self.radius, self.radius) plt.ylim(-self.radius, self.radius) plt.gca().set_facecolor("whitesmoke") plt.gca().tick_params(direction="in", axis="both") plt.xlabel("X-position") plt.ylabel("Y-position") plt.show() if save: plt.savefig("scatter_{}.png".format(self.num_games), dpi=150) return fig def plot_game(self, number=1, save=False): """ Plot of a single game and save option. """ fig, ax = plt.subplots() # Plot dart throws x = [i[1] for i in self.games_list[number]] y = [i[2] for i in self.games_list[number]] radii = [i[3] for i in self.games_list[number]] ax.scatter(x, y) x_length = len(x) for i in range(x_length): ax.annotate(str(i), (x[i], y[i])) # Draw circles circle1 = plt.Circle((0, 0), self.radius, fill=None) ax.add_artist(circle1) for i, r in enumerate(radii): new_circle = plt.Circle((0, 0), r, fill=None) ax.add_artist(new_circle) ax.annotate(str(i), (0, r)) plt.title("Plotting game {} of {}".format(number, self.num_games)) plt.xlim(-self.radius, self.radius) plt.ylim(-self.radius, self.radius) ax.set_aspect('equal') ax.set_facecolor('whitesmoke') plt.show() if save: plt.savefig("single_game_{}.png".format(number), dpi=150) return fig if __name__ == "__main__": # Try argparse here game_parser = argparse.ArgumentParser(description='Options for playing dart game.') game_parser.add_argument('ngames', nargs='?', default=1000, type=int, help='Specify number of games for simulation') game_parser.add_argument('coord', nargs='?', default=0, type=int, help='Randomly generate Cartesian (1) or polar coordinates (0)') args = game_parser.parse_args() print("Playing dart games...") print(args.coord) game = DartSimulation(args.ngames, 1, args.coord) game.simulate() print("Done!") game.hist_games()
99363bf5ae7e7128171b4b66cc43138f6fd05c6f
rockyboyyang/python_practices
/variables.py
329
3.953125
4
# a = 9 # b = 'marbles' # print(a, b) # print(float('nan')) # print('run'[-1:2]) # print('run'[-2]) def remove_last_vowel(word): vowels = "AEIOUaeiou" i = len(word) s = '' for x in reversed(range(i)): if word[x] not in vowels: s += word[x] return s print(remove_last_vowel('apples'))
2ac6674a5236c833a19ff1498fe7ba41c44970e7
ariellewaller/Python-Crash-Course
/Chapter 5/stages_of_life.py
1,710
4.46875
4
# Exercise 5-6. Stages of Life: Write an if-elif-else chain that determines a # personโ€™s stage of life. Set a value for the variable age, and then: # If the person is less than 2 years old, print a message that the person is a # baby. # If the person is at least 2 years old but less than 4, print a message # that the person is a toddler. # If the person is at least 4 years old but less than 13, print a message that # the person is a kid. # If the person is at least 13 years old but less than 20, print a message # that the person is a teenager. # If the person is at least 20 years old but less than 65, print a essage that # the person is an adult. # If the person is age 65 or older, print a message that the person is an # elder. age = 26 # Version 1: print('Version 1') if age < 2: stage = 'baby' print(f"You are a {stage}") if age >= 2 and age < 4: stage = 'toddler' print(f"You are a {stage}") if age >= 4 and age < 13: stage = 'kid' print(f"You are a {stage}") if age >= 13 and age < 20: stage = 'teenager' print(f"You are a {stage}") if age >= 20 and age < 65: stage = 'adult' print(f"You are an {stage}") if age >= 65: stage = 'elder' print(f"You are an {stage}") # Version 2: print('\nVersion 2') if age < 2: stage = 'baby' print(f"You are a {stage}") elif age < 4: stage = 'toddler' print(f"You are a {stage}") elif age < 13: stage = 'kid' print(f"You are a {stage}") elif age < 20: stage = 'teenager' print(f"You are a {stage}") elif age < 65: stage = 'adult' print(f"You are an {stage}") else: stage = 'elder' print(f"You are an {stage}")
d1da1670df51c984007ec3c4b65c76bd812b76af
asis-parajuli/Python-Basics
/queues.py
360
3.796875
4
# FIFO = First IN - First Out # if we use queues in a list of thousand item and when we remove the first item other 999 items should be shifted in the memory # for that we need to use deque from collections import deque queue = deque([]) queue.append(1) queue.append(2) queue.append(3) queue.popleft() print(queue) if not queue: print("empty")
3e0dc7bea0802a1cbe67e615fc969738cf1a91a4
HeywoodKing/mytest
/MyPractice/tuple (2).py
657
3.84375
4
print('ไธๅฏๅ˜็š„Tuple') tuple1 = (1, 2, 'aa', 'flack') print(tuple1[2]) print(tuple1[0:]) dic = {12, 32, 'chook'} print(dic.pop()) for x in tuple1: print('tuple:', x) age = 25 # if age >= 18: # print('ๆ‚จๅทฒ็ปๆˆๅนดไบ†') # else: # print('ๆ‚จ่ฟ˜ๆœชๆˆๅนด') if age >= 18: print('ๆ‚จๅทฒ็ปๆˆๅนดไบ†') elif age >= 12: print('ๆ‚จๅทฒ็ป้•ฟๅคงไบ†') elif age >= 6: print('ๆ‚จ่ฏฅไธŠๅฐๅญฆไบ†') elif age >= 3: print('ๆ‚จ่ฏฅไธŠๅนผๅ„ฟๅ›ญไบ†') else: print('ๆ‚จ่ฟ˜ๅฐ๏ผŒๅคšๅƒ้ฅญ๏ผŒๅฟซๅฟซๆˆ้•ฟ') sum = 0 for x in range(101): sum += x print(sum) sum = 0 n = 99 while n > 0: sum += n n -= 2 print(sum)
99fd14e433ce72ec855a699c8327fc057f812260
fossabot/IdeaBag2-Solutions
/Files/Zip File Maker/zip_file_maker.pyw
4,820
3.828125
4
#!/usr/bin/env python3 """A simple zip archive creator. Title: Create Zip File Maker Description: The user enters various files from different directories and maybe even another computer on the network and the program transfers them and zips them up into a zip file. For added complexity, apply actual compression to the files. """ import os import tkinter as tk import tkinter.filedialog from tkinter import ttk from zipfile import ZIP_DEFLATED, ZipFile class MainWindow(tk.Tk): """The class for interacting with tkinter.""" def __init__(self): """Initialize main window.""" super().__init__() self.resizable(width=False, height=False) self.geometry() self.title("Zip File Maker") # create frames self.treeview_frame = ttk.Frame(self) self.button_row_frame = ttk.Frame(self) # create other widgets self.files_treeview = ttk.Treeview(self.treeview_frame, columns=("path",), selectmode="browse", show="tree") self.files_treeview.column("#0", minwidth=0, width=0) self.files_treeview.column("path", width=400) self.files_treeview_scrollbar_y = ttk.Scrollbar(self.treeview_frame, orient=tk.VERTICAL, command=self.files_treeview.yview) self.files_treeview_scrollbar_x = ttk.Scrollbar(self.treeview_frame, orient=tk.HORIZONTAL, command=self.files_treeview.xview) self.files_treeview.config(yscrollcommand=self.files_treeview_scrollbar_y.set) self.files_treeview.config(xscrollcommand=self.files_treeview_scrollbar_x.set) self.add_file_button = ttk.Button(self.button_row_frame, text="Add new file(s)", command=self.add_files) self.remove_file_button = ttk.Button(self.button_row_frame, text="Remove file", command=self.remove_file) self.compress_button = ttk.Button(self.button_row_frame, text="Compress", command=self.compress_files) # display frames self.treeview_frame.grid(row=0, column=0, padx=10, pady=10) self.button_row_frame.grid(row=1, column=0, padx=10, pady=10) # display other widgets self.files_treeview.grid(row=0, column=0) self.files_treeview_scrollbar_y.grid(row=0, column=1, sticky=tk.NS) self.files_treeview_scrollbar_x.grid(row=1, column=0, sticky=tk.EW) self.add_file_button.grid(row=0, column=0, padx=2.5) self.remove_file_button.grid(row=0, column=1, padx=2.5) self.compress_button.grid(row=0, column=2, padx=2.5) def add_files(self): """Ask user to give file path and save new file.""" file_paths = tkinter.filedialog.askopenfilenames(parent=self) if not file_paths: return for file_path in file_paths: self.files_treeview.insert("", "end", values=(file_path,)) self.files_treeview.selection_set(self.files_treeview.get_children()[-1]) def remove_file(self): """Remove currently selected file.""" selected_column = self.files_treeview.selection() if not selected_column: return self.files_treeview.delete(selected_column) treeview_items = self.files_treeview.get_children() if treeview_items: self.files_treeview.selection_set(treeview_items[-1]) def compress_files(self): """Compress all files to zip archive.""" archive_file_path = tkinter.filedialog.asksaveasfilename(parent=self, defaultextension=".zip", filetypes=[("Zip File", "*.zip")]) treeview_items = self.files_treeview.get_children() if archive_file_path and treeview_items: with ZipFile(archive_file_path, "w", ZIP_DEFLATED) as archive: for row in treeview_items: file_path = self.files_treeview.item(row, "values")[0] file_name = os.path.basename(file_path) archive.write(file_path, arcname=file_name) def _start_gui(): """Start the Graphical User Interface.""" main_window = MainWindow() main_window.mainloop() if __name__ == "__main__": _start_gui()
04206f059a06def1872a099c0695961b1cb72470
rogerwoods99/UCDLessons
/UCDLessons/DataCampPandasSquareBrackets.py
1,771
4.1875
4
# This looks at the use of square brackets for import data and print out a subset # Import cars data import pandas as pd cars = pd.read_csv('cars.csv', index_col = 0) # Print out country column as Pandas Series print(cars['country']) # Print out country column as Pandas DataFrame print(cars[['country']]) # Print out DataFrame with country and drives_right columns print(cars[['country','drives_right']]) #================================================================== #================================================================== # Print out first 3 observations print(cars[0:3]) # Print out fourth, fifth and sixth observation print(cars[3:6]) print("") #================================================================== #================================================================== print(cars.loc['RU']) # this will provide data in rows print(cars.iloc[4]) print(cars.loc[['RU']]) # this in a single row print(cars.iloc[[4]]) print(cars.loc[['RU','AUS']]) # this returns info for 2 rows print(cars.iloc[[4,1]]) print() print(cars.loc['IN','cars_per_cap']) print(cars.loc[['IN','RU'],'cars_per_cap']) print(cars.iloc[[3,4],0]) #================================================================ #================================================================== # Print out drives_right value of Morocco print(cars.loc['MOR', 'drives_right']) # Print sub-DataFrame of Russia and Morocco and drive right value print(cars.loc[['RU','MOR'],['country','drives_right']]) # Print out drives_right column as Series for all countries print(cars.loc[:,'drives_right']) # Print out drives_right column as DataFrame print(cars.iloc[:,[2]]) # Print out cars_per_cap and drives_right as DataFrame print(cars.loc[:,['cars_per_cap','drives_right']])
f2ea252cdde340f41b36215ab05543c36aa9845a
SR-Sunny-Raj/Hacktoberfest2021-DSA
/33. Python Programs/Square of n numbers.py
354
4.3125
4
''' Problem Statement : To find square of given N numbers using Recursion and iterative approach''' n=int(input("Enter Number : ")) def squareIterative(n): for i in range(n,0,-1): print(i**2,end=" ") squareIterative(n) print() def squareRecursive(n): if n>0: print(n**2,end=" ") squareRecursive(n-1) squareRecursive(n)
1d341b59a694200af566f94b19790d8467173ddb
amritat123/dictionary-questions
/sum_of_keys_values.py
145
3.875
4
dict1={1:2,2:3,3:4,4:5} sum=0 for i in dict1.keys(): total=0 for j in dict1.values(): total+=j sum+=i print(total) print(sum)
ae2bda34b39fef2e79e0168de179e5c800557f0f
mochapup/Python-Programming-2nd-edition-John-Zelle
/Ch4/4.10.10.py
1,090
3.953125
4
# 4.10.10.py # This program displays information about a rectangle drawn by the user. # import libraries from graphics import * from math import sqrt def main(): win = GraphWin("Triangle Information",400, 400) for i in range(1): p1 = win.getMouse() p2 = win.getMouse() p3 = win.getMouse() # components needed aX = p1.getX()-p2.getX() aY = p1.getY()-p2.getY() bX = p2.getX()-p3.getX() bY = p2.getY()-p3.getY() cX = p3.getX()-p1.getX() cY = p3.getY()-p1.getY() a = sqrt((aX**2)+(aY**2)) b = sqrt((bX**2)+(bY**2)) c = sqrt((cX**2)+(cY**2)) s = ((a + b + c)/2) # Calculating area area = sqrt(s*(s-a)*(s-b)*(s-c)) # triangle shape triangle = Polygon(Point(p1.getX(),p1.getY()), Point(p2.getX(),p2.getY()), Point(p3.getX(),p3.getY())).draw(win) # textual information Text(Point(200,50),f"Area of the Triangle is {area}").draw(win) #quiting prompt quit = Text(Point(200,10),"Click again to quit") quit.setStyle("bold") quit.draw(win) win.getMouse() win.close() main()
3f1f893fb4921810d20aa8c96b808a35fe8debb2
Exabyte-io/express
/express/parsers/__init__.py
547
3.625
4
import os class BaseParser(object): """ Base Parser class. """ def __init__(self, *args, **kwargs): self.args = args self.kwargs = kwargs def _get_file_content(self, file_path): """ Returns the content of a given file. Args: file_path (str): file path. Returns: str """ content = "" if file_path and os.path.exists(file_path): with open(file_path) as f: content = f.read() return content
db814fc496d13c17a7e9c48d33436bbba58d7fe7
TumsaUmata/the_last_lap
/Google Assessment/New Grad/watering_flowers.py
2,005
3.75
4
# class Solution: # def waterPlants(self, plants, capacity1, capacity2): # # if len(plants) == 0: # return 0 # # pointer1 = 0 # pointer2 = len(plants) - 1 # # can1 = capacity1 # can2 = capacity2 # count = 2 # # while pointer1 != pointer2: # if can1 >= plants[pointer1]: # can1 -= plants[pointer1] # pointer1 += 1 # else: # can1 = capacity1 # can1 -= plants[pointer1] # pointer1 += 1 # count += 1 # # if can2 >= plants[pointer2]: # can2 -= plants[pointer2] # pointer2 -= 1 # else: # can2 = capacity2 # can2 -= plants[pointer2] # pointer2 -= 1 # count += 1 # # if (pointer1 == pointer2): # if ((can1 + can2) >= plants[pointer1]): # return count # else: # return count + 1 # # elif pointer2 < pointer1: # return count # # # if __name__ == "__main__": # arr = [2, 4, 5, 1, 2] # c1 = 5 # c2 = 7 # print(Solution().waterPlants(arr, c1, c2)) import math def solution(plants, cap1, cap2): if len(plants) == 0: return 0 end_m = len(plants) // 2 if (len(plants) % 2 == 0): start_f = len(plants) / 2 else: start_f = len(plants) // 2 + 1 water_needed_m = sum(plants[:end_m]) water_needed_f = sum(plants[start_f:]) refill_m = math.ceil(water_needed_m / cap1) refill_f = math.ceil(water_needed_f / cap2) if (len(plants) % 2 != 0): total_water_needed = water_needed_m + water_needed_f + plants[end_m] total_water_filled = cap1 * refill_m + cap2 * refill_f if (total_water_needed > total_water_filled): refill_m += 1 return refill_m + refill_f print(solution([2, 4, 5, 1, 2], 5, 7))
4b0961633e7be09f8a62f17ae79763eba6c86157
paulangton/lowest-case
/lowest.py
1,055
3.71875
4
# lowest.py # A non-serious attempt at creating a lowestcase implementation for python # strings # Author: Paul Langton import sys lowest_rules = { ' ': ' ', 'a': 'o', 'b': 'o', 'c': '_', 'd': 'o', 'e': 'o', 'f': 'l', 'g': 'o', 'h': 'l', 'i': ':', 'j': ':', 'k': 'l', 'l': 'l', 'm': '_', 'n': '_', 'o': 'o', 'p': 'o', 'q': 'o', 'r': '_', 's': '_', 't': 'l', 'u': '_', 'v': '_', 'w': '_', 'x': '_', 'y': 'l', 'z': '_', } def lowest(s): """ returns s in lowest-case - all the letters with tall bits become l - all the letters with holes become o - all the dotted boyes become : - all the other ones get squashed to become _ converts """ ls = "" s = s.lower() for c in s: if c in lowest_rules.keys(): ls += lowest_rules[c] else: ls += c return ls
2cb43824cec5ef9529ee50e3e74fc20daba4ee62
adrenalin/helpers
/helpers/get_recursive_filelist.py
1,053
3.53125
4
""" Get recursive filelist @author Arttu Manninen <[email protected]> """ import os import re def get_recursive_filelist( target_folder: str, filename_filter: str = None, filename_regex: re = None ) -> list: """ Get recursive filelist in the target folder with optional filename filter """ matched_files = [] for root_path, _directories, files in os.walk(target_folder): for file in files: full_path_to_file = os.path.join(root_path, file) if filename_filter is not None: if filename_filter in full_path_to_file: matched_files.append(full_path_to_file) continue if filename_regex is not None: if isinstance(filename_regex, str): filename_regex = re.compile(filename_regex) if filename_regex.search(full_path_to_file): matched_files.append(full_path_to_file) continue matched_files.append(full_path_to_file) return matched_files
bc5fd00494409469cb17195c704443dcfcf285a6
MMAGANADEBIA/Programming_Courses
/Python_course/numbers.py
628
3.84375
4
#podemos tener numeros enteros como: 10 #conocidos como int de integers #tambien numeros flotantes o float como: 14.4 #recuerda que podemos ver el tipo de dato asi: print(type(9)) print(type(10.1)) print(1 + 1 ) #simple suma de numeros print(3 - 1) #restas print(1 * 3) #multiplicaciones print(3 / 2) #diviciones print(2 ** 3) #para elevar un numero a x potencia se usa dos * print(3 // 2) #modulo nos devuelve residuo print(3 % 2) #modulo tambien puede ser igual que en javascript print(20 - 10 / 5 * 3 ** 2) #podemos hacer cadenas mas largas sin jerarquia print((20 - 10) / (5 * 3 ** 2)) #con parentesis ayua a la jerarquia
0dffb623150b70ee2b9f915a9541c78e8ddc735c
fhmurakami/Python-CursoemVideo
/Exercicios/Mundo 02 - Estruturas de Controle/Aula 15 - Interrompendo repetiรงรตes while/ex071.py
1,202
4.125
4
# Crie um programa que simule o funcionamento de um caixa eletrรดnico. No inรญcio, pergunte ao usuรกrio qual serรก o valor a # ser sacado (nรบmero inteiro) e o programa vai informar quantas cรฉdulas de cada valor serรฃo entregues. # OBS: Considere que o caixa possui cรฉdulas de R$50, R$20, R$10 e R$1. cd50 = cd20 = cd10 = cd1 = 0 print('=' * 50) print(f'{"BANCO MRK":^50}') print('=' * 50) valor = int(input('Qual valor vocรช quer sacar? R$')) while True: if valor > 0: if valor % 50 == 0: cd50 += 1 valor -= 50 elif valor %20 == 0: cd20 += 1 valor -= 20 elif valor % 10 == 0: cd10 += 1 valor -= 10 else: cd1 += 1 valor -= 1 else: break print('\nVocรช receberรก:') print(f'{cd50} cรฉdulas de R$50' if cd50 > 0 else '') # O 'else' รฉ sempre necessรกrio quando escrito em uma linha print(f'{cd20} cรฉdula(s) de R$20' if cd20 > 0 else '') print(f'{cd10} cรฉdula(s) de R$10' if cd10 > 0 else '') print(f'{cd1} cรฉdula(s) de R$1' if cd1 > 0 else '') print('=' * 50) print('Volte sempre ao BANCO MRK! Tenha um bom dia.')
03c5a22caef38221ee3885c6ecc8551ad1c5aa22
JBailey87/advent
/day1.py
774
3.6875
4
import collections #filepath = 'input/day1/day1-test.txt' strFilepath = 'input/day1/day1-puzzle1.txt' intTotalFrequency = 0 intFrequencySet = set() def duplicate(intFrequency): if intFrequency in intFrequencySet: raise ValueError("Duplicate frequency found {}".format(intFrequency)) with open(strFilepath) as oFile: strFileLine = oFile.readline() while strFileLine: intTotalFrequency += int(strFileLine) strFileLine = oFile.readline() print("Total Frequency {}".format(intTotalFrequency)) intTotalFrequency = 0 while True: with open(strFilepath) as oFile: strFileLine = oFile.readline() while strFileLine: intTotalFrequency += int(strFileLine) duplicate(intTotalFrequency) intFrequencySet.add(intTotalFrequency) strFileLine = oFile.readline()
5c7697f763ef3b439f4269c708585180bd5a4bb3
gschen/where2go-python-test
/1300-่“ๆกฅๆฏ/year-2016/JAVA-C/test01.py
125
3.515625
4
result='vxvxvxvxvxvxvvx' money=777 for i in result: if i=='v': money*=2 else: money-=555 print(money)
fe44437cbdea47b6ff3c0d1935d9dd60810bc2dc
guigui64/advent-of-code
/2020/21.py
2,103
3.9375
4
#!/usr/bin/env python import re from collections import Counter pattern = re.compile(r"(.*) \(contains (.*)\)") def solve(fname): # allergens is a dict of sets of ingredients per allergen allergens = {} # ingredients is a Counter of the ingredients ingredients = Counter() with open(fname) as f: for line in f: i_ingredients, i_allergens = pattern.fullmatch(line[:-1]).group(1, 2) i_ingredients = i_ingredients.split() i_allergens = i_allergens.split(", ") for allergen in i_allergens: if allergen in allergens: allergens[allergen] = allergens[allergen] & set(i_ingredients) else: allergens[allergen] = set(i_ingredients) for ing in i_ingredients: ingredients[ing] += 1 # safe ingredients are ingredients that cannot have any of the allergens found safe_ingredients = set(ingredients) for ing in allergens.values(): safe_ingredients -= ing # answer to part1 is the number of times all safe ingredients where found part1 = str(sum(ingredients[ing] for ing in safe_ingredients)) # remove safe ingredients from allergens for ing in allergens.values(): ing -= safe_ingredients # eliminate allergens_final = {} # dict whose key is NOW the ingredient while len(allergens) > 0: for allergen in allergens: allergens[allergen] -= set(allergens_final.keys()) if len(ing := allergens[allergen]) == 1: allergens_final[list(ing)[0]] = allergen del allergens[allergen] break # answer to part 2 is the canonical dangerous ingredient list sorted alphabetically by their # allergen part2 = ",".join(ing for ing in sorted(allergens_final, key=allergens_final.get)) return part1, part2 if __name__ == "__main__": print("\n".join(" ".join(z) for z in zip(("part1:", "part2:"), solve("21ex.txt")))) print("\n".join(" ".join(z) for z in zip(("part1:", "part2:"), solve("21.txt"))))
3e49718f247f2b9eb2956cd76ba636388c2dc822
marythought/sea-c34-python
/students/RichardGreen/weekthree/safe_input.py
589
3.921875
4
'''The raw_input() function can generate two exceptions: - EOFError or end-of-file (EOF) - KeyboardInterrupt or canceled input. - Create a wrapper function, perhaps safe_input() that returns None rather than raising these exceptions.''' def safe_input(): print "Enter a number:" input = raw_input() print "Your input:" print input try: input = int(input) # break except (KeyboardInterrupt, TypeError, ValueError, EOFError): None print(u"Input must be an integer, try again.") if __name__ == "__main__": # safe_input()
c6209e798d69c2d3e89f3dd9db75e060a177ce7d
osnipezzini/PythonExercicios
/ex054.py
516
3.921875
4
''' Crie um programa que leia o ano de nascimento de sete pessoas. No final, mostre quantas pessoas ainda nรฃo atingiram a maioridade e quantas jรก sรฃo maiores. ''' from datetime import date ano = date.today().year maior = 0 menor = 0 for c in range(1, 8): num = int(input('Digite o ano de nascimento da {}ยช pessoa: '.format(c))) if ano - num >= 21: maior += 1 else: menor += 1 print('Tivemos um total de {} pessoas maiores de idade e {} pessoas menores de idade'.format(maior, menor))
68a1177ea707d3eb596431db87984b559f05e899
shreayan98c/CompetitiveProgramming
/Arrays/BaruaRankReversal.py
1,453
3.78125
4
# Barua and his Rank Reversal # You've been given a permutation of containing N distinct elements between 1 and N, both included. (1<=N<=10^3) # The rank of an element in this array is the number of elements to it's left which are strictly lesser than it. # You have been given array,formulate it's rank array. # Seems tough right? Let's make the question a bit simpler :P # Instead of the actual array, you would be given a rank array. Formulate the initial array from it. It is guaranteed # that the solution would be unique. # Input Format # In the first line input N(1<=N<=10^3) # In the next line input rank array 0<=Rank[i] # Output Format # Print the N integers of the actual array. # NOTE : All elements in the rank array may or may not be distinct # Sample Input 0 # 3 # 0 1 2 # Sample Output 0 # 1 2 3 # Explanation 0 # If the actual array is : 1 2 3 # Rank array will be : 0 1 2 Thus it satisfies the provided input. # Because there are 0 elements to the left of 1 which are lesser than 1, 1 element to the left of 2 which is lesser than # 2 and 2 elements to the left of 3 which are lesser than 3. # Enter your code here. Read input from STDIN. Print output to STDOUT n = int(input()) l = [x for x in range(1,n+1)] # print(l) mylist = [x for x in range(1,n+1)] # print(mylist) res = [] for i in range(n): pos=ranks[n-i-1] res.append(mylist[pos]) mylist.pop(pos) for x in range(n-1,-1,-1): print(res[x],end=" ")
22be8e84368378228588fe8324e04e0f54727a0d
Shubham-iiitk/Codes
/linklist_insert.py
1,074
4.09375
4
class Node: def __init__(self,data): self.value= data self.next= None class Linklist: def __init__(self): self.head =None # for printing the linklist def printlist(self): temp = self.head while temp: print(temp.value) temp= temp.next # adding node at begning def addbeg(self,data): new = Node(data) new.next = l.head l.head = new # adding node at end def addend(self,data): new = Node(data) new.next=None last = self.head while last.next: last =last.next last.next= new # Inserting a node after a given node: def add(self,data,prev): new = Node(data) temp = self.head while temp.value != prev: temp =temp.next new.next = temp.next temp.next = new l=Linklist() l.head= Node(1) l2 = Node(2) l.head.next=l2 l3=Node(3) l2.next=l3 l.printlist() #l.addbeg(4) l.addend(4) l.add(5,3) l.printlist()
ce1b9b8e5c2793617536c7b33244469d7a865bcd
MarcelinaWojnarowska/Comment-on-a-random-book
/app/car.py
386
3.640625
4
class Car: def __init__(self, number_of_door, number_of_wheel): self.number_of_door = number_of_door self.number_of_wheel = number_of_wheel def get_number_of_doors(self): return self.number_of_door def get_number_of_wheels(self): return self.number_of_wheel my_car = Car(4, 4) my_car.get_number_of_doors() my_car.get_number_of_wheels()
1781ae7bc99693a6c7ffb4365f9676f5d542246a
flyingaura/PythonLearning
/LearnOOP/learning0417002.py
6,981
3.578125
4
# -*- coding: utf-8 -*- from LearnModule import StringSplit # ๅฎšไน‰ไธ€ไธช่ฟ‡ๆปค็š„่กŒๆ”ฟๅŒบๅˆ’ๅ่กจ # filter_province = ('็œ', 'ๅธ‚', '่‡ชๆฒปๅŒบ') filter_city = ('ๅŒบ', 'ๅŽฟ') filter_towns = ('่ก—้“', '้•‡', 'ไนก', 'ๅ›žๆฐ‘ไนก') filter_street = ('็คพๅŒบ','ๆ‘') class wordlist(object): #ๅฎšไน‰ไธ€ไธช่ฏ่กจๅ†…่ฏ่พ“ๅ‡บ็š„็ฑป def __init__(self,word_name,word_nominal,word_freq,word_note): self.word_name = word_name self.word_nominal = word_nominal self.word_freq = word_freq self.word_note = word_note class toponymy(object): #ๅฎšไน‰ไธ€ไธชๅœฐๅ่ฏ็š„็ฑป def __init__(self,province,city,towns,street): self.province = province self.city = city self.towns = towns self.street = street def alias_province(self): alias_province_list = [] for astr in filter_province: if(len(self.province) > len(astr) and len(self.province) > 2): filter_index = len(self.province) - len(astr) if(self.province.find(astr) == filter_index): alias_province_list.append(self.province[:filter_index]) if (alias_province_list): return alias_province_list else: return None def alias_city(self): alias_city_list = [] for astr in filter_city: if (len(self.city) > len(astr) and len(self.city) > 2): filter_index = len(self.city) - len(astr) if(self.city.find(astr) == filter_index): alias_city_list.append(self.city[:filter_index]) if(alias_city_list): return alias_city_list else: return None def alias_towns(self): alias_towns_list = [] for astr in filter_towns: if (len(self.towns) > len(astr) and len(self.towns) > 2): filter_index = len(self.towns) - len(astr) if(self.towns.find(astr) == filter_index): alias_towns_list.append(self.towns[:filter_index]) if (alias_towns_list): return alias_towns_list else: return None def alias_street(self): alias_street_list = [] for astr in filter_street: if (len(self.street) > len(astr) and len(self.street) > 2): filter_index = len(self.street) - len(astr) if(self.street.find(astr) == filter_index): alias_street_list.append(self.street[:filter_index]) if (alias_street_list): return alias_street_list else: return None toponymy_list = [] the_towns = '-' with open('C:/Users/flyingaura/Desktop/ๆ˜ŒๅนณๅŒบ.dat', mode = 'rb') as in_file: the_province = 'ๅŒ—ไบฌๅธ‚' the_city = in_file.readline().decode('utf-8').strip() for rec in in_file.readlines(): rec_data = rec.decode('utf-8').strip() if ('\t' in rec_data): rec_TS = StringSplit.stringsplit(rec_data,'\t') the_towns = rec_TS[0] rec_street = rec_TS[1].strip('\"') else: rec_street = rec_data.strip('\"') if(rec_street): for the_street in StringSplit.stringsplit(rec_street,'ใ€'): rec_toponymy = toponymy(the_province, the_city, the_towns, the_street) toponymy_list.append(rec_toponymy) # for rec_ty in toponymy_list: # print('============ %s' %rec_ty.street) province_list = [] city_list = [] towns_list = [] street_list = [] Aprovince_list = [] Acity_list = [] Atowns_list = [] Astreet_list = [] for A_toponymy in toponymy_list: if(A_toponymy.province not in Aprovince_list): province_list.append(wordlist(A_toponymy.province, 'tag', 1000, A_toponymy.province)) Aprovince_list.append(A_toponymy.province) alias_PL = A_toponymy.alias_province() if(alias_PL): for A_province in alias_PL: if(A_province not in Aprovince_list): province_list.append(wordlist(A_province, 'tag', 1000, A_toponymy.province)) Aprovince_list.append(A_province) # print(province_list) if (A_toponymy.city not in Acity_list): city_list.append(wordlist(A_toponymy.city, 'tag', 1000, A_toponymy.province)) Acity_list.append(A_toponymy.city) alias_CL = A_toponymy.alias_city() if(alias_CL): for A_city in alias_CL: if (A_city not in Acity_list): city_list.append(wordlist(A_city, 'tag', 1000, A_toponymy.province)) Acity_list.append(A_city) if (A_toponymy.towns not in Atowns_list): towns_list.append(wordlist(A_toponymy.towns, 'tag', 1000, A_toponymy.city)) Atowns_list.append(A_toponymy.towns) alias_TL = A_toponymy.alias_towns() if(alias_TL): for A_towns in alias_TL: if (A_towns not in Atowns_list): towns_list.append(wordlist(A_towns, 'tag', 1000, A_toponymy.city)) Atowns_list.append(A_towns) # if (A_toponymy.street not in street_list): street_list.append(wordlist(A_toponymy.street, 'tag', 1000, A_toponymy.towns)) alias_SL = A_toponymy.alias_street() if(alias_SL): for A_street in alias_SL: # if (A_street not in street_list): street_list.append(wordlist(A_street, 'tag', 1000, A_toponymy.towns)) with open('C:/Users/flyingaura/Desktop/ๅŒ—ไบฌๅœฐๅ€1.txt', mode = 'a') as out_file: for A_province in province_list: print('%s\t%s\t%d\t%s' %(A_province.word_name, A_province.word_nominal, A_province.word_freq, A_province.word_note)) out_file.write('%s\t%s\t%d\t%s\n' %(A_province.word_name, A_province.word_nominal, A_province.word_freq, A_province.word_note)) for A_city in city_list: print('%s\t%s\t%d\t%s' % (A_city.word_name, A_city.word_nominal, A_city.word_freq, A_city.word_note)) out_file.write('%s\t%s\t%d\t%s\n' % (A_city.word_name, A_city.word_nominal, A_city.word_freq, A_city.word_note)) for A_towns in towns_list: print('%s\t%s\t%d\t%s' % (A_towns.word_name, A_towns.word_nominal, A_towns.word_freq, A_towns.word_note)) out_file.write('%s\t%s\t%d\t%s\n' % (A_towns.word_name, A_towns.word_nominal, A_towns.word_freq, A_towns.word_note)) for A_street in street_list: print('%s\t%s\t%d\t%s' % (A_street.word_name, A_street.word_nominal, A_street.word_freq, A_street.word_note)) try: out_file.write('%s\t%s\t%d\t%s\n' % (A_street.word_name, A_street.word_nominal, A_street.word_freq, A_street.word_note)) except UnicodeEncodeError as e: out_file.write('******\t%s\n' %e)
0c36beccf0133044a5aa9cf8349d50a01a2d7e4e
rafi80/UdacityIntroToComputerScience
/varia/interacjaPoListach.py
372
3.734375
4
''' Created on 5 paz 2013 @author: Stefan ''' def iteracja(lista): i = 0 j = 0 for i in range(len(lista)): for j in range(len(lista)): print lista[i][j] def is_integer(a): t = int(a) return t correct = [[1,2,3], [2,3,1], [3,1,2]] iteracja(correct) print is_integer('a')
041bb1e2361e02f52db640028b3a914baa8ccbca
Elvis-Lopes/Curso-em-video-Python
/exercicios/ex069.py
609
3.75
4
idade = maiorIdade = qtdHomens = qtdMulheres =0 sexo = str() opcao = str while True: idade = int(input('Digite a idade: ')) sexo = str(input('Qual o sexo da pessoa? F/M')).strip().upper()[0] if sexo in 'M': qtdHomens += 1 if sexo in 'F': if idade < 20: qtdMulheres += 1 if idade >= 18: maiorIdade += 1 opcao = str(input('Deseja continua? [S/N] ')).strip().upper()[0] if opcao in 'N': break print(f'A {maiorIdade} maiores de idade\n' f'Foram cadastrados {qtdHomens} homens\n' f'Ha {qtdMulheres} mulheres com menos de 20 anos')
32fd30b03098605fbcebc5be1a83523a4b9eee38
jeevananthanr/Python
/File_handle.py
1,003
3.515625
4
#File handling #fname="Sample.txt" #fname="C:\\Users\\A603367\\Desktop\\Py\\File\\Sample.txt" fname="C:/Users/A603367/Desktop/Py/File/Sample.txt" #open fhandle=open(fname,"w") #'''create if its not exist otherwise overwrite''' #lst=['hello','hai'] #write content fhandle.write("Welcome to File handling\n") fhandle.write("________________________\n") fhandle.write("Hello!\n") #fhandle.write(lst) #file append fhandle1=open(fname,"a") fhandle1.write("Appended!") #close fhandle.close() fhandle1.close() print "File Created" print "_________________________________________________________" #Read mode fread=open(fname) #read, readline and readlines() print "Using read->",fread.read(25) print "Using readline->",fread.readline() print "Using readlines->",fread.readlines() fread.seek(0) print "readline slice->",fread.readlines()[2:3] fread.seek(0) for rd in fread.readlines(): print rd ''' other modes binary mode read -write r+,w+,a+ '''
c9f0852cb6ec754994217def77db1347040b96e3
chris-geelhoed/project-euler
/p17/main.py
1,364
3.953125
4
''' If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total. If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used? NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of "and" when writing out numbers is in compliance with British usage. ''' map = { 0: '', 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine', 10: 'ten', 11: 'eleven', 12: 'twelve', 13: 'thirteen', 14: 'fourteen', 15: 'fifteen', 16: 'sixteen', 17: 'seventeen', 18: 'eighteen', 19: 'nineteen', 20: 'twenty', 30: 'thirty', 40: 'forty', 50: 'fifty', 60: 'sixty', 70: 'seventy', 80: 'eighty', 90: 'ninety' } def write_num(n): m = '' if n == 1000: return 'onethousand' hundreds, tens, ones = [int(i) for i in str(n).zfill(3)] last_two_digits = 10 * tens + ones if hundreds > 0: m += map[hundreds] + 'hundred' if last_two_digits > 0: m += 'and' if last_two_digits < 20: return m + map[last_two_digits] return m + map[10 * tens] + map[ones] print(sum(len(write_num(i)) for i in range(1, 1000 + 1)))
e5c7e20a05f016ca1e4697f3aa15f27c25e910cc
AdamZhouSE/pythonHomework
/Code/CodeRecords/2325/59018/275895.py
255
3.546875
4
info=input().split(',') a=[int(y) for y in info] b=set(a) if len(a)==1: print(False) elif len(a)==2: if len(b)==1: print(True) else: print(False) else: if len(a)/len(b)>=2: print(True) else: print(False)
f06efa85b3ebf443d488197fd9acbcb759531be9
thecodice/practice_python
/1/richter_scale.py
1,120
4.125
4
#largest ever measured is in chile 9.5 in 1960 #prompt a user to enter a Rc measuremenet,accept floating point value and do some calculations and display the equivalent amount of energy in joules and in tons of exploded TNT for that user-selected value. #The Richter scale is a way to quantify the magnitude of an earthquake using a base-10 logarithmic scale.The magnitude is defined as the logarithm of the ratio of the amplitude of waves measured by a seismograph to an arbitrary small amplitude. #An earthquake that measures 5.0 on the Richter scale has a shaking amplitude 10 times larger than one that measures 4.0, and corresponds to a 31.6 times larger release of energy. # the energy in joules released for a particualr richter scale measurement is given by: # Energy = 10**(1.5*rc_measure) + 4.8 #one ton of exploded TNT yields 4.184*10**9 joules. #ok enough of this chitchat rc_input = input("enter a number sir/madam?") rc_input_float = float(rc_input) energy = 10**(1.5*rc_input_float) + 4.8 tons_of_tnt = energy / 4.184*10**9 print "energy :" + str(energy) print "tons of TNT:" + str(tons_of_tnt)
0ec3619cec0dc520dabfe5fe4317acc9f95312fb
bugxiaoc/spider-Demo
/spider_Demo/tools/stringu.py
808
3.515625
4
#!/usr/bin/python # -*- coding: UTF-8 -*- import re """ String Util """ def checkURI(str): if re.search('',str,re.S): return 1 else: return 0 def delete_space(obj): while '' in obj: obj.remove('') return obj def fromat_list(obj): temp = [] for x in obj: temp.append(x.strip().replace("\n", "").replace(" ", "")) return temp def toString(result,result1): ls1 = delete_space(fromat_list(result)) ls2 = delete_space(fromat_list(result1)) for i in range(0,len(ls1)): print ls1[i],ls2[i] def toString(result,result1,result2): ls1 = delete_space(fromat_list(result)) ls2 = delete_space(fromat_list(result1)) ls3 = delete_space(fromat_list(result2)) for i in range(0,len(ls1)): print ls1[i],ls2[i],ls3[i]
a54a67b3f2cbc93b59c9b9e0d9bb1b9918ddae4b
Geoff-Lucas/Challenge_Problems
/shortest_substring.py
1,535
4.125
4
# -*- coding: utf-8 -*- """ Created on Sun Mar 21 20:04:12 2021 @author: Geoff This problem was asked by Square. Given a string and a set of characters, return the shortest substring containing all the characters in the set. For example, given the string "figehaeci" and the set of characters {a, e, i}, you should return "aeci". If there is no substring containing all the characters in the set, return null. # Note: I'm just returning an empty string instead of null. """ s = "figehaeci" chars = ['a', 'e', 'i'] def shortest_substring(s, chars): start_idx = -1 best_substring = '' best_len = 9999 still_needed = chars.copy() i = 0 while i < len(s): if s[i] in chars and start_idx == -1: start_idx = i still_needed.remove(s[i]) elif s[i] in still_needed: still_needed.remove(s[i]) if len(still_needed) == 0: sub = s[start_idx:i+1] # Test for shortest substring if len(sub) < best_len: best_substring = sub best_len = len(best_substring) i = start_idx start_idx = -1 still_needed = chars.copy() i += 1 return best_substring print(shortest_substring(s, chars)) print(shortest_substring('flimflamifloopy', ['f', 'm', 'a'])) print(shortest_substring('Wethepeople', ['x', 'y', 'z']))
fa6990ad3c1c6aa0a56d494a0ccaa4a590ff6674
cheol-95/Algorithm
/Python/085. ์˜์–ด ๋๋ง์ž‡๊ธฐ/English.py
357
3.75
4
def solution(n, words): stack = [] for i in range(len(words)): if stack and stack[-1][-1] != words[i][0] or words[i] in stack: return [i%n+1,i//n+1] stack.append(words[i]) else: return [0,0] n, words = 3, ["tank", "kick", "know", "wheel", "land", "dream", "mother", "robot", "tank"] print(solution(n, words))
c99e0594d839ec5e7b42d4857c75cab4898cff27
OrangeCodelover/LeetCode-Solution
/1. Two Sum.py
284
3.65625
4
nums = [2,7,11,15] target = 9 # look through the entire array for i in range(len(nums)-1): for j in range(len(nums)-1): if i != j and nums[i]+ nums[j] == target: print([i,j]) break # break the nested loop else: continue break
c3f852b35705f28fba94e3603d320e96e4341a99
ddrifter/drifting1
/player.py
9,447
3.875
4
"""Class Player with it's properties and functions.""" import pygame from pygame.sprite import Sprite class Player(Sprite): """Defines the class Player with the player's properties.""" def __init__(self, screen, settings): """Initializes the player's properties.""" super(Player, self).__init__() self.image_left = pygame.image.load("images/player_left.bmp") self.image_right = pygame.image.load("images/player_right.bmp") self.image_damaged_left = pygame.image.load("images/player_lost_life_left.png") self.image_damaged_right = pygame.image.load("images/player_lost_life_right.png") self.rect = self.image_left.get_rect() self.screen = screen self.screen_rect = self.screen.get_rect() # Center the player in the middle bottom position of the screen self.rect.bottom = self.screen_rect.bottom self.rect.centerx = self.screen_rect.centerx # Set a custom marker for finer speed adjustments later on self.x = self.rect.x self.y = self.rect.y # Flags for moving and jumping self.moving_left = False self.moving_right = False self.moving_left_counter = settings.moving_left_counter self.moving_right_counter = settings.moving_right_counter self.staying_still = True self.jumped = False # Flags for determining which player image will be displayed # (in the beginning it's the 'right' image) self.moved_right = True self.moved_left = False # Gravity constant and variable, with the jump variable from settings and other # variables that help with jumping constrainst and gravity constrainst self.grav_var = settings.grav_var self.grav_const = settings.grav_const self.jump_var = settings.jump_var self.under_var = settings.under_var self.on_top = settings.on_top self.downward = False # Flags for drawing the images of the damaged player self.been_damaged_right = False self.been_damaged_left = False self.damaged_counter = 0 self.damaged_counter_threshold = 400 def update_moving(self, platforms): """ Updates the player's position based on the flags moving_left and moving_right and sets the moved_left and moved_right flags. Also checks if the player is near any side of any platform and (hopefully) stops movement to that side while the circumstances remain. """ # Set the counters to 0 so they can be increased if the player is near the side of a platform self.moving_left_counter = 0 self.moving_right_counter = 0 if self.moving_left and self.rect.left > 0: for platform in platforms: if (abs(self.rect.left - platform.rect.right) < 4 and self.rect.top < platform.rect.bottom and self.rect.bottom > platform.rect.top): # Increase the counter if the player is within the boundaries of the right # side of any platform self.moving_left_counter += 1 if self.moving_left_counter == 0: if self.damaged_counter > 0: self.x -= 0.9 self.rect.x = self.x else: self.x -= 1.5 self.rect.x = self.x # Flags for determining which player image will be displayed self.moved_right = False self.moved_left = True if self.moving_right and self.rect.right < self.screen_rect.right: for platform in platforms: if (abs(self.rect.right - platform.rect.left) < 4 and self.rect.top < platform.rect.bottom and self.rect.bottom > platform.rect.bottom): # Increase the counter if the player is within the boundaries of the left # side of any platform self.moving_right_counter += 1 if self.moving_right_counter == 0: # If the player lost a life recently -> apply a slowdown if self.damaged_counter > 0: self.x += 0.9 self.rect.x = self.x else: self.x += 1.5 self.rect.x = self.x # Flags for determining which player image will be displayed self.moved_left = False self.moved_right = True def player_gravity(self, platforms, settings, player): """Makes the player succeptible to gravitational influence.""" self.on_top = settings.on_top if self.rect.bottom < self.screen_rect.bottom: for platform in platforms: # Check if the player is in on top of any platform, and, if so, # adjust parameters accordingly so the player can land/stand on the platform # > if the downward flag is True then dont go into the conditional and just proceed to # > gravity calculations if ((abs(self.rect.bottom - platform.rect.top) < 2) and (self.rect.right > platform.rect.left) and (self.rect.left < platform.rect.right) and not self.downward): self.grav_var = settings.grav_var self.jump_var = settings.jump_var self.jumped = False self.on_top += 1 # Performs the gravity calculations if the player is not ontop of a platform if self.on_top == 0: self.effect_of_gravity() # Checks if the player is near the bottom of the screen and resets grav_var and jump_var # and turns jumped flag off if abs(self.rect.bottom - self.screen_rect.bottom) < 4: self.grav_var = settings.grav_var self.jump_var = settings.jump_var self.jumped = False self.downward = False def effect_of_gravity(self): """Effects of gravity on the player, changes the y-coordinate.""" self.y += 0.1 + self.grav_var*self.grav_const self.rect.y = self.y self.grav_var += 0.01 * self.grav_var def jump(self, platforms, settings): """Function for jumping.""" self.under_var = settings.under_var for platform in platforms: # Check, for every platform, if the player is positioned right underneath it and stop # jumping, reset jump_var and set jumped flag to False if (abs(self.rect.top - platform.rect.bottom) < 3 and self.rect.right > platform.rect.left and self.rect.left < platform.rect.right): self.jump_var = settings.jump_var self.jumped = False self.under_var += 1 # If the player is not underneath any platform -> jump OR is on top of a platform if (self.jump_var >= -6 and self.under_var == 0) or self.on_top > 0: self.y -= (5 + self.jump_var) self.rect.y = self.y self.jump_var -= 0.1 def reset_player(self): """Resets the player if he's lost a life.""" self.rect.x = self.screen_rect.centerx self.rect.bottom = self.screen_rect.bottom def blitme(self): """ Draws the player at its current location keeping in mind the last known direction the player was facing to have a uniform player picture displayed without unnecessary alteration """ # Drawing the damaged player images if the counter is running if self.moved_right and self.damaged_counter > 0: self.screen.blit(self.image_damaged_right, self.rect) if self.moved_left and self.damaged_counter > 0: self.screen.blit(self.image_damaged_left, self.rect) # Drawing the usual player images if self.moved_right and self.damaged_counter == 0: self.screen.blit(self.image_right, self.rect) elif self.moved_left and self.damaged_counter == 0: self.screen.blit(self.image_left, self.rect) class PlayerLives(Sprite): """A class for drawing thumbnails of player lives.""" def __init__(self, screen): """Initializes with 3 thumbnails.""" self.screen = screen self.image_3_lives = pygame.image.load("images/player_life_3.png") self.image_2_lives = pygame.image.load("images/player_life_2.png") self.image_1_lives = pygame.image.load("images/player_life_1.png") self.rect_3 = self.image_3_lives.get_rect() self.rect_2 = self.image_2_lives.get_rect() self.rect_1 = self.image_1_lives.get_rect() self.rect_1.y = 20 self.rect_1.x = 20 self.rect_2.y = 20 self.rect_2.x = self.rect_3.width + 40 self.rect_3.y = 20 self.rect_3.x = self.rect_3.width + self.rect_2.width + 60 def blitme(self, stats): """Draws the current number of lives.""" if stats.lives_left >= 1: self.screen.blit(self.image_1_lives, self.rect_1) if stats.lives_left >= 2: self.screen.blit(self.image_2_lives, self.rect_2) if stats.lives_left == 3: self.screen.blit(self.image_3_lives, self.rect_3)
1438a398a4c9c99d56734b214b9c9e1a6356447f
alu-rwa-dsa/week-3---dynamic-array-josephine_samwel_modester_cohort2
/Question 2.py
868
3.984375
4
#Authors:Modester, Samwel, Josephine #Question:Create a dynamic array subclass which also has the following basic methods: # importing modules from numpy import random array1 = [] i = 0 while i < 5: i += 1 x = random.randint(10) + 1 array1.append(x) class Array: def check_val(self, val): print(array1) for j in array1: if j == val: return True return False def reverse(self): val2 = int(input("Enter number to be reversed: ")) rev_num = 0 while val2 > 0: rem = val2 % 10 rev_num = (rev_num * 10) + rem val2 //= 10 print(f"This is the reversed number: {rev_num}\n\n") def insert(self, val, i): x = 0 for _ in array1: x += 1 if x == i: array1[x] = val print(f"{array1}\n\n")
838f97bcad6c015f344328ca08ffd189a7368cce
liuouya/MIT_6.00_assignments
/ps3b.py
496
3.59375
4
#! /usr/bin/python2.5 -tt # Problem Set 3 # Name: Anna Liu # Collaborators: N/A # Time: 00:05:00 # Date: 10/04/2014 # search and return a tuple of starting points of 'key' in 'target'. def subStringMatchExact(target,key): if key == '': match = range(0, len(target)) return match match = () location = 0 while location < len(target): i = str.find(target, key, location) if i >= 0: match += (i,) location = (i + len(key)) else: break return match
60bc545c91ddf384c7c3f60378c9375182238673
tooyoungtoosimplesometimesnaive/probable-octo-potato
/p_y/520_detect_capital.py
446
3.65625
4
class Solution: def detectCapitalUse(self, word): """ :type word: str :rtype: bool """ first_capital = self.is_capital(word[0]) count = 0 for c in word: if self.is_capital(c): count += 1 return count == 0 or count == len(word) or (first_capital and count == 1) def is_capital(self, c): return c >= 'A' and c <= 'Z'
3d34eafd7b2354f6578575b9c3ba3bd29ae0eb62
xiaoweigege/Python_senior
/chapter01/type_object_class.py
577
4.09375
4
a = 1 b = 'str' print(type(a)) print(type(int)) print(type(b)) print(type(str)) # ๅ…ณ็ณปไธบ type ๅฏน่ฑก็”Ÿๆˆ int , intๅฏน่ฑก็”Ÿๆˆ 1 # type -> class -> object # object ๆ˜ฏ้กถๅฑ‚ๅŸบ็ฑป # type ไนŸๆ˜ฏไธ€ไธช็ฑป ๅŒๆ—ถtype ไนŸๆ˜ฏไธ€ไธช class Student(object): pass stu = Student() print(type(stu)) print(type(Student)) print(Student.__bases__) # type object print('-------') print(type.__bases__) print(object.__bases__) print(type(object)) # ็”ฑๆญคๅฏไปฅ็œ‹ๅ‡บ type ็ปงๆ‰ฟ่‡ช object , object ๅฎžไพ‹ๅŒ–ไน‹ๅŽๆ˜ฏtype # Python ไธญๆ‰€ๆœ‰ๅฏน่ฑก้ƒฝๆ˜ฏ็”ฑtype ๅˆ›ๅปบๅ‡บๆฅ็š„
362b8bdd815de739832be89e28003b4ee7214d54
martica/aoc2019
/day7/day7.py
1,282
3.5625
4
import itertools from intcode.computer import Computer def main(): program_text = next(open("day7.txt")) largest_output = 0 best_combination = None for a, b, c, d, e in itertools.permutations(range(5, 10)): print(a, b, c, d, e, end=' ') amp1 = Computer(program_text, [a]) amp2 = Computer(program_text, [b]) amp3 = Computer(program_text, [c]) amp4 = Computer(program_text, [d]) amp5 = Computer(program_text, [e]) output5 = 0 new_output5 = "something" while new_output5 is not None: output1 = amp1.run([output5]) print(repr(output1), end=' ') output2 = amp2.run([output1]) print(repr(output2), end=' ') output3 = amp3.run([output2]) print(repr(output3), end=' ') output4 = amp4.run([output3]) print(repr(output4), end=' ') new_output5 = amp5.run([output4]) if new_output5 is not None: output5 = new_output5 print(repr(output5)) if output5 > largest_output: largest_output = output5 best_combination = (a, b, c, d, e) print(largest_output) print(best_combination) if __name__ == "__main__": main()
97795611e94f77cb5d43b57333bf61c74038a718
shivdazed/Python-Projects-
/ListFunctions.py
2,468
4
4
a = [] n = int(input("Enter the number of elements in the List:")) for i in range(n): l = input("Enter an element") a.append(l) print("\nList is:",a) def ListOps(): o = input("\nEnter the operation you would like to perform on list:\n1.Append\n2.Extend\n3.Count\n4.Index\n5.Clear\n6.Remove\n7.Copy\n8.Length\n9.Insert\n10.Pop\n11.Exit\n\n\n\n") while(o != '11'): if o == '1': ap_e=input("\nEnter element you wish to append to list:\n") a.append(ap_e) print("\nAppended List is:\n",a) elif o == '2': x = int(input("\nEnter the number of elements you wish to add or extend inital list by:\n")) for i in range(x): j = input("\nEnter an element") a.extend(j) print("\nExtended list is:",a) elif o == '3': c_el= input("\nEnter an element you wish to find the count for:") a.count(c_el) print("\nThe Count or number of data elements in the list is:",a) elif o == '4': dat_el=input("\nEnter the element you wish to find the index of:") a.index(dat_el) print("\nThe position or index of the data element is:",a) elif o == '5': a.clear() print("\nThe list value after clearing is:",a) elif o == '6': re_el=input("\nEnter the element to be removed:") a.remove(re_el) print("\nThe new list after removing element is:",a) elif o == '7': new_l = a.copy() print("\nThe copy of the list is:",new_l) elif o == '8': print("\nThe length of the list is:",length(a)) elif o == '9': p = int(input("\nEnter the index position you want to add an element:\n")) e= input("\nEnter the element you wish to add:") a.insert(p,e) print("The new list is:",a) elif o == '10': p = int(input("Enter the index of the element you wish to pop(last element in list is popped)):")) pop_e = a.pop(p) print("\nThe popped elements is:",pop_e) print("\nThe new list is :",a) break ListOps() choice = input("Do you wish to continue enter Y for Yes and N for No:") while choice == 'Y': ListOps(o) if choice == 'N': break
d7db83626a0c1049497292cc82efb6fc4dabdbf5
Walrusbane524/Basic-python-projects
/Project_3.py
431
4.15625
4
# Recebe o nome e dia do mรชs do usuรกrio e imprime um olรก, o dia anterior e posterior ao dado. # Receives the user name and day of month and prints a hello, the day before and the day after the given one. nome = str(input('Insira o seu nome: ')) dia = int(input('Insira o dia do mรชs de hoje: ')) print('Olรก, ' + nome) print('Ontem foi ' + str(dia - 1)) print('Hoje รฉ ' + str(dia)) print('Amanhรฃ serรก ' + str(int(dia) + 1))
7ed7fa1cfd7ec2b92aca1205339cbf4c7fabefe7
yyyuaaaan/python7th
/crk/8.1stairsNcoinchange.py
1,577
3.890625
4
"""__author__ = 'anyu' 9.1 A child is running up a staircase with n steps, and can hop either 1step, 2 steps, or 3 steps at a time. Implement a method to count how many possible ways the child can run up the stairs. not permutation and not combination """ def npermu(n): if n<=0: return 0 elif n ==1: return 1 elif n==2: return 2 elif n==3: return 4 else: return npermu(n-1)+npermu(n-2)+npermu(n-3) def npermuiter(n): if n<0: return 0 elif n==0: return 1 elif n ==1: return 1 elif n==2: return 2 elif n==3: return 4 else: t1=1 t2=2 t3=4 for i in range(4,n+1): temp= t1+t2+t3 t1=t2 t2=t3 t3=temp return temp print npermuiter(10) coins = [1, 2, 5] amount = 11 def minNumOfCoin(amount, coins): """ for j in range (amountsum) for valuei in [coins] m(j) = min(m(j-valuei))+1 M(i) = min(M(i-1), M(i-2),M(i-5))+1 wrong thinking: l to hold t1 t2 t5, coz we may also need t4 wrong thinking: recursion, right thinking: creat an array where index is just range(amount), right thinking: forward dp """ maxnum=10000 res=[maxnum]*(amount+1) for x in coins: if x <amount+1: res[coins] =1 for i in range(1,amount+1): for denom in coins: if i-denom>0 and res[i-denom] is not maxnum: res[i] = min(res[i-denom]+1, res[i]) return res[-1] if res[-1] is not maxnum else -1
c8b2e28af43e614b072b02ac8fdd6614441dd615
anayatrabbi/Python_Basic_Data_Structure
/4_Looping_Over_List.py
375
4.53125
5
letters = ["a", "b", "c", "d", "e"] for letter in letters: print(letter) # if we want index we should use enumerate which will return iterable object # which is tuple and we can insert any item in tuple for letter in enumerate(letters): print(letter) # we can unpack tuple as we did for our list for index, letter in enumerate(letters): print(index, letter)
1fa5c17ecdad06ce8e46c5a3f700340c4ffab8b0
kbalasub78/Python-CS1
/checkpoint1/jacket.py
739
4.3125
4
## jacket.py ## Write a program to accept the temperature value and ## to tell a person to bring heavy jacket if temperature is < 20, ## if temperature is between 20 and 30, bring light jacket. ## if temperature > 30, do not bring any jacket. ## ## import sys module for graceful error handling import sys #### Get user input for temperature try: temperature = float( input ("Enter the temperature: ") ) except: print('Error in data entered') sys.exit() ## Check the range of temperature and suggest the type of jacket to wear if (temperature < 20): print("Bring a heavy jacket") elif ( temperature >= 20 and temperature < 30): print("Bring a light jacket") elif(temperature >= 30): print("No need of a jacket")
644d999a3834c116b55e3bcb8aeed4b7aba0499c
estherGomezCantarero/practica
/sample/tdd.py
4,796
3.859375
4
import unittest from sample.strings_example import StringsExamples class TestStringsExamples(unittest.TestCase): def test_concat_strings(self): string1 = "hola" string2 = "adios" result = StringsExamples.concat_strings(string1, string2) assert result=="holaadios" def test_concat_int_string(self): str1 = 1 str2 = "adios" self.assertRaises (TypeError,StringsExamples.concat_strings,str1,str2) def test_concat_string_int(self): str1 = "hola" str2 = 2 self.assertRaises(TypeError,StringsExamples.concat_strings,str1,str2) def test_concat_int(self): str1= 1 str2=2 self.assertRaises(TypeError, StringsExamples.concat_strings,str1, str2) def test_concat_two_strings(self): str1= "Espana" str2= "Belgica" result = StringsExamples.concat_strings(str1, str2) assert result == "EspanaBelgica" def test_concat_string1_1(self): str1="a" str2 = "b" result = StringsExamples.concat_strings(str1,str2) assert result=="ab" def test_concat_string1_2(self): str1="a" str2 = "bb" result = StringsExamples.concat_strings(str1,str2) assert result=="abb" def test_concat_string2_1(self): str1="aa" str2 = "b" result = StringsExamples.concat_strings(str1,str2) assert result == "aab" def test_concat_string2_2(self): str1="aa" str2 = "bb" result = StringsExamples.concat_strings(str1,str2) assert result == "aabb" def test_concat_string3_2(self): str1="aaa" str2 = "bb" result = StringsExamples.concat_strings(str1,str2) assert result == "aaabb" def test_concat_string3_3(self): str1="aaa" str2 = "bbb" result = StringsExamples.concat_strings(str1,str2) assert result == "aaabbb" def test_concat_string3_4(self): str1="aaa" str2 = "bbbb" result = StringsExamples.concat_strings(str1,str2) assert result == "aaabbbb" def test_concat_string4_4(self): str1="aaaa" str2 = "bbbb" result = StringsExamples.concat_strings(str1,str2) assert result == "aaaabbbb" def test_concat_string5_4(self): str1 = "aaaaa" str2 = "bbbb" result = StringsExamples.concat_strings(str1, str2) assert result == "aaaaabbbb" def test_concat_string5_5(self): str1 = "aaaaa" str2 = "bbbbb" result = StringsExamples.concat_strings(str1, str2) assert result == "aaaaabbbbb" def test_concat_string5_6(self): str1 = "aaaa" str2 = "bbbbbb" result = StringsExamples.concat_strings(str1, str2) assert result == "aaaabbbbbb" def test_concat_string6_6(self): str1 = "aaaaaa" str2 = "bbbbbb" result = StringsExamples.concat_strings(str1, str2) assert result == "aaaaaabbbbbb" def test_concat_string6_7(self): str1 = "aaaaaa" str2 = "bbbbbbb" result = StringsExamples.concat_strings(str1, str2) assert result == "aaaaaabbbbbbb" def test_concat_string7_7(self): str1 = "aaaa" str2 = "bbbbb" result = StringsExamples.concat_strings(str1, str2) assert result == "aaaabbbbb" def test_concat_string8_7(self): str1 = "aaaaaaaa" str2 = "bbbbbbb" result = StringsExamples.concat_strings(str1, str2) assert result == "aaaaaaaabbbbbbb" def test_concat_string8_8(self): str1 = "aaaaaaaa" str2 = "bbbbbbbb" result = StringsExamples.concat_strings(str1, str2) assert result == "aaaaaaaabbbbbbbb" def test_concat_string8_9(self): str1 = "aaaaaaaa" str2 = "bbbbbbbbb" result = StringsExamples.concat_strings(str1, str2) assert result == "aaaaaaaabbbbbbbbb" def test_concat_string9_9(self): str1 = "aaaaaaaaa" str2 = "bbbbbbbbb" result = StringsExamples.concat_strings(str1, str2) assert result == "aaaaaaaaabbbbbbbbb" def test_concat_string9_10(self): str1 = "aaaaaaaaa" str2 = "bbbbbbbbbb" result = StringsExamples.concat_strings(str1, str2) assert result == "aaaaaaaaabbbbbbbbbb" def test_concat_string10_10(self): str1 = "aaaaaaaaaa" str2 = "bbbbbbbbbb" result = StringsExamples.concat_strings(str1, str2) assert result == "aaaaaaaaaabbbbbbbbbb" if __name__ == '__main__': unittest.main()
eb7d5fd2d03c64f653154cc27012f990a0b70439
wtokarz80/Python
/fibonacci/fibonacci.py
884
3.96875
4
def fibonacci(): i = 0 j = 1 k = 0 fib = 0 fib_list = [] while i < int(number): fib_list.append(fib) fib = j + k j = k k = fib i += 1 max_n = max(fib_list) for z, e in enumerate(fib_list): z += 1 print(f"{z}. " + str(e).rjust(len(str(max_n)))) keep_asking = True while keep_asking: number = input("How many numbers of Fibonacci sequence do you want to print out?: ") if number.isdigit() and int(number) > 0: fibonacci() break else: ask = input("Invalid value, do you want to try again? [Y/N]: ") while ask not in ["Y", "y", "N", "n"]: ask = input("Invalid command, do you want to try again? [Y/N]: ") if ask == "N".lower(): print("Bye, bye.") break elif ask == "Y".lower(): keep_asking
4acbbf6fe06f43883a425c9ffdf8378924060874
dylanplayer/ACS-1100
/lesson-2/example-6.py
2,795
4.59375
5
# Convert the lyrics into string: # When I find myself in times of trouble, Mother Mary comes to me # Speaking words of wisdom, let it be # And in my hour of darkness she is standing right in front of me # Speaking words of wisdom, let it be # Let it be, let it be, let it be, let it be # Whisper words of wisdom, let it be # Each line should be assigned to its own variable! # Look for patterns and use different string operators # Example: # + - concatenation (adding two strings together) # * - generate multiple copies of the string be = "let it be" wisdom = "words of wisdom" line_1 = "When I find myself in times of trouble, Mother Mary comes to me" line_2 = "Speaking " + wisdom + ', ' + be line_3 = "And in my hour of darkness she is standing right in front of me" line_4 = line_2 line_5 = be * 4 line_6 = "Whisper " + wisdom + ", " + be # Challenge! Put the song together and print # the lyrics to the console: print(line_1) print(line_2) print(line_3) print(line_4) print(line_5) print(line_6) # DRY is an accronym for Don't Repeat Yourself! # Its a best practice for computer programmers! # Notice the code above does it's best to avoid # repeating values and code that has already # been written! # Below are the lyrics to Smokestack Lightnin' by Howlin Wolf # Using the example above how could you break the lines below # into variables. Use the + and * operators to # There is a lot of repetition in the lyrics below # your goals is to use code to avoid the repeating # code that you have already written! """ Ah oh, smokestack lightnin' Shinin' just like gold Why don't ya hear me cryin'? A whoo hoo, whoo hoo, whoo Whoa oh tell me, baby What's the matter with you? Why don't ya hear me cryin'? Whoo hoo, whoo hoo, whooo Whoa oh tell me, baby Where did ya, stay last night? A-why don't ya hear me cryin'? Whoo hoo, whoo hoo, whoo Whoa oh, stop your train Let her go for a ride Why don't ya hear me cryin'? Whoo hoo, whoo hoo, whoo """ # Challenge: Define some variables for each line of the lyrics above line_1 = "Ah oh, smokestack lightnin'" line_2 = "Shinin' just like gold" corus = "Why don't ya hear me cryin'?\nA whoo hoo, whoo hoo, whoo" whoa = "Whoa oh tell me, baby" line_3 = "What's the matter with you?" line_4 = "Where did ya, stay last night?" line_5 = f"A-{corus}" line_6 = "Whoa oh, stop your train" line_7 = "Let her go for a ride" # Challenge: Print the song below print("\n") print(line_1) print(line_2) print(corus) print("\n") print(whoa) print(line_3) print(corus) print("\n") print(whoa) print(line_4) print(line_5) print("\n") print(line_6) print(line_7) print(corus) print("\n") # Stretch goal: After solving the above challenge identify any # repeated lyrics and use a variable # Stretch Challenge: As above but use your own lyrics
5284ab9e157bc94da6a6ca56ae737aadcdfcc577
Apro123/projectEuler
/problem 2.py
289
3.71875
4
#!/usr/bin/env python3 def main(): sum = 0 num1 = 1 num2 = 2 while(num2 <= 4000000): if(num1 % 2 == 0): sum += num1 if(num2 % 2 == 0): sum += num2 num1 += num2 num2 += num1 print(sum) main()
c7efb42dc967a153a2c710ec161faa478b0eb2a4
codebind-luna/exercism_python
/scrabble-score/scrabble_score.py
429
3.640625
4
dict = {} dict[1] = ['A', 'E', 'I', 'O', 'U', 'L', 'N', 'R', 'S', 'T'] dict[2] = ['D', 'G'] dict[3] = ['B', 'C', 'M', 'P'] dict[4] = ['F', 'H', 'V', 'W', 'Y'] dict[5] = ['K'] dict[8] = ['J', 'X'] dict[10] = ['Q', 'Z'] def score(word): return sum([get_score(dict, x.upper()) for x in list(word)]) def get_score(dict, char): for key, value in dict.items(): if char in value: return int(key)
25bf001a28be5c4ce991a62cb5392af79c3fb191
shourya192007/A-dance-of-python
/Basics/14. CSV to JSON.py
3,645
3.71875
4
import csv import json # ------------------------------------------------------------ # TODO: FIND A EFFICIENT WAY TO INCLUDE HEADERS IN EACH ROW # ------------------------------------------------------------ # Function to convert a CSV to JSON # Takes the file paths as arguments def make_json(csvFilePath, jsonFilePath): # create a dictionary data = {} # Open a csv reader called DictReader with open(csvFilePath, encoding='utf-8') as csvf: csvReader = csv.DictReader(csvf) # Convert each row into a dictionary # and add it to data for rows in csvReader: # Assuming a column named 'No' to # be the primary key key = rows['Status'] data[key] = rows # Open a json writer, and use the json.dumps() # function to dump data with open(jsonFilePath, 'w', encoding='utf-8') as jsonf: jsonf.write(json.dumps(data, indent=4)) # Driver Code # Decide the two file paths according to your # computer system csvFilePath = r'SHPT_PLC_BALTRANS_20210702_145035824_1.csv' jsonFilePath = r'Names.json' # Call the make_json function make_json(csvFilePath, jsonFilePath) { "PushRateRequest": { # "Envelope": { # "SenderID": "string", # "ReceiverID": "string", # "AccessToken": "string", # "Type": "string", # "Version": "string", # "RequestID": -22801399999999.8 # }, "RateDetails": { "RateHeader": { "Customer": "string", "MemberSCAC": "AB", "MemberOfficeCode": "string", "OriginRegion": "string", "OriginInlandCFS": "ABCD", "OriginConsolCFS": "AB", "PortOfLoading": "AB", "Transhipment_1": "ABCD", "Transhipment_2": "AB", "Transhipment_3": "A", "DestinationRegion": "string", "PortOfDischarge": "AB", "DestinationConsolCFS": "ABC", "DestinationInlandCFS": "ABC", "QuotingRegion": "string", "DeleteAllRate": "Y/N" }, "ChargeDetails": [ { "Customer": "string", "MemberSCAC": "AB", "MemberOfficeCode": "string", "OriginRegion": "string", "OriginInlandCFS": "ABCD", "OriginConsolCFS": "AB", "PortOfLoading": "AB", "Transhipment_1": "ABCD", "Transhipment_2": "AB", "Transhipment_3": "A", "DestinationRegion": "string", "PortOfDischarge": "AB", "DestinationConsolCFS": "ABC", "DestinationInlandCFS": "ABC", "QuotingRegion": "string", "DeleteAllRate": "Y/N", "ChargeName": "string", "ChargeCode": "string", "Aspect": "string", "Currency": "ABC", "Rate": 11716500000000.2, "Basis": "string", "Minimum": -31641799999999.8, "Maximum": -41910699999999.8, "EffectiveDate": "2004-04-18", "ExpirationDate": "2001-08-21", "ScaleUom": "W/M", "From": 10409300000000.2, "To": 28200000000000.2, "Notes": "string", "Delete": "", "IsMandatory": "Y/N" }, { "ChargeName": "string", "ChargeCode": "string", "Aspect": "string", "Currency": "ABC", "Rate": 11716500000000.2, "Basis": "string", "Minimum": -31641799999999.8, "Maximum": -41910699999999.8, "EffectiveDate": "2004-04-18", "ExpirationDate": "2001-08-21", "ScaleUom": "W/M", "From": 10409300000000.2, "To": 28200000000000.2, "Notes": "string", "Delete": "", "IsMandatory": "Y/N" } ] } } }
6e31824b3c3ccf8d4adfd26150aa3efb9e10f9d5
anovacap/daily_coding_problem
/imp_autocomplete.py
1,211
3.890625
4
#!/usr/bin/python # Daily Coding Problem - Tries: 8.1 Implement autocomplete system class Trie: def __init__(self): self.ends_here = '#' self.trie = {} def __repr__(self): # allows print return repr(self.trie) def _insert(self, *words): trie = {} for word in words: temp_dict = trie for char in word: temp_dict = temp_dict.setdefault(char, {}) temp_dict[self.ends_here] = self.ends_here return trie def _find(self, word): sub_trie = self.trie for char in word: if char in sub_trie: sub_trie = sub_trie[char] else: return False else: if self.ends_here in sub_trie: return True else: return False def add_word(self, word): if self._find(word): print("Word exists") return self.trie temp_trie = self.trie for char in word: if char in temp_trie: temp_trie = temp_trie[char] else: temp_trie = temp_trie.setdefault(char, {}) temp_trie[self.ends_here] =self.ends_here return temp_trie if __name__ == "__main__": tr = Trie() tr.add_word('bear') tr.add_word('bingo') tr.add_word('cat') tr.add_word('coat') tr.add_word('dog') print(tr) print(tr._find("dog")) print(tr._find("bear")) print(tr._find("bingo"))
6bdcc955245a8cb7b26f2c5b212b632f2097fd77
IdeaventionsAcademy7/chapter-1-part-1-beginnings-Ninja858
/asknumb.py
181
3.9375
4
import math numb_str = input("Ennter a number: ") numb_int = int(numb_str) n = numb_int n = n + 2 n = n * 3 n = n - 6 n = n / 3 print("And your number is...",n)
c6bf95d666d67b33e384afeb22c2ec313609dbe4
Yoo-an/Algorithm
/Brute-Force/15650 - N๊ณผ M (2).py
991
3.5
4
# ๋ฌธ์ œ # ์ž์—ฐ์ˆ˜ N๊ณผ M์ด ์ฃผ์–ด์กŒ์„ ๋•Œ, ์•„๋ž˜ ์กฐ๊ฑด์„ ๋งŒ์กฑํ•˜๋Š” ๊ธธ์ด๊ฐ€ M์ธ ์ˆ˜์—ด์„ ๋ชจ๋‘ ๊ตฌํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค. # # 1๋ถ€ํ„ฐ N๊นŒ์ง€ ์ž์—ฐ์ˆ˜ ์ค‘์—์„œ ์ค‘๋ณต ์—†์ด M๊ฐœ๋ฅผ ๊ณ ๋ฅธ ์ˆ˜์—ด # ๊ณ ๋ฅธ ์ˆ˜์—ด์€ ์˜ค๋ฆ„์ฐจ์ˆœ์ด์–ด์•ผ ํ•œ๋‹ค. # ์ž…๋ ฅ # ์ฒซ์งธ ์ค„์— ์ž์—ฐ์ˆ˜ N๊ณผ M์ด ์ฃผ์–ด์ง„๋‹ค. (1 โ‰ค M โ‰ค N โ‰ค 8) # # ์ถœ๋ ฅ # ํ•œ ์ค„์— ํ•˜๋‚˜์”ฉ ๋ฌธ์ œ์˜ ์กฐ๊ฑด์„ ๋งŒ์กฑํ•˜๋Š” ์ˆ˜์—ด์„ ์ถœ๋ ฅํ•œ๋‹ค. ์ค‘๋ณต๋˜๋Š” ์ˆ˜์—ด์„ ์—ฌ๋Ÿฌ ๋ฒˆ ์ถœ๋ ฅํ•˜๋ฉด ์•ˆ๋˜๋ฉฐ, ๊ฐ ์ˆ˜์—ด์€ ๊ณต๋ฐฑ์œผ๋กœ ๊ตฌ๋ถ„ํ•ด์„œ ์ถœ๋ ฅํ•ด์•ผ ํ•œ๋‹ค. # # ์ˆ˜์—ด์€ ์‚ฌ์ „ ์ˆœ์œผ๋กœ ์ฆ๊ฐ€ํ•˜๋Š” ์ˆœ์„œ๋กœ ์ถœ๋ ฅํ•ด์•ผ ํ•œ๋‹ค. answer=[0] def findAnswer(index,n,m): if index==(m+1): ans = "" for i in range(1,m+1): ans+=str(answer[i])+" " print(ans) return for i in range(answer[-1]+1,n+1): answer.append(i) findAnswer(index+1,n,m) answer.pop(-1) n, m = map(int,input().split()) findAnswer(1,n,m)
0a0394e926b61899bdd952ab401cb57b498aeb35
albertusdev/competitive-programming
/AtCoder/ABC094/A.py
146
3.609375
4
A, B, C = [int(x) for x in input().split(" ")] if A > C: print("NO") elif A == C: print("YES") elif A + B >= C: print("YES") else: print("NO")
665db8b550c90dcf3e1fffac90064aa4a6987642
mnauman-tamu/ENGR-102
/interactingWithTheUser.py
676
3.765625
4
# interactingWithTheUser.py # # Work together to format a list of projects and dates # # Muhammad Nauman # UIN: 927008027 # September 10, 2018 # ENGR 102-213 # # Patrick Zhong # # Lab 3A - 2 projects = [] dates = [] for i in range(1, 5): projects.append(input("\nEnter the name of project %d: " % i)) dates.append(input("Enter the due date for project %d: " % i)) print("----------------------------------------------------------------") for i in range(0, 4): s = " " * max(32 - len(projects[i]), 5) print("Project %d: " % (i+1) + projects[i] + s + dates[i]) print("----------------------------------------------------------------")
860d48a74ac4f57a0fad6bdba30e0b5418b5f403
palcu/algo
/Contests/MindCoding-2015/runda2/pr1.py
370
3.796875
4
def solve(line): x, y, z = line.strip().split() if x == "0" and y == "0" and z == "0": return False x = x.replace(y, z) x = list(x) while len(x) and x[0] == "0": x.pop(0) if not len(x): x = 0 else: x = "".join(x) print x return True while True: value = raw_input() c = solve(value) # next line was found if c == False: break
5872d6e790035c643e70f910437f175794e66840
Arko98/Alogirthms
/Competitive_Coding/Search_2D_Matrix_Binary_Search.py
885
3.890625
4
# Problem URL: https://leetcode.com/problems/search-a-2d-matrix class Solution: def binarySearch(self, array, begin, end, target): mid = (begin + end)//2 while begin<=end: if array[mid] == target: return True elif array[mid] < target: begin = mid + 1 return self.binarySearch(array,begin,end,target) else: end = mid - 1 return self.binarySearch(array,begin,end,target) return False def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: rows = len(matrix) cols = len(matrix[0]) for row in range(rows): if target>= matrix[row][0] and target<= matrix[row][cols-1]: return self.binarySearch(matrix[row],0,cols-1,target) return False
fc8b059aeabf699dd8816a9d3d521ad4eedd983b
zk97/lab-code-simplicity-efficiency
/your-code/challenge-1.py
2,186
4.34375
4
""" This is a dumb calculator that can add and subtract whole numbers from zero to five. When you run the code, you are prompted to enter two numbers (in the form of English word instead of number) and the operator sign (also in the form of English word). The code will perform the calculation and give the result if your input is what it expects. The code is very long and messy. Refactor it according to what you have learned about code simplicity and efficiency. """ numbers={"zero":0,"one":1,"two":2,"three":3,"four":4,"five":5} words={0:"zero",1:"one",2:"two",3:"three",4:"four",5:"five",6:"six",7:"seven",8:"eight",9:"nine",10:"ten"} #Get number function receives if it is first or second number and asks input until number between 0 or 5 is received word or numbers accepted def get_number(place): x=input(f'Please choose your {place} number (zero to five): ') try: x=int(x) if x not in range(6): print("Incorrect input please try again") x=get_number(place) except: try: x=numbers[x] except: print("Incorrect input please try again") x=get_number(place) return x #Ask for operator until valid is received, word or symbols is accepted def get_operation(): x=input('What do you want to do? plus or minus: ') if x=='plus' or x=='+': return 'plus' elif x=='minus' or x=='-': return 'minus' else: print('Please enter a valid operator') return get_operation() #Operate numbers and print result def result(first,second,operator): if operator=='plus': result=first+second result=words[result] else: result=first-second try: result=words[result] except: result="negative "+words[-result] print(f'{words[first]} {operator} {words[second]} equals {result}') if __name__=='__main__': print('Welcome to this calculator!') print('It can add and subtract whole numbers from zero to five') a = get_number('first') b = get_operation() c = get_number('second') result(a,c,b) print("Thanks for using this calculator, goodbye :)")
7439623479d31fa7128ffaf7c48cd9be2d115883
javedmomin99/Spam-Identifier
/main.py
780
4.21875
4
# Identify the spam comments from the given list below and write a code to show the user whether the comment is a spam comment or not? options_text = ["hello","make a lot of money","buy now","how are you","subscribe this", "click this","Have a nice day"] print(options_text) text = input("\nplease select any 1 comment from the above options\n").lower() if "make a lot of money" in text: spam = True elif "buy now" in text: spam = True elif "subscribe this" in text: spam = True elif "click this" in text: spam = True elif "hello" in text: spam = False elif "how are you" in text: spam = False elif "have a nice day" in text: spam = False if spam: #Above line means if spam = True print("This is Spam") else: print("Not a Spam")
92cb3210e2c254324fe7f3ae1e0f123e99ecd7b1
dtwin/shiyanlou_code
/squares2.py
193
3.828125
4
squares=[] for x in range(10): squares.append(x**2) print(squares) squares=[x**2 for x in range(10)] print(squares) matrix=[(z,y) for z in [1,2,3] for y in [3,2,1] if z!=y] print(matrix)
2f8c8033e21ea0e7383ee2eab86181d3d2efb047
scorp6969/Python-Tutorial
/loop/nested_loops.py
347
4.375
4
# nested loops = The inner loops will finish all of its iterations before finishing one iteration # of the outer loop rows = int(input('How many rows?: ')) columns = int(input('How many columns?: ')) symbol = input('Enter a symbol: ') for i in range(rows): for j in range(columns): print(symbol, end="") print('')
10f8db69373d0a6515ceaddb65c66de9d49620d0
junkwd/AizuOnlineJudge
/ALDS1_2_A.py
512
4.03125
4
def bubbleSort(array): sw = 0 flag = True i = 0 while (flag): flag = False for j in range(len(array) - 1, i, -1): # for (int j = array.length - 1; j > i; j--) {...} if (array[j] < array[j - 1]): array[j - 1], array[j] = array[j], array[j - 1] # ้…ๅˆ—ใฎ็ฝฎๆ› flag = True sw += 1 i += 1 return sw n = int(input("nใ‚’ๅ…ฅๅŠ›")) r = [] for i in range(0, n): r.append(int(input(str(i + 1) + "็•ช็›ฎใฎๆ•ดๆ•ฐใ‚’ๅ…ฅๅŠ›"))) sw = bubbleSort(r) print(r) print(sw)
5b55f223e006bc75f233dfb213515810e0c4a0bd
YutingYao/leetcode-3
/leetcode/string/14.py
624
3.734375
4
from typing import List class Solution: def longestCommonPrefix(self, strs: List[str]) -> str: '''ๆœ€้•ฟๅ…ฌๅ…ฑๅ‰็ผ€ @Note: ็บตๅ‘ๆฏ”่พƒ ''' if len(strs)==0: return '' for j in range(len(strs[0])): for i in range(1,len(strs)): if len(strs[i])<j+1 or strs[i][j]!=strs[0][j]: return strs[0][:j] return strs[0]#ๆณจๆ„่ฟ™,ๅฆ‚ๆžœๅ‰้ขๆกไปถ้ƒฝๆปก่ถณ,้‚ฃไนˆ่ฟ”ๅ›žstrs[0] if __name__=='__main__': string=input().strip() solution=Solution() print(solution.longestCommonPrefix(string))
bf4064961fb45c50ab1dc1779e3eab843919d4e6
bluedynamics/bda.calendar.base
/src/bda/calendar/base/inspector.py
1,243
3.71875
4
from datetime import datetime from timezone import timezoneAdjuster def dtYear(dt, context=None): """Return the year of dt.""" if pyDt(dt): dt = timezoneAdjuster(context, dt) return dt.year return dt.year() def dtMonth(dt, context=None): """Return the month of dt.""" if pyDt(dt): dt = timezoneAdjuster(context, dt) return dt.month return dt.month() def dtDay(dt, context=None): """Return the day of dt.""" if pyDt(dt): dt = timezoneAdjuster(context, dt) return dt.day return dt.day() def dtHour(dt, context=None): """Return the hour of dt.""" if pyDt(dt): dt = timezoneAdjuster(context, dt) return dt.hour return dt.hour() def dtMinute(dt, context=None): """Return the minute of dt.""" if pyDt(dt): dt = timezoneAdjuster(context, dt) return dt.minute return dt.minute() def dtWeekday(dt, context=None): """Return the weekday of dt.""" if pyDt(dt, context=None): dt = timezoneAdjuster(context, dt) return dt.weekday() + 1 return dt.dow() def pyDt(dt, context=None): """Return wether dt is instance of datetime object.""" return isinstance(dt, datetime)