blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
9b6bb96d315064a1b0ceb0ba45f31ad4827facf8
ashwini-cm-au9/DS-and-Algo-with-Python
/HackerRank/operatos_hacker.py
373
3.65625
4
import math import os import random import re import sys # Complete the solve function below. def solve(meal_cost, tip_percent, tax_percent): tip=float(meal_cost*float(tip_percent/100)) tax=float(meal_cost*float(tax_percent/100)) tot=float(meal_cost+tip+tax) print(round(tot)) if __name__ == '__main__': meal_cost = float(input())
4fcf4d2382a0222c93bcd328383399ea292ea031
isrishtisingh/python-codes
/URI-manipulation/uri_manipulation.py
1,173
4.125
4
# code using the uriModule # the module contains 2 functions: uriManipulation & uriManipulation2 import uriModule # choice variable is for choosing which function to use for manipulating the URL/URI choice = -1 try: choice = int(input(" \n Enter 1 to parse given URL/URIs \n Enter 2 to enter your own URI/URL \n")) except ValueError: print("Invalid input\n") exit() if (choice == 1): print(" \n Enter any of the following numbers to get parts of the URI/URL : ") n = input(" 1 for scheme \n 2 for sub-domain \n 3 for domain \n 4 for directory/path \n 5 for sub-directory/query \n 6 for page/fragment\n\n ") try: if (type(n) != int): uriModule.uriManipulation(n) except TypeError: print("Your input must be a number\n") elif(choice == 2): url = input("Enter a URL: ") print(" \n Enter any of the following numbers to get parts of the URI/URL : ") n = int(input(" 1 for scheme \n 2 for authority+domain \n 3 for directory/path \n 4 for sub-directory/query \n 5 page/fragment\n\n ")) print(uriModule.uriManipulation2(url, n)) else: print("\nInvalid choice\n")
5668afb596dbdd9f78abefce058cf09794d74d44
GuanYangCLU/AlgoTestForPython
/LeetCode/tree/1379_Find_a_Corresponding_Node_of_a_Binary_Tree_in_a_Clone_of_That_Tree.py
857
3.703125
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode: self.path = [] self.getPath(original, target, []) return self.findNode(cloned, self.path) def getPath(self, node, target, path): if not node: return if node == target: self.path = path return self.getPath(node.left, target, path + ['left']) self.getPath(node.right, target, path + ['right']) def findNode(self, node, path): while path: side = path.pop(0) node = node.left if side == 'left' else node.right return node
0cc41bc3bc9a4375e0d2e22f7b1ab088a59362ac
PurplePenguin4102/stuff
/Lorenzo tutorial series/linespinsupport.py
765
3.875
4
import math def pixel_to_xy((pix_x,pix_y),(width,height)): '''Takes a 2 tuple with pixel coordinates and converts it to x, y coordinates centered at the center of the screen''' x = pix_x - width/2 y = height/2 - pix_y return (x,y) def xy_to_pixel((x,y),(width,height)): '''inverts pixel_to_xy''' pix_x = x + width/2 pix_y = height/2 - y return (int(pix_x),int(pix_y)) def originspin((x_0,y_0),theta): '''Spins a line originating at (0,0) by theta ''' hyp = float(math.sqrt(x_0**2 + y_0**2)) y_1 = math.sin(theta) * hyp x_1 = math.cos(theta) * hyp return (x_1,y_1) def spinstep((x_0,y_0), (x_1,y_1), theta): '''Spins a line that starts at x_0,y_0 and terminates at x_1,y_1 by theta and returns a new start and terminate point''' pass
a5a42a21096a35eeb920b0cafab4a3db0ce1d342
zdyxry/LeetCode
/array/1961_check_if_string_is_a_prefix_of_array/1961_check_if_string_is_a_prefix_of_array.py
219
3.578125
4
class Solution: def isPrefixString(self, s: str, words: List[str]) -> bool: comp = "" for w in words: comp += w if comp == s: return True return False
2e17d29ed1f728b0d4422c5edf6fa8ffc83d964f
ikenticus/blogcode
/python/tasks/rolodex/reader.py
1,613
3.6875
4
''' reader: contains all the function used to parse and organize data file ''' import config import json import os import re def parse(line): ''' parse each line and compare with valid_line pattern in config ''' entry = {} for valid in config.valid_lines: check = valid['patt'].match(line) if check: for item in valid['list']: idx = valid['list'].index(item) + 1 if item.startswith('phone'): if item == 'phonenumber': #entry[item] = '-'.join(check.group(*tuple(range(idx, idx+3)))) # using shorter comma-separated-tuple instead of *tuple(range) entry[item] = '-'.join(check.group(idx, idx+1, idx+2)) else: entry[item] = check.group(idx) return entry def read(filename): ''' read data input file and create rolodex json ''' idx = 0 output = { 'entries': [], 'errors': [] } with open(filename, 'r') as lines: for line in lines: entry = parse(line.rstrip()) if entry: output['entries'].append(entry) else: output['errors'].append(idx) idx += 1 return output def write(output, filename): ''' sort and write the corresponding output json file ''' output['entries'].sort(key=lambda x: (x['lastname'], x['firstname'])) data = json.dumps(output, sort_keys=True, indent=2) with open(filename, 'w+') as out: out.write(data)
6766acfddb1731ac74ba33ce4acecfe20836abc1
CodecoolBP20172/pbwp-2nd-tw-python-game-python-game-pair-12
/pair_12_tictactoe.py
4,466
4.0625
4
import sys import datetime class color: """Adds color to the X and O symbol""" BLUE = '\033[94m' GREEN = '\033[92m' END = '\033[0m' def print_table(): """Prints out the game field""" print("\n") print(" " + table[7] + " | " + table[8] + " | " + table[9] + " ") print("-----------------") print(" " + table[4] + " | " + table[5] + " | " + table[6] + " ") print("-----------------") print(" " + table[1] + " | " + table[2] + " | " + table[3] + " ") print("\n") def checkwin(): """Checks if there is a winning position or draw""" if (table[1] == table[2] and table[2] == table[3]) or \ (table[4] == table[5] and table[5] == table[6]) or \ (table[7] == table[8] and table[8] == table[9]) or \ (table[1] == table[4] and table[4] == table[7]) or \ (table[2] == table[5] and table[5] == table[8]) or \ (table[3] == table[6] and table[6] == table[9]) or \ (table[1] == table[5] and table[5] == table[9]) or \ (table[3] == table[5] and table[5] == table[7]): win() elif any(element.isdigit() for element in table) is False: draw() else: global counter counter += 1 def print_current_score(): """Prints out the score, called after a finished round""" print("{}: {} - {}: {}".format(name1, name1_score, name2, name2_score)) def win(): global name1_score global name2_score if counter % 2 != 0: print(name1 + " won!") name1_score += 1 want_to_play_again() else: print(name2 + " won!") name2_score += 1 want_to_play_again() def draw(): print("Tie!") want_to_play_again() def cell_is_empty(cell_num): """Checks if a cell is empty or not""" return table[cell_num] == str(cell_num) def want_to_play_again(): """Asking if the players want another round or not. If so, it resets the table. If not, it exports the scores to a txt file and exits.""" print_current_score() while True: try: more = input("Want to play again? (y/n)") more = more.upper() assert more == "Y" or more == "N" except Exception: print("Please choose between 'y' or 'n'.") else: break if more == "Y": global table table = ["X", "1", "2", "3", "4", "5", "6", "7", "8", "9"] print_table() global counter counter += 1 elif more == "N": with open("scores.txt", "a") as scores: scores.write(str(datetime.datetime.now().date())+"\n") scores.write("{}: {}\n".format(name1, name1_score)) scores.write("{}: {}\n".format(name2, name2_score)) scores.write("◡◠◡◠◡◠◡◠◡"+"\n") sys.exit() def start_game(): """Prints out game rules and the table, and asks for the players' names.""" print(""" - For this game, two players are required. - Decide who starts. - The first player starts with "X". - After the first round, you can either continue or stop. - The loser starts next round. - After a finished game, scores can be reviewed in the "scores.txt" file. """) print_table() global name1 global name2 name1 = input("First player, enter your name: ") name2 = input("Second player, enter your name: ") def game_play(): """Changes the numbers to the signs on the table, handles exceptions (wrong input).""" global counter counter = 0 more = "y" while more == "y": checkwin() if counter % 2 != 0: char = color.BLUE + "X" + color.END name = name1 else: char = color.GREEN + "O" + color.END name = name2 num = input("\nIt's your turn, " + name + ". Enter a number according to the table above: ") if len(num) != 1 or (not num.isdigit()): print("Please choose from 1-9.") counter -= 1 elif cell_is_empty(int(num)): table[int(num)] = char print_table() else: print("This block is not empty.") counter -= 1 def main(): global table global name1_score global name2_score table = ["X", "1", "2", "3", "4", "5", "6", "7", "8", "9"] name1_score = 0 name2_score = 0 start_game() game_play() if __name__ == "__main__": main()
1347c15bd05a8a99b6cb7a2d35eba91a9f277b56
jgrissom/wctc-iot
/bits_and_bytes.py
1,119
3.640625
4
from gpiozero import Button, LED from signal import pause # set button and led pins pins = ( { "btn": 20, "led": 21 } { "btn": 13, "led": 19 }, { "btn": 6, "led": 12 }, { "btn": 8, "led": 11 }, { "btn": 10, "led": 9 }, { "btn": 23, "led": 24 }, { "btn": 17, "led": 27 }, { "btn": 15, "led": 18 } ) # when a button is pressed def toggle_led(btn): for i in range(len(pins)): if pins[i]["btn"] == btn.pin.number: # toggle led on/off leds[i].toggle() # set bit to 0/1 bits[i] = 1 if leds[i].is_lit else 0 break display_bits() # display the collection of bits def display_bits(): s = ''.join(map(str, bits)) print(s) # uncomment the following to display the decimal ASCII code # and the extended ASCII symbol - https://www.ascii-code.com #print(s + " " + str(int(s,2)) + " " + chr(int(s,2))) buttons = [] leds = [] bits = [] # create arrays of buttons, leds, and bits for i in range(len(pins)): buttons.append(Button(pins[i]["btn"])) leds.append(LED(pins[i]["led"])) bits.append(0) buttons[i].when_released = toggle_led display_bits() pause()
99ebb10443533a3d5dc2b138b6e32e284bb42670
bssrdf/pyleet
/S/ShortestImpossibleSequenceofRolls.py
1,985
4.125
4
''' -Hard- You are given an integer array rolls of length n and an integer k. You roll a k sided dice numbered from 1 to k, n times, where the result of the ith roll is rolls[i]. Return the length of the shortest sequence of rolls that cannot be taken from rolls. A sequence of rolls of length len is the result of rolling a k sided dice len times. Note that the sequence taken does not have to be consecutive as long as it is in order. Example 1: Input: rolls = [4,2,1,2,3,3,2,4,1], k = 4 Output: 3 Explanation: Every sequence of rolls of length 1, [1], [2], [3], [4], can be taken from rolls. Every sequence of rolls of length 2, [1, 1], [1, 2], ..., [4, 4], can be taken from rolls. The sequence [1, 4, 2] cannot be taken from rolls, so we return 3. Note that there are other sequences that cannot be taken from rolls. Example 2: Input: rolls = [1,1,2,2], k = 2 Output: 2 Explanation: Every sequence of rolls of length 1, [1], [2], can be taken from rolls. The sequence [2, 1] cannot be taken from rolls, so we return 2. Note that there are other sequences that cannot be taken from rolls but [2, 1] is the shortest. Example 3: Input: rolls = [1,1,3,2,2,2,3,3], k = 4 Output: 1 Explanation: The sequence [4] cannot be taken from rolls, so we return 1. Note that there are other sequences that cannot be taken from rolls but [4] is the shortest. Constraints: n == rolls.length 1 <= n <= 105 1 <= rolls[i] <= k <= 105 ''' from typing import List class Solution: def shortestSequence(self, rolls: List[int], k: int) -> int: # Time: O(n), Space: O(k) res = 1 s = set() for a in rolls: s.add(a) if len(s) == k: # got a complete set, length res sequence is possible res += 1 # res + 1 is the length of sequence not possible so far s.clear() return res if __name__ == "__main__": print(Solution().shortestSequence(rolls = [4,2,1,2,3,3,2,4,1], k = 4))
799ee2bcad0d39768554a73694f83dc92c8b2e89
kishkumarr/python
/lists.py
368
3.828125
4
a=['a','b',1,2] a.append(3) print(a) a=['a','b',1,2] a.insert(2,3) print(a) a1 = [1, 2, 3] a2 = [2, 3, 4, 5] a1.extend(a2) print(a1) a2.extend(a1) print(a2) a = [1, 2, 3, 4, 5] print(sum(a)) b = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1] print(b.count(3)) c1 = [0.3, 2.1, 3.2, 5.1, 1, 2.5] print(min(c1)) c2 = [2.3, 4.4, 3, 5.3, 1, 2.5] print(max(c2))
0df892af0863d3238e940192eb0ef4ebd4bc6869
CodecoolBP20172/pbwp-3rd-si-code-comprehension-Rannamari
/comprehension.py
2,433
4.3125
4
# the code below is a game where the comptures generates a number between 1 to 19 and the player has 5 guesses to take import random # imports pseudo-random number generator named random module guessesTaken = 0 # assigs 0 to global variable named guessesTaken print('Hello! What is your name?') # prints out a message to the console myName = input() # assigning input value (str) to myName variable number = random.randint(1, 20) # assigns random integer to variable named number within the range of 1 to 19 print('Well, ' + myName + ', I am thinking of a number between 1 and 20.') # printing out a message while guessesTaken < 6: # iterating through the indented code while guessesTaken variable is lower than 6 print('Take a guess.') # printing out the message to the console,requesting user input guess = input() # assigns user input to variable named guess guess = int(guess) # converts str input to integer guessesTaken += 1 # increases the guessesTaken variable's value by one if guess < number: # decides whether the guess variable is lower than the number variable, if yes, executes the indented code below print('Your guess is too low.') # prints out the str in the parentheses to the console if guess > number: # decides whether the guess variable is higher than the number variable, if yes, executes the indented code below print('Your guess is too high.') # prints out the str in the parentheses to the console if guess == number: # decides whether the guess variable is equal to the number variable, if yes, executes the indented code below break # breaks out from the while loop if guess == number: # decides whether the guess variable is equal to the number variable, if yes, executes the indented code below guessesTaken = str(guessesTaken) # converts the int type guessesTaken to a str type variable print('Good job, ' + myName + '! You guessed my number in ' + guessesTaken + ' guesses!') # prints out the str in the parentheses and the variable named guessesTaken to the console if guess != number: # decides whether the guess variable is equal to the number variable, if not, executes the indented code below number = str(number) # converts the int type guessesTaken to a str type variable print('Nope. The number I was thinking of was ' + number) # prints out the str in the parentheses and the variable named number to the console
c16f7ce861fb16ac89d5af6396b503fc6d2b68c3
SuHyeonJung/iot_python2019
/01_Jump_to_python/4_Input_Output/1_Function/164.py
437
3.578125
4
a = 10 def vartest(): print(a) # 전역변수를 단순히 조회하는 것은 문제가 없다. '''def vartest2(): print(a) a = a + 1 # 지금과 같은 방식으로 전역 변수의 값을 수정할 수 없다. print(a)''' def vartest3(): global a print(a) a = a + 1 # 지금과 같은 방식으로 전역 변수의 값을 수정할 수 없다. print(a) vartest() vartest2() vartest3() print(a)
7b9139a49638565885710e0acedb37fc4b1345f8
mnbotk/python_study
/map3.py
248
3.59375
4
# coding: utf-8 #def to_cm(inch): # return inch * 2.54 # #inches = [9, 5.5, 6, 4, 5, 6.5, 10] #for cm in map(to_cm,inches): # print(cm) #上記をlamda式で for cm in map(lambda inch: inch * 2.54,[9, 5.5, 6, 4, 5, 6.5, 10]): print(cm)
8d419417cbf44717450c97e3070618504acf37a4
Ved005/project-euler-solutions
/code/triangle_on_parabola/sol_397.py
706
3.890625
4
# -*- coding: utf-8 -*- ''' File name: code\triangle_on_parabola\sol_397.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #397 :: Triangle on parabola # # For more information see: # https://projecteuler.net/problem=397 # Problem Statement ''' On the parabola y = x2/k, three points A(a, a2/k), B(b, b2/k) and C(c, c2/k) are chosen. Let F(K, X) be the number of the integer quadruplets (k, a, b, c) such that at least one angle of the triangle ABC is 45-degree, with 1 ≤ k ≤ K and -X ≤ a < b < c ≤ X. For example, F(1, 10) = 41 and F(10, 100) = 12492. Find F(106, 109). ''' # Solution # Solution Approach ''' '''
b349e47b20ac6cfc3be52985603755e0ef113178
rjmendus/pythonBasics
/challengelist.py
295
3.578125
4
l = [] ch = 1 print("Enter the values for list(enter finish when your done):") while 1: ch = input() if ch == 'finish': break l.append(ch) print(l) while 1: print("Enter the operation:") str = input() print(str) a = str.split() if a[1] == '': cmd1 = str(a[0]) print(cmd1) break
cb8316dda16548301aeef125694acda8d3009cbb
bwbobbr/pycharm-xx
/图灵学院视频练习/advance/函数式编程/text_enumerate.py
386
3.75
4
# enumerate功能和zip类似 # 就是给所迭代的对象里,配上一个索引,然后索引和内容构建成tuple类型 l1 = [11,22,33,44,55] em = enumerate(l1, start = 100) print(type(em)) # for i in em: # print(i) 每行输出()形式 # 记住这个写法 l2 = [j for j in em] # 输出形式[(),()] 类同zip当执行6,7,8语句时,该9,10语句输出为空[] print(l2)
5c4aa34cd4a5fcd130dd3d388de4e80bf177707e
sheikh210/LearnPython
/strings_and_operators/operators.py
175
3.828125
4
a = 12 b = 3 print(a + b) print(a - b) print(a * b) print(a / b) print(a // b) print(a % b) print() # for i in range(1, a // b): # print(i) print(a + b / 3 - 4 * 12)
2f43b6fc87b1661a36a0438f17996ad878d7c21d
GaganDureja/Algorithm-practice
/palindromes.py
300
3.6875
4
#Link: https://www.hackerrank.com/challenges/the-love-letter-mystery/problem def theLoveLetterMystery(s): l = len(s)//2 left = s[:l] right = s[l+(1 if len(s)%2 else 0):] [::-1] return sum([abs(ord(left[x])-ord(right[x])) for x in range(len(left))]) print(theLoveLetterMystery('abcd'))
94c6566a12ca30ec73d28f0417f51f790c6bc322
rafaelperazzo/programacao-web
/moodledata/vpl_data/428/usersdata/281/105483/submittedfiles/jogoDaVelha_BIB.py
1,103
4.09375
4
# -*- coding: utf-8 -*- # COLOQUE SUA BIBLIOTECA A PARTIR DAQUI import random def desenhaTabela(board): # Desenha a tabela # "board" é uma lista de 10 strings representando uma tabela (ignorando o indice [0]) print(' | |') print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9]) print(' | |') print('-----------') print(' | |') print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6]) print(' | |') print('-----------') print(' | |') print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3]) print(' | |') def solicitaSimboloDoHumano(): # Escolhe a letra letter = '' while not (letter == 'X' or letter == 'O'): print('Você quer ser X ou O?') letter = input().upper() # Define a letra do computador if letter == 'X': return ['X', 'O'] else: return ['O', 'X'] def sorteioPrimeiraJogada(): # Escolhe quem joga primeiro if random.randint(0, 1) == 0: return 'computer' else: return nomeJogador
6806a44684ff58ff0b2d854cd171c3c82d77d04f
Fulvio7/curso-python-guppe
/guppe/exercicios_secao_4/ex_21.py
272
3.609375
4
""" 21- Leia uma massa em libras e apresente-a convertida para quilogramas. A fómula de conversão é: K[kg] = L[lb] * 0.45 """ lb = float(input('Digite uma massa em libras ')) kg = lb * 0.45 print('Convertendo para quilogramas temos: ') print(f'{lb} lb = {kg} kg ')
c33466d4165083ea9cf6484eb97db61f598ad708
YK-Orfeluna/python-arduino
/path_filter.py
809
3.75
4
from math import pi p = 1e-12 u = 1e-6 capacitor = { 100:10*p, 101:100*p, 102:0.001*u, 103:0.01*u, 104:0.1*u, 105:u, 106:10*u, 223:0.022*u, 333:0.033*u, 473:0.047*u, 474:0.47*u } def filter(fc) : global capacitor t = 1.0 / (fc * 2*pi) for i in capacitor : r = str(round((t / capacitor[i]), 2)) print("%s %s and %s" %(r, "\u03a9", i)) def freq(r, c) : global capacitor c = capacitor[c] fc = 1.0 / (2 * pi * r * c) return fc if __name__ == "__main__" : print("A frequency which you want to cut using HPF or LPF") fc = int(input("Hz >>>")) filter(fc) print("Which resister do you use?") r = float(input("\u03a9 >>>")) print("Which capacitor do you use?") c = int(input("No. >>>")) print("\n%.3f Hz" %freq(r, c)) exit()
97ada3d0acb20c735ee07c70e1936834fe8ed619
jbischof/algo_practice
/epi3/recursion.py
3,112
4.03125
4
"""Recursive problems.""" import random def gen_permutations(a): """ Generate all permutations of the elements in list. Args: a: A list Returns: A set of all permutations. Idea: A permutation can be defined recursively in terms of positions. If the first i positions are already chosen than the i+1 should be a random selection of the remaining ones Time: O(n * n!) because n! permutations and each perm requires n swaps. Space: O(1) """ ret = [] gen_permutations_helper(0, a, ret) return ret def gen_permutations_helper(pos, a, ret): # Base case: all positions filled if pos == len(a) - 1: ret.append(a[:]) return # Otherwise choose all remaining element for pos for i in range(pos, len(a)): a[pos], a[i] = a[i], a[pos] gen_permutations_helper(pos + 1, a, ret) a[i], a[pos] = a[pos], a[i] class Node(object): def __init__(self, value): self.value = value self.left = None self.right = None def tree_diameter(root): """ Determine the longest path on a tree, where a path is defined as the number of edges between two leaf nodes. Idea: The longest path may or may not include the root. For example, the left child of the root might have a path of length 8 on its right and 7 on its left, but the root node has to choose one of these, not the sum. That suggests that each node must pass up *both* the longest path on the subtree as well as the longest *composable* branch that can be used by its parent; in this case 8. Note that 8 includes the subtree root itself. The solution at the parent is then the max of the paths on the left and right vs the sum of composable branches on left and right + 1. The base case is a None node, which returns (0, 0). Example: Longest path is between G and J (length 8) Example*: Longest path is between N and P and does not include the root A / \ / \ B C / \ / \ D E H I / / \ K* F J / \ L* G / \ M* O* / \ N* P* node lb, ld, rb, rd, mb, rd, bd N, 0, 0, 0, 0, 1, 1, 1 N, 0, 0, 0, 0, 1, 1, 1 G, 0, 0, 0, 0, 1, 1, 1 F, 0, 0, 1, 1, 2, 2, 2 E, 2, 2, 0, 0, 3, 3, 3 B, 1, 1, 3, 3, 4, 5, 5 """ if root is None: return (0, 0) left_branch, left_dia = tree_diameter(root.left) right_branch, right_dia = tree_diameter(root.right) # Biggest branch reusable by parent node max_branch = max(left_branch, right_branch) + 1 # Diameter of subtree rooted on this node root_dia = left_branch + right_branch + 1 # Best diameter seem so far best_dia = max(root_dia, max(left_dia, right_dia)) return max_branch, best_dia
ce6877ba30456b79d099cdabfc1051c5015d82dd
hackfengJam/LintCode
/lintCode/dynamic_programming/lintCode_119.py
1,099
3.5625
4
#!/usr/bin/env python # -*- coding:utf-8 -*- __Author__ = "HackFun" __Date__ = "2018/3/6 下午2:21" class Solution(object): """ @param word1: A string @param word2: A string @return: The minimum number of steps. """ def minDistance(self, word1, word2): # write your code here if len(word1) == 0: return len(word2) if len(word2) == 0: return len(word1) len1 = len(word1) len2 = len(word2) res = [[0 for _ in range(len2 + 1)] for _ in range(len1 + 1)] for i in range(1, len1 + 1): res[i][0] = i for i in range(1, len2 + 1): res[0][i] = i for i in range(1, len1 + 1): c1 = word1[i - 1] for j in range(1, len2 + 1): c2 = word2[j - 1] if c1 == c2: res[i][j] = res[i - 1][j - 1] else: res[i][j] = min(res[i - 1][j], min(res[i][j - 1], res[i - 1][j - 1])) + 1 return res[len1][len2] s = Solution() print s.minDistance("mart", "karma")
8c82501cb03c7ac407733afc06401016a2f155e4
PavelStransky/PCInPhysics
/python/work/sin.py
329
3.640625
4
import matplotlib.pyplot as plt x = 0 v = 1 xs = [x] vs = [v] dt = 0.001 tmax = 100 t = 0 ts = [t] while t < tmax: x1 = x + v * dt v1 = v - x * dt t1 = t + dt xs.append(x1) vs.append(v1) ts.append(t1) x = x1 v = v1 t = t1 plt.plot(ts, xs) plt.xlabel("t") plt.ylabel("sin t") plt.show()
f3973a0940513bd69dd85a7d95f0e5cbf319f418
zhangyuhang926/Leetcode
/组合.py
341
3.515625
4
def combine(n, k): res, path = [], [] if k == 0 or k > n: return res dfs(n, k, 1, path, res) return res def dfs(n, k, beg, path, res): if len(path) == k: res.append(path[:]) for i in range(beg, n+1): path.append(i) dfs(n, k, i+1, path, res) path.pop() print(combine(4, 2))
7ecf7e11009f534edc19a4490ad2c21d48d219e6
hakloev/it3105-aiprog-project1
/datastructures.py
4,156
3.78125
4
# -*- coding: utf-8 -*- from common import * class Node(object): """ Basic Node object that keeps the foundational properties of a Node that might be used in some sort of state or graph representation """ def __init__(self, index=None, x=None, y=None): """ Constructor """ self.index = index self.x = x self.y = y self.parent = None self.children = set() def __str__(self): return 'N' + str(self.index) def __repr__(self): """ String representation of the BasicNode object """ return 'Node %d (%d, %d)' % (self.index, self.x, self.y) class Graph(object): """ Jazzing the graph since 1985 """ @staticmethod def read_all_graphs(): return [Graph.read_graph_from_file(fp) for fp in fetch_files_from_dir()] @staticmethod def read_graph_from_file(file_path, networkx_graph=None, lightweight=False): """ Reads input data from a file and generates a linked set of nodes :param file_path: Path to the file that is to be read into memory :return: A set of nodes """ node_cache = {} edge_set = [] # Read contents from specified file path with open(file_path) as g: # Retrieve the node and edge count from first line of file nodes, edges = map(int, g.readline().split()) if networkx_graph: debug('NetworkX Graph instance provided, adding nodes directly to graph.') # Retrieve all node coordinates for node in range(nodes): i, x, y = map(float, g.readline().split()) n = Node(index=int(i), x=x, y=y) node_cache[int(i)] = n # Add the node to the networkx graph if networkx_graph is not None: networkx_graph.add_node(n) # Connect all nodes together based on edge declarations in file for edge in range(edges): from_node, to_node = map(int, g.readline().split()) node_cache[from_node].children.add(node_cache[to_node]) node_cache[to_node].children.add(node_cache[from_node]) # This is nice to have edge_set.append((from_node, to_node)) # Add the edge in the networkx graph if networkx_graph is not None: networkx_graph.add_edge(node_cache[from_node], node_cache[to_node]) if lightweight: return [n.index for n in node_cache.values()], edge_set else: return node_cache.values(), edge_set class CSPState(object): """ This class represent a state in a GAC problem, and contains only the current domain sets for all the nodes in the problem. A contradiction flag can be set during iteration """ def __init__(self, nodes={}): """ Constructor, takes in dict mapping from node to domain set """ self.nodes = nodes self.contradiction = False class AStarState(Node): """ The AstarNode is a specialization of a Node, that in addition keeps track of arc-cost, start and goal flags, as well as F, G and H values. """ def __init__(self, index=None, x=None, y=None): super(AStarState, self).__init__(index=index, x=x, y=y) self.is_start = None self.is_goal = None self.state = index self.arc_cost = 1 self.g = 0 self.h = 0 self.f = 0 self.walkable = True self.full_repr_mode = True def __lt__(self, other): if self.f == other.f: return self.h < other.h return self.f < other.f def __gt__(self, other): if self.f == other.f: return self.h > other.h return self.f > other.f def __repr__(self): if self.full_repr_mode: return 'A*Node(%d, %d, F: %d, G: %d, H: %d)' % (self.x, self.y, self.f, self.g, self.h) else: return 'A*Node(%d (%d, %d))' % (self.index, self.x, self.y)
fdb93768b406547f4db3af788fadf7e312e1c253
VictorO98/ADA
/Tarea4/cycle.py
1,720
3.8125
4
# Nombre: Victor Manuel Ospina Bautista # Materia: Analisis y Diseño de Algoritmos # Semestre: 7 # Codigo: 8922377 from sys import stdin class dforest(object): """Disjoint-Union implementation with disjoint forests using path compression and ranking""" def __init__(self, size = 100): """Create an empty disjoint forest""" self.__parent = [i for i in range(size)] self.__rank = [0 for _ in range(size)] def __str__(self): """Return the string representation""" return str(self.__parent) def find(self, x): """Return the representative of x""" if(self.__parent[x] != x): self.__parent[x] = self.find(self.__parent[x]) return self.__parent[x] def union(self, x, y): """Performs the union of the collections where x and y belong""" rx, ry = self.find(x), self.find(y) krx, kry = self.__rank[rx], self.__rank[ry] if(krx >= kry): self.__parent[ry] = rx if(krx == kry): self.__rank[rx] = self.__rank[rx] + 1 else: self.__parent[rx] = ry def kruskal(G, lenv): ans = [] G.sort(key = lambda x: x[2]) df = dforest(lenv) for u, v, w in G: if(df.find(u) != df.find(v)): df.union(u, v) else: ans.append(w) return ans def main(): N = stdin.readline().strip().split() end = ['0','0'] while N != end: grafo = list() nodos = int(N[0]) aristas = int(N[1]) for i in range(0, aristas): tok = stdin.readline().strip().split() lin = list() a = int(tok[0]) b = int(tok[1]) c = int(tok[2]) lin.append(a) lin.append(b) lin.append(c) grafo.append(lin) #Llamar Funcion ans = kruskal(grafo, nodos) if len(ans) == 0: print("forest") else: for i in range(0, len(ans)): print(ans[i],end = " ") print("") N = stdin.readline().strip().split() main()
162ae47a8e3f6cd812f17e4f97d35b066b10dda4
5at05h1/python_function
/base3.py
248
3.734375
4
# グローバル変数 def printAnimal(): global animal animal = 'Cat' print('関数内animal = {}, id = {}'.format(animal, id(animal))) # animal = 'Dog' printAnimal() print('関数内animal = {}, id = {}'.format(animal, id(animal)))
0bbaa0d36aa4b2255a1df0733e4c50c39bdf82d4
leylagcampos/Python
/75.py
856
3.640625
4
#75 Documentación from modulo import funcmat class Areas: """Esta clase se calcula las areas de diferentes figuras geométricas""" def areaCuadrado(lado): """ Calcula el área de un cuadrado elevando al cuadrado el lado pasado por parámetro""" return "El área del cuadrado es: "+ str(lado+lado) def areaTriangulo(base,altura): """Calcula el área del triangulo utilizando los parámetros base y altura""" return "El área del triangulo es : "+ str((base*altura)/2) print(Areas.areaTriangulo(2,7)) print("----------------------------") help(Areas) print("----------------------------") help(Areas.areaTriangulo) print("----------------------------") print(Areas.areaCuadrado.__doc__) print("----------------------------") print(Areas.areaCuadrado(3)) print("----------------------------") help(Areas.areaCuadrado) help(funcmat)
ceced9bead0d08ecf4f2b7f8d5200288bac79d59
AjaniLevy/BankAccount
/courses/CS/CS1.1/Superhero/team.py
723
3.796875
4
class Team: def __init__(self, name): self.name = name self.heroes = list() def remove_hero(self, name): '''Remove hero from heroes list. If Hero isn't found return 0. ''' foundHero = False for hero in self.heroes: if hero.name == name: self.heroes.remove(hero) foundHero = True # if we looped through our list and did not find our hero, # the indicator would have never changed, so return 0 if not foundHero: return 0 def view_all_heroes(self): for hero in self.heroes: print(hero.name) def add_hero(self, hero): self.heroes.append(hero)
32e118f6cc6e109de0f837998b36f666aa6af2a4
Ljuba-Ljuba/Hometasks
/task_07_02.py
801
4.125
4
""" Реализовать генератор случайных паролей указанной длины. В пароле можно использовать любые символы в верхнем и нижнем регистре. Например: password_generator(16), вернет случайный пароль длиной 16 символов. Пригодится стандартный модуль random Имя файла task_07_02.py Имя функции-генератора password_generator Возвращаемое значение Генератор """ import random from string import digits, ascii_letters def password_generator(n): listing = list(digits + ascii_letters) for i in range(n): letter = random.choice(listing) yield letter
ca6d11805afc721c464ad22cb143e9446f92dd06
kennedy0597/projects
/Python/reversestring.py
215
4.03125
4
str1=input("Enter a string: ") length=len(str1) reversedstr=[] while length>0: reversedstr += str1[length-1] length= int(length)-1 reversedstr = ''.join(reversedstr) print(reversedstr) print(str1[::-1])
97c0c30a16e771059a0dd9cee4119e2598cb2335
crazycracker/PythonPractice
/fourth.py
154
4.15625
4
vowels = list(['a', 'e', 'i', 'o', 'u']) alphabet = input("Enter the alphabet\n") if alphabet in vowels: print("Vowel") else: print("Consonant")
c48272e2c2b45907295eec17fb8efae37f78c89e
Brownxin/Alogrithm_learning
/leetcode/Subsets.py
530
3.53125
4
__author__ = 'Brown' class Solution(object): def subsets(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ if len(nums)==0: return [] res=[] def dfs(depth,start,list): if not list in res: res.append(list) if depth==len(nums): return for i in range(start,len(nums)): dfs(depth+1,i+1,list+[nums[i]]) nums.sort() dfs(0,0,[]) return res
a5172fa41c1d5296d9536cfbde617e6235504f43
alxcarrion713/PythonAlgos
/node.py
931
3.59375
4
# Sam thinks Tad might be somewhere in a very long line waiting to attend the Superman movie. Given a ListNode pointer and a val, return whether val is found in any node in the list” # Excerpt From: Martin Puryear. “Algorithm Challenges: E-book for Dojo Students.” iBooks. class Node: def __init__(self, valueInput): self.value = valueInput self.next = None class SLL: def __init__(self): self.head = None def addfront(self, valueInput): #createNewNode newnode = Node(valueInput) newnode.next = self.head self.head = newnode return self def display(self): runner = self.head print(runner) while runner != None: print(runner.value) runner = runner.next return self # def removefront(self): # #your code here sll1 = SLL() sll1.addfront(5).addfront(8).addfront(15).display()
1270fc50649291048f06307caf9dd19a9d40e642
kongziqing/Python-2lever
/实战篇/第15章-并发编程/15.1.5-psutil模块/psutil-CPU.py
924
3.53125
4
""" 通过psutil模块分别获取CPU的物理数量与逻辑数量,同时利用该模块也可以准确地获取CPU的使用率信息,在进行系统管理过程中 经常需要对CPU的状态进行监控,所以本程序利用for循环并结合psutil.cpu_percent()方法每隔1秒获取当前系统中的CPU占用率嘻嘻 """ import psutil def main(): print("[理CPU数量:%d"%psutil.cpu_count(logical=False))#提示信息 print("逻辑CPU数量:%d"%psutil.cpu_count(logical=True))#提示信息 print("用户CPU使用时间:%f、系统CPU使用时间:%f、CPU空闲时间:%f"%(psutil.cpu_times().user,psutil.cpu_times().system,psutil.cpu_times().idle)) #提示信息 for x in range(10):#循环监控CPU信息,每一秒获取一次CPU信息,一共获取10次信息 print("CPU使用率监控:%s"%psutil.cpu_percent(interval=1,percpu=True)) if __name__ == '__main__': main()
452ea9d31ae6d228b743676f3b680b932c79c921
iftekharchowdhury/Problem-Solving-100-Days
/func.py
1,792
4.53125
5
''' - difference between arguments and parameters - Positional and keyword arguments - Default arguments - variable-length arguments(*args and **kwargs) -container unpacking into function arguments - Local vs Global arguments - Parameter Passing( by value or by reference?) ''' # - difference between arguments and parameters def print_name(name): # name is parameter print(name) print_name('Alex') # here Alex is a arguments # Positional and keyword arguments def foo(a, b, c): print(a, b, c) # foo(a=1, b =2 , c=3) # keyword arguments a is keyword 1 is a value # foo(c=9, b=4, a=2) # foo(1, b=2, 3) # error # Default arguments def loo(a, b, c, d=5): print(a,b,c,d) # loo(1,3,0) # - variable-length arguments(*args and **kwargs) def moo(a, b, *args, **kwargs): # kwargs = keyword arguments print(a,b) for arg in args: print(arg) for k, v in kwargs.items(): print(k,v) moo(1, 2, 3, 4, 5, six=6, seven=7) def lol(a,b, *, c, d): # after * all parameter must be keyword arguments print(a, b, c, d) lol(1, 2, c=3,d=4) # container unpacking into function arguments def unpack_var(a, b, c): print(a,b,c) my_list= [1,2,3] my_dict = {'a':1, 'b':2, 'c':3} unpack_var(*my_list) unpack_var(**my_dict) # local vs global var # param passing - call by obj reference # mutable objects can be modified in a function def modified_obj(a_list): return a_list.append(4) my_list = [1,2,3] modified_obj(my_list) print(my_list) def foo(x): x = 5 var = 10 foo(var) print(var) # ************* asterisk operator my_tuple = (1,2,3) my_list = [1,2,3] my_dict = {1,2,3} dict_a = {'a':1, 'b': 2} dict_b = {'c':3, 'd':4} new_dict = {**dict_a, **dict_b} new_list = [*my_tuple, *my_list, *my_dict] print(new_list, new_dict)
bb623e9fb3625ae7527176a57f20d61868e658e2
Jgusbc/Board-Games
/Puzzle 15.py
4,717
3.9375
4
""" Autores del código José Gustavo Buenaventura Carreón César Armando Lara Liceaga """ import random import math import os #Crear matriz aletoria. def matriz_aleatoria(): nums = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,''] random.shuffle(nums) matriz = [[],[],[],[]] temp = 0 for i in range(4): for j in range(4): matriz[i].append(nums[temp]) temp+= 1 return matriz #Poner una matriz predeterminada. def matriz_escogida(): nums=[] while len(nums)!=16: nums = input('Teclea los números separados por espacios (y el vació con un 0): ') nums = nums.split() dummy_nums = ['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','0'] temp1 = [] for i in nums: if (i not in temp1 and i in dummy_nums): temp1.append(i) else: print('Hay un número repetido o no disponible') nums = temp1 for i in nums: if i == '0': nums[nums.index(i)] = "" else: nums[nums.index(i)] = int(i) assert len(nums) == 16 matriz = [[],[],[],[]] temp = 0 for i in range(4): for j in range(4): matriz[i].append(nums[temp]) temp+= 1 return matriz #Enseñar el tablero. def print_tablero(matriz): for i in matriz: for j in i: print('{:5s}'.format(str(j)),end=' ') print('\n') #posibles respuests a elegir respuestaNormal = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,""]] respuestaInversa = [["",15,14,13],[12,11,10,9],[8,7,6,5],[4,3,2,1]] respuestaEspiral = [[1,2,3,4],[12,13,14,5],[11,15,"",6],[10,9,8,7]] respuestaEspiralInversa = [[4,3,2,1],[5,14,13,12],[6,15,"",11],[7,8,9,10]] respuestaVerticalNormal = [[1,5,9,13],[2,6,10,14],[3,7,11,15],[4,8,12,""]] respuestaVerticalInversa = [["",12,8,4],[15,11,7,3],[14,10,6,2],[13,9,5,1]] #Set de siglas de las respuestaEspiral respuestas=['n','i','e','ei','vn','vi'] #Encontrar la casilla de un número dado. def buscar_casillas(casilla,tablero): for i in tablero: i_index = tablero.index(i) for j in i: j_index= i.index(j) if tablero[i_index][j_index] == casilla: return (i_index,j_index) #Distancia entre 2 casillas. def distance(p0, p1): return math.sqrt((p0[0] - p1[0])**2 + (p0[1] - p1[1])**2) #Realizar el movimiento. def movimiento(ficha,tablero): posicion1= buscar_casillas(ficha, tablero) posicion2= buscar_casillas('', tablero) dist= distance(posicion1,posicion2) if dist!=1: print('No es un movimiento posible') else: tablero[posicion1[0]][posicion1[1]],tablero[posicion2[0]][posicion2[1]]=tablero[posicion2[0]][posicion2[1]],tablero[posicion1[0]][posicion1[1]] return tablero #main def juego(): count = 0 modo = '' tipo = '' print('En caso de querer interrumpir el juego, ingrese 0.') while modo != "a" or modo != "p": modo= input('¿Quieres un tablero aleatorio(a) o uno predeterminado(p)? ') if modo == "a": matriz = matriz_aleatoria() break elif modo == "p": matriz = matriz_escogida() break while tipo not in respuestas: tipo = input('¿Cual tipo de juego quiere jugar? \nNormal (n) \nInverso (i) \nEspiral (e) \nEspiral Inverso (ei)\nVertical (v)\nVertical inverso(vi)\n') print_tablero(matriz) if tipo == 'n': solucion= respuestaNormal elif tipo == 'i': solucion=respuestaInversa elif tipo =='e': solucion=respuestaEspiral elif tipo == 'ei': solucion=respuestaEspiralInversa elif tipo == 'v': solucion=respuestaVerticalNormal elif tipo == 'vi': solucion = respuestaVerticalInversa while matriz != solucion: ficha = int(input('Seleccione la tecla que quiere mover: ')) if ficha == 0: print('Gracias por jugar') break else: os.system('cls') movimiento(ficha, matriz) print_tablero(matriz) count += 1 if matriz == solucion: print_tablero(matriz) print("Felicidades lo has resuelto en " + str(count) + " movimientos.") juego() """ Caso de prueba tablero=[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,'',15]] intercambiar 15 con '' función movimiento(ficha, tablero) se encuentra la ficha con la función buscar_casillas se intercambia tablero=[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,'']] tablero==soluciónote se termina el juego Función movimientos Dos casos Fichas adyacentes Fichas no adyacentes Todas las fichas adyacentes están a una distancia 1 Si la ficha no está a distancia 1, no es posible moverla Solo intercambiar fichas si distancia=1 para evitar que el usuario de inputs no deseados, se usaron while loops hasta que el usuario de el input correcto """
ca8f98ae7a91cb25c6e7048e66cde2a68e7a4d3f
RMDircio/CSPT13_IntroPython_GP
/IntroIII/store.py
3,778
4.3125
4
# lets write a store class with a name and categories # class Store: # def __init__(self, name, categories): # # attributes # self.name = name # self.categories = categories # def __str__(self): # ret = f"{self.name}\n" # for i, c in enumerate(self.categories): # ret += " " + str(i + 1) + ": " + c.name + "\n" # ret += " " + str(i + 2) + ": Exit" # return ret # def __repr__(self): # return f"Store({self.name}, {self.categories})" # how can we represent this class data as a string? #----------------------------------------------------------------# #----------------------------------------------------------------# #----------------------------------------------------------------# ''' Artem Litchanov's Lecture CSPT 8 ''' # import the category class we made from category import Category class Store: # attributes # name # categories - different departments # constructor (every class has one) - function that runs at every new instance # in python it is --> __init__() def __init__(self, name, categories): # self is the current instance of class # need to assign the variables self.name = name self.categories = categories self.employees = [] # make some employees # make a function to share over all instances # welcome message for example # __str__ --> cast instance of Class Store as a string for printing def __str__(self): output = f'Welcome to {self.name}!' # loop over categories counter = 1 for category in self.categories: output += f'\n {counter}. {category.name}' # incriment the counter - adding it then setting it counter += 1 # return a string representing the store return output # printing function - returns a string def __repr__(self): return f'Self.name = {self.name} ; self.categories = {self.categories}' ### stores # new categories # empty [] here is the product array - we are makeing it empty for now running_category = Category('Running', "All your running needs", []) baseball_category = Category('Baseball', "Cubs Unite!", []) basketball_category = Category('Basketball', 'Indoor and outdoor products', []) sports_store = Store('REI', [running_category, baseball_category, baseball_category]) # print(sports_store) grocery_store = Store("ALdi's", ['Meat', 'Dairy', 'Produce', 'Frozen', 'Baking']) # print(grocery_store) # print(sports_store.name) # print(grocery_store.name) # print the repr version # print(repr(sports_store)) # print(repr(grocery_store)) # print a category # print(running_category) ### REPL <-- READ EVALUATE PRINT LOOP # print(sports_store) # READ part of REPL # get user input # user_choice = input('Please choose a category (#): ') # EVALUATE part of REPL and PRINT part of REPL # seperating this out: # chosen_category = sports_store.categories[int(user_input)] # print(chosen_category) # last two part put together # print(sports_store.categories[int(user_choice)]) # put everything into a loop choice = -1 print(sports_store) print('Type q to quit') while True: # READ choice = input('Please choose a category (#): ') try: # EVALUATE if (choice =='q'): break choice = int(choice) -1 if choice >= 0 and choice < len(sports_store.categories): chosen_category = sports_store.categories[choice] # PRINT print(chosen_category) else: print('The number is out of range') # how to prevent a error when strings are entered for choice except ValueError: print("Please enter a number")
b8e9c2feea84ba0013b2e0a06d96a3f5f81c263d
flaviogf/examples
/name_to_array.py
480
3.78125
4
from functools import reduce strip = lambda text: text.strip() upper = lambda text: text.upper() split = lambda sep: lambda text: text.split(sep) compose = lambda *fns: lambda value: reduce(lambda previous_value, fn: fn(previous_value), fns[::-1], value) pipe = lambda *fns: lambda value: reduce(lambda previous_value, fn: fn(previous_value), fns, value) name = input() print(split(' ')(upper(strip(name)))) print(compose(upper, strip)(name)) print(pipe(strip, upper)(name))
a0c0379da4342d55dc8a9361a06cdc73a3af22e9
Goldac77/101Computing-Challenges
/The Honeycomb challenge.py
2,712
4.0625
4
#<-----------------------------------------------------------------------------------------------------------------------------------------------------> # ----------------This is my first solution before I realized you need to use "NESTED FOR LOOPS"----------------------- #<-----------------------------------------------------------------------------------------------------------------------------------------------------> #The honeycomb challenge - www.101computing.net/honeycomb-challenge/ import turtle import math myPen = turtle.Turtle() myPen.shape("arrow") myPen.color("#a86f14") myPen.fillcolor("#efb456") myPen.pensize(2) myPen.delay(10) #Set the speed of the turtle #A Procedue to draw a pentagonal cavity at a given (x,y) position. def drawCavity(x,y,edgeLength): myPen.penup() myPen.goto(x,y) myPen.pendown() myPen.begin_fill() for i in range(0,6): myPen.forward(edgeLength) myPen.left(60) myPen.end_fill() #Main Program Starts Here #Comlpete this code to draw a full honeycomb pattern for x in range(-150,150,60): #little something to define my parameters p1 = 150 p2 = 132 u = x+30 z = 20*(math.sqrt(3)) tks = 0 while(tks <= 8): drawCavity(x,p1,20) drawCavity(u,p2,20) p1 -= z p2 -= z tks += 1 myPen.hideturtle() #<-----------------------------------------------------------------------------------------------------------------------------------------------------> # -----------------------------This is my second solution using a for loop------------------------------------- #<-----------------------------------------------------------------------------------------------------------------------------------------------------> #both solutions give the same result(obviously), but I can't confirm if this is how they expect it to be #The honeycomb challenge - www.101computing.net/honeycomb-challenge/ import turtle import math myPen = turtle.Turtle() myPen.shape("arrow") myPen.color("#a86f14") myPen.fillcolor("#efb456") myPen.pensize(2) myPen.delay(10) #Set the speed of the turtle #A Procedue to draw a pentagonal cavity at a given (x,y) position. def drawCavity(x,y,edgeLength): myPen.penup() myPen.goto(x,y) myPen.pendown() myPen.begin_fill() for i in range(0,6): myPen.forward(edgeLength) myPen.left(60) myPen.end_fill() #Main Program Starts Here #Comlpete this code to draw a full honeycomb pattern for x in range(-150,150,60): #little something to define my parameters p1 = 150 p2 = 132 u = x+30 z = 20*(math.sqrt(3)) for i in range(8): drawCavity(x,p1,20) drawCavity(u,p2,20) p1 -= z p2 -= z myPen.hideturtle()
450749bb37c3cefb767dab9a4098ff1ff9df9b65
santhosh-kumar/AlgorithmsAndDataStructures
/python/test/unit/problems/backtracking/test_all_unique_permutations.py
736
3.84375
4
""" Unit Test for all_unique_permutations """ from unittest import TestCase from problems.backtracking.all_unique_permutations import AllUniquePermutations class TestAllUniquePermutations(TestCase): """ Unit test for AllUniquePermutations """ def test_solve(self): """Test solve Args: self: TestAllUniquePermutations Returns: None Raises: None """ # Given input_list = [1, 2, 3] permutation_problem = AllUniquePermutations(input_list) # When result = permutation_problem.solve() # Then self.assertEqual(result, [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]])
a4bbe3f147919eb66cd635ca8613cf5deea088f3
CelioTI/exemplopython
/Vetor.py
381
3.5625
4
# nome = "Celio TI" # Idade = 31 # Nomes = ["Fernando", "Maria", "João"] # #print (Nomes) # # Array E a mesma coisa que vetor # clientes = [] # print(clientes) # clientes.append("Fernando") # print(clientes) # clientes.append("Maria") # print(clientes) # clientes.append("João") # print(clientes) # print(clientes[2]) # for cliente in clientes: # print(cliente)
b5d4572f5713434cfe0d2ccd6c14053a246130ea
JiarongChang/main
/0319_Class4.py
2,009
3.640625
4
flag = True balance = 0 drinks = [ {"name":"可樂","price":20}, {"name":"雪碧","price":20}, {"name":"茶裏王","price":25}, {"name":"原萃","price":25}, {"name":"純粹喝","price":30}, {"name":"水","price":20}, ] while flag: #當true的時候會執行以下程式 print("\n==========================") select = eval(input("1.儲值\n2.購買\n3.查詢餘額\n4.離開\n請選擇:")) if select == 1: #儲值 value = eval(input("儲值金額:")) while value < 1: #若使用者輸入數字小於零,需要重新輸入 print("====儲值金額需大於零====") value = eval(input("儲值金額:")) balance += value print(f"儲值後餘額為{balance}元") #'pass'的功能為代替像java的大括號({}) 用於將程式區分開 elif select == 2: #購買 #印出品項 print("\n請選擇商品") for i in range(0, len(drinks)): print(f'({i + 1})\t{drinks[i]["name"]} \t {drinks[i]["price"]}元') choose = eval(input("請選擇編號:")) while choose < 1 or choose > 6: print("====清輸入1-6之間====") choose = eval(input("請選擇:")) buy_drink = drinks[choose-1] if balance < buy_drink["price"]: print("====餘額不足====") else: print(f'已購買{buy_drink["name"]} {buy_drink["price"]}元') balance -= buy_drink["price"] print(f'購買後餘額為{balance}元') elif select == 3: #查詢餘額 print(f"目前餘額為{balance}元") elif select == 4: #離開 print("bye") flag = 0 break else: #重新輸入 print("====請輸入1~4之間====") continue #函式 : 將一段程式群組起來,以後需要用到那一段程式的功能時,打出他的函示就好, #比較快速,要修改程式時也比較快速不用一個一個改
2eb8b6ddc3a1d428edad01d523abc3c7d70d1834
HankerZheng/LeetCode-Problems
/python/039_Combination_Sum.py
1,249
3.609375
4
# Given a set of candidate numbers (C) and a target number (T), # find all unique combinations in C where the candidate numbers sums to T. # The same repeated number may be chosen from C unlimited number of times. # Note: # All numbers (including target) will be positive integers. # The solution set must not contain duplicate combinations. # For example, given candidate set [2, 3, 6, 7] and target 7, # A solution set is: # [ # [7], # [2, 2, 3] # ] # Subscribe to see which companies asked this question # Key Points: Backtracing # # Runtime: 120 ms class Solution(object): def combinationSum(self, candidates, target): """ :type candidates: List[int] :type target: int :rtype: List[List[int]] """ def helper(candidates, target, combination): if target == 0: res.append(combination) else: for x in candidates: if x <= target and (not combination or x >= combination[-1]): helper(candidates, target - x, combination+[x]) res = [] helper(candidates, target, []) return res if __name__ == '__main__': sol = Solution() print sol.combinationSum([3,2,7],7)
bc013d7491fc6020512a8dc8ad3ea267de5f688a
zkloveai/solt
/solt/utils/_utils.py
3,529
3.53125
4
from functools import wraps def img_shape_checker(method): """Decorator to ensure that the image has always 3 dimensions: WxHC Parameters ---------- method : _apply_img method of BaseTransform Returns ------- out : method of a class Result """ @wraps(method) def wrapper(self, *args, **kwargs): res = method(self, *args, **kwargs) if len(res.shape) == 2: h, w = res.shape return res.reshape((h, w, 1)) elif len(res.shape) != 3: raise ValueError return res return wrapper def validate_parameter(parameter, allowed_modes, default_value, basic_type=str, heritable=True): """ Validates the parameter and wraps it into a tuple with the inheritance option (if parameter is not a tuple already). In this case the parameter will become a tuple (parameter, 'inherit'), which will indicate that the stream settings will override this parameter. In case if the parameter is already a tuple specified as parameter=(value, 'strict'), then the parameter will not be overrided. Parameters ---------- parameter : object The value of the parameter allowed_modes : dict or set Allowed values for the parameter default_value : object Default value to substitute if the parameter is None basic_type : type Type of the parameter. heritable : bool Whether to check for heretability option. Returns ------- out : tuple New parameter value wrapped into a tuple. """ if parameter is None: parameter = default_value if isinstance(parameter, basic_type) and heritable: parameter = (parameter, 'inherit') if isinstance(parameter, tuple) and heritable: if len(parameter) != 2: raise ValueError if not isinstance(parameter[0], basic_type): raise TypeError if parameter[0] not in allowed_modes: raise ValueError if parameter[1] not in {'inherit', 'strict'}: raise ValueError elif heritable: raise NotImplementedError return parameter def validate_numeric_range_parameter(parameter, default_val, min_val=None, max_val=None): """Validates the range-type parameter, e.g. angle in Random Rotation. Parameters ---------- parameter : tuple or None The value of the parameter default_val : object Default value of the parameter if it is None. min_val: None or float or int Check whether the parameter is greater or equal than this. Optional. max_val: None or float or int Check whether the parameter is less or equal than this. Optional. Returns ------- out : tuple Parameter value, passed all the checks. """ if not isinstance(default_val, tuple): raise TypeError if parameter is None: parameter = default_val if not isinstance(parameter, tuple): raise TypeError if len(parameter) != 2: raise ValueError if parameter[0] > parameter[1]: raise ValueError if not (isinstance(parameter[0], (int, float)) and isinstance(parameter[1], (int, float))): raise TypeError if min_val is not None: if parameter[0] < min_val or parameter[1] < min_val: raise ValueError if max_val is not None: if parameter[0] > max_val or parameter[1] > max_val: raise ValueError return parameter
ff6edd5ccd3e9666ff6dc8e76c1706d24b1cac3c
bentoMiguel/programacaoSenai
/sa2-exercicios/exercicio3.py
496
3.71875
4
valores = [] for i in range(20): valores.append(int(input("informe o próximo valor: "))) total = 0 i = 0 while i < len(valores): total += valores[i] i += 1 maiorValor = -999999 for i in range(len(valores)): if valores[i] > maiorValor: maiorValor = valores[i] menorValor = 999999 for i in range(len(valores)): if valores[i] < menorValor: menorValor = valores[i] print("Média:", total/len(valores)) print("Maior:", maiorValor) print("Menor:", menorValor)
6739d3ffd7a6088547b131ff32dc7d3d071eb074
lidiyam/algorithms
/trees/validate_bst.py
809
3.6875
4
from utils import TreeNode class Solution(object): def isValidBST(self, root): if not root: return True if root.left and root.val <= root.left.val: return False if root.right and root.val >= root.right.val: return False return self.isValid(root.left, -float('inf'), root.val) and self.isValid(root.right, root.val, float('inf')) def isValid(self, root, lo, hi): """ :type root: TreeNode :rtype: bool """ if not root: return True res = lo < root.val < hi if root.right: res = res and root.val < root.right.val and self.isValid(root.right, root.val, hi) if root.left: res = res and root.val > root.left.val and self.isValid(root.left, lo, root.val) return res
87cc3a60f32a900570026289accfabd015da1ff0
hpca01/MoreAlgoPractice
/divide_conquer/majority_element.py
1,851
3.78125
4
# python3 import sys def majority_element_naive(elements): assert len(elements) <= 10 ** 5 for e in elements: if elements.count(e) > len(elements) / 2: return 1 return 0 def find_major(seq, l_bound, r_bound): if r_bound-l_bound <=2: return seq[l_bound] mid = l_bound + (r_bound - l_bound)//2 l = find_major(seq, l_bound, mid) r = find_major(seq, mid, r_bound) counter_1, counter_2 = 0,0 for number in seq[l_bound:r_bound]: if number == l: counter_1 +=1 elif number == r: counter_2 +=1 if counter_1 > (r_bound - l_bound)//2 and l != -1: return l elif counter_2 > (r_bound - l_bound)//2 and r != -1: return r else: return -1 def majority_element(elements): assert len(elements) <= 10 ** 5 value = find_major(elements, 0, len(elements)) return value def alternate_majority(elements): elements.sort() if len(elements) % 2 == 0: mid = len(elements)//2 possible_majority = elements[mid] if possible_majority == elements[mid-1] and possible_majority == elements[mid+1]: return 1 else: return -1 elif len(elements) % 2 != 0 : mid = len(elements)//2 possible_majority = elements[mid] if possible_majority == elements[mid-1] and possible_majority == elements[mid+1]: return 1 else: return -1 # if __name__ == '__main__': # input_n = int(input()) # input_elements = list(map(int, input().split())) # assert len(input_elements) == input_n # print(majority_element(input_elements)) if __name__ == '__main__': input = sys.stdin.read() n, *a = list(map(int, input.split())) if majority_element(a) != -1: print(1) else: print(0)
3fe9eba974daa84c73d2841234665313ae0c11a6
jaypee37/15-112-TermProject
/tpFinal/letter.py
644
3.5
4
import pygame class Letter(object): def __init__(self,x,y,letter,bold = True,font = "Algerian" ): self.x,self.y = x,y self.x1 = x self.a = -12 self.velocity = 100 self.rect = pygame.Rect(self.x,self.y,20,20) self.t = 0 self.myfont = pygame.font.SysFont(font,(30),bold ) self.text = self.myfont.render('%s' %letter, False, (255,0,0)) self.textW, self.textH = self.text.get_size() def move(self): self.t+= 1 if self.t <10: self.x = (self.velocity * self.t) + (.5 * -9 * (self.t**2)) + self.x1 self.rect = pygame.Rect(self.x,self.y,20,20) def draw(self,screen): screen.blit(self.text,(self.x,self.y))
929b8cebe52b9ab0362ed66bc2a0b207573fad05
roosbot/Bootcamp-Assignments
/module-1/Code-Simplicity-Efficiency/your-code/challenge-1-roos.py
3,773
4.25
4
#!/usr/bin/env python # coding: utf-8 # In[ ]: """ 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. """ # In[ ]: # I seperated the code and put it in different functions ## so that each function does only one thing # In[ ]: # I made the userinput lowercase friendly # In[ ]: # I gave variables a more descriptive name # In[149]: # Ask for first user input in words print("Welcome to this calculator!") print("It can add and subtract whole numbers from zero to five") inputWord = [] if len(inputWord) < 1: word = input("Please choose your first number (zero to five): ").lower() inputWord.append(word) print(inputWord) # In[150]: # Ask for plus or minus in words if len(inputWord) < 2: word = input("What do you want to do? plus or minus: ").lower() inputWord.append(word) print(inputWord) # In[151]: # Ask for second user input in words if len(inputWord) < 3: word = input("Please choose your second number (zero to five): ").lower() inputWord.append(word) print(inputWord) # In[152]: # Convert words into numbers inputNumber = [] for x in inputWord: if x == "zero": inputNumber.append("0") elif x == "one": inputNumber.append("1") elif x == "two": inputNumber.append("2") elif x == "three": inputNumber.append("3") elif x == "four": inputNumber.append("4") elif x == "five": inputNumber.append("5") elif x == "plus": inputNumber.append("+") elif x == "minus": inputNumber.append("-") else: print("Something went wrong") print(inputNumber) # In[153]: if inputNumber[1] == "+": result = int(inputNumber[0]) + int(inputNumber[2]) inputNumber.append(str(result)) elif inputNumber[1] == "-": result = int(inputNumber[0]) - int(inputNumber[2]) inputNumber.append(str(result)) else: print("I am not able to read plus or minus") print(inputNumber) # In[154]: # Convert numbers into words outputWord = [] for x in inputNumber: if x == "0": outputWord.append("zero") elif x == "1": outputWord.append("one") elif x == "2": outputWord.append("two") elif x == "3": outputWord.append("three") elif x == "4": outputWord.append("four") elif x == "5": outputWord.append("five") elif x == "6": outputWord.append("six") elif x == "7": outputWord.append("seven") elif x == "8": outputWord.append("eight") elif x == "9": outputWord.append("nine") elif x == "10": outputWord.append("ten") elif x == "+": outputWord.append("plus") elif x == "-": outputWord.append("minus") else: print("Something went wrong") print(outputWord) # In[123]: # Calculate result print(outputWord[0], outputWord[1], outputWord[2], "equals", outputWord[3]) # "four minus zero equals four # In[ ]: def reStart(): answer = input("Do you want to calculate another time? Enter yes or no. ").lower() if answer == "yes": print("Let's calculate some more!") userInput() elif answer == "no": print("Alright, thank you and goodbye!") else: print("Sorry, I don't understand. Please enter yes or no.") reStart() # In[ ]: userInput() reStart() # In[ ]:
6fc4da1001ad7633dbb4155c89b62b865550b502
LordExodius/lc-daily-2021
/Print Zero Even Odd/zeroevenodd.py
1,158
3.71875
4
# Oscar Yu # June 12th, 2021 import threading class ZeroEvenOdd: def __init__(self, n): self.n = n self.zeroLock = threading.Lock() self.evenLock = threading.Lock() self.evenLock.acquire() self.oddLock = threading.Lock() self.oddLock.acquire() self.output = "" # printNumber(x) outputs "x", where x is an integer. def zero(self, printNumber: 'Callable[[int], None]') -> None: for i in range(1, self.n + 1): self.zeroLock.acquire() if not i % 2: self.evenLock.release() else: self.oddLock.release() printNumber(0) def even(self, printNumber: 'Callable[[int], None]') -> None: for i in range(2, self.n + 1, 2): self.evenLock.acquire() printNumber(i) self.zeroLock.release() def odd(self, printNumber: 'Callable[[int], None]') -> None: for i in range(1, self.n + 1, 2): self.oddLock.acquire() printNumber(i) self.zeroLock.release()
48c218df9be404e42f21b6aeb6bc5ceadbc1c323
wasim-ahmed/Py-prog
/prac/__fib.py
104
3.65625
4
var1 = 0 var2 = 1 num = 0 while num <100: num = var1 + var2 var2 = var1 var1 = num print(num)
9e1c75440bcc0402e9341228ebb2727891ed25b1
greedbob/Learn-Pyhton
/Programming-in-Pyhton3/practice1.3.py
398
3.859375
4
# Question:第一章例题3 # Solution: import random guanci = ['a','the'] zhuti = ['cat','dog','man','women'] dongci = ['sang','ran','jumped'] zhuangyu = ['loudly','quietly','well'] if random.randint(0,2) < 1: print(random.choice(guanci),random.choice(zhuti),random.choice(dongci),random.choice(zhuangyu)) else: print(random.choice(guanci),random.choice(zhuti),random.choice(dongci))
6c62984e05c480144083e2c21b67420fe4a3a857
printfoo/leetcode-python
/problems/0251/flatten_2D_vector.py
1,133
3.625
4
""" Solution for Flattern 2D Vector. Idea: """ # Solution. class Vector2D(object): def __init__(self, vec2d): """ Initialize your data structure here. :type vec2d: List[List[int]] """ self.vec2d, self.i, self.j = vec2d, -1, 0 def next(self): """ :rtype: int """ if self.i + 1 < len(self.vec2d[self.j]): self.i += 1 # same row else: while not self.vec2d[self.j + 1]: self.j += 1 self.i = 0; self.j += 1 # next row return self.vec2d[self.j][self.i] def hasNext(self): """ :rtype: bool """ if not self.vec2d: return False # vec2d = [] if self.i + 1 < len(self.vec2d[self.j]): return True # same row temp_j = self.j while temp_j + 1 < len(self.vec2d) and not self.vec2d[temp_j + 1]: temp_j += 1 if temp_j + 1 < len(self.vec2d): return True # next row return False # Main. if __name__ == "__main__": vec2d = [[], [1,2], [], [3], []] i, v = Vector2D(vec2d), [] while i.hasNext(): v.append(i.next()) print(v)
7db4b7191dfad4a7928f4e960bd43252c3991e5a
ProgFuncionalReactivaoct19-feb20/clase01-Jorgeflowers18
/programacion/ejemplo1.py
108
3.84375
4
# Ejemplo de función imperativa valores = [10, 2, 11, 12, 15] for i in valores: if i%2==0: print(i)
6b798dc8ef54475712d96c8a202501222a61f0e2
parrisem/PythonBasics
/StringFormatting.py
823
4.5625
5
# C-style string formatting using '%' operator e.g. "%s" and "%d" # This prints out "Hello, John!" name = "Parris" print("Hello, %s!" % name) # using two or more argument specifiers age = 22 print("%s is %d years old." % (name, age)) # Any object which is not a string can be formatted using the %s operator as well. mylist = [1,2,3] print("A list: %s" % mylist) # Basic argument specifiers to know # %s - String (or any object with a string representation, like numbers) # %d - Integers # %f - Floating point numbers # %.<number of digits>f - Floating point numbers with a fixed amount of digits to the right of the dot. # %x/%X - Integers in hex representation (lowercase/uppercase) # Exercise data = ("John", "Doe", 53.44) format_string = "Hello %s %s. Your current balance is $%s." print(format_string % data)
fdc8381e8f57b117e5a1c0df4a63aef9480da52e
YuanMartinRen/COMP6441WarGame
/Set1/fixedXOR.py
710
3.796875
4
#!/usr/local/bin/python3.5 import sys ''' Check input Convert hex to binary XOR two arrays Convert binary to hex ''' def fixedXOR(): if (len(sys.argv) != 3): return if (len(sys.argv[1]) != len(sys.argv[2])): print (len(sys.argv[1]) + " " + len(sys.argv[2])) return hex_str1 = str(sys.argv[1]) hex_str2 = str(sys.argv[2]) bi_str1 = "" bi_str2 = "" result = "" n = 0 while (n < len(hex_str1)): bi_str1 += "{0:04b}".format(int(hex_str1[n],16)) bi_str2 += "{0:04b}".format(int(hex_str2[n],16)) n += 1 n = 0 while (n < len(bi_str1)): if (bi_str1[int(n)] == bi_str2[int(n)]): result += "0" else: result += "1" n += 1 result = hex(int(result, 2)) print (result) fixedXOR()
075b3a3257cc2f6fc4fc0e86bb90a4a2dbc0cff5
aditya-doshatti/Leetcode
/set_mismatch_645.py
1,194
3.859375
4
''' 645. Set Mismatch Easy The set S originally contains numbers from 1 to n. But unfortunately, due to the data error, one of the numbers in the set got duplicated to another number in the set, which results in repetition of one number and loss of another number. Given an array nums representing the data status of this set after the error. Your task is to firstly find the number occurs twice and then find the number that is missing. Return them in the form of an array. Example 1: Input: nums = [1,2,2,4] Output: [2,3] https://leetcode.com/problems/set-mismatch/ ''' class Solution: def findErrorNums(self, nums: List[int]) -> List[int]: # val,retVal,sumVal = {},0,0 # for i in nums: # if val.get(i, None): # retVal = i # else: # val[i] = 1 # sumVal += i # n = len(nums) # actSum = int((n*(n+1))/2) # diff = actSum - sumVal # #print(val, retVal, actSum, diff, sumVal) # return [retVal, retVal+diff] n = len(nums) actSum = int((n*(n+1))/2) setSum, listSum = sum(set(nums)), sum(nums) return [listSum-setSum, actSum - setSum]
44f478fcb7e8e7883bf9f2b1da89e24b9ffff8f3
codingcn/python-notes
/c2.py
1,140
3.84375
4
from collections import namedtuple, Counter from random import randint ''' 如何为元祖中的每个元素命名,提高程序的可读性 ''' # 1. 通过常量 NAME, AGE, GENDER = range(3) student = ('Bob', '18', '男') print(student[NAME]) # 2. 通过collections.namedtuple Student = namedtuple('Student', ['name', 'age', 'gender']) res = Student('Bob', '18', '男') print(res.name) ''' 统计序列中元素的出现次数 ''' data = [randint(15, 20) for _ in range(12)] print(data) # 1.通过字典 c = dict.fromkeys(data, 0) for x in data: c[x] += 1 print(c) # 2.通过collections.Counter.most_common print(Counter(data).most_common(2)) ''' 如何根据字典中值的大小,对字典中的项排序 某班英语成绩以字典形式存储为{'Bob':66,'Alan':78,'Jim':33...},根据成绩高低,计算学生排名 使用内置函数sorted ''' data = {x: randint(20, 100) for x in 'ABCDEFG'} print(data) # 1.使用zip将字典转元组再排序 new_data = zip(data.values(), data.keys()) res = sorted(new_data) print(res) # 2.利用sorted函数的key参数 res = sorted(data.items(), key=lambda i: i[1]) print(res)
71c74debe7812287d84d78b62c26584bc4e3ee6b
21Lilly/newProject
/test.py
1,274
3.53125
4
#coding:utf-8 import time ''' 给定一个非空正整数的数组,按照数组内数字重复出现次数,从高到低排序 items()方法将字典的元素转化为了元组 key参数对应的lambda表达式的意思则是选取元组中的第二个元素作为比较参数 lambda x:y中x表示输出参数,y表示lambda函数的返回值 ''' # 1、给定一个非空正整数的数组,按照数组内数字重复出现次数,从高到低排序 # list = [1,1,1, 6, 6, 7, 3, 9] # d = {} # list_sorted = [] # for i in list: # d[i] = list.count(i) # print(d) # # 根据字典值的降序排序 # d_sorted = sorted(d.items(), key=lambda x: x[1], reverse=True) # [(1, 2), (6, 2), (7, 1), (3, 1), (9, 1)] # print(d_sorted) # # 输出排序后的数组 # for x in d_sorted: # print(x) # for number in range(0, x[1]): # print(number) # print(x[1]) # list_sorted.append(x[0]) # print(list_sorted) # print("按照重复次数排序后的数字是:{}".format(list_sorted)) # [ 1, 1, 6, 6, 7, 3, 9] # print(time.time()) # print(time.localtime()) # print(time.localtime(time.time())) # rq1 = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time())) # rq2 = time.strftime('%Y%m%d%H%M%S', time.localtime()) # print(rq1) # print(rq2)
92860c52a46e18424c3ea6091c1d6144979cc0ea
jeandy92/Python
/ExerciciosCursoEmVideo/Mundo_2/ex071.py
858
3.640625
4
print('=' * 50) print('BANCO DEV') print('=' * 50) valor = int(input('Quanto deseja sacar ? ')) total = valor ced = 50 totalced = 0 while True: if total >= ced: total = total - ced totalced = totalced + 1 else: if totalced > 0: print(f'Total de {totalced} cédulas de R${ced}') if ced == 50: ced = 20 elif ced == 20: ced = 10 elif ced == 10: ced = 1 totalced = 0 if total == 0: break # # vNotas50 = valor // 50 # vNotas20 = (valor - (vNotas50*50)) // 20 # vNotas10 = ((valor - ((vNotas20*20)+(vNotas50*50))) // 10) # vNotas1 = (valor - ((vNotas20*20)+(vNotas50*50)+(vNotas10*10)) // 1) # # print(vNotas50) # print(vNotas20) # print(vNotas10) # print(vNotas1) # # # # vNotas1 = valor // 1 # #
f495c3aab68eda082f1b2dab401d773c1ba05d8b
mailund/compthink
/src/insertion-sort.py
166
3.578125
4
x = [1, 3, 2, 4, 5, 2, 3, 4, 1, 2, 3] print(x) for i in range(1,len(x)): j = i while j > 0 and x[j-1] > x[j]: x[j-1], x[j] = x[j], x[j-1] j -= 1 print(x)
9b0bcc30022f172e278f073a2ddd48cd89f65c82
m-lobocki/Python-ExercisesSamples
/ex35.py
329
4.21875
4
# Define a function which can generate a dictionary where the keys are numbers between 1 and 20 (both included) and the # values are square of keys. The function should just print the values only. def print_squares(): dictionary = {x: x*x for x in range(1,21)} for key, value in dictionary.items(): print(value)
46ed7c9cfef0c58f332742927506d252b097b23a
andymur/riseandset
/riseandset.py
3,941
3.703125
4
#!/usr/bin/python3.5 import sys from enum import Enum import time # Here I'm trying to play with daylight time # # 1. I want to understand whether daylight has equal decrease / increase value # from day to day between equinoxes / solstices throughout the year or not. # # 2. Do we have same (similar) scenario for the question above for different latitudes # (also to show how different are daylight times for different latitudes) # # Currently data are taken from here (links are general and an example for Seattle WA, USA): # https://aa.usno.navy.mil/data/docs/RS_OneYear.php # http://aa.usno.navy.mil/cgi-bin/aa_rstablew.pl?ID=AA&year=2018&task=0&state=WA&place=Seattlei months = Enum('Month', 'Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec') def days_in_month(month): if month == months.Feb: return 28 elif month in [months.Jan, month.Mar, month.May, month.Jul, month.Aug, month.Oct, month.Dec]: return 31 else: return 30 def each_month_day_rise_and_set(encoded_line): day_size = 2 next_space_size = 2 rise_and_set_time_size = 9 month_in_year = len(months) encoded_line = encoded_line[day_size:] # take out day number rise_and_set_for_days = [] for month_index in range(0, month_in_year): encoded_line = encoded_line[next_space_size:] rise_set_times = encoded_line[:rise_and_set_time_size] encoded_line = encoded_line[rise_and_set_time_size:] rise_and_set_for_days.append(rise_set_times.strip()) return rise_and_set_for_days def calculate_daylight_time_in_hours(sunrise_time, sunset_time): #times are encoded like '%H%M' e.g. 0813 or 1952 time_pattern = '%H%M' return (time.mktime(time.strptime(sunset_time, time_pattern)) - time.mktime(time.strptime(sunrise_time, time_pattern))) / (60 * 60) def calculate_daylight_times_in_hours(month_rise_and_set): result = [] for day_rise_and_set in month_rise_and_set: sunrise_time, sunset_time = day_rise_and_set.split(" ") result.append(calculate_daylight_time_in_hours(sunrise_time, sunset_time)) return result def calendar_lines(filename): linecounter = 0 body_started = False calendar = [] header_size = 6 calendar_lines = 4 + header_size + 31 with open(filename) as f: for line in f: if (not body_started) and ('<pre>' in line): body_started = True if body_started: linecounter += 1 if linecounter > header_size and linecounter < calendar_lines: calendar.append(line) # skip first three lines: month names line, rise-set line and h-m line return calendar[3:] if __name__ == "__main__": #input_filename = "seattle.dat" # sys.argv[1] input_filename = sys.argv[1] day_lines = [] calendar = {month: [None] * days_in_month(month) for month in months} day_lines = calendar_lines(input_filename) day_number = 0 for day_line in day_lines: months_day_rise_and_set = each_month_day_rise_and_set(day_line) for month in months: if months_day_rise_and_set[month.value - 1]: calendar[month][day_number] = months_day_rise_and_set[month.value - 1] day_number += 1 for month in months: print(str(month) + ": ") print("="*80) print(len(calendar[month]), calendar[month]) print("="*80) daylights = calculate_daylight_times_in_hours(calendar[month]) print(daylights) print("="*80) daylight_delta_vector = [abs(j-i) for i, j in zip(daylights[:-1], daylights[1:])] print(daylight_delta_vector) print("="*80) print("Average Delta: " + str(sum(daylight_delta_vector) / len(daylight_delta_vector))) print("="*80) #print(days_in_month(months.Apr)) #print(len(calendar[months.Jun]), calendar[months.Jun]) #print(calculate_daylight_times_in_hours(calendar[months.Feb]))
90f0bf5fc0117b49a872aef229a44a420ed2c95b
AndreasHaagh/LinuxHardwareSurveillance
/PythonApplication1/PythonApplication1/Menu.py
738
3.609375
4
import CPU import MemoryControll import FileControll isRunning = True data = 'data log' """ Function to show user interactive menu performing monitoring of the system """ def DisplayMenu(): print(""" 1: CPU 2: RAM 3: Read Log file 4: Exit """) menuItem = input("Choose menu item: ") #providing information efter user input if (menuItem == "1"): print("") CPU.printCpuUsage() elif (menuItem == "2"): MemoryControll.printMemoryUsage() elif (menuItem == "3"): FileControll.ReadLogFile() elif (menuItem == "4"): global isRunning isRunning = False print("Closing system!") else: print("\nError: invaild input")
264eb01935e9905e4660677c68fc5a6976b234e5
mhearne-usgs/neicutil
/neicutil/timeutil.py
3,851
3.640625
4
#!/usr/bin/env python #stdlib imports import datetime def timeForXML(dtime): """ Convert datetime object (in UTC) to XML dateTime format, i.e. 2002-05-30T09:30:10Z @param dtime: Datetime object, presumed already referenced to UTC. @return: String representing that datetime object in the XML dateTime datatype format. """ fmt = '%Y-%m-%dT%H:%M:%SZ' return dtime.strftime(fmt) def getTimeElapsed(time1,time2): td = time2 - time1 nseconds = 0 nminutes = 0 nhours = 0 ndays = 0 nweeks = 0 nseconds = td.seconds + td.days*86400 if nseconds >= 60: nminutes = nseconds/60 nseconds = round(((nseconds/60.0)-nminutes)*60) if nminutes >= 60: nhours = nminutes/60 nminutes = round(((nminutes/60.0)-nhours)*60) if nhours >= 24: ndays = nhours/24 nhours = round(((nhours/24.0)-ndays)*24) if ndays >= 7: nweeks = ndays/7 ndays = round(((ndays/7.0)-nweeks)*7) return (nweeks,ndays,nhours,nminutes,nseconds) def getTimeElapsedString(thentime,nowtime): """ Return string describing time elapsed between first input time and now, or first and second input times. @param thentime: Input datetime object (in the past). @keyword nowtime: Input datetime object (forward in time from thentime). @return: String describing elapsed time in the two longest applicable units of time, up to years. '10 minutes, 30 seconds', '10 hours, 47 minutes', '10 days, 23 hours', '10 months, 22 days', etc. """ nweeks,ndays,nhours,nminutes,nseconds = getTimeElapsed(thentime,nowtime) if nweeks: return getTimeStr(nweeks,ndays,'week') if ndays: return getTimeStr(ndays,nhours,'day') if nhours: return getTimeStr(nhours,nminutes,'hour') if nminutes: return getTimeStr(nminutes,nseconds,'minute') if nseconds != 1: return '%i seconds' % (nseconds) else: return '1 second' def getTimeStr(bigtime,smalltime,unit): """ Return a time string describing elapsed time. @param bigtime: Number of years, months, days, hours, or minutes. @param smalltime: Number of months, days, hours, minutes, or seconds. @param unit: String representing the units of bigtime, one of: 'second','minute','hour','day','week','month','year'. @return: String elapsed time ('10 days, 13 hours'). """ periods = ['second','minute','hour','day','week','month','year'] bigunit = periods[periods.index(unit)] smallunit = periods[periods.index(unit)-1] if bigtime != 1: bigunit = bigunit+'s' if smalltime != 1: smallunit = smallunit+'s' return '%s %s, %i %s' % (bigtime,bigunit,smalltime,smallunit) if __name__ == '__main__': tnow = datetime.datetime.now() offset = 10 #10 seconds before print getTimeElapsedString(tnow - datetime.timedelta(seconds=offset)) offset = 75 #1 minute, 15 seconds before print getTimeElapsedString(tnow - datetime.timedelta(seconds=offset)) offset = int(1.77*3600) #1.77 hours before print getTimeElapsedString(tnow - datetime.timedelta(seconds=offset)) offset = int(1.5*3600*24) #1.5 days before print getTimeElapsedString(tnow - datetime.timedelta(seconds=offset)) offset = int(9.5*3600*24) #9.5 days before print getTimeElapsedString(tnow - datetime.timedelta(seconds=offset)) offset = int(36.5*3600*24) #36.5 days before print getTimeElapsedString(tnow - datetime.timedelta(seconds=offset)) offset = int(382*3600*24) #382 days before print getTimeElapsedString(tnow - datetime.timedelta(seconds=offset)) offset = 150*365 #150 years before print getTimeElapsedString(tnow - datetime.timedelta(days=offset))
fd1c308dad49d806458ef5c15ee731ed1835e8ad
mgirardin/Project-Euler-Solutions
/Solutions_Python/P020.py
345
4.09375
4
# function to calculate n! def factorial(n): if n == 0: return 1 elif n == 1: return 1 else: return n*factorial(n-1) # function that calculate the sum of digits of n def sum_of_digits(n): n = str(n) sum = 0 for i in n: sum += int(i) return sum print(sum_of_digits(factorial(100)))
8b4d3b6248a6d9726c104b9cf6b98133b7e72d50
Aasthaengg/IBMdataset
/Python_codes/p02756/s668694250.py
561
3.703125
4
#!/usr/bin/env python3 from collections import deque def main(): d = deque() d.extend(list(input())) Q = int(input()) reflag = False for i in range(Q): query = list(input().split()) if query[0] == '1': reflag = not reflag elif (query[1] == '1' and not reflag) or (query[1] == '2' and reflag): d.appendleft(query[2]) else: d.append(query[2]) if reflag: print("".join(reversed(d))) else: print("".join(d)) if __name__ == "__main__": main()
7510aefa9cc130ef3ed05e1e374352e752e4a7e1
liuhuipy/Algorithm-python
/tree/binary-tree-preorder-traversal.py
1,157
4.1875
4
""" 二叉树的前序遍历: 给定一个二叉树,返回它的前序遍历。 示例: 输入: [1,null,2,3] 1 \ 2 / 3 输出: [1,2,3] 进阶: 递归算法很简单,你可以通过迭代算法完成吗? 方法1: 递归 方法2: 迭代 """ from typing import List # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def preorderTraversql(self, root: TreeNode) -> List[int]: res, queue = [], [root] while queue: node = queue.pop() res.append(node.val) if node.right is not None: queue.append(node.right) if node.left is not None: queue.append(node.left) return res def preorderTraversal1(self, root: TreeNode) -> List[int]: self.res = [] self.helper(root) return self.res def helper(self, node: TreeNode) -> None: if not node: return self.res.append(node.val) self.helper(node.left) self.helper(node.right)
876a89aedc1b72cfca95e242146a87d75439a3ba
aguscoppe/ejercicios-python
/TP_2_ Estructura_secuencial/TP2_EJ9.py
399
3.671875
4
#EJERCICIO 9 totalDinero = int(input("Ingrese la cantidad total de dinero: ")) aux = totalDinero cant100 = totalDinero // 100 aux = totalDinero % 100 cant50 = aux // 50 aux = aux % 50 cant10 = aux // 10 aux = aux % 10 cant5 = aux // 5 cant1 = aux % 5 print("Dinero total:", totalDinero) print("Billetes:", cant100, "de $100,", cant50, "de $50,", cant10, "de $10,", cant5, "de $5 y", cant1, "de $1")
b92d11c202ca7fec24782597c17124141d62880c
rrodrigu3z/questionnaire-generator-models
/predictors/utils/downloads.py
1,163
3.5
4
"""Utility functions for performing file downloads""" import requests import tqdm import os.path def download_file(url, filename=False, verbose=False): """Download file with progressbar Taken from: https://gist.github.com/ruxi/5d6803c116ec1130d484a4ab8c00c603 Args: url: URL of the file to download. filename: Name for the output file (optional) verbose: Show file size info (optional). """ if filename: local_filename = filename else: local_filename = os.path.join(".", url.split('/')[-1]) r = requests.get(url, stream=True) file_size = int(r.headers['Content-Length']) chunk = 1 chunk_size = 1024 num_bars = int(file_size / chunk_size) if verbose: print(dict(file_size=file_size)) print(dict(num_bars=num_bars)) with open(local_filename, 'wb') as fp: for chunk in tqdm.tqdm(r.iter_content(chunk_size=chunk_size), total=num_bars, unit='KB', desc=local_filename, leave=True): fp.write(chunk) return
826f35ad42e8feecfc20025ea9307f149396cc30
minism/algorithms
/print_powerset.py
514
3.6875
4
def powerset_rec(L): if len(L) < 1: return [[]] return [L[0] + subset for subset in powerset_rec(L[1:])] def print_powerset_rec(L): print powerset_rec(L) def print_powerset_nonrec(L): stack = L[:] powerset = [[]] while len(stack) > 0: item = stack.pop() new = [] for existing in powerset: new.append([item] + existing) powerset.extend(new) print powerset A = ['a', 'b', 'c', 'd'] # print_powerset_nonrec(A) print_powerset_rec(A)
7a3807940dd82ff7501ba132e5597b5b256d0f91
ecaterinacatargiu/AI
/Lab2/informedSearch.py
5,327
3.59375
4
# -*- coding: utf-8 -*- """ Created on Tue Mar 10 16:13:11 2020 @author: Cati """ from random import choice from copy import deepcopy class State: def __init__(self, n): self.initialState = [[-1]*n]*n self.size = n def getInitialStateValues(self): return self.initialState def getSize(self): return self.size def __str__(self): s="" for i in self.initialState: for j in i: s=s+"" +str(j) s+="\n" return s #x=State(3) #print(x.getInitialState()) class Problem: def __init__(self, n): self.initialState = State(n) def getInitialState(self): return self.initialState def getRoot(self): return deepcopy(self.initialState) def getEmptyCells(self, emptyM:list): empty = [] for i in range(len(emptyM)): for j in range(len(emptyM)): if emptyM[i][j] == 0: empty.append((i,j)) return empty def checkRow(self): n = self.finalState.getSize() for i in range(n): count = 0 for j in range(n): if self.finalState.getInitialStateValues()[i][j] == 1: count = count + 1 if count > 1: return False return True def checkColumn(self): n = self.finalState.getSize() for i in range(n): count = 0 for j in range(n): if self.finalState.getInitialStateValues()[i][j] == 1: count = count + 1 if count > 1: return False return True def checkAbs(self): n = self.finalState.getSize() for i1 in range(0,n): for i2 in range(i1,n): for j1 in range(0,n): for j2 in range(j1, n): if abs(i1-i2)-abs(j1-j2) !=0 and not self.finalState.getInitialStateValues()[i1][j1] == 1 and not self.finalState.getInitialStateValues()[i2][j2] == 1: return False return True def isValid(self): if self.isFinal(): return self.checkRow() and self.checkColumn() and self.checkAbs() def expand(self): values = [0,1] n = self.initialState.getSize() for i in range(n): l = [] for j in range(n): k= choice(values) l.append(k) self.initialState.getInitialStateValues()[i] = l def isFinal(self): for i in self.initialState.getInitialStateValues(): for j in self.initialState.getInitialStateValues(): if j==-1: return False return True #x=Problem(2) #x.expand() #print(x.initialState.getInitialState()) #print(x.isValid()) class Controller: def __init__(self, problem): self.problem = problem def dfs(self,state): stk = [state] visited = [] while len(stk) > 0: node = stk.pop() if self.problem.isFinal(): print("Solution") print(node) return visited.append(node) if self.problem.isValid(): lst = [] for newState in self.problem.expand(): if newState not in visited: lst.append(newState) stk += lst print("No solution") def gbfs(self, state): pass #p=Problem(3) #c = Controller(p) #print(c.dfs(p.getInitialState())) class UI: def __init__(self, controller): self.controller = controller def printMenu(self): print() print("1 - DFS style") print("2 - Greedy style") print() def start(self): self.printMenu() command = int(input("Enter your command: ")) while command !=0: if command == 1: state = self.controller.problem.initialState self.controller.dfs(state) else: if command == 2: self.controller.gbfs() else: if command == 0: break else: print("No command") self.printMenu() command = int(input("Enter your command: ")) def main(): size=int(input("Enter the size of the table: ")) p=Problem(size) c = Controller(p) ui = UI(c) ui.start() main()
cc7f392faa4286d2d69207a9ad13f22c14b3a1d1
JeniMercy/code
/Nov21task4.py
989
4.21875
4
#Nov-21 #Task4: #Get one string from user #extract middle letter of the string #check whether middle letter is vowel or no a = input("Please enter your string : ") middle_letter = len(a) // 2 print("The middle letter is {}".format(a[middle_letter])) if a[middle_letter] in "aeiou": print(" The middle letter {} is vowel".format(a[middle_letter])) else: print("The middle letter {} is not vowel".format(a[middle_letter])) """OUTPUT: = RESTART: C:/Users/Admin/AppData/Local/Programs/Python/Python310/Nov21task4.py Please enter your string : Niralya The middle letter is a The middle letter a is vowel = RESTART: C:/Users/Admin/AppData/Local/Programs/Python/Python310/Nov21task4.py Please enter your string : 12456 The middle letter is 4 The middle letter 4 is not vowel = RESTART: C:/Users/Admin/AppData/Local/Programs/Python/Python310/Nov21task4.py Please enter your string : aeiou The middle letter is i The middle letter i is vowel"""
e421d829b8413eef8c3e3964b62a5dc0ae6214c3
wwunlp/sner
/sner/classes/display.py
3,703
4.03125
4
"""Display Class""" import time class Display: """Display the progress of a process. Will print a progress bar updated by function calls made off of an instance of this type. Will also estimate time to completion via naieve averaging. Attributes: start_time (float): Seconds since epoch to when progress starts. elapsed_time (float): Seconds since progress started. last_updated (float): Seconds since epoch to when progress was last updated. """ def __init__(self): self.start_time = None self.elapsed_time = None self.last_updated = None def start(self, message=None): """Used to denote the beginning of whatever process you are displaying the progress of. Will mark down the current time for purposes of estimating the time remaining. May display an initial message that you can pass in. Args: message (string): Optional start message. Returns: None Raises: None """ self.start_time = time.time() if message: print(message) def update_progress_bar(self, step, end): """Call at the end of each 'iteration', whatever that happens to mean in the current context. Will update the progress bar and estimated time remaining accordingly. Args: step (float): Current iteration of process. end (float): Final iteration of process. Returns: None Raises: None """ percent = float(step) / float(end) start_time = self.start_time current_time = time.time() if self.last_updated and current_time < self.last_updated + 0.017: return else: self.last_updated = current_time elapsed_time = current_time - start_time self.elapsed_time = elapsed_time estimated_time = (elapsed_time / percent) - elapsed_time hours = int(estimated_time / 3600.0) minutes = int((estimated_time - (hours * 3600)) / 60.0) seconds = int(estimated_time - (minutes * 60) - (hours * 3600)) time_remaining = "{:02d}:{:02d}:{:02d}".format( hours, minutes, seconds ) progress_bar = "{}".format('\u2588' * int(percent * 25.0)) remainder = (percent * 25.0) - len(progress_bar) if remainder >= 0.75: progress_bar += '\u258a' elif remainder >= 0.5: progress_bar += '\u258c' elif remainder >= 0.25: progress_bar += '\u258e' progress_bar += ' ' * (25 - len(progress_bar)) output = " {:05.2f}% |{}| Time Remaining: {}".format( percent * 100.0, progress_bar, time_remaining ) print(' ' * 80, end='\r') print(output, end='\r') def finish(self): """Displays elapsed time of the tracked process. Clears attributes. Call upon the completion of whatever it is you are tracking. Args: None Returns: None Raises: None """ hours = int(self.elapsed_time / 3600.0) minutes = int(self.elapsed_time / 60.0) seconds = int(self.elapsed_time - (minutes * 60) - (hours * 3600)) elapsed_time = "{:02d}:{:02d}:{:02d}".format( hours, minutes, seconds ) print(" 100.00% |{}| Elapsed Time: {} ".format( '\u2588' * 25, elapsed_time )) self.start_time = None self.elapsed_time = None self.last_updated = None
0c7a5dc82373fe315ad10e8903f09f0c3eecbd7c
Srinjana/CC_practice
/DATA STRUCT/ARR n STACK/matrixdiagonal.py
2,183
4.46875
4
# Given a matrix of n*n size, the task is to print its elements in a diagonal pattern. # Input: mat[3][3] = {{1, 2, 3}, # {4, 5, 6}, # {7, 8, 9}} # Output: 1 2 4 7 5 3 6 8 9. # Explanation: Start from 1 # Then from upward to downward diagonally i.e. 2 and 4 # Then from downward to upward diagonally i.e 7, 5, 3 # Then from up to down diagonally i.e 6, 8 # Then down to up i.e. end at 9. # Create variables i = 0, j = 0 to store the current indices of row and column # Run a loop from 0 to n*n, where n is side of the matrix. # Use a flag isUp to decide whether the direction is upwards or downwards. Set isUp = true initially the direction is going upward. # If isUp = 1 then start printing elements by incrementing column index and decrementing the row index. # Similarly if isUp = 0, then decrement the column index and increment the row index. # Move to the next column or row(next starting row and column # Do this till all the elements get traversed. MAX = 100 def DiagonalMatrixTraversal(mat, n): i, j, k = 0, 0, 0 isUp = True while (k < n*n): if isUp: # If isUp = True then traverse from downwards to upwards while (i >= 0 and j < n): print(str(mat[i][j]), end=" ") k += 1 j += 1 i -= 1 # Set i and j according to direction if (i < 0 and j <= n - 1): i = 0 if (j == n): i = i + 2 j -= 1 else: # If isUp = False then traverse from upwards to downwards while (j >= 0 and i < n): print(str(mat[i][j]), end=" ") k += 1 j += 1 i -= 1 # Set i and j according to direction if (j < 0 and i <= n - 1): j = 0 if (i == n): j = j + 2 i -= 1 #reset flag to change direction isUp = not isUp # Driver program if __name__ == "__main__": mat = [[1, 2, 3],[4, 5, 6],[7, 8, 9]] n = len(mat[0]) DiagonalMatrixTraversal(mat, n)
5ccbd7628bf9cc9026fc9f067c73e35c8b901320
souravde008/Data-Manager
/datamanager.py
5,213
3.75
4
def showAll(): #print("showAll") f = open("db.txt", "r") print(f.read()) def showByID(): #print("showByID") ID = input("> ID?") while not valid("db.txt",ID): print("invalid ID") ID = input("> ID?") f = open("db.txt", "r") lines = f.readlines() for line in lines: if ID in line: print(line) break def showByName(): #print("showByName") name = input("> Name?") while not valid("db.txt",name): print("invalid Name") name = input("> Name?") f = open("db.txt", "r") lines = f.readlines() for line in lines: if name in line: print(line) break def update(): #print("update") ID = input("> ID?") while not valid("db.txt",ID): print("invalid ID") ID = input("> ID?") print("*****************************") print("*** UPDATE MENU ***") print("* 1 Name 3 In Stock *") print("* 2 Price 4 Exit *") print("*****************************") ch = int(input("> ")) f = open("db.txt", "r") lines = f.readlines() c = False while(ch != 4 ): if ch == 1: c =True new_name = input("> Name?") for line in lines: if ID in line: updated = line.replace(line.split()[0], new_name) #print(updated) f.close() deleteLine("db.txt",ID) break f = open("db.txt", "a") f.write("{}".format(updated)) f.close() print("> Done") break elif ch == 2: c = True new_price = float(input("> Price?")) for line in lines: if ID in line: updated = line.replace(line.split()[2], str(new_price)) #print(updated) f.close() deleteLine("db.txt",ID) break f = open("db.txt", "a") f.write("{}".format(updated)) f.close() print("> Done") break elif ch == 3: c =True new_stock = int(input(">In Stock?")) for line in lines: if ID in line: updated = line.replace(line.split()[3], str(new_stock)) #print(updated) #print(line) f.close() deleteLine("db.txt",ID) break f = open("db.txt", "a") f.write("{}".format(updated)) f.close() print("> Done") break else: if not c: print("> Update aborted") def delete(): #print("delete") ID = input("> ID?") while not valid("db.txt",ID): print("invalid ID") ID = input("> ID?") deleteLine("db.txt",ID) print("> Deleted") def add(): #print("add") name = input("> Name?") while(valid("db.txt",name)): print("> ERROR Name EXISTS") name = input("Name?") ID = input("> ID?") print(len(ID)) while(valid("db.txt",ID)): print("> ERROR ID EXISTS") ID = input("ID?") print("> ID MUST BE 10 DIGIT") price = float(input("> PRICE?")) stock = int(input("> ADD STOCK?")) f = open("db.txt", "a") f.write("{} {} {} {} \n".format(name,ID,str(price),str(stock))) f.close() print('OK') def valid(fname,txt): with open(fname) as f: return any(txt in line for line in f) def deleteLine(fname, ID): #print("dataline") f = open(fname) output = [] for line in f: if not ID in line: output.append(line) f.close() f = open(fname, 'w') f.writelines(output) f.close() #print("deletion done") if __name__ == "__main__": print("*****************************") print("***WELCOME TO DATAMANAGER ***") print("*** MENU ***") print("* 1 List All 4 Delete ID *") print("* 2 List ID 5 Update ID *") print("* 3 List Name 6 Add *") print("* 7 Exit *") print("*****************************") ch = int(input("> ")) while(ch != 7 ): if ch == 1: showAll() ch = int(input("> ")) elif ch == 2: showByID() ch = int(input("> ")) elif ch == 3: showByName() ch = int(input("> ")) elif ch == 4: delete() ch = int(input("> ")) elif ch == 5: update() ch = int(input("> ")) elif ch == 6: add() ch = int(input("> ")) else: print("Sorry!") ch = int(input("> ")) else: print("bye")
5262bdd3bd00fb8b2e8e1b4ba58fe2be17558e86
hkh9715/pythonworkspace
/py4e/loop_input_biggest_smallest.py
413
3.953125
4
bb = None ss = None while True: num = input("Enter a number: ") if num == "done" : break try: inum = float(num) if bb is None: bb=inum elif inum>bb: bb=inum if ss is None: ss=inum elif inum<ss: ss=inum except: print('invalid input') continue print("Maximum is ", bb) print("Minimum is ", ss)
25ced57817c656ae3c40493df114cc13f1e2adfa
nivethida/PythonLearning
/Day4/practice.py
6,720
3.75
4
# -*- coding: utf-8 -*- thesum = 0 for i in range(2,25): print(i) if i% 5 == 0: break thesum+=i print(thesum) for i in "35": print(i) def func(*args): n = sum(args) while abs(n) > 9: print(n, "n1") p = 1 for i in str(n): print(i, "i", n ) p*=int(i) print(p, "p") n = p print(n, "N") return n print(func(15,20)) import pandas as pd # list of strings lst = ['Geeks', 'For', 'Geeks', 'is', 'portal', 'for', 'Geeks'] # Calling DataFrame to make the list a dataframe df = pd.DataFrame(lst) print(df) data = [[1,2,3,4,5],[6,7,8,9,10]] df2 = pd.DataFrame(data) print(df2) import pandas as pd data1 = {'Name':['Tom', 'nick', 'krish', 'jack'], 'Age':[20, 21, 19, 18]} # the column names are already included. df4 = pd.DataFrame(data1) print(df4) import pandas as pd data3 = {'Name':['A', 'B', 'C', 'D'], 'Age':[27, 24, 22, 32], 'Address':['W', 'A', 'S', 'D'], 'Qualification':['Msc', 'MA', 'MCA', 'Phd']} df5 = pd.DataFrame(data3) print(df5) # print the full dataset # select two columns using column names print(df5[['Name', 'Qualification']]) print(df5['name'])# this is a series if you check print(type(df['name'])) print(df5[['name']]) # this is a dataframe, again, you can check the data type name1=df5['Name'] name2=df5[['Name']] print(name1[0]) # this is atomic value "A" print(name2.iloc[2]) # this is a series # but if you want to get two columns you need print(df[['Name', 'Qualification']]). x = 1 while x < 5: print(x) x = x + 1 x = 1 while True: print(x) x = x + 1 if x >= 5: break for i in range(1,5): print(i) print("cheers!") x = [1,3,4,5] for i in x: if i > 2: print(i) import pandas as pd data23 ={'Name':['Tom','nick','krish','jack'],'Age':[20, 21, 19, 18]} df45=pd.DataFrame(data23) print(df45) print(df45.iloc[:,0]) print(df45.iloc[0,:]) df13=df45.loc[df45['Age']<20,:] print(df13) for letter in 'Python': # First Example if letter == 'h': continue print('Current Letter :', letter) var = 10 while var > 0: var = var -1 if var == 5: continue print('Current variable value :', var) print("Good bye!") x=['1st entry','2nd entry'] for i,entry in enumerate(x): print(i) # the index of iteration we are currently at print(entry) # the iterator f=[x for x in range(1,10)] print(f) for x in range(1,4): print(x) g=[(x,y) for x in range(1,4) for y in range(5,7)] print(g) r=[(x,y) for x in range(1,4) for y in range(x+1,x+3)] print(r) h=[(y,x) for y in range(5,7) for x in range(1,4)] print(h) # for each y, populates all possible x i=[{'key {}'.format(y):x} for x in range(4,6) for y in range(1,3)] print(i) x=[1,2,3] y=[4,5,6] z=[x/y for x,y in zip(x,y)] print(z) tuple_list=[(1,2),(3,4),(5,6)] j=[(x**2+1,y) for (x,y) in tuple_list] print(j) dictionary={'color':'yellow','num_core':8,'ram':16} print(dictionary) for i in dictionary: print('the',i,'is',dictionary[i]) word='success' dictionary1={} # define an empty dictionary, get ready for entries. for c in word: if c not in dictionary1: # if the dictionary has not pick up the key dictionary1[c]=1 # create the key and set the value to 1 because this is the first occurrence else: # if the dictionary has already picked up the key dictionary1[c]=dictionary1[c]+ 1 # add 1 to the current value due to another occurrence. print(dictionary1) d=dict() for x in range(1,16): d[x]=x**2 print(d) my_dict = {'data1':100,'data2':-54,'data3':247} result=1 for value in my_dict.values(): result *= value print(result) import numpy as np rand5=np.random.randint(2,10,size=(2,4)) print(rand5) x=[54,12,32,41,33] y=[1,2,3,4] for i in zip(x,y): print(i) import pandas as pd data = {'Name':['A', 'B', 'C', 'D'], 'Age':[27, 24, 22, 32], 'Address':['W', 'A', 'S', 'D'], 'Qualification':['Msc', 'MA', 'MCA', 'Phd']} df = pd.DataFrame(data) print(df) # print the full dataset # select two columns using column names name1=df['Name'] name2=df[['Name']] print(name1,'series') print(name2,'df') print(name1[0]) # this is atomic value "A" print(name2.iloc[2]) from datetime import datetime now = datetime.now() year = now.strftime("%Y") print("year:", year) month = now.strftime("%m") print("month:", month) month = now.strftime("%B") print("month:", month) time = now.strftime("%H:%M:%S") print("time:", time) time = now.strftime("%I:%M:%S %a") print("time:", time) import random print(random.uniform(5, 100)) import numpy as np print(np.random.randn(5)) print(np.random.randn(5,2)) x=[54,12,32,41,33] print(x[1:3]) x = 5 y = 1 p = y/x if y>=x else "lower vaue" print(p) for i in range(3): print(i) def charcount(word): dict = {} for i in word: dict[i] = dict.get(i,0)+1 return dict print(charcount("error")) str1 = "asfgthfs" str2 = "12345677" dict1 = dict(zip(str1,str2)) print(dict1) dict2 = {} print(type(dict2), len(dict2)) import statistics x=[1,2,3,4,5,6,7,8] for i in x[:3]: print(i) for i in x[-3:]: print(i) print(statistics.mean(x[:3])) print(statistics.mean(x[-2:])) list1 = [1,2,3,4,5,6,7,8] result = ["Even" if x%2==0 else "Odd" for x in range(1,10)] print(result) ar1 = [1,5,10,20,40,80] ar2 = [6,7,80,100] ar3 = [3,4,15,20,30,70,80,120] def function(*thelist): outputset = set(thelist[0]) for i in thelist: outputset = outputset & set(i) print(outputset) return outputset print(function(ar1,ar2,ar3)) def function1(list1, N): final_list = [] for i in range(0,N): max1 = 0 for j in range(len(list1)): print(len(list1)) if list1[j] > max1: max1 = list1[j]; list1.remove(max1); final_list.append(max1) print(final_list) print(function1([1,2,3,4,5,6],3)) var = 9 while var%2==1 and var>=0: var = var-2 if var == 4: continue print(var) x=[56,32,21,8,56,21,35] print(x[:2]) for index,value in enumerate(x): if value in x[:index]: print(x[:index]) print(value,index) Keys=['length','width','depth','weight','reliability'] Values=[6,7,8,9,'good'] dict4 = {x:y for x,y in zip(Keys,Values)} print(dict4) print(dict4.get('width', 'feature not found')) unique={} d1 = {'a': 100, 'b': 200, 'c':300} d2 = {'a': 300, 'b': 200, 'd':400} unique.update(d1) L1 = list() L1.append([1, [2, 3], 4]) L1.extend([7, 8, 9]) print(L1) print(L1[0][1][1] + L1[2]) l=[1,2,3,4] print(l.index(1))
e2cab6e0113a866ae4f5a2835d4c40878a33ec1b
Ibramicheal/Onemonth
/Onemonth/conditionals.py
252
4.15625
4
answer = input("Could you like to hear a joke? ") if answer == "Yes" or answer == "yes": print("Life is a joke all the time..!!!") elif answer == "No" or answer == "no": print("No worries") else: print("please make a choice of either Yes or No")
645338d527776260db517cde9bc6b69c5d5d589b
alexey-kynin/gb
/python/les_1/1_3.py
139
3.59375
4
a = int(input("Введите число n: ")) s = (a + int(str(a) + str(a)) + int(str(a) + str(a) + str(a))) print(f"n + nn + nnn = {s}")
d96f21399b72404204d41ba18e5f99fc75f95f41
SungLinHsieh/LeetCode
/Python/019.Remove.Nth.Node.From.End.of.List.py
594
3.765625
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def removeNthFromEnd(self, head, n): """ :type head: ListNode :type n: int :rtype: ListNode """ pre = ListNode(None) pre.next = head front = pre back = pre for i in range(n): front = front.next while front.next != None: front = front.next back = back.next back.next = back.next.next return pre.next
6b6a92c5ca3ce614673d2646eb8b9c9be66292bb
kumargaur/coding-challenges
/Hackerrank/Algorithms/Warmup/09. Birthday Cake Candles/birthday-cake-candles.py
361
3.671875
4
#!/bin/python3 import sys def candles_blown(n, heights): max_height = 0 count = 0 for h in heights: if h > max_height: max_height = h count = 1 elif h == max_height: count += 1 return count n = int(input().strip()) heights = [int(height_temp) for height_temp in input().strip().split(' ')] print(candles_blown(n, heights))
6c845f215de7668d75d3282d8840fe91918a240c
VladaLukovskaya/Python
/lesson20_function_scope/thrown_stone.py
513
3.9375
4
dt = 0.05 # Шаг по времени ax, ay = 0, -9.81 # Ускорения вдоль осей x, y = 0, 0 # Начальные координаты vx, vy = 10, 10 # Начальные скорости while y >= 0: # Обновляем скорости vx += ax * dt vy += ay * dt # Обновляем координаты x += vx * dt y += vy * dt # Точки траектории печатаем округленными до 3 знака print(round(x, 3), round(y, 3))
9f316ed30cf16abf49593700466a75e8e48060ad
ron71/PythonLearning
/Input_Output(I_O)/FileExercise_1.py
426
4.125
4
# Exercise 16.1 # Write a program that reads the contents of the file “pc_woodchuck.txt,” # splits it into words (where everything that is not a letter is considered a word boundary), # and case-insensitively builds a dictionary that stores for every word how often it occurs in # the text. Then print all the words with their quantities in alphabetical order. print(bytes([255])) x = b'hello\x20world' print(x.decode())
7676d81220efadf34c34d65743768d098a3194df
alexetsnyder/OuroborosPython
/Misc/password_gen.py
810
3.84375
4
#python import sys import random import string def gen_password(sym1, sym2): return sym1 + gen_random_number(3) + sym2 + gen_random_number(3) + gen_random_word(4) def gen_random_number(l): number = '' for i in range(l): number += random.choice(string.digits) return number def gen_random_word(l): word = '' capi = random.choice([0, 1, 2, 3]) for i in range(l): if capi == i: word += random.choice(string.ascii_uppercase) else: word += random.choice(string.ascii_lowercase) return word if __name__ == '__main__': #for i in range(len(sys.argv)): # print(i, ') ', sys.argv[i]) if len(sys.argv) != 3: print('Must provide exactly two command line arguments') exit(1) print(gen_password(sys.argv[1], sys.argv[2])) #syml = symbols.split() #print(gen_password(syml[0], syml[1]))
83d42f4ff5352322f2dcb5aba9f3fb66d14c2926
langlang0/data_structure
/力扣/汉明距离461,477.py
726
3.71875
4
from typing import List class Solution: def hammingDistance(self, x: int, y: int) -> int: a = x ^ y count = 0 while a != 0: a = a & (a - 1) count += 1 return count def totalHammingDistance(self, nums: List[int]) -> int: sum = 0 for i in range(len(nums) - 1): for j in range(i + 1, len(nums)): a = nums[i] ^ nums[j] count = 0 while a != 0: a = a & (a - 1) count += 1 sum += count return sum if __name__ == '__main__': s = Solution() print(s.hammingDistance(1, 4)) print(s.totalHammingDistance([4, 14, 2]))
77d5a57d0970b9db1b1f6bd370625f4c19feccd7
monty123456789/space
/ship.py
2,126
3.59375
4
import numpy as np import math import utils from numpy import linalg as LA import pygame class Ship: def __init__(self, x, y, surface): # Position of the tip of the ship self.pos = np.array([x, y]) # Rotation angle of the ship relative to the tip of the ship self.angle = np.zeros(2) # Additional properties goes here: # Leave the rest of these properties self.surface = surface self.radius = 20 self.color = (255, 0, 0) self.collided = False # Update properties of the ship def update(self, mouse_pos, asteroids, game_status): # Action required! desired = mouse_pos - self.pos #LA.norm(desired) #np.true_divide(desired, 300) velocity = desired/300 velocity *= 10 self.pos += velocity # Set position of ship based on given parameter #self.pos = self.pos # Determine rotation angle of ship to point at cursor angx = mouse_pos[0] - self.pos[0] angy = mouse_pos[1] - self.pos[1] self.angle = math.atan2(angx, angy) #self.angle *= 180/math.pi print(self.angle) # Leave the rest of the code # Check for collision if game_status == "started": self.collision(asteroids, game_status) # Draw the ship onto the canvas def draw(self): p1 = np.array(utils.rotate((0, 0), self.angle)) + self.pos p2 = np.array(utils.rotate((40, 20), self.angle)) + self.pos p3 = np.array(utils.rotate((30, 0), self.angle)) + self.pos p4 = np.array(utils.rotate((40, -20), self.angle)) + self.pos pygame.draw.polygon( self.surface, self.color, [p1, p2, p3, p4] ) # Detect whether ship has collided with an asteroid def collision(self, asteroids, game_status): for asteroid in asteroids: if np.linalg.norm(asteroid.pos - self.pos) < (asteroid.radius + self.radius): self.color = (255, 255, 0) self.collided = True break
e01ca80a143b2ba844ca2bef4605bc1a65de1a7c
sukhvir786/Python-Day-6-Lists
/list8.py
279
3.703125
4
#list replication L = ['VIOLET'] L = L * 3 print(L) # Prints ['VIOLET', 'VIOLET', 'VIOLET'] print(len(L)) if 'VIOLET' in L: print('The color is Present in List') for i in L: print(i) L1 = [2,3,1,4,5,6] for i in L1: print(i*2,end=' ')
82326cde56e93f2f0ad25f2aa669ea7f09de5cb0
eltrompetero/kalman_filter
/kalman.py
8,367
3.84375
4
# An implementation of the Kalman filter. # Written by Edward Lee edl56@cornell.edu import numpy as np from numpy.linalg import inv class Kalman(object): def __init__(self,x0,covx0,z,covz,A,b,covupdate,M,dt=1): """ Kalman filter is an example of a Gaussian process where the future predicted probability distribution an application of Bayes' rule where the prior and likelihoods are just Gaussian on a Markov chain. 2016-12-23 Params: ------- x0 (ndarray) Initial estimate of hidden state of system. covx0 (ndarray) Covariance of x0. z (ndarray) n_dim x n_samples. Observations of observable states. covz (ndarray) (n_dim,n_dim) Covariance of z. A (ndarray) Transition update. x_{t+1}=A*x_t+b b (ndarray) (n_dim,1) or (n_dim,n_samples). Constant offset in transition update. covupdate (ndarray) Covariance of error in update step. M (ndarray) Matrix to convert from hidden to observable state. z=M*x. dt (float=1) Time scale for observations. This is important in unscented filter where we have to make local derivative estimates. """ self.x0=x0 self.covx0=covx0 self.z=z self.covz=covz self.A=A if b.ndim==1 or b.shape[1]==1: self.b=np.tile(b,(1,z.shape[1])) else: self.b=b self.covupdate=covupdate self.M=M self.L=inv(covupdate) self.Q=inv(covz) self.dt=dt self.ndim=len(x0) # Should make sure that Qij=0 and Qii=1 for unobserved states. def filter(self,delay=0): """ Standard Kalman filter. If delay>0, predict into the future. Store list of expected mu0 in correctedmux. Update estimate of state in the past using the correction step in the KF and use that to predict delay into the future. 2016-12-25 Params: ------- delay (int=0) Values: ------- predictedx CovPred correctedx CovCorrected """ T=self.z.shape[1] if delay==0: correctedmux=np.zeros((len(self.x0),T)) # result of prediction once accounting for obs predictedmux=np.zeros((self.ndim,T+1)) CovPred=np.zeros((T+1,self.ndim,self.ndim)) # cov of error on predictions CovCorrected=np.zeros((T,self.ndim,self.ndim)) # cov of error on corrections # Calculate KF corrected estimate of state with data. CovPred[0]=self.covx0 predictedmux[:,0]=self.x0 iCovPred=inv(CovPred[0]) for i in xrange(T): # Calculate corrections on predicted future state given observation. R=self.M.T.dot(self.Q.dot(self.M.T))+iCovPred # inv cov of corrected state estimate correctedmux[:,i]=(inv(R).dot(iCovPred).dot(predictedmux[:,i]) + inv(R).dot(self.M.T).dot(self.Q).dot(self.z[:,i])) # corrected state estimate # Calculate prior on next state. predictedmux[:,i+1]=self.A.dot(correctedmux[:,i]) + self.b[:,i] iCovPred=(inv(self.A.T).dot(inv( inv(self.A.T.dot(self.L).dot(self.A))+inv(R) )).dot(inv(self.A))) CovCorrected[i]=inv(R) CovPred[i+1]=inv(iCovPred) else: correctedmux=np.zeros((self.ndim,T+delay)) # result of prediction once accounting for obs correctedmux[:,:delay]=np.tile(self.x0[:,None],(1,delay)) predictedmux=np.zeros((self.ndim,T+delay+1)) # result of prediction once accounting for obs predictedmux[:,:delay]=np.tile(self.x0[:,None],(1,delay)) CovPred=np.zeros((T+1,self.ndim,self.ndim)) CovCorrected=np.zeros((T,self.ndim,self.ndim)) # Calculate KF corrected estimate of state with data. CovPred[0]=self.covx0 iCovPred=inv(CovPred[0]) mux=self.x0 for i in xrange(T): R=self.M.T.dot(self.Q.dot(self.M.T))+iCovPred # cov of state estimate correctedmux[:,i]=(inv(R).dot(iCovPred).dot(predictedmux[:,i]) + inv(R).dot(self.M.T).dot(self.Q).dot(self.z[:,i])) # corrected state estimate # Calculate prior on next state. predictedmux[:,i+delay+1]=self.A.dot(correctedmux[:,i])+self.b[:,i] iCovPred=(inv(self.A.T).dot(inv( inv(self.A.T.dot(self.L).dot(self.A))+inv(R) )).dot(inv(self.A))) CovPred[i+1]=inv(iCovPred) return predictedmux,CovPred,correctedmux,CovCorrected def extended_filter(self,delay=0): """ Kalman filter using local Jacobian approximation to model nonlinear dynamics. 2016-12-26 Params: ------- delay (int=0) Values: ------- predictedmux correctedmux """ if delay==0: T=self.z.shape[1] correctedmux=np.zeros((self.ndim,T)) # result of prediction once accounting for obs predictedmux=np.zeros((self.ndim,T+1)) CovPred=np.zeros((T+1,self.ndim,self.ndim)) CovCorrect=np.zeros((T,self.ndim,self.ndim)) # Calculate KF corrected estimate of state with data. CovPred[0]=self.covx0 predictedmux[:,0]=self.x0 for i in xrange(T): iCovPred=inv(CovPred[i]) R=self.M.T.dot(self.Q.dot(self.M.T))+iCovPred # inverse cov of state estimate mux=(inv(R).dot(iCovPred).dot(predictedmux[:,i]) + inv(R).dot(self.M.T).dot(self.Q).dot(self.z[:,i])) # corrected state estimate correctedmux[:,i]=mux[:] # Calculate prior on next state. spline=self.der(correctedmux[:,i-3:i+1])*self.dt A=self.A predictedmux[:,i+1]=A.dot(mux) + self.b[:,i] + spline # Now must account for extra uncertainty hidden in spline estimate. if type(spline)==float: L=self.L else: L=inv( inv(self.L)+(inv(R)+CovPred[i-3])/4 ) iCovPred=(inv(A.T).dot(inv( inv(A.T.dot(L).dot(A))+inv(R) )).dot(inv(A))) try: CovPred[i+1]=inv(iCovPred) except np.linalg.LinAlgError: print A print iCovPred else: T=self.z.shape[1] correctedmux=np.zeros((len(self.x0),T+delay)) # result of prediction once accounting for obs correctedmux[:,:delay]=np.tile(self.x0[:,None],(1,delay)) predictedmux=np.zeros((len(self.x0),T+delay+1)) # result of prediction once accounting for obs predictedmux[:,:delay]=np.tile(self.x0[:,None],(1,delay)) CovPred=np.zeros((T+1,self.ndim,self.ndim)) CovCorrect=np.zeros((T+delay,self.ndim,self.ndim)) # Calculate KF corrected estimate of state with data. CovPred[0]=self.covx0 iCovPred=inv(CovPred[0]) predictedmux[:,0]=self.x0 for i in xrange(T): R=self.M.T.dot(self.Q.dot(self.M.T))+iCovPred # cov of state estimate mux=(inv(R).dot(iCovPred).dot(predictedmux[:,i]) + inv(R).dot(self.M.T).dot(self.Q).dot(self.z[:,i])) # corrected state estimate correctedmux[:,i]=mux[:] # Calculate prior on next state. predictedmux[:,i+delay+1]=self.A.dot(mux)+self.b[:,i] iCovPred=(inv(self.A.T).dot(inv( inv(self.A.T.dot(self.L).dot(self.A))+inv(R) )).dot(inv(self.A))) CovPred[i+1]=inv(iCovPred) CovCorrect[i]=inv(R) return predictedmux,CovPred,correctedmux,CovCorrect def der(self,x,n=1): if x.shape[1]<3: return 0. return [(x[:,-1]-x[:,-3])/(2*self.dt), ][n-1]
e311ecf09764942c0f8015ede66c17e74eb30399
ParkChangJin-coder/pythonProject
/break_continue_Quiz.py
1,682
3.71875
4
import os import random # i = 1 # sum = 0 # while i <= 1000: # if i % 3 !=0 or (i % 3 == 0 and i % 5 == 0): # sum += i # i+=1 # print("sum = ",sum) # Menu = {"콜라":1200, "사이다":1200, "조지아":1000, "컨피던스":600} # Money = int(input("돈을 넣으세요 : ")) # while True: # os.system("cls") # print("잔돈 {0}".format(Money)) # print("==========자판기==========") # j = 0 # keyList = list(Menu.keys()) # while j < len(keyList): # print("{0}\t:\t{1}".format(keyList[j],Menu[keyList[j]])) # j += 1 # print("> 종료") # select = input("음료를 선택하세요 : ") # if select in keyList: # if Money - Menu[select] < 0: # print("잔액이 부족합니다") # break # Money -= Menu[select] # elif select == "종료": # print("프로그램을 종료합니다.") # else: # print("잘못된 입력입니다.") # os.system("pause") # point = 0 # wordList = ["itbank","hello","dog", "boy"] # MaxPoint = len(wordList) # #random.randrange(4) -> 0 부터 3까지 랜덤수 # #random.randrange(2,5) -> 2 이상 5 미만 # while wordList: # index = random.randrange(len(wordList)) # print(wordList[index][0]) # Answer = input("단어를 입력") # if Answer == wordList[index]: # print("정답") # point += 1 # else: # print("오답입니다.") # del wordList[index] # #wordlist.remove(Answer) # if point == MaxPoint: # print("모두 맞췄습니다") # else: # print("{0}개 만큼 맞췄습니다.".format(point))
ff8b6db6798a7dd3436fbeba3278279817b8bdbe
yeshsurya/ImageProcessing
/Image_Transformations/illuminate_color_range.py
710
3.84375
4
import cv2 import numpy as np # Load the image image = cv2.imread('input_image.jpg') # Convert the image to the HSV color space hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) # Define the lower and upper bounds of the color range you want to illuminate lower_range = np.array([hue_min, saturation_min, value_min], dtype=np.uint8) upper_range = np.array([hue_max, saturation_max, value_max], dtype=np.uint8) # Create a binary mask based on the color range mask = cv2.inRange(hsv, lower_range, upper_range) # Apply the mask to the original image result = cv2.bitwise_and(image, image, mask=mask) # Display the result cv2.imshow('Result', result) cv2.waitKey(0) cv2.destroyAllWindows()
c1bfc0911afdf9790883c0d001f23a2395352da2
kingcunha23/python-learning
/fatorial.py
124
4.09375
4
# -*- coding: utf-8 -*- n = int(input('Digite o valor de n: ')) x = 0 while x < n : print(2 * x +1) x = x + 1
ba94983ed575d9e1ac63cd0a79f745207a931846
bgoonz/UsefulResourceRepo2.0
/_RESOURCES/my-gists/__CONTAINER/89502bf395/89502bf3959da/word_break.py
5,685
3.875
4
""" Word Break (Find the original words) Given a dictionary of words and a string made up of those words (no spaces), return the original sentence in a list. If there is more than one possible reconstruction, return solution with less words. If there is no possible reconstruction, then return null. Input: sentence = 'thequickbrownfox', words = ['quick', 'brown', 'the', 'fox'] Output: ['the', 'quick', 'brown', 'fox'] Input: sentence = 'bedbathandbeyond', words = ['bed', 'bath', 'bedbath', 'and', 'beyond'] Output: ['bedbath', 'and', 'beyond'] (['bed', 'bath', 'and', 'beyond] has more words) ========================================= Optimized dynamic programming solution (more simpler solutions can be found here https://www.geeksforgeeks.org/word-break-problem-dp-32/) Time Complexity: O(N*M) , N = number of chars in the sentence, M = max word length Space Complexity: O(N+W) , W = number of words Bonus solution: Backtracking, iterate the sentence construct a substring and check if that substring exist in the set of words. If the end is reached but the last word doesn't exist in the words, go back 1 word from the result (backtracking). * But this solution doesn't give the result with the smallest number of words (gives the first found result) Time Complexity: O(?) , (worst case, about O(W! * N), for example sentence='aaaaaac', words=['a','aa','aaa','aaaa','aaaaa', 'aaaaaa']) Space Complexity: O(W) """ ############ # Solution # ############ import math def word_break(sentence, words): n, w = len(sentence), len(words) if (n == 0) or (w == 0): return None dw = [-1 for i in range(n + 1)] dp = [math.inf for i in range(n + 1)] dp[0] = 0 matched_indices = [0] dic = {} # save all words in dictionary for faster searching max_word = 0 # length of the max word for i in range(w): dic[words[i]] = i max_word = max(max_word, len(words[i])) for i in range(1, n + 1): matched = False # start from the back of the matched_indices list (from the bigger numbers) for j in range(len(matched_indices) - 1, -1, -1): matched_index = matched_indices[j] # break this loop if the subsentence created with this matched index is bigger than the biggest word if matched_index < i - max_word: break subsentence = sentence[matched_index:i] # save this result if this subsentence exist in the words and number of words that forms sentence is smaller if (subsentence in dic) and (dp[matched_index] + 1 < dp[i]): dp[i] = dp[matched_index] + 1 dw[i] = dic[subsentence] matched = True if matched: matched_indices.append(i) # the sentence can't be composed from the given words if dp[n] == math.inf: return None # find the words that compose this sentence result = ["" for i in range(dp[n])] i = n j = dp[n] - 1 while i > 0: result[j] = words[dw[i]] i -= len(words[dw[i]]) j -= 1 return result ######################### # Solution Backtracking # ######################### from collections import deque def word_break_backtracking(sentence, words): all_words = set() # create a set from all words for i in range(len(words)): all_words.add(words[i]) n = len(sentence) i = 0 subsentence = "" result = deque() # go letter by letter and save the new letter in subsentence while (i < n) or (len(subsentence) != 0): # if there are no left letters in the sentence, then this combination is not valid # remove the last word from the results and continue from that word if i == n: i -= len(subsentence) # if there are no words in the result, then this string is not composed only from the given words if len(result) == 0: return None subsentence = result[-1] result.pop() # add the new letter into subsentence and remove it from the sentence subsentence += sentence[i] i += 1 # check if the new word exist in the set if subsentence in all_words: result.append(subsentence) subsentence = "" return list(result) ########### # Testing # ########### # Test 1 # Correct result => ['the', 'quick', 'brown', 'fox'] print(word_break("thequickbrownfox", ["quick", "brown", "the", "fox"])) # Test 2 # Correct result => ['bedbath', 'and', 'beyond'] print(word_break("bedbathandbeyond", ["bed", "bath", "bedbath", "and", "beyond"])) # Test 3 # Correct result => ['bedbath', 'andbeyond'] print( word_break( "bedbathandbeyond", ["bed", "and", "bath", "bedbath", "bathand", "beyond", "andbeyond"], ) ) # Test 4 # Correct result => None ('beyo' doesn't exist) print(word_break("bedbathandbeyo", ["bed", "bath", "bedbath", "bathand", "beyond"])) # Test 5 # Correct result => ['314', '15926535897', '9323', '8462643383279'] print( word_break( "3141592653589793238462643383279", ["314", "49", "9001", "15926535897", "14", "9323", "8462643383279", "4", "793"], ) ) # Test 6 # Correct result => ['i', 'like', 'like', 'i', 'mango', 'i', 'i', 'i'] print( word_break( "ilikelikeimangoiii", [ "mobile", "samsung", "sam", "sung", "man", "mango", "icecream", "and", "go", "i", "like", "ice", "cream", ], ) )
014f4e2260e73a9490b96dd68103b285e40ea815
DizzyYunxuan/Leetcode_answers
/210.course-schedule-ii.py
1,003
3.5
4
# # @lc app=leetcode id=210 lang=python3 # # [210] Course Schedule II # class Solution: def findOrder(self, numCourses: int, prerequisites): # topo sort stack = dict.fromkeys(range(numCourses), []) for cur, pre in prerequisites: stack[cur] = stack.get(cur, []) + [pre] toposort = [] while stack: flag = False for idx in stack: if not stack[idx]: flag = True break if not flag: return [] toposort.append(idx) stack.pop(idx) for pres in stack: if idx in stack[pres]: stack[pres].remove(idx) return toposort ✔ Accepted ✔ 44/44 cases passed (380 ms) ✔ Your runtime beats 6.38 % of python3 submissions ✔ Your memory usage beats 78.57 % of python3 submissions (14.8 MB) # if __name__ == "__main__": # rs = Solution().findOrder(2, [[0,1],[1,0]])
361c2f5994707dc91bfd81697b8ee19564de2994
GauthamAjayKannan/guvi
/mid*.py
117
3.828125
4
#mid* s=list(input()) if len(s)%2: s[len(s)//2]="*" else: s[(len(s)//2)-1]="*" s[len(s)//2]="*" print("".join(s))
b6f3f5e0c7fa0319635116bf2c37f85ae2f1674b
ayanakshi/journaldev
/Python-3/argparse/argparse_example.py
164
3.609375
4
import argparse parser = argparse.ArgumentParser() parser.add_argument('number', help="Enter number to triple it.") args = parser.parse_args() print(args.number*3)
dbce1f94ba067749c8d06c9893484eda869e0cfb
untalinfo/holbertonschool-web_back_end
/0x00-python_variable_annotations/8-make_multiplier.py
423
3.828125
4
#!/usr/bin/env python3 """ Complex types - functions """ from typing import Callable def make_multiplier(multiplier: float) -> Callable[[float], float]: """takes a float multiplier as argument and returns a function that multiplies a float by multiplier. Args: multiplier (float): number float Returns: Callable[[float], float]: [description] """ return lambda x: x * multiplier
246a0a9f443e10e8d01461edb2f1c50eeaf24244
smspillaz/algorithms
/python/server.py
928
3.59375
4
class ServerTime: def __init__(self): self.jobs = [] self.used = 0 def serverFarm(jobs, servers): serverArray = [ServerTime() for i in range(0, servers)] # Greedy approach - re-arrange jobs into # a list of index/tuple and then sort by # the time taken for each job, then assign # to each server the next time it will be # available jobsArray = reversed(sorted([(i, j) for i, j in enumerate(jobs)], key=j)) for job_index, job_time in jobsArray: # Find the server with the shortest time best_time = 100 * 1000 serverToUse = None for server in serverArray: if server.used < best_time: serverToUse = server # Allocate the job to that server serverToUse.jobs.append(job_index) serverToUse.used += job_time return [s.jobs for s in serverArray]