blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
5c6326a007fd51f2f6fff8887d81dd04c8e1dffc
shuklak13/Python-Notes
/Types_and_Collections/collections.py
1,328
3.78125
4
from collections import * # Deque: O(1) insertion and removal on both ends d = deque() d.append(1); d.pop() # Stack d.append(1); d.popleft() # Queue d.rotate(2) # equivalent to d.appendLeft(d.pop()) twice # Counter: a dictionary optimized for counting # functions: "most_common", "update" (add), and "subtract" c = Counter('aaaaaaaaabbbbbbbcc'); c.most_common(3) # [('a', 9), ('b', 7), ('c', 2)] d = Counter({'a': 1, 'b': 2, 'c': 3}) c.subtract(d); c # Counter({'a': 8, 'b': 5, 'c': -1}) c.update(d); c # Counter({'a': 9, 'b': 7, 'c': 2}) # Default Dict: automatically does dict.setdefault() for you # choose the default data type (list, int, set, dict, etc.) at creation time d = defaultdict(list) for k, v in [('yellow', 1), ('blue', 2), ('red', 1), ('blue', 4)]: d[k].append(v) d = {} for k, v in [('yellow', 1), ('blue', 2), ('red', 1), ('blue', 4)]: d.setdefault(k, []).append(v) # Ordered Dict: remembers key insertion order (doesn't care about value) # 'move_to_end' lets you shuffle items to front or back d = OrderedDict.fromkeys('abcd') print(d) # odict_keys(['a', 'b', 'c', 'd']) d.move_to_end('b'); print(d) # odict_keys(['a', 'c', 'd', 'b']) d.move_to_end('b', last=False); print(d) # odict_keys(['b', 'a', 'c', 'd'])
dccc6ad62cc6bbd375f5624d39836121e7a87dca
robertokondo8496/TechStartPro
/show.py
432
3.53125
4
# this module is responsible for showing data into database import pymongo def show(collection, filter = {}): """This function is responsible for showing data into database""" # creates a connection with database result = [] myclient = pymongo.MongoClient("mongodb://localhost:27017/") db = myclient["techstart"] col = db[collection] for x in col.find(filter): result.append(x) return result
d5da1debe4f7d456f2bf6073e2f25f04cfa5c8b3
da-ferreira/uri-online-judge
/uri/2712.py
539
4.125
4
casos = int(input()) for i in range(casos): placa = input() if (len(placa) != 8) or (not placa[0:3].isupper()) or (not placa[-4:].isnumeric()) or (placa[3] != '-'): print('FAILURE') else: if placa[-1] in '12': print('MONDAY') elif placa[-1] in '34': print('TUESDAY') elif placa[-1] in '56': print('WEDNESDAY') elif placa[-1] in '78': print('THURSDAY') elif placa[-1] in '90': print('FRIDAY')
9141f80eed4510952ce41f8d7fea5b7fe8b19dc8
tessied/snake_game
/food.py
467
3.59375
4
# A module to generate the food particle for the snake from turtle import Turtle import random class Food(Turtle): def __init__(self): super().__init__() self.shape("circle") self.pu() self.shapesize(stretch_len=0.5, stretch_wid=0.5) self.color("green") self.speed("fastest") self.change_location() def change_location(self): self.goto(random.randint(-280, 280), random.randint(-280, 280))
31b0bfd5d9fb52113a793f2f1451dfd31434f0fe
CiyoMa/leetcode
/wordBreakII.py
2,945
3.890625
4
""" Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences. For example, given s = "catsanddog", dict = ["cat", "cats", "and", "sand", "dog"]. A solution is ["cats and dog", "cat sand dog"]. """ class Solution: # @param s, a string # @param dict, a set of string # @return a list of strings def wordBreak(self, s, dict): # def convert(dp, end, l): # result = [] # for i in dp[end]: # tail = s[i:end] # if i == 0: # result += [tail] # continue # temp = convert(dp, i, l) # for j in range(len(temp)): # temp[j] += ' ' + tail # result += temp # #print end, result # return result ##### Try DP + DP - DFS (with memorization) ########### ################################################################ ################# SINGLE PASS -- FAIL, For No Result Case, ################# too many interminate result say, waste memory ################################################################ # dp = [[] if i > 0 else [''] for i in range(len(s)+1)] # for i in range(1,len(s)+1): # for j in range(i): # #print j,i,#s[j:i], # tail = s[j:i] # if len(dp[j]) and tail in dict: # print True # if i == len(s): # BLANK = '' # else: # BLANK = ' ' # for k in dp[j]: # dp[i].append(k+tail+BLANK) # print dp[i] # continue # print # #print dp # return dp[len(s)] #################### FULL ############################ dp = [[] if i > 0 else [''] for i in range(len(s)+1)] for i in range(1,len(s)+1): for j in range(i-1,-1,-1): #print j,i,s[j:i], #tail = s[j:i] if len(dp[j])>0 and s[j:i] in dict: #print True dp[i].append(j) continue #print #print dp l = len(s) if len(dp[l]) <= 0: return [] resultList = [[] for i in range(l)] for i in range(l): for j in dp[i+1]: tail = s[j:i+1] if i == l-1: BLANK = '' else: BLANK = ' ' if j == 0: resultList[i].append(tail+BLANK) else: for k in resultList[j-1]: resultList[i].append(k+tail+BLANK) #print resultList return resultList[l-1] return convert(dp, l, l) st,dic = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab", ["a","aa","aaa","aaaa","aaaaa","aaaaaa","aaaaaaa","aaaaaaaa","aaaaaaaaa","aaaaaaaaaa"] #"bbbbbbbbbbbbb", ['b','bb','abc','abce'] s = Solution() print s.wordBreak(st, dic)
d2881fc5dea40152215737d221aa73c05536d3a2
iverson52000/DataStructure_Algorithm
/LeetCode/0054. Spiral Matrix.py
959
3.796875
4
""" 54. Spiral Matrix Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order. """ class Solution: def spiralOrder(self, matrix: List[List[int]]) -> List[int]: if not matrix or not matrix[0]: return [] res = [] left = 0; right = len(matrix[0])-1 top = 0; bottom = len(matrix)-1 while left <= right and top <= bottom: for i in range(left, right+1): res.append(matrix[top][i]) top += 1 for i in range(top, bottom+1): res.append(matrix[i][right]) right -= 1 if left > right or top > bottom: break for i in range(right, left-1, -1): res.append(matrix[bottom][i]) bottom -= 1 for i in range(bottom, top-1, -1): res.append(matrix[i][left]) left += 1 return res
69d7bffa72327e10478cd24cfec340419696eae0
guolinbuaa/LeetCode
/test.py
536
3.5625
4
s='()' d = {'(': ')', '{': '}', '[': ']'} l = '' if len(s) == 1 or len(s) == 0: print('false') # return False for i in range(len(s)): print(s[i]) if s[i] in d: l += d[s[i]] print(l) if i == len(s) - 1: print('false') # return False elif s[i] == l[len(l) - 1:]: l = l[:len(l) - 1] print(l) if i == len(s) - 1: if l == '': print('true') else: print('false') else: print('false')
621fc4e5914911597e7571f0637fb00801b247ff
JSebastianP96/intermediate-python-course
/dice_roller.py
929
3.953125
4
import random def main(): player_n = int(input('Numero de jugadores')) dice_rolls = int(input('How many dice would you like to roll?')) dice_size = int(input('How many sides are the dice?')) dice_sum = [] player_name = [] mayor = 0 player_win = 0 for p in range (0,player_n): player_name.append("") dice_sum.append(0) player_name[p] = str(input('what is team name?')) for x in range(0,dice_rolls): roll = random.randint(1,dice_size) dice_sum[p] = dice_sum[p] + roll print(f'You rolled a {roll}') print(f'You have rolled a total of {dice_sum[p]}') if dice_sum[p] > mayor: mayor = dice_sum[p] player_win = p print(f'El jugador ganador es {player_win}') print(f'El jugador ganador es {player_name[player_win]}') print(f'You have rolled a total of {dice_sum[player_win]}') print(f'You have rolled a total of {dice_sum}') if __name__== "__main__": main()
d28f4b0dfec576d8074cb284934066c1ce108f00
shma1664/Project
/Python/runoob/src/com/shma/ๅพช็Žฏ่ฏญๅฅ/whileๅพช็Žฏ.py
1,288
3.640625
4
''' Created on 2015ๅนด10ๆœˆ15ๆ—ฅ @author: admin ''' from pip._vendor.distlib.compat import raw_input num = 10; print("start while"); while(num > 0) : print("This is count : ", num); num -= 1; print("end while"); #ไฝฟ็”จbreak๏ผŒcontinue i = -1; while(i < 10) : i += 1; if(i % 2 == 0) : continue; print(i); print("end...."); j = 0; while 1 : j += 2; if(j > 10) : break; print(j); print("end...."); #ๆ— ้™ๅพช็Žฏ while 1==1 : num = raw_input("Enter number : "); print(str.isdigit(num)); if(int(num) == -1) : break; print("Your enter num : " + num); print("good bye"); ''' while ... else ... ๅฆ‚ๆžœwhileๅพช็Žฏๆญฃๅธธๆ‰ง่กŒ็ป“ๆŸ๏ผŒๅณๆฒกๆœ‰้€š่ฟ‡break้€€ๅ‡บ๏ผŒๅˆ™ไผšๆ‰ง่กŒelse่ฏญๅฅ ''' ''' 1 less than 5 3 less than 5 5 less than 5 6 not less than 5 ''' k = 0; while (k <= 5) : k += 1; if(k % 2 == 0) : continue; print(k , " less than 5"); else : print(k , " not less than 5"); ''' 1 less than 5 2 less than 5 ''' l = 0; while(l <= 5) : l += 1; if(l == 3) : break; print(l , " less than 5"); else : print(l , " not less than 5"); m = 1; while(m) : print("Given flag is really true!"); # die loop print("good bye");
3758f03aface24522eb22ff4392e41957ab63a39
jalelegenda/bulkuploadtest
/utility.py
4,465
3.875
4
"""Utility classes the app uses""" import random import string import sys from params import Command, PLATES_NUM class UserInputValidator: """Provides utility functions validating user input for numeric menus""" def __init__(self, user_options, dbc): self.__user_options = user_options self.__dbc = dbc def __process_accounts(self): """Secure existing account selection""" counter = 1 accounts = [] while True: print("Account %d.:\t" % counter, end="") user_input = sys.stdin.readline().strip() if user_input not in string.digits: print("Only numbers accepted, try again...") elif user_input == "": print("Accounts saved...") self.__user_options.update({"accounts": accounts}) return 0 else: if not self.__dbc.account_exists(user_input): print("That account does not exist, try again...") else: accounts.append(user_input) counter += 1 def process(self, key, min_rng=0, max_rng=0): """Limit user input to digits within min and max range and save user choices""" if key == "accounts": self.__process_accounts() return 0 while True: user_input = sys.stdin.readline().strip() if user_input not in string.digits: print("Only numbers accepted, try again...") continue if int(user_input) >= min_rng and\ int(user_input) <= max_rng: self.__user_options.update({key : str(user_input)}) return print("Let's try that again (numbers %d to %d):\t"\ % (int(min_rng), int(max_rng)), end="") class Generator: """Generates rows to be written to file""" def __init__(self, user_options): self.__user_options = user_options def __generate_command(self): """Generate TollCRM command""" index = (random.choice(string.digits)for _ in range(2, 4)) return Command(index).name def __generate_plates(self, limit): """Generate a random plate number with two letters and 3 numbers""" plates = [] for i in range(1, limit): #plate is a string starting with 2 random letters and ending in 3 random numbers plate = ''.join(random.choice(string.ascii_lowercase)for _ in range(2))\ .join(random.choice(string.digits)for _ in range(3)) if plate in plates: i -= 1 continue plates.append(plate) return plates def __generate_group(self): """Generate a random group name""" groups = ["", "Drinks", "Food", "Clothes", "Transportation", "Hardware", "Furniture"] group = groups[random.randrange(0, len(groups)-1)] return group def __construct_row(self, command, accountnum, platenum, groupname): """Generate entry for writing to file""" line = command + ","\ + accountnum + ","\ + platenum + ",,,,,,,"\ + groupname\ + "\n" return line def generate_output(self): """Generates list with 2500 rows""" plates = self.__generate_plates(PLATES_NUM[self.__user_options["plates"]]) accounts = self.__user_options["accounts"] output = [] for _ in range(1, 2500): command = self.__generate_command() if self.__user_options["commands"]\ not in Command else Command(self.__user_options).name accnts_last = len(accounts)-1 accountnum = accounts[random.randrange(0, accnts_last)] plates_last = len(plates)-1 plate = plates[random.randrange(0, plates_last)] #possible additions #make = self.__generate_make() #model = self.__generate_model() #color = self.__generate_color() groupname = self.__generate_group() row = self.__construct_row(command, accountnum, plate, groupname) output.append(row + "\n") return output class Writer: """Class that writes output to file""" def write(self, output, path): """Write to actual file""" with open(path + "/bulk_test.csv", "w+") as file_handle: file_handle.write(output)
9457fa3e812bea651efb39c272dd332fadfdd6af
devDeejay/Python
/Programs/XOR is Mad.py
232
3.5
4
def calculate(x): n = x count = 0 for A in range(1,n): if((A ^ n) == (A + n)): count += 1 print(count) testCases = int(input()) for i in range(0,testCases): X = int(input()) calculate(X)
e0e1cbef14504d96d067b872208fb13412a18adb
JosephLevinthal/Research-projects
/5 - Notebooks e Data/1 - Anรกlises numรฉricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/226/users/4165/codes/1637_2703.py
124
3.640625
4
idade = int(input("idade ")) if(idade > 18): mensagem = "eleitor" else: mensagem = "nao_eleitor" print(mensagem.lower())
114aeb9908f7f700da4e9612d481ce0bcccbfa7b
maximekabel/Advent-Of-Code-2020
/Day-2/password-philosophy.py
911
3.578125
4
file = open("Day-2/input.txt") input = file.read().splitlines() correct_passw1 = 0 correct_passw2 = 0 test_list = [] for i in input: lower_lim = int(i.split("-", 1)[0]) upper_lim = int(i.split("-")[1].split(" ")[0]) char = i.split("-")[1].split(" ")[1].rstrip(":") password = i.split(":")[1].strip() dic = {"lower": lower_lim, "upper": upper_lim, "char": char, "password": password} test_list.append(dic) for m in test_list: occurance = m["password"].count(m["char"]) if occurance >= m["lower"] and occurance <= m["upper"]: correct_passw1 += 1 for k in test_list: char_pos_a = k["password"][k["lower"] - 1] char_pos_b = k["password"][k["upper"] - 1] if (char_pos_a == k["char"] and char_pos_b != k["char"]) or ( char_pos_a != k["char"] and char_pos_b == k["char"] ): correct_passw2 += 1 print(correct_passw1) print(correct_passw2)
dcde90103b611d9d14154674b860563d23e16acd
Anurag9697/Pythoncodes
/PythonMagicBall-08-01.py
539
3.984375
4
#import modules import sys,random #initial variables #loop variable #list of responses variable l=["IT IS CERTAIN","YOU MAY RELY ON IT","AS I SEE IT, YES","OUTLOOK LOOKS GOOD","MOST LIKELY","IT IS DECIDELY SO","WITHOUT A DOUBT","YES, DEFINETLY" ] #while loop while True: #write the code that will recieve the user input #return the random response #and quit the application question=input("Ask a question(Press Enter to exit)") if(question==""): sys.exit() else: print(random.choice(l))
32e4e1a50f11f559355436e138cdb00575d0a107
JosephLevinthal/Research-projects
/5 - Notebooks e Data/1 - Anรกlises numรฉricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/226/users/4153/codes/1638_651.py
194
3.796875
4
h = float(input("Insira kbuvgdhybvkuhd: ")) s = input("uhygdsvcjuysedt: (M/F)").upper() if(s == "M"): pi = (72.7 * h) - 58 print(round(pi,2)) else: pi = (62.1 * h) - 44.7 print(round(pi,2))
23a130c56e2291d14b1327f5b7f61734f5e94f61
Riceyo/QA-Consulting-ONS-Academy
/PySpark/task_calc_student_grades.py
2,346
3.53125
4
from pyspark import SparkConf, SparkContext def SplitPer(x): split = x.split(",") return split[0], split[1], split[2] def SplitRes(x): split = x.split(",") return split[0], split[2] # only keep the student regno (key) and their marks data so we can use the reducebykey method to sum their marks def Add(x, y): return int(x) + int(y) def CalcGrade(x): if x > 89: return 'A+' if x > 79 and x < 90: return 'A' if x > 69 and x < 80: return 'B' if x > 59 and x < 70: return 'C' if x < 60: return 'Fail' conf = SparkConf() sc = SparkContext(conf = conf) rddper = sc.textFile("file:///home/cloudera/student_perinfo.csv", 0) rddres = sc.textFile("file:///home/cloudera/student_results.csv", 0) rddperhead = rddper.first() # get the header (first row) from the student personal info data rddreshead = rddres.first() # get the header (first row) from the student results data rddperremhead = rddper.filter(lambda line: line != rddperhead).map(lambda x: x.encode("ascii", "ignore")) # remove header from the data and encode rddresremhead = rddres.filter(lambda line: line != rddreshead).map(lambda x: x.encode("ascii", "ignore")) # remove header from the data and encode rddpersplit = rddperremhead.map(SplitPer) # split the data rddressplit = rddresremhead.map(SplitRes) # split the data rddresadd = rddressplit.reduceByKey(Add) # sum the students marks dataper = rddpersplit.collect() datares = rddressplit.collect() dataresadd = rddresadd.collect() datarescount = rddressplit.countByKey() # count how marks we have for the student bestpercent = 0 for resloop in dataresadd: # loop the student results summed up data for perloop in dataper: # loop the student personal info data if perloop[0] == resloop[0]: # if the regno match count = datarescount[perloop[0]] # count how many marks we have for the student percent = resloop[1] * 100 / int(str(count) + '00') # calculate their percentage based on how many marks we have for them grade = CalcGrade(percent) # calculate their grade based on their percent if percent > bestpercent: bestpercent = percent beststudent = perloop[1] print "" print "student reg number:", perloop[0] print "student name:", perloop[1] print "exams taken:", count print "percentage:", percent, "%" print "grade:", grade print "" print "best student:", beststudent
8887190f541121b0c758939aca9d4775109e893d
bbsathyaa/PYTHON
/task 8.py
2,521
3.65625
4
#errorTypes:Syntax error,Logical error(Exceptions) #Syntax error a,b=1,2 print(a ,b) #SyntaxError: invalid syntax #Exceptions print(dir(locals()['__builtins__'])) #list of built-in exceptions l1=list(range(5)) l1[7] # IndexError: list index out of range import module1 #ModuleNotFoundError: No module named 'module1' d1={'a':'1','b':'2'} d1['c'] #KeyError: 'c' from math import cube #ImportError: cannot import name 'cube' from 'math' (unknown location) t1=iter([1,2]) print(next(t1)) print(next(t1)) print(next(t1)) #StopIteration print('hello'+2) #TypeError: can only concatenate str (not "int") to str int('abc') #ValueError: invalid literal for int() with base 10: 'abc' print(d) #NameError: name 'd' is not defined print(12/0) #ZeroDivisionError: division by zero #exceptionHandling try: l1 = list(range(5)) l1[7] except IndexError: print("list index out of range") else: print("success") try: import mod1 except ModuleNotFoundError: print("No module named 'module1'") try: d1 = {'a': '1', 'b': '2'} d1['c'] except KeyError: print("Key not found") try: print(d) except NameError: print("name not found") try: print(10/0) except ZeroDivisionError: print("Division by zero") #simpleCalculator def calc(): try: a=int(input("enter no1")) b=int(input("enter no2")) c=input("enter opertion:+,-,*,/") if(c=='+'): print(f"{a}+{b}={a + b}") elif (c == '-'): print(f"{a}-{b}={a - b}") elif (c == '*'): print(f"{a}*{b}={a * b}") elif (c == '/'): try: print(f"{a}/{b}={a / b}") except ZeroDivisionError: print("Division by zero") else: print("enter a valid input") except ValueError: print("enter a valid input") calc() #try block raises a nameError try: print(d) except NameError: print("name not found") except: print("Error") #input inside try block try: a=int(input("enter number")) print(a) except ValueError: print("Enter interger value!")
13ff8935e7aefcad532e884926075ce45a23bc29
wuxm669/python
/obj.py
1,450
3.9375
4
# a = 1 # b = 1 # c = a+b # d =a-b # def add(x,y): # print(x+y) # return x+y # add(1,2) #ๅฃฐๆ˜Žไธ€ไธชemployee็ฑป class Employee: pay_raist_amount=1.2 #ๅˆ›ๅปบไธ€ไธชๆž„้€ ๅ™จ def __init__(self,first,last,pay,domin="ersoft.cn"): self.first =first self.last =last self.pay =pay self.email =last+first+'@'+domin #ๅˆ›ๅปบไธ€ไธชๆ–นๆณ• def fullname(self): #print('{} {}'.format(self.last,self.first) ) #ๅคงๆ‹ฌๅท็š„ไฝฟ็”จๆ–นๆณ• return self.first + self.last def new_pay0(self): return self.pay*self.pay_raist_amount #ๅผ•็”จๆ–นๆณ•ๆœฌ่บซ็š„ๅ˜้‡๏ผˆๅฎž้™…็”จ่ฟ™็งๆ–นๆณ•ๆฏ”่พƒๅคš๏ผ‰ def new_pay1(self): return self.pay*Employee.pay_raist_amount #ๅผ•็”จ็š„ๅ…จๅฑ€ๅ˜้‡ #ๅฎžไพ‹ๅŒ– emp1 =Employee('xiaoming','wang',1000) emp1.fullname() emp2 =Employee('xiaohong','zhang',2000) print(emp1.first,emp1.last,emp1.pay,emp1.email) #่ฐƒ็”จไธ€ไธชๆ–นๆณ• print(emp1.new_pay0()) print(emp1.new_pay1()) Employee.pay_raist_amount = 1.4 print('Employee.pay_raist_amount = 1.4',emp1.new_pay0()) print(emp1.new_pay1()) print(emp2.new_pay0()) print(emp2.new_pay1()) emp1.pay_raist_amount = 1.5 print("emp1. raise, emp1.newpay0()",emp1.new_pay0()) print(emp1.new_pay1()) print(emp2.new_pay0()) print(emp2.new_pay1()) emp2.pay_raist_amount = 1.6 print('emp2. raise, emp2.newpay0()',emp1.new_pay0()) print(emp1.new_pay1()) print(emp2.new_pay0()) print(emp2.new_pay1())
c18a779f4c7ededcb962aa05ae6d3844d12b00de
bakker4444/Algorithms
/Python/leetcode_433_minimum_genetic_mutation.py
2,819
4.21875
4
## 433. Minimum Genetic Mutation # # A gene string can be represented by an 8-character long string, with choices from "A", "C", "G", "T". # # Suppose we need to investigate about a mutation (mutation from "start" to "end"), where ONE mutation is defined as ONE single character changed in the gene string. # # For example, "AACCGGTT" -> "AACCGGTA" is 1 mutation. # # Also, there is a given gene "bank", which records all the valid gene mutations. A gene must be in the bank to make it a valid gene string. # # Now, given 3 things - start, end, bank, your task is to determine what is the minimum number of mutations needed to mutate from "start" to "end". If there is no such a mutation, return -1. # # Note: # 1. Starting point is assumed to be valid, so it might not be included in the bank. # 2. If multiple mutations are needed, all mutations during in the sequence must be valid. # 3. You may assume start and end string is not the same. # # Example 1: # start: "AACCGGTT" # end: "AACCGGTA" # bank: ["AACCGGTA"] # # return: 1 # # Example 2: # start: "AACCGGTT" # end: "AAACGGTA" # bank: ["AACCGGTA", "AACCGCTA", "AAACGGTA"] # # return: 2 # # Example 3: # start: "AAAAACCC" # end: "AACCCCCC" # bank: ["AAAACCCC", "AAACCCCC", "AACCCCCC"] # # return: 3 ## ## BFS with queue approach ## time complexity : O(L*4*N), for L:length of a gene, N: numver of genes in bank ## space complexity : O(N) for bank length from collections import deque class Solution(object): def minMutation(self, start, end, bank): """ :type start: str :type end: str :type bank: List[str] :rtype: int """ bank = set(bank) queue = deque() queue.append((start, 0)) while queue: gene, dist = queue.popleft() if gene == end: return dist for i in range(len(gene)): for c in "ACGT": temp_gene = gene[:i] + c + gene[i+1:] if temp_gene in bank: bank.remove(temp_gene) queue.append((temp_gene, dist+1)) return -1 import unittest class Test(unittest.TestCase): def test_minMutation(self): test_input = [ ["AACCGGTT", "AACCGGTA", ["AACCGGTA"]], ["AACCGGTT", "AAACGGTA", ["AACCGGTA", "AACCGCTA", "AAACGGTA"]], ["AAAAACCC", "AACCCCCC", ["AAAACCCC", "AAACCCCC", "AACCCCCC"]] ] test_result = [1, 2, 3] for i in range(len(test_input)): result = Solution().minMutation(test_input[i][0], test_input[i][1], test_input[i][2]) self.assertEqual(result, test_result[i]) print(result) if __name__ == "__main__": unittest.main()
ec92211831b5ec2c00b887bab22f3f731b9aae37
Hellofafar/Leetcode
/Medium/542.py
2,384
3.625
4
# ------------------------------ # 542. 01 Matrix # # Description: # Given a matrix consists of 0 and 1, find the distance of the nearest 0 for each cell. # # The distance between two adjacent cells is 1. # # Example 1: # Input: # [[0,0,0], # [0,1,0], # [0,0,0]] # # Output: # [[0,0,0], # [0,1,0], # [0,0,0]] # # Example 2: # Input: # [[0,0,0], # [0,1,0], # [1,1,1]] # # Output: # [[0,0,0], # [0,1,0], # [1,2,1]] # # Note: # # The number of elements of the given matrix will not exceed 10,000. # There are at least one 0 in the given matrix. # The cells are adjacent in only four directions: up, down, left and right. # # Version: 1.0 # 01/19/20 by Jianfa # ------------------------------ class Solution: def updateMatrix(self, matrix: List[List[int]]) -> List[List[int]]: if not matrix or not matrix[0]: return matrix m = len(matrix) n = len(matrix[0]) dist = [[sys.maxsize] * n for _ in range(m)] # fist pass: check for the left and the top for i in range(m): for j in range(n): if matrix[i][j] == 0: dist[i][j] = 0 else: if i > 0: dist[i][j] = min(dist[i][j], dist[i-1][j] + 1) if j > 0: dist[i][j] = min(dist[i][j], dist[i][j-1] + 1) # second pass: check for the bottom and the right for i in range(m)[::-1]: for j in range(n)[::-1]: if i < m - 1: dist[i][j] = min(dist[i][j], dist[i+1][j] + 1) if j < n - 1: dist[i][j] = min(dist[i][j], dist[i][j+1] + 1) return dist # Used for testing if __name__ == "__main__": test = Solution() # ------------------------------ # Summary: # I used BFS solution at first, checking distance for every 1 using BFS, but it's not efficient. # According to solution from: https://leetcode.com/problems/01-matrix/solution/ , a better # idea would be starting from every 0 to update distance of 1s in the matrix. # # But here I used the DP solution from the same link, which is to traverse the matrix twice. # Once from upper left to bottom right, once from bottom right to top left. As long as a 1 # is met, its distance is minimum distance of any neightbour + 1
fff02c80f0497eb4a410ce5f2d6ccaee03fc1f28
boguslaw-chojecki/codewars
/Valid_Parentheses.py
293
3.9375
4
def valid_parentheses(s): # your code here check = 0 for i in s: if i == "(": check += 1 elif i == ")": check -= 1 if check < 0: return False if check == 0: return True else: return False
6c40be694bd4d8b84d5b9e693ecf57319842a78a
cifpfbmoll/practica-5-python-miquel21-hub
/P5EJ5.py
219
3.8125
4
#PRรCTICA 5 EJERCICIO 5 anchura=int(input("Introduce la anchura del rectangulo\n")) altura=int(input("Introduce la altura\n")) for i in range(altura): for x in range(anchura): print("*", end="") print()
974e4f1a4f6418226ed4a52ded4b07f48504d34f
pongpisut261/CP3-Pongpisut-Choothong
/Exercise5_1_Pongpisut_C.py
327
3.8125
4
input1 = int(input('เธฃเธฐเธšเธธเธ•เธฑเธงเน€เธฅเธ‚ :')) input2 = int(input('เธฃเธฐเธšเธธเธ•เธฑเธงเน€เธฅเธ‚ :')) print(input1 , '+' , input2 , '=' , input1 + input2 ) print(input1 , '-' , input2 , '=' , input1 - input2 ) print(input1 , '*' , input2 , '=' , input1 * input2 ) print(input1 , '/' , input2 , '=' , input1 / input2 )
bba2d3f52fb5be3efdf0fb5de4d06a17c53b15fa
RandhirJunior/python_programming
/python-programming-workshop/python_cookbook/src/1/removing_duplicates_from_a_sequence_while_maintaining_order/example.py
401
4.03125
4
# example.py # Remove duplicate entries from a sequence while keeping order def dedupe(items): seen = set() for item in items: if item not in seen: yield item seen.add(item) print(seen) # this is an additional line i added to print the "seen" variable if __name__ == '__main__': a = [1, 5, 2, 1, 9, 1, 5, 10] print(a) print(list(dedupe(a)))
f7bef01bc72af50b1ccbe2f3cbc9304265598628
glissader/Python
/ะ”ะ— ะฃั€ะพะบ 2/main3.py
608
3.96875
4
# ะŸะพะปัŒะทะพะฒะฐั‚ะตะปัŒ ะฒะฒะพะดะธั‚ ะผะตััั† ะฒ ะฒะธะดะต ั†ะตะปะพะณะพ ั‡ะธัะปะฐ ะพั‚ 1 ะดะพ 12. # ะกะพะพะฑั‰ะธั‚ัŒ, ะบ ะบะฐะบะพะผัƒ ะฒั€ะตะผะตะฝะธ ะณะพะดะฐ ะพั‚ะฝะพัะธั‚ัั ะผะตััั† (ะทะธะผะฐ, ะฒะตัะฝะฐ, ะปะตั‚ะพ, ะพัะตะฝัŒ). # ะะฐะฟะธัˆะธั‚ะต ั€ะตัˆะตะฝะธั ั‡ะตั€ะตะท list ะธ dict. n = 0 while n not in range(1, 13): n = int(input("ะ’ะฒะตะดะธั‚ะต ะผะตััั† ะพั‚ 1 ะดะพ 12 ").strip()) seasons = {"ะทะธะผะฐ": [12, 1, 2], "ะฒะตัะฝะฐ": [3, 4, 5], "ะปะตั‚ะพ": [6, 7, 8], "ะพัะตะฝัŒ": [9, 10, 11]} for season in seasons: if n in seasons.get(season): print(season) break
b45b91f1beeece214d96dea903fde88a56f849c8
robdunn220/THPython
/OOPython/filledlist.py
309
3.59375
4
import copy class FilledList(list): def __init__(self, count, value, *args, **kwargs): super().__init__() for _ in range(count): self.append(copy.copy(value)) def __len__(self): return super(FilledList, self).__len__() + 2 fl = FilledList(3, 2) print(len(fl))
8e942ac0ff9186ffbf352022906ae3a3d159a60b
7ard1grad3/Snake-turtle-py
/food.py
316
3.796875
4
from turtle import Turtle from random import randint class Food: def __init__(self): self.food = Turtle("turtle") self.food.reset() self.food.goto((randint(-280, 280), randint(-280, 280))) self.food.color("green") def pos(self): return self.food.pos()
f2779d883436c15d1ce65f43a13e820bd4da04f7
KWilliamson90/Term_Project_Ken_Williamson
/Search.py
1,441
3.578125
4
from Database import * from Management import * ''' Postcondition1: Connects to Job Database. Postcondition2: Prompts user to enter a job number. Postcondition3: Displays list of potential jobs for the user to select. Postcondition4: Prompts user to select correct job. Postcondition5: Passes job number to Main Job Window class. ''' class Job_Search(Job_Database):#Objective: Act as search engine to find jobs in Job Database. def __init__(self): selection = []#Holds potential jobs for user to select. super().connect()#Connects to Job Database. field = int(input('Enter a Job Number: '))#Prompts User to enter a job number. for job in Job_Database.Jobs:#Runs though Job Database. if field == job['Job Number']:#Identifies potential jobs. print(str(job['Job Number']) +': ' + job['Client'])#Displays job number and client name on console. selection.append(job)#Adds potentails jobs to list. else: None#No action is taken on jobs that do not match. select = int(input('\nEnter a job number from the list above: '))#Prompts User to select correct job. for line in selection:#Runs through potential job list. if select == line['Job Number']:#Identifies correct job. MJW = Main_Job_Window() MJW.Main(select)#Passes job number to Main Job class.
11d27007037e7d01d7848ebac6f10fbfce463df0
Svensson17/python-project-lvl1
/brain_games/games/brain_even.py
249
3.609375
4
import random RULE = "Answer \"yes\" if the number is even, otherwise answer \"no\"." def get_question_and_answer(): question = random.randint(0, 100) right_answer = "yes" if question % 2 == 0 else "no" return question, right_answer
84d20d185a5fe4993cf5ba868e9dbf71742b85e3
CodeWithShamim/python-t-code
/Read and write a file/Read and Write a file.py
999
3.875
4
''' # r for readble, w for writable, r+ for read/write, a for append............. #use readable.. file = open("name.txt", "r") #check vale true or false.................... s = file.readable() print(s) result = file.read() print(result) file.close() #when use writable then remove all text file.. file = open("name.txt", "w") result = file.write("\nSalman islam joy-106") print(result) file.close() #use append.. file = open("name.txt", "a") result = file.write("\nSalman islam joy-106") print(result) file.close() #create new text file...... file = open("name111.txt", "r") result = file.read() print(result) file.close() ''' file = open("name.txt", "r") #when use readlines then all text print list........... result = file.readlines()[0] print(result) file.close() file = open("name.txt", "r") #use loop .................... file = open("name.txt", "r") for i in file: print(i) #html tag use file = open("hello.html", "w") result = file.write("\n<h1>Hello everyone<h1>") print(result)
3fcdc6c0dfa2c49465527194a47f650f4b7fef58
xistadi/Python-practice
/it academy/old homework/practice.py
1,556
4.03125
4
a = int(input("ะ’ะฒะตะดะธั‚ะต ั‡ะธัะปะพ ะฐ: ")) b = int(input("ะ’ะฒะตะดะธั‚ะต ั‡ะธัะปะพ b: ")) c = int(input("ะ’ะฒะตะดะธั‚ะต ั‡ะธัะปะพ c: ")) #ะ’ั‹ะฒะตัั‚ะธ ะฝะฐ ัะบั€ะฐะฝ 0, ะฝะต ะตัะปะธ ะฝะตั‚ ะฝะธ ะพะดะฝะพะณะพ ะฝัƒะปั - ะฒั‹ะฒะตัั‚ะธ: "ะะตั‚ ะฝัƒะปะตะฒั‹ั… ะทะฝะฐั‡ะตะฝะธะน!!!" (ะฑะตะท if) print(a and b and c and "ะะตั‚ ะฝัƒะปะตะฒั‹ั… ะทะฝะฐั‡ะตะฝะธะน!!!") #ะ’ั‹ะฒะตัั‚ะธ ะฟะตั€ะฒะพะต ะฝะตะฝัƒะปะตะฒะพะต ะทะฝะฐั‡ะตะฝะธะต,ะฝะพ ะตัะปะธ ะฒะฒะตะดะตะฝั‹ ะฒัะต ะฝัƒะปะธ - ะฒั‹ะฒะตัั‚ะธ "ะ’ะฒะตะดะตะฝั‹ ะฒัะต ะฝัƒะปะธ!" (ะฑะตะท if) print(a or b or c or "ะ’ะฒะตะดะตะฝั‹ ะฒัะต ะฝัƒะปะธ!") #ะ•ัะปะธ ะฟะตั€ะฒะพะต ะทะฝะฐั‡ะตะฝะธะต ะฑะพะปัŒัˆะต ั‡ะตะผ ััƒะผะผะฐ ะฒั‚ะพั€ะพะณะพ ะธ ั‚ั€ะตั‚ัŒะตะณะพ ะฒั‹ะฒะตัั‚ะธ a - b - c (ะฟ3 ะธ ะฟ4 ะฟั€ะพะฒะตั€ะธั‚ัŒ ะพะดะฝะธะผ ัƒัะปะพะฒะธะตะผ(ะบะพะฝัั‚ั€ัƒะบั†ะธะตะน) if a > (b + c): print(a - b - c) #ะ•ัะปะธ ะฟะตั€ะฒะพะต ะทะฝะฐั‡ะตะฝะธะต ะผะตะฝัŒัˆะต ะธะปะธ ั€ะฐะฒะฝะพ ััƒะผะผะต ะฒั‚ะพั€ะพะณะพ ะธ ั‚ั€ะตั‚ัŒะตะณะพ ะฒั‹ะฒะตัั‚ะธ b + c - a if a <= (b + c): print(b + c - a) #ะ•ัะปะธ ะฟะตั€ะฒะพะต ะทะฝะฐั‡ะตะฝะธะต ะฑะพะปัŒัˆะต 50 ะธ ะฟั€ะธ ัั‚ะพะผ ะพะดะฝะพ ะธะท ะพัั‚ะฐะฒัˆะธั…ัั ะทะฝะฐั‡ะตะฝะธะต ะฑะพะปัŒัˆะต ะฟะตั€ะฒะพะณะพ ะฒั‹ะฒะตัั‚ะธ "ะ’ะฐัั" (ะฟั€ะพะฒะตั€ะธั‚ัŒ ะพะดะฝะธะผ ัƒัะปะพะฒะธะตะผ) if a > 50 and a < b or a < c: print("ะ’ะฐัั") #ะ•ัะปะธ ะฟะตั€ะฒะพะต ะทะฝะฐั‡ะตะฝะธะต ะฑะพะปัŒัˆะต 5 ะธะปะธ ะพะฑะฐ ะธะท ะพัั‚ะฐะฒัˆะธั…ัั ะทะฝะฐั‡ะตะฝะธะน ั€ะฐะฒะฝั‹ 7 ะฒั‹ะฒะตัั‚ะธ "ะŸะตั‚ั"(ะฟั€ะพะฒะตั€ะธั‚ัŒ ะพะดะฝะธะผ ัƒัะปะพะฒะธะตะผ) if a > 5 or b == 7 and c == 7: print("ะŸะตั‚ั")
fb1b1e73c7d5311e36eb7f1fd8d2cddd9ad9fb7b
starmap0312/refactoring
/simplifying_conditional_expressions/introduce_null_object.py
722
4.15625
4
# - if you have repeated checks for a null value, then replace the null value with a null object # - if one of your conditional cases is a null, use introduce null object # before: use conditionals class Customer(object): # abstract class def getPlan(self): raise NotImplementedError # client has a conditional that handles the null case if customer is None: plan = doSomething() else: plan = customer.getPlan() # after: add null object in which it performs doSomething(), thus the conditional can be removed class NullCustomer(Customer): def getPlan(self): doSomething() # simplified code: client uses polymorphism that is able to perform the null case plan = customer.getPlan()
32c5e1c536f8612465b35801d5349b0765a4060e
rivelez65/Snake-Game_OOP-Turtle
/snake.py
1,719
3.6875
4
from turtle import Turtle STARTING_POSITIONS = [(0, 0), (-20, 0), (-40, 0)] MOVE_DISTANCE = 20 UP = 90 DOWN = 270 LEFT = 180 RIGHT = 0 class Snake: def __init__(self): self.snake_sections = [] self.snake_body() self.head = self.snake_sections[0] def snake_body(self): for square in STARTING_POSITIONS: t = Turtle() t.color('black') t.speed('fastest') t.penup() t.shape('square') t.goto(square) t.color('white') t.seth(0) self.snake_sections.append(t) def extend(self): new = Turtle() new.penup() new.shape('square') new.color('white') new.goto(self.snake_sections[-1].position()) self.snake_sections.append(new) def move(self): for seg in range(len(self.snake_sections) - 1, 0, -1): new_x = self.snake_sections[seg - 1].xcor() new_y = self.snake_sections[seg - 1].ycor() self.snake_sections[seg].goto(new_x, new_y) self.head.forward(MOVE_DISTANCE) def up(self): if self.head.heading() != DOWN: self.head.setheading(UP) def down(self): if self.head.heading() != UP: self.head.setheading(DOWN) def left(self): if self.head.heading() != RIGHT: self.head.setheading(LEFT) def right(self): if self.head.heading() != LEFT: self.head.setheading(RIGHT) def reset(self): for section in self.snake_sections: section.goto(1000, 1000) self.snake_sections.clear() self.snake_body() self.head = self.snake_sections[0]
007b7f38d0ef48be92a26362109b03c8aa2189f7
JoaoBatistaJr/Cuso-Intensivo-de-Python-Projeto-Pygame-Aliens
/ship.py
1,356
3.703125
4
import pygame class Ship: """Classe que controla a espaรงonave.""" def __init__(self, ai_game): """Inicializa a espaรงonave e a coloca na posiรงรฃo.""" self.screen = ai_game.screen self.settings = ai_game.settings self.screen_rect = ai_game.screen.get_rect() # Carrega a imagem da espaรงonave e posiciona em rect. self.image = pygame.image.load('images/ship.bmp') self.rect = self.image.get_rect() # Iniciar a nava na parte inferior central da tela. self.rect.midbottom = self.screen_rect.midbottom # Armazena um valor descimal para a posiรงรฃo horizontal da espaรงonave. self.x = float(self.rect.x) # Flags de movimento self.moving_right = False self.moving_left = False def update(self): """Atualiza a posiรงรฃo da nave com base nas flags de movimento""" # Atualiza o valor x da nave e nao o de rect if self.moving_right and self.rect.right < self.screen_rect.right: self.x += self.settings.ship_speed if self.moving_left and self.rect.left > 0: self.x -= self.settings.ship_speed # Atualiza o rect do self.x self.rect.x = self.x def blitme(self): """Desenha a nave na posiรงรฃo atual""" self.screen.blit(self.image, self.rect)
e0646d5163bdc26d2b81d0b08b418267e09ab4ec
AlyoshaS/codes
/startingPoint/01-EstruturasCondicionais/exercicios_propostos/14.py
2,561
4.09375
4
""" 14 - Faรงa um programa que receba o valor do salรกrio mรญnimo, o nรบmero de horas trabalhadas, o nรบmero de dependentes do funcionรกrio e a quantidade de horas extras trabalhadas. Calcule e mostre o salรกrio a receber do funcionรกrio de acordo com as regras a seguir: O valor da hora trabalhada รฉ igual a quinta parte do salรกrio mรญnimo. O salรกrio do mรชs รฉ igual ao nรบmero de horas trabalhadas multiplicado pelo valor da hora trabalhada. Para cada dependente, acrescentar R$ 32,00. Para cada hora extra trabalhada, calcular o calor da hora trabalhada acrescida de 50%. O salรกrio bruto รฉ igual ao salรกrio do mรชs mais o valor dos dependentes mais o valor das horas extras. Calcular o valor do imposto de renda retido na fonte de acordo com a tabela a seguir: IRRF SALรRIO BRUTO Isento Inferior a R$ 200,00 10% De R$ 200,00 atรฉ R$ 500,00 20% Superior a R$ 500,00 O salรกrio lรญquido รฉ igual ao salรกrio bruto menos IRRF. A gratificaรงรฃo de acordo com a tabela a seguir: SALรRIO LรQUIDO GRATIFICAร‡รƒO Atรฉ R$ 350,00 R$ 100,00 Superior a R$ 350,00 R$ 50,00 O salรกrio a receber do funcionรกrio รฉ igual ao salรกrio lรญquido mais a gratificaรงรฃo. """ # DEFINE O IMPOSTO DE RENDA imposto_0 = 0 imposto_10 = 0.10 imposto_20 = 0.20 # DEFINE A GRATIFICACAO gratificacao_100 = 100 gratificacao_50 = 50 salario_min = int(input("Digite o valor do salรกrio mรญnimo: ")) numero_horast = int(input("Digite o nรบmero de horas trabalhadas: ")) dependentes = int(input("Digite o nรบmero de dependentes: ")) numero_horas_extrast = int(input("Digite o nรบmero de horas extras trabalhadas: ")) # DEFINE SALARIO BRUTO valor_hora = 1 / 5 * salario_min salario_mes = numero_horast * valor_hora valor_dependentes = 32 * dependentes valor_horae = numero_horas_extrast * (valor_hora + (valor_hora * 50 / 100)) salario_bruto = salario_mes + valor_dependentes + valor_horae # CALCULA IMPOSTO: if(salario_bruto < 200): imposto = imposto_0 if(salario_bruto >= 200) and (salario_bruto <= 500): imposto = salario_bruto * imposto_10 if(salario_bruto> 500): imposto = salario_bruto * imposto_20 salario_liquido = salario_bruto - imposto # CALCULA GRATIFICACAO: if(salario_liquido <= 350): gratificacao = gratificacao_100 if(salario_liquido > 350): gratificacao = gratificacao_50 # DEFINE SALARIO A RECEBER: salario_receber = salario_liquido + gratificacao print("O salรกrio ร  receber serรก: R$", salario_receber)
3325622b2c9e2c6b874c59fd7b07d189ad4b60eb
pythonwithalex/Spring2015
/week6/twitter/4_tweets_to_file.py
608
3.59375
4
# get a Twitter API key # run this as 'python script.py > output.txt' to store the json data in a file import tweepy import json consumer_key = '' consumer_secret = '' access_token = '' access_token_secret = '' auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth) max_tweets=100 query='#redsox' tweets = [status._json for status in tweepy.Cursor(api.search, since_id="2015-05-13",until="2015-05-14", q=query).items(max_tweets)] #tweet_file = open('output.txt','w') tweet_count = 0 for tweet in tweets: print tweet
a87e543bf4f0eef77929a9d4299bfae4088131bf
MaxRaine/Max_Rain-_TE19D
/programmering/Blackjack/blackjack.py
1,961
3.71875
4
import kortlek # behรถver rรคkna ut vรคrden pรฅ korten def rรคknaPoรคng(hand): poรคng = 0 for kort in hand: if kort == "J" or kort == "Q" or kort == "K": poรคng += 10 elif kort == "A" and poรคng < 11: poรคng += 11 elif kort == "A" and poรคng >= 11: poรคng += 1 else: poรคng += kort return poรคng # skriv handen def skrivUtHanden(hand): print("Dina kort รคr: ", end="") for kort in hand: print(str(kort) + ", ", end="") # checka vinnare def checkaVinnare(hand, dealer): dealerPoรคng = rรคknaPoรคng(dealer) spelarePoรคng = rรคknaPoรคng(hand) print(f"Dealerns kort รคr {dealer[0]} och {dealer[1]}") print(f"Dealerns totala poรคng รคr {dealerPoรคng}") print(f"Din totala poรคng รคr {spelarePoรคng}") if spelarePoรคng == 21: print("Blackjack, du vinner!") elif spelarePoรคng <= dealerPoรคng or spelarePoรคng > 21: print("Dealern tar dina pengar") else: print("Du vinner") # spel-loop while True: spela = input("Vill du spela blackjack? (j fรถr ja, annan tangent fรถr nej)") if spela != "j": break lek = kortlek.skapaKortlek() # dealer tar tvรฅ kort print(lek) dealer = [lek.pop(0), lek.pop(0)] print(f"Dealerns fรถrsta kort รคr {dealer[0]}") hand = [lek.pop(0), lek.pop(0)] print(f"Dina fรถrsta tvรฅ kort รคr: {hand[0]} och {hand[1]}") fortsรคtt = True # gรถra val (ta ett till kort eller stanna) while fortsรคtt: # frรฅga anvรคndaren om hen vill ta ett kort taKort = input( "Ta nytt kort? (j fรถr ja, annan tangent fรถr att stanna)") if taKort == "j": #dela ut ett kort hand.append(lek.pop(0)) #skriv ut hand skrivUtHanden(hand) else: fortsรคtt = False checkaVinnare(hand, dealer) print("Spelet slutar har en bra dag")
4593f273aa303179b363399385c3fea5c43ab4c8
JessRogeliana/Estudando_Python
/Python 1/Semana 3/fizzbuzz.py
138
4.0625
4
numero = int(input("Digita um nรบmero aรช: ")) if ((numero % 5 == 0) and (numero % 3 == 0)): print("FizzBuzz") else: print(numero)
31c2affe0122aad341f05d9752c59c1186d113e0
Jennysgithub/learn_python_the_hard_way
/working_with_files_1.py
396
3.5625
4
from sys import argv file_name, from_file, to_file = argv from_fh = open(from_file) indata = from_fh.read() username = raw_input("What is your name?") to_fh = open(to_file, 'w') line1 = "Hello {}, here is some text from another file: \n".format(username) to_fh.write(line1) to_fh.write(indata) line2 = "\nGoodbye {}".format(username) to_fh.write(line2) from_fh.close() to_fh.close()
f2c892376027f13fb5b7e225ff62ad248d13779d
ArronHZG/algorithm-with-python
/leetcode/binarySearch/154_findMin.py
1,802
3.984375
4
import unittest from typing import List class Solution: def findMin(self, nums: List[int]) -> int: left, right = 0, len(nums) - 1 while left < right: mid = (left + right) >> 1 print(f"left {left} mid {mid} right {right}") if nums[mid] > nums[right]: left = mid + 1 elif nums[mid] < nums[right]: right = mid else: right -= 1 return nums[left] class Test(unittest.TestCase): def test_one(self): nums = [4, 5, 6, 7, 0, 1, 2] answer = 0 result = Solution().findMin(nums) self.assertEqual(answer, result) def test_two(self): nums = [1, 1, 2, 2, 3] answer = 1 result = Solution().findMin(nums) self.assertEqual(answer, result) def test_three(self): nums = [1, 1, 1, 0, 0, 0, 0] answer = 0 result = Solution().findMin(nums) self.assertEqual(answer, result) def test_four(self): nums = [1, 1, 1, 0, 1] answer = 0 result = Solution().findMin(nums) self.assertEqual(answer, result) def test_five(self): nums = [1, 1, 2, 0, 0, 1] answer = 0 result = Solution().findMin(nums) self.assertEqual(answer, result) def test_six(self): nums = [3, 3, 1, 3] answer = 1 result = Solution().findMin(nums) self.assertEqual(answer, result) def test_seven(self): nums = [3, 3, 3, 3] answer = 3 result = Solution().findMin(nums) self.assertEqual(answer, result) def test_eight(self): nums = [3, 1, 3, 3, 3] answer = 1 result = Solution().findMin(nums) self.assertEqual(answer, result)
94a852760250df8fccadd14a7136a00cb902caff
wenima/data-structures
/src/binheap.py
2,959
4
4
"""Implementation of the binheap data structure. A binary heap is defined as a binary tree with two additional constraints: Shape property: a binary heap is a complete binary tree; that is, all levels of the tree, except possibly the last one (deepest) are fully filled, and, if the last level of the tree is not complete, the nodes of that level are filled from left to right. Heap property: the key stored in each node is either greater than or equal to or less than or equal to the keys in the node's children, according to some total order. Taken from: https://en.wikipedia.org/wiki/Binary_heap """ class Binheap(object): """Create a binary heap tree structure.""" def __init__(self, maybe_an_iterable=None): """Initialize an instance of the binheap.""" self._heap = [0] self._size = 0 if maybe_an_iterable: try: for value in maybe_an_iterable: value + 0 self._heap.append(value) except TypeError: return "Only an iterable of integers is an accepted input" for item in reversed(maybe_an_iterable): self._raise_up(self._heap[1:].index(item) + 1) self._size = len(self._heap) - 1 def push(self, value): """Push a new value to the heap.""" self._heap.append(value) self._raise_up(len(self._heap) - 1) self._size += 1 def pop(self): """Remove the root node from the tree.""" if self._size == 0: raise IndexError("You can't remove the head of an empty binary heap") root = self._heap[1] self._heap[1] = self._heap[-1] del self._heap[-1] self._size -= 1 self._sink_down(1) return root def _raise_up(self, i): """Raise i into the tree until the tree structure is satisfied.""" while i // 2 > 0: if self._heap[i] < self._heap[i // 2]: self._heap[i], self._heap[i // 2] = self._heap[i // 2], self._heap[i] i = i // 2 return self._heap def _sink_down(self, i): """Sink the input node down the tree until the tree structure is satisfied.""" if self._size != 0: parent = self._heap[i] while i * 2 < len(self._heap): child = self._heap[self._get_min_child(i)] idx_child = self._get_min_child(i) if parent > child: self._heap[i], self._heap[idx_child] = self._heap[idx_child], self._heap[i] parent = self._heap[idx_child] i = idx_child return self._heap return self._heap def _get_min_child(self, i): """Determine the smaller of two children.""" if i * 2 == self._size: return i * 2 if self._heap[i * 2] > self._heap[i * 2 + 1]: return i * 2 + 1 else: return i * 2
71656850c1d3095179cb45175f1136fb4c503dca
ShuaiWang0410/LeetCode-2nd-Stage
/LeetCode-Stage2/Tricks/Problem_90.py
970
3.609375
4
''' 90. Subsets II Deepin of Problem 78 ่ฟ™ๆฌก็š„้›†ๅˆไธญๅ…ƒ็ด ๆœ‰duplicate๏ผŒไฝ†ไธ่ƒฝ่พ“ๅ‡บduplicate Input: [1,2,2] Output: [ [2], [1], [1,2,2], [2,2], [1,2], [] ] ''' class Solution(object): def subsetsWithDup(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ nums = sorted(nums) sets = [] sets.append([]) last = '' dup_end = -1 for i in nums: if last == i: l = len(sets) tsets = [] for j in sets[dup_end:]: tsets.append(j + [i]) sets += tsets dup_end = l else: dup_end = len(sets) tsets = [] for j in sets: tsets.append(j + [i]) sets += tsets last = i return sets c = Solution() print(c.subsetsWithDup([]))
b2c590ef0417d15ffc7a69abe7914e264ab82803
ynonp/python3-beginners
/18-datastructures-examples/ab.py
1,067
3.703125
4
import sys DATAFILE = 'contacts.txt' def load_datafile(): contacts = {} try: with open(DATAFILE, 'r') as f: for line in f: words = line.split() name = words[0] emails = words[1:] contacts[name] = emails except FileNotFoundError: pass return contacts def save_datafile(contacts): with open(DATAFILE, 'w') as f: for name, emails in contacts.items(): f.write("{} {}\n".format(name, ' '.join(emails))) def add_new_contact(contacts, name, email): email_list = contacts.get(name, []) email_list.append(email) contacts[name] = email_list def get_mail_for_contact(contacts, name): print("Emails: {}".format(contacts.get(name))) contacts = load_datafile() if len(sys.argv) == 2: get_mail_for_contact(contacts, sys.argv[1]) elif len(sys.argv) > 2: add_new_contact(contacts, sys.argv[1], sys.argv[2]) save_datafile(contacts) else: sys.exit("Missing name")
5f1843c3c7bd53852ab7459c22f459553d8e81d2
hsclinical/leetcode
/Q03__/22_Coin_Change/Solution.py
1,484
4.03125
4
from typing import List class Solution: def coinChange(self, coins: List[int], amount: int) -> int: # similar to the question that use combination of substring to build a whole string # use recursive if amount == 0: return 0 else: coins.sort(reverse=True) minCoinNum = {} return self.coinCombination(coins, amount, minCoinNum) # input coins have been sorted from the largest to the smallest def coinCombination(self, coins, amount, minCoinNum): if amount in minCoinNum: return minCoinNum[amount] if amount < coins[-1]: minCoinNum[amount] = -1 return -1 elif amount in coins: minCoinNum[amount] = 1 return 1 else: found = False outAll = -1 for coin in coins: if coin < amount: outSingle = self.coinCombination(coins, amount-coin, minCoinNum) if outSingle != -1: if outAll == -1: outAll = outSingle else: if outAll > outSingle: outAll = outSingle found = True if found: minCoinNum[amount] = outAll + 1 return outAll + 1 else: minCoinNum[amount] = -1 return -1
b33d2e95dbc65d1ccc5c2bfecaa28408dc1192cb
JosephLevinthal/Research-projects
/5 - Notebooks e Data/1 - Anรกlises numรฉricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/223/users/4444/codes/1679_1099.py
217
3.921875
4
area = int(input("Digite a รกrea a ser pintada: ")) litros = area//3 if area % 3 > 0: litros = litros + 1 latas = litros//18 if litros % 18 > 0: latas = latas + 1 print("Vocรช precisara de", latas, "latas.") print("
4f9fe3c1b6ccdf7722b02c830ef9fd73c2103514
paleolimbot/wss
/rras/rstools.py
16,932
3.640625
4
import json import random MAX_ITERATIONS = 10000 def order_choices(choices): """Orders the choices used consistently every time""" order = ["Yes", "No", "Always", "Frequently", "Occasionally", "Sometimes", "Never", "Above Compliance", "Meets Compliance", "Less than Compliance"] return list(sorted(choices, key=lambda choice: order.index(choice) if choice in order else len(order))) def get_choices(obj): """Gets the (ordered) choices from all the dictionaries in the (question) object""" choices = set() for value in obj.values(): if isinstance(value, dict) and "question" not in value: for key in value: choices.add(key) return order_choices(choices) def get_dependent_questions(obj): """Get (direct) dependent questions of an object so they may be iterated through""" if not isinstance(obj, dict): return {} questions = {} for value in obj.values(): if isinstance(value, dict): for choice, question in value.items(): if isinstance(question, dict) and "question" in question: if choice not in questions: questions[choice] = [] questions[choice].append(question) return questions def get_independent_questions(obj): """Get (direct) child questions of an object so they may be iterated through. Could be either a list of a value or the value itself""" questions = [] if isinstance(obj, dict): for value in obj.values(): if isinstance(value, list): for question in value: if isinstance(question, dict) and "question" in question: questions.append(question) elif isinstance(value, dict) and "question" in value: questions.append(value) elif isinstance(obj, list): for value in obj: if isinstance(value, dict) and "question" in value: questions.append(value) return questions def add_ids(obj, questions=None): """Recursively walks through questions and generates unique IDs for each, making sure key orders remain consistent (for ID stability)""" if questions is None: questions = [] if isinstance(obj, dict): if "question" in obj: obj["_id"] = len(questions) questions.append(len(questions)) choices = get_choices(obj) for key in sorted(obj.keys()): if isinstance(obj[key], dict): for choice in choices: if choice in obj[key]: add_ids(obj[key][choice], questions) else: add_ids(obj[key], questions) else: for key in sorted(obj.keys()): add_ids(obj[key], questions) elif isinstance(obj, list): for value in obj: add_ids(value, questions) def add_dependency(obj, dependency, dependencies, follow_lists): """drill down to add a single dependency and keep track of which objects use those dependencies (used in add_dependencies()). Parent/child relations follow dependencies in questions, where dependency relations require question/subquestion answering. These are used for different purposes in the flat version of the survey. Passing follow_lists=False will result in a dependency relation, True will result in a parent/child one.""" if isinstance(obj, dict) and "question" in obj: depkey = "parents" if follow_lists else "dependencies" if depkey not in obj: obj[depkey] = [] obj[depkey].append(dependency) dependencies.append(obj["_id"]) if isinstance(obj, dict): for value in obj.values(): add_dependency(value, dependency, dependencies, follow_lists) elif isinstance(obj, list) and follow_lists: for value in obj: add_dependency(value, dependency, dependencies, follow_lists) def add_next_question(obj, next_id=None): # avoid re-adding next_question (happens with lax dependent/independent question rules) if isinstance(obj, dict) and "next_question" in obj: return dependent_questions = get_dependent_questions(obj) independent_questions = get_independent_questions(obj) # go through independent questions first for j in range(len(independent_questions)): if j == len(independent_questions)-1: # if last question, pass to parent next_id add_next_question(independent_questions[j], next_id) else: # use the next question's id add_next_question(independent_questions[j], independent_questions[j+1]["_id"]) # assess dependents if isinstance(obj, dict) and "question" in obj: next_id = independent_questions[0]["_id"] if independent_questions else next_id next_questions = {} for choice in get_choices(obj): if choice in dependent_questions: # there is a sub question. use the first as the next question and recursively add next question to that # using next_id as the next question next_questions[choice] = dependent_questions[choice][0]["_id"] depquests = dependent_questions[choice] for i in range(len(depquests)): if i == (len(depquests)-1): # last question, use next_id for recursion add_next_question(depquests[i], next_id) else: # use next question id for this choice for recursion add_next_question(depquests[i], depquests[i+1]["_id"]) else: # this is an endpoint. use next_id for this choice next_questions[choice] = next_id obj["next_question"] = next_questions # recursively pass on to non-questions if isinstance(obj, dict): for value in obj.values(): if not isinstance(value, dict) or "question" not in value: add_next_question(value, next_id) elif isinstance(obj, list): for value in obj: if not isinstance(value, dict) or "question" not in value: add_next_question(value, next_id) def add_dependencies(obj, next_id=None): """Adds dependency information (i.e. the next question ID to show given an answer)""" if isinstance(obj, dict): if "question" in obj: dependents = [] children = [] dependent_questions = get_dependent_questions(obj) independent_questions = get_independent_questions(obj) # iterate through direct dependents for choice, questions in dependent_questions.items(): for question in questions: # add dependencies add_dependency(question, obj["_id"], dependents, follow_lists=False) # add parent/child relations add_dependency(question, obj["_id"], children, follow_lists=True) # iterate through direct independents for question in independent_questions: # dependency relations are not meaningful here, just parent/child add_dependency(question, obj["_id"], children, follow_lists=True) obj["dependents"] = dependents obj["children"] = children if "dependencies" not in obj: obj["dependencies"] = [] if "parents" not in obj: obj["parents"] = [] for value in obj.values(): add_dependencies(value) elif isinstance(obj, list): for value in obj: add_dependencies(value) def add_recursion_level(obj, level=0): if isinstance(obj, dict): if "question" in obj: obj["level"] = level level += 1 for value in obj.values(): add_recursion_level(value, level) elif isinstance(obj, list): for value in obj: add_recursion_level(value, level) def question_list(obj, questions=None): """Generates a flat list of questions with relevant information for printing (but not scoring)""" if questions is None: questions = [] if isinstance(obj, dict): if "question" in obj: choices = get_choices(obj) qout = {"choices": choices} for key in ("_id", "question", "level", "next_question", "answer", "comment", "children", "parents", "dependents", "dependencies", "title"): if key in obj: qout[key] = obj[key] questions.append(qout) for value in obj.values(): question_list(value, questions) elif isinstance(obj, list): for value in obj: question_list(value, questions) return questions def flatten(survey): add_ids(survey) add_next_question(survey) add_dependencies(survey) add_recursion_level(survey) flat = question_list(survey) return list(sorted(flat, key=lambda x: x["_id"])) def merge_list(obj1, obj2): """Merge two objects together as lists""" if not isinstance(obj1, list): obj1 = [obj1, ] if not isinstance(obj2, list): obj2 = [obj2, ] return obj1 + obj2 def merge_dicts(d1, d2, key, list_merge): if "question" in d2: for k, v in d2.items(): if k in list_merge and k in d1: d1[k] = merge_list(d1[k], v) else: d1[k] = v if d1[key] is d2: del d1[key] def has_sub_questions(obj): for v in obj.values(): if isinstance(v, dict) and "question" in v: return True def recursive_merge(obj, list_merge=("question", "answer", "_id", "comment", "message")): if isinstance(obj, dict): # introducing niter ensures the process never gets stuck in an infinite loop niter = 0 while has_sub_questions(obj): if niter > MAX_ITERATIONS: raise ValueError("Infinite loop detected in recursive merge operation for obj %s" % obj) niter += 1 for key in list(obj.keys()): if isinstance(obj[key], dict): merge_dicts(obj, obj[key], key, list_merge) break for k, v in obj.items(): obj[k] = recursive_merge(v, list_merge) return obj elif isinstance(obj, list): return [recursive_merge(value, list_merge) for value in obj] else: return obj def evaluate(obj, answers): """Uses the answer key to 'take' the survey and collapse back values""" if isinstance(obj, dict): if "question" in obj: answer = answers[obj["_id"]]["answer"] if "answer" in answers[obj["_id"]] else None obj["answer"] = answer # evaluate keys that depend on the answer. if there is no answer, we have to assume that # these are all the sub-dicts in this object and return none for these keys if not answer: for key in list(obj.keys()): if isinstance(obj[key], dict): obj[key] = None elif isinstance(obj[key], list): obj[key] = [evaluate(v, answers) for v in obj[key]] else: keys = [] for key, value in obj.items(): if isinstance(value, dict) and answer in value: keys.append(key) for key in keys: obj[key] = evaluate(obj[key][answer], answers) # evaluate keys that do not depend on the answer for key in set(obj.keys()).difference(set(keys)): obj[key] = evaluate(obj[key], answers) return obj else: out = {} for key, value in obj.items(): out[key] = evaluate(value, answers) return out elif isinstance(obj, list): return [evaluate(value, answers) for value in obj] else: return obj def shell_ask(question, choices): """Generates an answer to a question from shell input""" prompt = "\n".join([question, ] + ["[%s] %s" % (i + 1, choice) for i, choice in enumerate(choices)] + ["Enter number: ", ]) while answer is None: try: answer = int(input(prompt)) if 1 <= answer <= len(choices): answer = choices[answer-1] except ValueError: pass if answer is None: print("Please enter a number corresponding to the correct choice.") return answer def random_choice(question, choices): """Generates a random answer to question""" return random.choice(choices) def shell_survey(obj, ask): """Turns questions into values""" if isinstance(obj, dict): if "question" in obj: choices = get_choices(obj) answer = ask(obj["question"], choices) obj["answer"] = answer out = {} for key, value in obj.items(): out[key] = shell_survey(value[answer], ask) if isinstance(value, dict) else shell_survey(value, ask) return obj else: out = {} for key, value in obj.items(): out[key] = shell_survey(value, ask) return False elif isinstance(obj, list): return [shell_survey(item, ask) for item in obj] else: return obj if __name__ == "__main__": # command line interface import argparse try: from tools_common import internal_fail, get_json, do_output, check_output_file except ImportError: from .tools_common import internal_fail, get_json, do_output, check_output_file parser = argparse.ArgumentParser("Recursive Survey Tools") parser.add_argument("action", help="The action to perform on the survey JSON", choices=("flatten", "id", "evaluate", "random", "test")) parser.add_argument("input", help="JSON file or escaped JSON to use as survey input") parser.add_argument("-a", "--answers", help="The JSON file or escaped json to use as answer key for action 'evaluate'") parser.add_argument("-o", "--output", help="The output file (missing for STDOUT)") args = parser.parse_args() action = args.action survey = get_json(args.input, "input") answers = get_json(args.answers, "answers") if args.answers else None outfile = args.output # ensure evaluate/answer options are consistent if action in "evaluate" and answers is None: internal_fail("Option '--answers' is required for action 'evaluate'") elif action != "evaluate" and answers is not None: internal_fail("Option '--answers' is not required for action '%s'" % action) check_output_file(outfile) # get output based on action try: output = {} if action == "flatten": output = flatten(survey) elif action == "id": add_ids(survey) output = survey elif action == "evaluate": add_ids(survey) output = evaluate(survey, answers) output = recursive_merge(output) elif action == "random": shell_survey(survey, random_choice) output = flatten(survey) elif action == "survey": shell_survey(survey, shell_ask) output = survey elif action == "test": import copy # test that ID creation is stable print("test that id creation is stable") original = copy.deepcopy(survey) add_ids(original) for i in range(10): s = copy.deepcopy(survey) add_ids(s) if json.dumps(s) != json.dumps(original): raise ValueError("non-stable id creation") print("...pass") # test that flattening creation is stable print("test that flattening creation is stable") original = copy.deepcopy(survey) original_flat = flatten(original) for i in range(10): s = copy.deepcopy(survey) sf = flatten(s) if json.dumps(sf) != json.dumps(original_flat): raise ValueError("non-stable flat survey creation") print([q["_id"] for q in sf]) print("...pass") else: internal_fail("unsupported action: " % action) do_output(output, outfile) except Exception as e: internal_fail("Error executing action '%s' (%s: %s)" % (action, type(e).__name__, e))
231f6d19572a51af407faf5192d84d58051e02eb
SaeSimcheon/employee_or_farm
/Chapter3/4. ๋‘ ๋ฆฌ์ŠคํŠธ ํ•ฉ์น˜๊ธฐ/SH_cht3_4.py
467
3.5
4
import sys sys.stdin = open("cht3_4_input.txt","rt") n1 = int(input()) list1 = list(map(int,input().split())) n2 = int(input()) list2 = list(map(int,input().split())) list1.extend(list2) list1.sort() print(*list1) # ์ค‘๋ณต์„ ์—†์•จ ํ•„์š”๋„ ์—†๊ณ  ๊ทธ๋ƒฅ ๋‘ ๊ฐœ ๋ฆฌ์ŠคํŠธ ํ•ฉ์น  ๋ฐฉ๋ฒ•๋งŒ ์ƒ๊ฐํ•˜๋ฉด ๋์—ˆ์Œ. # 1๊ฐœ list๋ฅผ ํ™•์žฅํ•˜๋Š” ๋ฐฉ๋ฒ•์œผ๋กœ, ๊ตฌ์ฒด์ ์œผ๋กœ extend๋ฅผ ํ†ตํ•˜์—ฌ ๋‘ ๊ฐœ ๋ฆฌ์ŠคํŠธ๋ฅผ ํ•˜๋‚˜๋กœ ๋งŒ๋“ค์–ด ์ฃผ์—ˆ๊ณ , # sort๋กœ ์ •๋ ฌ
e95db27d4c5ae8a3dfcfbe22a240e145e2b77f2c
Taha-Topac/LearningPython
/src/KullanฤฑcฤฑGiriลŸi.py
337
3.5625
4
a1 = "taha" a2 = 159753 a3=input("Adฤฑnฤฑzฤฑ girin:") a4=int(input("ลžifrenizi ลŸifrenizi:")) if ( a1==a3) and (a2==a4): print("GiriลŸ baลŸarฤฑlฤฑ !!! ") elif ( a1!=a3) and (a2==a4): print("Kullamฤฑcฤฑ adฤฑ yanlฤฑลŸ !!! ") elif ( a1==a3) and (a2!=a4): print("ลžifre hatalฤฑ !!!! ") else: print("Tekrar deneyin !!! ")
102ead847cc85f2b6ce58bde8c56237d8467dc25
AbdulMoizChishti/pythonpractice
/guessgame.py
322
4.09375
4
import random num=0 print("Welcome to Guessing game") rv = random.randint(1, 21) for i in range(1,6): num= int(input("Select number")) if num<rv: print("number is less than rv") elif num>rv: print("number is greater than rv") else: print("your ans is correct") break
e5bbb0316c486edf53e6447f97891e14b4e095eb
egrabs/DailyCodingProblem
/elyes/139_eg.py
1,194
4
4
# Given an iterator with methods next() and hasNext(), create a wrapper iterator, # PeekableInterface, which also implements peek(). peek shows the next element that would be returned on next(). # Here is the interface: # class PeekableInterface(object): # def __init__(self, iterator): # pass # def peek(self): # pass # def next(self): # pass # def hasNext(self): # pass class Empty(Exception): pass class PeekableInterface(object): def __init__(self, iterator): self.iterator = iterator self.peeked = None def peek(self): if self.peeked != None: return self.peeked elif self.iterator.hasNext(): nextEl = self.iterator.next() self.peeked = nextEl return nextEl else: raise Empty() def next(self): if self.peeked != None: tmp = self.peeked self.peeked = None return tmp elif self.iterator.hasNext(): return self.iterator.next() else: raise Empty() def hasNext(self): return self.peeked != None or self.iterator.hasNext()
265d5b8a99faeb93b29929b1d5bb7c0790fdb043
secfordoc23/MyFirstRepository
/Assignment1/CelsiusToFahrenheitUtility.py
731
4.0625
4
""" Program: Celsius to Fahrenheit Utility File: CelsiusToFahrenheitUtility.py Author: Jason J. Welch Date: 8/24/2019 Purpose: A utility to calculate the degrees Fahrenheit from entered degrees Celsius """ print('*******************************') print(' Celsius to Fahrenheit Utility') print('*******************************') # Enter Temperature in Celsius tempInCelsius = float(input('Enter the temperature in degrees celsius: ')) # Convert Celsius to Fahrenheit # FORMULA: degreesCelsius1 * 9/5 + 32 or degreesCelsius * 1.8 + 32 tempInFahrenheit = float((tempInCelsius * 1.8) + 32) # Display Temperature in Fahrenheit print('\n*******************************\n') print(f'Temperature in Fahrenheit: {tempInFahrenheit}')
a186e23db6e1be81781da4e3a8d5fd2ae4658865
manojakumarpanda/This-is-first
/sequence/set and list and dict/uper_lower_diognal mat.py
847
4
4
#program to take a n*n matrics and print all the uper matrics and lower matrics and diogna matrics m=int(input('Enter the number of row and collumn in to the matrixs::')) mat=[] i=0 while i<m: mat.append([]) i+=1 for i in range(m): for j in range(m): ele=int(input('Enter a element for the matrxs mat[{0}][{1}]'.format(i,j))) mat[i].append(ele) for i in range(m): for j in range(m): if i<=j: print(mat[i][j],end=' ') else: print(' ',end=' ') print() for i in range(m): for j in range(m): if j<=i: print(mat[i][j],end=' ') else: print(' ',end=' ') print() for i in range(m): for j in range(m): if j==i: print(mat[i][j],end=' ') else: print(' ',end=' ') print()
5a895f41f33695f6ea6909b40c034879c22df084
zingelst/PiecesOfPy
/cmd/argparse_subparse.py
2,263
4.0625
4
# Example of using argparse with sub parsers, useful for # building interfaces like that of the docker cli import argparse def sub1_cmd(args): """The command that gets called if user uses the sub1 command on the commandline""" print("This is sub1") print("You passed args:", str(args)) def sub2_cmd(args): """The command that gets called if user uses the sub2 command on the commandline""" print("This is sub2") print("You passed args:", str(args)) def run(): # Create a parser object parser = argparse.ArgumentParser(description='Example of using argparse with subcommands') # Add a subparser to the parser subparsers = parser.add_subparsers() # Use the subparser to create sub parser (duh) sub1 = subparsers.add_parser('cmd1', help='Subcommand 1') # Some simple arguments, use the sub1 parser like any normal ArgParser sub1.add_argument('-a',type=str, default='option', help='cmd1 a option') sub1.add_argument('-b',type=int, default=42, help='cmd1 b option') # Set a function to be called if the user picks command 'sub1' # this is a trick from the documentation. We just put in our own default # variable and use it to store a function reference to use. sub1.set_defaults(cmd_func=sub1_cmd) # Do the same for another command. Add as many of these as you like sub2 = subparsers.add_parser('cmd2', help='Subcommand 2') sub2.add_argument('-a',type=str, default='optiona', help='cmd2 a option') sub2.add_argument('-b',type=str, default='optionb', help='cmd2 b option') sub2.add_argument('-c',type=str, default='optionc', help='cmd2 c option') # Use a different function if user picks 'sub2' command sub2.set_defaults(cmd_func=sub2_cmd) # ok, parse out the args provided in sys.argv (per documentation) args = parser.parse_args() # If the user picked no command at the command line, we won't have # a cmd_func (unless you add one with parser.set_defaults(cmd_func=...)) # So, if that's the case, just print the help and quit if 'cmd_func' in args: # Provide the args that were parsed to the sub command we're calling args.cmd_func(args) else: parser.print_help() if __name__ == "__main__": run()
e112bf1c2729e0e4d808cf65ee06ce22f7f9b676
topliceanu/learn
/python/algo/src/strassen_array_multiplication.py
4,068
4.125
4
# -*- coding: utf-8 -*- def op (x, y, op = '+'): """ Liniar operation over two square matrices. Args: x: array of size n*n y: array of size n*n op: str with operations to apply on two arrays, can be either + or - Returns: A 2D list resulting from applying op to each element of x and y. """ n = len(x) out = [] for i in xrange(n): line = [] for j in xrange(n): if op is '+': res = x[i][j] + y[i][j] elif op is '-': res = x[i][j] - y[i][j] line.append(res) out.append(line) return out def add (x, y): """ Adds two square arrays. """ return op(x, y, '+') def sub (x, y): """ Subtracts two square arrays. """ return op(x, y, '-') def arr_section (x, m, n, o, p): """ Method extracts an array section of the original array x, denoted by lines m through n and columns o through p. """ out = [] for i in range(m, n): line = [] for j in range(o, p): line.append(x[i][j]) out.append(line) return out #return [x[i][o:p] for i in range(m, n)] def arr_join (a, b, c, d): """ Recomposes an array from for four equal-sized section arrays as follows: x = (a b) (c d) """ out = [] n = len(a) for i in range(n): line = [] for j in range(n): line.append(a[i][j]) for j in range(n): line.append(b[i][j]) out.append(line) for i in range(n): line = [] for j in range(n): line.append(c[i][j]) for j in range(n): line.append(d[i][j]) out.append(line) return out def strassen_array_multiplication (x, y): """ Multiplies two array using the strassen algorithm. Ie. splits x and y into four sectors each: x = (a b) y = (e f) x*y = (ae+bg af+bh) (c d) (g h) (cd+dg cf+dh) It then computes the 7 strassen coeficients recursively: p1 = a(f-h) p2 = (a+b)h p3 = (c+d)e p4 = d(g-e) p5 = (a+d)(e+h) p6 = (b-d)(g+h) p7 = (a-c)(e+f) Finally compute x*y components using the strassen coeficients: ae+bg = p5 + p4 - p2 + p6 af+bh = p1 + p2 ce+dg = p3 + p4 cf+dh = p1 + p5 - p3 - p7 NOTE: to make it work for mxn * nxm or for the cases where n is not a multiple of 2 a padding of 1s can be added. Complexity: O(n^2) Args: x: list, square array of nxn, where n is a multiple of 2 y: list, square array of nxn, where n is a multiple of 2 Returns: A 2D array. """ n = len(x) # width/height of both arrays. if n is 2: a = x[0][0] b = x[0][1] c = x[1][0] d = x[1][1] e = y[0][0] f = y[0][1] g = y[1][0] h = y[1][1] aebg = a*e + b*g afbh = a*f + b*h cedg = c*e + d*g cfdh = c*f + d*h return [ [aebg, afbh], [cedg, cfdh] ] else: m = int(n/2) a = arr_section(x, 0, m, 0, m) b = arr_section(x, 0, m, m, n) c = arr_section(x, m, n, 0, m) d = arr_section(x, m, n, m, n) e = arr_section(y, 0, m, 0, m) f = arr_section(y, 0, m, m, n) g = arr_section(y, m, n, 0, m) h = arr_section(y, m, n, m, n) p1 = strassen_array_multiplication(a, sub(f, h)) p2 = strassen_array_multiplication(add(a, b), h) p3 = strassen_array_multiplication(add(c, d), e) p4 = strassen_array_multiplication(d, sub(g, e)) p5 = strassen_array_multiplication(add(a, d), add(e, h)) p6 = strassen_array_multiplication(sub(b, d), add(g, h)) p7 = strassen_array_multiplication(sub(a, c), add(e, f)) aebg = add(sub(add(p5, p4), p2), p6) afbh = add(p1, p2) cedg = add(p3, p4) cfdh = sub(sub(add(p1, p5), p3), p7) out = arr_join(aebg, afbh, cedg, cfdh) return out
eaacea6bfecffef36dd39a7ac37780fac1f2eedd
maximusg/Python_Game
/highscore.py
5,601
3.71875
4
#CONSTANTS MAX_ENTRIES = 20 #Change this to grow or shrink the high score list class Scoreboard(object): '''Linked List data structure that contains the High Score List for Day0.''' class Entry(object): '''Object representing a single entry within the overall Scoreboard class. Contains: name - Must be a string. score - Must be an integer. nextEntry - Must point to the next Entry object in the list (can be None). ''' def __init__(self, name, score): '''Initializes Entry with string name and int score.''' self.name = name self.score = score self.nextEntry = None @property def name(self): return self.__name @property def score(self): return self.__score @property def nextEntry(self): return self.__nextEntry @name.setter def name(self, nameIn): if not isinstance(nameIn, str): raise RuntimeError(str(nameIn) + ' is not a valid name for score entry') self.__name = nameIn @score.setter def score(self, scoreIn): if not isinstance(scoreIn, int): raise RuntimeError(str(scoreIn) + ' is not a valid score for score entry') self.__score = scoreIn @nextEntry.setter def nextEntry(self, entryIn): if not (isinstance(entryIn, self.__class__) or entryIn == None): raise RuntimeError(entryIn + ' is not a valid assignment for nextEntry') self.__nextEntry = entryIn def __str__(self): return self.name + ' | ' + str(self.score) def __init__(self): '''Initializes the high score list and loads in the persistent list from disk.''' self.head = None self.tail = None self.readFromFile('resources/event_scrolls/highscores.asset') @property def head(self): return self.__head @property def tail(self): return self.__tail @head.setter def head(self, value): if not isinstance(value, Scoreboard.Entry) and value != None: raise RuntimeError(str(value) + 'is not a valid head entry.') self.__head = value @tail.setter def tail(self, value): if not isinstance(value, Scoreboard.Entry) and value != None: raise RuntimeError(str(value) + 'is not a valid tail entry.') self.__tail = value def add(self, name, score): '''Adds an entry into the linked list sorted based on score. Assumes it "belongs" on the list already.''' entry = self.Entry(name, score) if self.head == None: self.head = entry self.tail = entry if self.head.score < entry.score: entry.nextEntry = self.head self.head = entry else: currEntry = self.head while currEntry.nextEntry != None and currEntry.nextEntry.score >= entry.score: currEntry = currEntry.nextEntry entry.nextEntry = currEntry.nextEntry currEntry.nextEntry = entry self.__trim() def resetList(self): '''Resets the list by removing all contents, then readding dummy values to refill. Does __NOT__ write out the new list to disk, you must do that manually.''' self.head = None self.tail = None for i in range(MAX_ENTRIES): self.add('CRN', 10000) def belongsOnList(self, score): '''Returns true if the score is higher than the lowest score on the list. Requires a fully populated list.''' return score > self.tail.score def writeToFile(self, filename): '''Write the list out to file based on a simple delimiter scheme. Periods deliniate the name from the score, while commas deliniate between entries.''' fileName = open(filename, 'w') currEntry = self.head while currEntry: if currEntry.nextEntry != None: fileName.write(currEntry.name+'.'+str(currEntry.score)+',') else: fileName.write(currEntry.name+'.'+str(currEntry.score)) currEntry = currEntry.nextEntry fileName.close() def readFromFile(self, fileName): '''Reads in a file, breaks it down based on periods separating name and score and commas separating entries, and automatically readds each entry into the list.''' with open(fileName) as f: read_data = f.read().split(',') for entry in read_data: temp = entry.split('.') self.add(temp[0],int(temp[1])) def __trim(self): '''Trims the list to length set by MAX_ENTRIES. Should not be called directly.''' currEntry = self.head i = 1 while currEntry.nextEntry != None and i < MAX_ENTRIES: currEntry = currEntry.nextEntry i += 1 self.tail = currEntry self.tail.nextEntry = None def __str__(self): result = '***HALL OF FAME!***\n' currEntry = self.head i = 1 while currEntry.nextEntry: result += str(i) + ') ' + str(currEntry) + '\n' i += 1 currEntry = currEntry.nextEntry result += str(i) + ') ' + str(currEntry) + '\n' return result
15284701a1c10cae57f8a2bec7c809833db14f65
MANC3636/2WeekPython
/4_string_ops.py
836
3.9375
4
#let's create a string file file="string_file.txt" author="Bootsy Collins" a=open(file, "w") a.write(f"one nation under a groove, getting down just for the funk of it {author}") a.close() #----------2, now let's open it and read it a=open(file, "r") listing=[a.readline()] print("nation" in listing[0]) print(listing[0][0:25]) print("nation" in listing[0][26:]) #touch on Booleans, but don't dwell #let them create their own text files, put text in the file and parse the text #introduce the following using_join="-".join("the") using_replace=listing[0].replace("the","-") print(using_join) print(using_replace) print("nation".find(using_replace[0])) print(using_replace.split(" ")) #the point is not join, replace, split, nor replace. The point is: for a container type, the coder has #a bunch of things she can do print(dir(str))
c83c80a5ae86d94eddaddfa6e6b6d1341a21d4b9
hyeokjinson/algorithm
/psํ”„๋กœ์ ํŠธ/DP/ํŒŒ๋„๋ฐ˜ ์ˆ˜์—ด.py
242
3.546875
4
if __name__ == '__main__': padovan=[0]*100 padovan[0:5]=1,1,1,2,2,3 t=int(input()) for i in range(6,100): padovan[i]=padovan[i-1]+padovan[i-5] for _ in range(t): n=int(input()) print(padovan[n-1])
4be10d7a0d4dc5755fd74888086a855e79c34336
ortizp978/Ortiz_P_RPS
/main.py
1,214
4.34375
4
from random import randint # add player playerLives = 5 computerLives = 5 # Save the player as a variable called player # the value of player will be one of three choices to type (input) player =input("chosse rock, paper or scissors: ") print("player chose: " + player) # an array is just a container. It bholds multiple values in a 0-based index # you can store anything in an array and retrieve it later. Arrays have square bracket notation choices = ["rock", "paper", "scissors"] computer = choices[randint(0,2)] print("computer chose: " + computer) if (computer == player): print("Tie! Try egain") elif (player == "rock"): if (computer == "paper"): print("you lose!") playerLives = playerLives - 1 else: print("you win!") computerLives = computerLives - 1 elif (player == "paper"): if (computer == "scissors"): print("you lose!") playerLives = playerLives - 1 else: print("you win!") computerLives = computerLives - 1 elif (player == "scissors"): if (computer == "rock"): print("you lose!") playerLives = playerLives - 1 else: print("you win!") computerLives = computerLives - 1 print("computer Lives: " + str(computerLives)) print("player Lives " + str(playerLives))
1cd19dee209abe9fa959c87b9b38a65c9a02289a
nvasturino52/assignment-9.1
/cars_pickups.py
2,559
3.9375
4
# CIS 245 Week 8 Car Assignment class Vehicle: def __init__(self): #Initialize Vehicle Attributes self.make = "make" self.model = "model" self.color = "color" self.fuelType = "fuelType" self.options = 0 self.optionsList = ["1: cruise control", "2: bluetooth", "3: heated seats", "4: backup camera", "5: premium audio system", "6: leather seats", "7: navigation package", "8: self-park\n"] def getMake(self): self.make = str(input("What's the make of your vehicle?\n")) def getModel(self): self.model = input("What's the model of your vehicle?\n") def getColor(self): self.color = input("Enter the color of your vehicle:\n") def getfuelType(self): self.fuelType = input("Is your vehicle gasoline, diesel, hybrid, or electric?\n") def getOptions(self): print(self.optionsList) inputOptions = input("Please select the options you'd like to include for your vehicle.\n") self.options = self.optionsList[inputOptions - 1] print(self.options) class Car(Vehicle): def __init__(self): Vehicle.__init__(self) self.engineSize = 0.0 self.numDoors = 0 #Initialize Car Attributes def getengineSize(self): print(self.engineSize) engineSize = float(input("What engine size will your car have?")) def getnumDoors(self): print(self.numDoors) numDoors = [4, 2] numDoors = int(input("How many doors will your car have?")) if numDoors != 4 or 2: print("Sorry, your vehicle can have either two doors or four. Please try again.") class Pickup(Vehicle): def __init__(self): Vehicle.__init__(self) #Initialize Pickup Attributes def getcabStyle(self): print(self.cabStyle) def bedLength(self): print(self.bedLength) addVehicle = True counter = 0 myGarage = [] vehicleChoice = 0 while addVehicle: vehicleChoice = int(input("Car (1) or Truck (2) or None (3)\n")) if vehicleChoice == 1: myGarage.append(Car()) myGarage[counter].getMake() myGarage[counter].getModel() print("Car added to Garage.\n") elif vehicleChoice == 2: myGarage.append(Pickup()) myGarage[counter].getMake() myGarage[counter].getModel() print("Truck added to Garage.\n") else: addVehicle = False counter += 1 x = 0 while x < len(myGarage): print(myGarage[x].make) print(myGarage[x].model) x += 1
9144364d0612ea74d32baa4c2d5caa2b793c430c
Ranjana151/python_programming_pratice
/reverse_word.py
109
4.15625
4
#word reversing word=input("Enter the word") for i in range(len(word)-1,-1,-1): print(word[i],end=" ")
d98ef73f1be22c4fcc58c3c2a537f9aacd66620c
demonlittledog/pythonproject
/newpython/t07ๅŒๆญฅๆกไปถๅ’Œ็”Ÿไบงๆถˆ่ดนๆจกๅž‹.py
1,814
3.765625
4
#็”Ÿไบง่€…-ๆถˆ่ดน่€…ๆจกๅž‹ import threading import time import random #ๅŒ…ๅญ class Baozi(): def __init__(self, count): super(Baozi, self).__init__() self.count = count def add(self,x): self.count += x def sub(self,x): self.count -= x #ไปฅไธ‹ไธบ็”Ÿไบง่€…ๅ’Œๆถˆ่ดน่€…๏ผŒ้ƒฝ็ปงๆ‰ฟไบ†Thread็ฑป #็”Ÿไบง่€… class Producer(threading.Thread): def __init__(self, cond, food): super(Producer, self).__init__() self.food = food #็”Ÿไบง็š„ๅ•†ๅ“ไธบๅŒ…ๅญ self.cond = cond #็”จไบŽๆŽงๅˆถๅŒๆญฅ็š„ๆกไปถ def run(self): while True: time.sleep(5)#ๆฏ5็ง’็”Ÿไบงไธ€ๆฌก13ไธชๅŒ…ๅญ if food.count<=37:#ๅฆ‚ๆžœๅฝ“ๅ‰ๆ•ฐ้‡ไธ่ถณๅˆ™็”Ÿไบง cond.acquire() food.add(13) cond.notifyAll()#้€š็Ÿฅ็ญ‰ๅพ…็š„็บฟ็จ‹ cond.release() print('็”ŸไบงๅฎŒๆฏ•๏ผŒๆ•ฐ้‡๏ผš%d'%food.count) else:#ๅฝ“ๅ‰ๆ•ฐ้‡่ถ…่ฟ‡้™ๅฎšๅ€ผๅˆ™ๆš‚ๅœ็”Ÿไบง print('ๆš‚ๅœ็”Ÿไบง๏ผŒๆ•ฐ้‡๏ผš%d'%food.count) #ๆถˆ่ดน่€… class Consumer(threading.Thread): def __init__(self,num,cond,food): super(Consumer, self).__init__() self.cond = cond #ๅŒๆญฅๆกไปถ self.food = food #ๆถˆ่ดน็š„็‰ฉๅ“ self.num = num #ๆฏๆฌกๆถˆ่ดนๆ•ฐ้‡ def run(self): while True: time.sleep(6) #ๆฏ6็ง’ๆถˆ่ดนไธ€ๆฌก cond.acquire() #่ฏทๆฑ‚้” x=random.randrange(4,10)#้šๆœบๆถˆ่ดน4-9ไธช if food.count<x: print('ๆถˆ่ดน่€… %d ็ญ‰ๅพ…่ดญไนฐ'%self.num) cond.wait()#ๅฆ‚ๆžœๅบ“ๅญ˜ไธ่ถณๅˆ™็ญ‰ๅพ… else: food.sub(x) print('ๆถˆ่ดน่€… %d ่ดญไนฐ%dไธชๅฎŒๆฏ•๏ผŒๅ‰ฉไฝ™ๆ•ฐ้‡:%d'%(self.num,x,food.count)) cond.release()#่ดญไนฐๅฎŒๆฏ•ๅˆ™้‡Šๆ”พ #ๆž„้€ ็”Ÿไบง็‰ฉๅ“ๅ’ŒๅŒๆญฅๆกไปถ food=Baozi(0) cond=threading.Condition() #ๆž„้€ ไธ€ไธช็”Ÿไบง่€…๏ผŒไธ‰ไธชๆถˆ่ดน่€… prd=Producer(cond,food) csm1=Consumer(1,cond,food) csm2=Consumer(2,cond,food) csm3=Consumer(3,cond,food) #ๅฏๅŠจ็บฟ็จ‹ prd.start() csm1.start() csm2.start() csm3.start()
5a296025686b84c26d394ec6b261db3bea5ecf6a
madhav9691/python
/lcm_gcd.py
324
4.03125
4
def gcd(x,y): while y>0: x,y=y,x%y return(x) def lcm(a,b): return(a*b)//gcd(a,b) num1,num2=map(int,input("Enter two numbers seperated by\ space:").split()) print("GCD of given numbers= ",gcd(num1,num2)) print("LCM of given numbers= ",lcm(num1,num2))
5b3e88f8a33a006395a893830a6f4ac88032542a
r0meroh/DataStructure_exercises
/game_score_statistics.py
1,237
4.15625
4
""" This program takes in a list of scores from the user. Processes the scores in order to do the following: Get all the scores from user. Calculate the lowest score. Calculate the highest score. Calculate the average(mean). Calculate the standard Deviation. """ import statistics as stat def user_scores(): """ take in scores from user and put them into a list """ scores = [] answer = int(input('enter scores, otherwise answer "-1" to end\n')) while (answer != -1): scores.append(answer) answer = int(input('enter next score\n')) return scores def minimum (scores): mini = sorted(scores) print('lowest score was:\n') return mini[0] def highest(scores): print('highest score was:\n') mini = sorted(scores) return mini[-1] def average(score): print('average is:\n') return stat.mean(score) def deviation(scores): print('standard deviation is:\n') return stat.stdev(scores) def main(): scores = user_scores() print('the scores entered are \n') print(scores) print(minimum(scores)) print(highest(scores)) print(average(scores)) print(deviation(scores)) if __name__ == '__main__': main()
3b3f692ec325251e5853a67d233441ab921112df
Akashic-Projects/akashic
/akashic/util/type_converter.py
1,836
3.5625
4
def clips_to_py_type(ctype): """ Converts CLIPS type to Python type Parameters ---------- ctype : str CLIPS type, possible values: "INTEGER", "FLOAT", "STRING" and maybe "BOOLEAN" Returns ------- ptype: type Coresponding python type """ ptype = None if ctype == "INTEGER": ptype = int elif ctype == "FLOAT": ptype = float elif ctype == "STRING": ptype = str elif ctype == "BOOLEAN": ptype = bool return ptype def py_to_clips_type(ptype): """ Converts Python type to CLIPS type Parameters ---------- ptype : str Python type Returns ------- ctype: str Coresponding CLIPS type """ ctype = None if ptype == int: ctype = "INTEGER" elif ptype == float: ctype = "FLOAT" elif ptype == str: ctype = "STRING" elif ptype == bool: ctype = "BOOLEAN" return ctype # TODO: Check what's up with boolean as 1s of 0s # in data_provider tempalte type def translate_if_c_bool(value): """ Translates python bool into the CLIPS boolean Parameters ---------- value : bool Python boolean value Returns ------- str: "TRUE" or "FALSE" If passed value is of python bool type value Else """ if value.__class__ == bool: if value == True: return "1" else: return "0" else: return value def string_to_py_type(s, to_type): if to_type == "INTEGER": return int(s) elif to_type == "FLOAT": return float(s) elif to_type == "BOOLEAN": if s == "True" or s == "TRUE" or s == "1": return True else: return False else: return s
d3ca10fd201cc24daf6574a2a1c488813c0f8e58
sremedios/AdventOfCode2016
/day16.py
1,006
3.640625
4
puzzleInput = '00101000101111010' diskSize = 35651584 # change to 272 for part 1 resultData = puzzleInput while len(resultData) <= diskSize: b = [] # reverse order of data in resultData and store in b for i in range(len(resultData)): b.append(resultData[-1-i]) # flip bits b[i] = '0' if b[i] == '1' else '1' # append to resultData resultData = resultData + '0' + ''.join(b) # truncate down to diskSize resultData = ''.join(list(resultData)[:diskSize]) # calculate checksum checkSum = [] # initial checksum calc for x in range(0,len(resultData),2): if resultData[x] == resultData[x+1]: checkSum.append('1') else: checkSum.append('0') # if checksum is not odd, repeat checksum on itself while len(checkSum)%2 == 0: temp = [] for x in range(0,len(checkSum),2): if checkSum[x] == checkSum[x+1]: temp.append('1') else: temp.append('0') checkSum = temp print(''.join(checkSum))
79129238e0d5eb7698e016b84fc3a5e3eb0761be
Disguised-Minstrel/Python4Everyone
/13 and before/average_conf.py
496
3.65625
4
fhand = None while fhand == None: file_name = input("Enter name of the file: ") if file_name == "na na boo boo": print("why?") try: fhand = open(file_name, 'r') except: print("Invalid filename.") total = 0 count = 0 for line in fhand: if line.startswith("X-DSPAM-Confidence"): sub = line[line.find(':')+1:] total = total + float(sub.strip()) count += 1 average = total / count print("Average spam confidence: %g" % average)
f13869f07f79eee6ba2953e736f9ed9a25b9bde7
dmccoystephenson/Acronym-Maker
/acronymMaker.py
258
4.09375
4
originalString = raw_input("Enter what you want to make into an acronym: ") list = originalString.split(" ") acronym = "" for x in list: acronym = acronym + x[:1] print "Your new acronym is %r" % acronym raw_input("Press 'Enter' to exit the program.")
a68294d4e47c146198d47ff12a80304fd7e69a24
MavineRakiro/Reverse_array
/reverse_sentence.py
502
4.3125
4
"""Write a function reverseSentence(A) that takes in an array of characters , A, and reverses the the "words" (not individual characters). Example: A = ['t','h','i','s',' ','i','s',' ','g','o','o','d'] reverseSentence(A) A // ['g','o','o','d',' ','i','s',' ','t','h','i','s'] """ A = ['t', 'h', 'i', 's', ' ', 'i', 's', ' ', 'g', 'o', 'o', 'd'] def reverseSentence(A): a = ''.join(A).split() b = a[::-1] c = ' '.join(b) return list(c) print(reverseSentence(A))
fafa1a461e52f9e51d666c2ee759b8c6eca41d1c
2648226350/Python_learn
/pych-four/4_10to4_12.py
797
4.15625
4
#4-10 ninjas = ["uzumaki naruto","uchiha sasuke","haruno sakura","hatake kakashi", "nara shikamaru","sai","yamanaka lno","tsunade","yamato"] print("The first three ninjas in the list are: ") for ninja in ninjas[:3]: print(ninja.title()) print("Three ninjas form the middle of the list are: ") for ninja in ninjas[int(len(ninjas)/2)-1:int(len(ninjas)/2)+2]: print(ninja.title()) print("The last three ninjas in the list are: ") for ninja in ninjas[len(ninjas)-3:]: print(ninja.title()) #4-11 friend_ninjas = ninjas.copy() friend_ninjas.append("hyuga hinata") print("My favorite ninjas are: ") for ninja in ninjas: print(ninja.title().ljust(30),end = "") print() print("My friend's favorite pizzas are: ") for ninja in friend_ninjas: print(ninja.title().ljust(30),end = "") print() #4-12 """Use multiple circulate"""
ff552b7f3935d4a6aa68443748cb2d8799edf766
jtbishop/CS506-Fall2020
/02-library/cs506/kmeans.py
5,046
3.5625
4
from collections import defaultdict from math import inf import random import csv def point_avg(points): """ Accepts a list of points, each with the same number of dimensions. (points can have more dimensions than 2) Returns a new point which is the center of all the points. """ summation: list = [sum(x) for x in zip(*points)] return [colSum /len(points) for colSum in summation] def update_centers(dataset, assignments): """ Accepts a dataset and a list of assignments; the indexes of both lists correspond to each other. Compute the center for each of the assigned groups. Return `k` centers in a list """ temp = defaultdict(list) centers = [] for assignment, point in zip(assignments, dataset): temp[assignment].append(point) for i in temp.values(): centers.append(point_avg(i)) return centers def assign_points(data_points, centers): """ """ assignments = [] for point in data_points: shortest = inf # positive infinity shortest_index = 0 for i in range(len(centers)): val = distance(point, centers[i]) if val < shortest: shortest = val shortest_index = i assignments.append(shortest_index) return assignments def distance(a, b): """ Returns the Euclidean distance between a and b """ if (hasattr(a[0], '__len__')): rows = len(a); cols = len(a[0]) summation = 0 for i in range(rows): vec = [a[i][j] - b[i][j] for j in range(cols)] s = sum(i**2 for i in vec) summation += s else: summation = sum([(a[i] - b[i])**2 for i in range(len(a))]) return summation**(1/2) def distance_squared(a, b): return distance(a, b)**2 def generate_k(dataset, k): """ Given `data_set`, which is an array of arrays, return a random set of k points from the data_set """ points = [dataset[random.randint(0, len(dataset) - 1)] for i in range(0, k)] return points def cost_function(clustering): total_cost = 0 for data_set in clustering.keys(): datas = clustering[data_set] centers = point_avg(datas) for indiv_data in datas: total_cost += distance(indiv_data, centers) return total_cost def generate_k_pp(dataset, k): """ Given `data_set`, which is an array of arrays, return a random set of k points from the data_set where points are picked with a probability proportional to their distance as per kmeans pp """ random_centers: list = generate_k(dataset, k) random_assignments: list = assign_points(dataset, random_centers) distances: list = [distance(random_centers[random_assignments[i]], dataset[i]) for i in range(len(dataset))] # Generate indices for each distance then sort in ascending order of distance indices: list = [i for i in range(len(distances))] indices = [j for i, j in sorted(zip(distances, indices))] weighted_indices: list = [] for i in range(len(indices)): n: int = int(distances[indices[i]]) for j in range(n): weighted_indices.append(indices[i]) N: int = len(weighted_indices) - 1 pp_centers: list = [] random_numbers: list = [] choices: list = [] for i in range(k): random_choice: int = random.randint(0, N) index = weighted_indices[random_choice] if random_choice in random_numbers or index in choices: while random_choice in choices or index in choices: random_choice = random.randint(0, N) index = weighted_indices[random_choice] random_numbers.append(random_choice) choices.append(index) pp_centers.append(dataset[index]) return pp_centers def _do_lloyds_algo(dataset, k_points): assignments = assign_points(dataset, k_points) old_assignments = None while assignments != old_assignments: new_centers = update_centers(dataset, assignments) old_assignments = assignments assignments = assign_points(dataset, new_centers) clustering = defaultdict(list) for assignment, point in zip(assignments, dataset): clustering[assignment].append(point) return clustering def k_means(dataset, k): if k not in range(1, len(dataset)+1): raise ValueError("lengths must be in [1, len(dataset)]") k_points = generate_k(dataset, k) return _do_lloyds_algo(dataset, k_points) def k_means_pp(dataset, k): if k not in range(1, len(dataset)+1): raise ValueError("lengths must be in [1, len(dataset)]") k_points = generate_k_pp(dataset, k) return _do_lloyds_algo(dataset, k_points) if __name__ =='__main__': from cs506 import read data = read.read_csv('D:/OneDrive/College Notebook/Boston University/Fall Senior Year/CS 506/CS506-Fall2020/02-library/tests/test_files/dataset_1.csv') res = (k_means(data, 4)) print(res[0])
b0c02e9efa43d087e5eaf90f17d3d41ed3d7b3e9
ashutoshEr/python-code
/basic program/greatest number.py
219
4.1875
4
a=int(input("Please Enter a Number : ")) if(a&1==1): print("This Number is Odd") else: print("This Number is Even") for i in range(1,101): if i%3==0 or i%5==0: continue print(i)
2f4a9a5bef04ddfc41f3f303a1c9aa4c4d040f54
zyj16602159899/lemon_class
/class_1030/function_2.py
1,482
3.609375
4
#!/usr/bin/python #-*- coding:utf-8 -*- #@Author๏ผšzhuxiujie #ๅ˜้‡ไฝœ็”จๅŸŸ # a = 1 #ๅ…จๅฑ€ๅ˜้‡ # def add(b): # a =5 #ๅฑ€้ƒจๅ˜้‡ # print(a+b) # # add(10) #ๅ…จๅฑ€ๅ˜้‡ๅ’Œๅฑ€้ƒจๅ˜้‡ #1.ไฝœ็”จ่Œƒๅ›ดไธไธ€ๆ ท ๅ…จๅฑ€ๅ˜้‡๏ผšๆจกๅ—้‡Œ้ƒฝ่ƒฝ็”จ๏ผ›ๅ‡ฝๆ•ฐ็š„ๅฑ€้ƒจๅ˜้‡ๅช่ƒฝ็”จไบŽๅ‡ฝๆ•ฐ #2.ๅฝ“ๅ…จๅฑ€ๅ˜้‡ๅ’Œๅฑ€้ƒจๅ˜้‡ๅŒๅไธ”ๅŒๆ—ถๅญ˜ๅœจๆ—ถ๏ผŒๅ‡ฝๆ•ฐไผ˜ๅ…ˆ่ฐƒ็”จๅฑ€้ƒจๅ˜้‡ #3.ๅฝ“ๅฑ€้ƒจๅ˜้‡ๆฒกๆœ‰ๆ—ถ๏ผŒๅฐฑไผ˜ๅ…ˆ็”จๅ…จๅฑ€ๅ˜้‡ #4.global #5.ไธ€่ˆฌๆƒ…ๅ†ตไธ‹๏ผŒ่ฐจๆ…Žไฝฟ็”จๅ…จๅฑ€ๅ˜้‡๏ผŒไผ˜ๅ…ˆไฝฟ็”จๅฑ€้ƒจๅ˜้‡ # def add(b): # global a #ๅฃฐๆ˜Ž่ฟ™ๆ˜ฏไธ€ไธชๅ…จๅฑ€ๅ˜้‡ # a = 5 # print(a + b) # add(10) # print(a) #ๆ€Žไนˆๅผ•ๅ…ฅไธๅŒ็š„ๆจกๅ—---> #็ฌฌไธ‰ๆ–นๅบ“ #a.ๅœจ็บฟๅฎ‰่ฃ… 1)ๆ‰“ๅผ€cmd--->pip install ๆจกๅ—ๅ #2)ไฝฟ็”จๅ›ฝๅ†…ๆบๅŽป่ฟ›่กŒๅฎ‰่ฃ… pip install ๅ›ฝๅ†…ๆบๅœฐๅ€ ๆจกๅ—ๅ #3๏ผ‰file--setting--project interpreter-->+ #b.็ฆป็บฟๅฎ‰่ฃ… #1)ๅœจ็ฝ‘ไธŠๆ‰พๅˆฐ็ฆป็บฟๅฎ‰่ฃ…ๅŒ…;2)่งฃๅŽ‹;3)ๆ‹ท่ด่งฃๅŽ‹ๅŽ็š„ๆ–‡ไปถๅˆฐpythonๅฎ‰่ฃ…่ทฏๅพ„;4)ๅˆฐcmdไธญ่ฟ›ๅ…ฅๅˆฐๅฎ‰่ฃ…ๅŒ…ๆ–‡ไปถ่ทฏๅพ„๏ผŒๅฎ‰่ฃ…ๆ–‡ไปถ python setup.py install #ๆ€Žไนˆ็”จ #1.python่‡ชๅธฆ็š„/ๆˆ–็ฌฌไธ‰ๆ–นๅบ“๏ผš1)import... 2)from ...import...(่‡ณๅฐ‘็ฒพ็กฎๅˆฐๆจกๅ—ๅ๏ผŒๅˆฐๅŒ…ๅไธๅฏไปฅ๏ผ‰ #import email.mime.base #from email.mime import base #2.่‡ชๅทฑๅ†™็š„ # if __name__ == '__main__': #ไธป็จ‹ๅบ็š„ๆ‰ง่กŒๅ…ฅๅฃ๏ผŒๅชๆœ‰ๅœจๅฝ“ๅ‰ๆจกๅ—ไธ‹ๆ‰ง่กŒๆ—ถ๏ผŒๆ‰ไผšๆ‰ง่กŒไธ‹้ข็š„ๆ‰€ๆœ‰ไปฃ็ ๏ผ›ๅ…ถไป–ๆ–‡ไปถๅผ•ๅ…ฅๆ—ถ๏ผŒๅชๆ‰ง่กŒๅผ•ๅ…ฅ็š„ไปฃ็  # print('1') # print('hero')
ce9f9c335952074c67a9961633fc186e0c2208c2
Rakesh-vcs73/9229580
/DAY_2_20_12_2020/Task_2_Mettl/4_NoOfPrimeInRange.py
489
3.5625
4
def NoOfPrimeInaRange(input1,input2): count=0 if(input1==1): input1+=1 for i in range(input1,input2+1): flag=0 for j in range(2,(i//2)+1): if(i%j==0): flag=1 break if(flag==0): #print(i) count+=1 return count input1=int(input("Enter first number : ")) input2=int(input("Enter second number : ")) res=NoOfPrimeInaRange(input1,input2) print("Count : ",res)
c156b4d25bd5896ee4f7feaf9cb35d067c7a741b
loust333/python-workspace
/branches.py
188
3.65625
4
humans = 20 dinosaurs = 30 fish = 35 if humans < dinosaurs: print 'Wow humans less in number than dinosaurs' elif humans < fish: print 'More humans than fish' else: print 'Nothing'
c1c8cb6deb32e19378566ae76096a3dfab1dee73
LYTXJY/python_full_stack
/Code/src/hellopython/็ฌฌๅ››็ซ /4.2bool.py
585
3.921875
4
#bool()ๅ‡ฝๆ•ฐไธญ๏ผš้ž้›ถไธบTrue,ๅพ—้›ถไธบ้›ถ print(bool(0)) print(bool(4)) print(bool(-10)) print(bool("eqw")) print(bool([1, 2, 3])) print(bool((1, 2, 3))) print(bool({1:24, 2:25})) print("\n") print(0 == False) print(1 == True) print("\n") print(bool()) print(bool("")) if -1: print("-1ไนŸๆ˜ฏ็œŸ") if "": print("็ฉบๅญ—็ฌฆไธฒๆ˜ฏ็œŸ") else: print("็ฉบๅญ—็ฌฆไธฒๆ˜ฏๅ‡") if " ": print("็ฉบๆ ผๆ˜ฏ็œŸ") else: print("็ฉบๆ ผไธฒๆ˜ฏๅ‡") print("--------------------------------------------") print(bool(" ")) print(bool(None))
9d38f6c315cb6292b0f3dd07239330ff7e9168d6
adiboy6/python-practice
/string.py
670
3.796875
4
# add raw string instead of adding backslash(/) print(r'C:\some\name') # multi-line string literal can be achieved by using ("""...""") or ('''...''') print("""\ Usage: thingy [OPTIONS] -h Display this usage message -H hostname Hostname to connect to """) # String literals can be divided if it's large print('Py''thon') text = ('Put several strings within parentheses ' 'to have them joined together.') print(text) random_string = 'hello' # only works with two literals though, not with variables or expressions: # print(random_string'world') # string is immutable ''' >>>x="hi" >>>x[0]="g" #not possbile '''
4f7aa1ecaf3b11a65d1f7505151c3626b42d74de
hiranomo/dokpro
/3-21/stack.py
525
3.90625
4
class Stack: def __init__(self): self.items = [] def is_empy(self): return not self.items def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): return self.items[-1] def size(self): return len(self.items) if __name__ == '__main__': stack = Stack() for i in range(0, 5): stack.push(i) rev = [] while stack.size(): i = stack.pop() rev.append(i) print(rev)
b5969b528622cbf952e8d154b99a53f736b5f723
rashigupta37/tic_tac_toe
/playerMinimax.py
2,876
3.78125
4
from random import randint, seed #returns best move and best score if max is the player def getMax(moves,bestScore,scores,bestMove): #traverse all the moves in the board for i in range(len(moves)): #if curretnt score is better than the best score if scores[i] > bestScore: bestScore = scores[i] bestMove = moves[i] return bestMove, bestScore #returns best move and best score if min is the player def getMin(moves,bestScore,scores,bestMove): #traverse all the moves in the board for i in range(len(moves)): #if curretnt score is better than the best score if scores[i] < bestScore: bestScore = scores[i] bestMove = moves[i] return bestMove, bestScore #minimax algorithm It considers all the possible ways the game can go and returns the best score and the best move of the board def minimax(newGame, game,depth): #print(depth) emp = newGame.getEmp() if newGame.checkForWinner() == game.curPlayer: return -1, 100 elif newGame.checkForWinner() == game.curPlayer % 2 + 1: return -1, -100 elif not emp: return -1, -5 moves = [] scores = [] for i in range(len(emp)): newGame.move(emp[i]) newGame.curPlayer = newGame.curPlayer % 2 + 1 #if depth is not zero, minimax is called if depth!=0: result = minimax(newGame, game,depth-1) moves.append(emp[i]) scores.append(result[1]) newGame.clearMove(emp[i]) #player changes newGame.curPlayer = newGame.curPlayer % 2 + 1 bestMove = None #max player if newGame.curPlayer == game.curPlayer: #intialise bestScore with minimum value as it's max player's turn bestScore = -10000 bestMove, bestScore=getMax(moves,bestScore,scores,bestMove) #min player else: #intialise bestScore with maximum value as it's min player's turn bestScore = 10000 bestMove, bestScore=getMin(moves,bestScore,scores,bestMove) #returns best move and best score return bestMove, bestScore #function is called when player chooses minimax player def playerMinimax(game,depth): #print(depth) #copy the current state newGame = game.getCopy() #if minimax player starts first, choose any box randomly to minimize the time if len(game.getEmp()) == 9: seed() myMove = [randint(0, 8), None] else: #if second turn is of minimax player's call minimax myMove = minimax(newGame, game, depth) #print(myMove[0]) is minimax move #print(myMove[1]) is minimax score #return minimax move return myMove[0]
c160ac7cd34eed5e497fd004b0e13e43fbd0db6d
ariscon/DataCamp_Files
/11-pandas-foundations/03-time-series-in-pandas/01-reading-and-slicing-times.py
664
3.625
4
''' Reading and slicing times For this exercise, we have read in the same data file using three different approaches: df1 = pd.read_csv(filename) df2 = pd.read_csv(filename, parse_dates=['Date']) df3 = pd.read_csv(filename, index_col='Date', parse_dates=True) Use the .head() and .info() methods in the IPython Shell to inspect the DataFrames. Then, try to index each DataFrame with a datetime string. Which of the resulting DataFrames allows you to easily index and slice data by dates using, for example, df1.loc['2010-Aug-01']? INSTRUCTIONS 50XP Possible Answers df1. press 1 df1 and df2. press 2 df2. press 3 df2 and df3. press 4 df3. press 5 ''' df3
649e90039dd35d4c51f165886afcf07a0dfb470c
Oscar1305/Python
/Python/Repaso_Funciones.py
218
3.59375
4
x = 0 def calcularSuma(num1, num2, num3): suma = num1 + num2 + num3 return suma while x <= 10: if calcularSuma(x, x, x) > 20: break print(calcularSuma(x, x, x)) x += 1
3b43484609397a1aa69cbce58c31371035ad4fb6
rahularoradfs/euler
/solved/018.py
2,117
3.6875
4
# for this, you should work row-by-row # there will be several possible ways to get to a number # of these, only one way will have the maximum total # store only that maximum total associated with it # take the example four-row triangle provided """ 3 7 4 2 4 6 8 5 9 3 """ # go row by row: # row 1: only one way to get to 3, with total 3 # row 2: only one way to get to 7 and 4, totals 10 and 7 respectively # row 3: only one way to get to 2 and 6, totals 12 and 13 respectively; # two ways to get to 4, totals 14 and 11; store only the 14 total # row 4: only one way to get to 8 and 3, with totals 20 and 16 respectively # two ways to get to 5, totals 17 and 19; store only the 19 total # two ways to get to 9, totals 23 and 21; store only the 23 total # solve: the maximum total on the final row is 23; output that alone # can get to 2,1 by 1,1; 2,2 by 1,1 # 3,1 by 2,1; 3,2 by 2,1, 2,2; 3,3 by 2,2 # 4,1 by 3,1; 4,2 by 3,1, 3,2,; 4,3 by 2,2, 2,3; 4,4 by 2,3 # generally: index the triangle as [row][elem] # can access [row][elem] via [row-1][elem-1] or [row-1][elem] # only if they exist def max_weight(tri): max_tri = [None] * len(tri) for i, row in enumerate(tri): max_tri[i] = [None] * len(row) for j, elem in enumerate(row): if i > 0 and j > 0: rt1 = 0 rt1 = max_tri[i-1][j-1] if i > 0 and j > 0 else 0 rt2 = max_tri[i-1][j] if i > 0 and j < (len(row) - 1) else 0 max_tri[i][j] = elem + max(rt1, rt2) return max(max_tri[-1]) def parse_text(input): return [[int(e) for e in row.split(' ')] for row in input.split('\n')] sample_tri = """3 7 4 2 4 6 8 5 9 3""" tri_018 = """75 95 64 17 47 82 18 35 87 10 20 04 82 47 65 19 01 23 75 03 34 88 02 77 73 07 63 67 99 65 04 28 06 16 70 92 41 41 26 56 83 40 80 70 33 41 48 72 33 47 32 37 16 94 29 53 71 44 65 25 43 91 52 97 51 14 70 11 33 28 77 73 17 78 39 68 17 57 91 71 52 38 17 14 91 43 58 50 27 29 48 63 66 04 68 89 53 67 30 73 16 69 87 40 31 04 62 98 27 23 09 70 98 73 93 38 53 60 04 23""" print('Sample triangle: {}'.format(max_weight(parse_text(sample_tri)))) print('Puzzle 018: {}'.format(max_weight(parse_text(tri_018))))
6ef3f7e0f98bed39eba4866863bf1d894811ee3d
D00dGuy07/Minecraft-Coordinate-Tools
/PortalCalculator.py
1,455
3.703125
4
# Portal Calculator takes a file made in locations list and calculates those coordinates in the nether # By D00dGuy07 import math name = "Portal Calculator" description = "Takes a save file made in Locations List and calculates those coordinates in the nether" def getInfo(): return "{0} - {1}".format(name, description) def start(library): print("Portal Calculator\nYou have to make a list in the Locations List tool to use this.\nThis tool will convert these files to portal coordinates but in a copy.\n") files = library.DataBase.GetDictionaryFiles() print("Chose a file to convert:") count = 0 for _file in files: count += 1 print("{0}) {1}".format(count, _file[:-5])) print("") fileToOpen = input() loadedFile = None while True: if library.RepresentsInt(fileToOpen): locationsList = library.DataBase.LoadDictionary(files[int(fileToOpen) - 1][:-5]) break else: print("Pick the number of the file.") fileToOpen = input() for name, coordinate in locationsList.items(): locationsList[name] = convertToNetherCoords(coordinate.ConvertToVector2(), library) print("Choose a name for the file:") fileName = input() library.DataBase.SaveDictionary(fileName, locationsList) def convertToNetherCoords(coordinate, library): return coordinate // 8
53e9897291cdb38546a8e06f5460f84e52c6ad08
stcybrdgs/myPython-refresher
/learningPython/basicHTMLparser.py
1,727
3.78125
4
# # Example file for parsing and processing HTML # # import the HTMLParser classs that Python provides from html.parser import HTMLParser metacount = 0 class MyHTMLParser(HTMLParser): # override default implementation of handle_comment # that's already in the HTML parser class def handle_comment(self, data): print("Encountered comment: ", data) pos = self.getpos() # get position where comment was encountered print("\tAt line: ", pos[0], " position ", pos[1]) # handle the start tag def handle_startag(self, tag, attrs): global metacount if tag == 'meta': metacount += 1 print("Encountered tag: ", tag) pos = self.getpos() print("\tAt line: ", pos[0], " position ", pos[1]) if attrs.__len__() > 0: print("\tAttributes:") for a in attrs: print("\t", a[0], "=", a[1]) # handle the end tag def handle_endtag(self, tag): print("Encountered tag: ", tag) pos = self.getpos() print("\tAt line: ", pos[0], " position ", pos[1]) # handle text data def handle_data(self, data): if (data.isspace()): print("Encountered data: ", data) pos = self.getpos() print("\tAt line: ", pos[0], " position ", pos[1]) def main(): # instantiate the parser and feed it some HTML parser = MyHTMLParser() # open and read the html file f = open("samplehtml.html") if f.mode == 'r': contents = f.read() # the parer reads through the passed-in html string # line by line parser.feed(contents) # to test the parser, we'll read from a sample HTML file # # but usually we'd use URL lib to open up a URL # and read the HTML data straight from the web if __name__ == "__main__": main()
ad6f765839cb90b1149d702a79f7c1623251d63c
TylerBrock/books
/Learning Python/ch24/formats.py
466
4.125
4
""" Various specialized string display formatting utilities. Test me with canned self-test or command line arguments. """ def commas(N): """ format positive integer-like N for display with commas between digit groupings: xxx,yyy,zzz """ digits = str(N) assert(digits.isdigit()) result = '' while digits: digits, last3 = digits[:-3], digits[-3:] result = (last3 + ',' + result) if result else last 3 return result
45c3b3ae5842ca22a79124ffa52dc5eab8e38782
PatrickFang05/PythonToGit
/Homework/turtle_race.py
940
4.125
4
import turtle import random numTurtles = int(turtle.numinput('race', 'How many turtles?')) colors = ['red', 'blue', 'green', 'purple', 'black', 'magenta', 'cyan', 'brown'] turtle.screensize(2000, 2000) turtles = [] # Create each turtle object and push them to the turtles list for i in range(numTurtles): t = turtle.Turtle() t.shape('turtle') t.color(colors[i]) t.speed(1) turtles.append(t) # Position each turtle at their starting coordinates for i in range(numTurtles): t = turtles[i] t.penup() t.goto(-250, 100 - 30 * i) t.pendown() # Set up empty winner variable winner = '' # Let all the turtles move 100 steps at a random pixel in each step for j in range(50): for i in range(numTurtles): steps = random.randint(1, 5) turtles[i].forward(steps) # Print all the turtles' final position for i in range(numTurtles): turtles[i].write(turtles[i].position()) turtle.done()
a882494642f1c36c99e925844c731ec1bba7e416
yulaimusin/zadachki-na-pythone
/ะŸั€ะพะณั€ะฐะผะผะพั‡ะบะธ/palindrome.py
1,059
4.0625
4
""" ะŸั€ะพะณั€ะฐะผะผะฐย palindrome.py ะทะฐะฟั€ะฐัˆะธะฒะฐะตั‚ ะธ ะฟะพะปัƒั‡ะฐะตั‚ ัƒ ะฟะพะปัŒะทะพะฒะฐั‚ะตะปั ั‡ะธัะปะพ ะธะปะธ ัะปะพะฒะพ, ะฐ ะทะฐั‚ะตะผ ะฒั‹ะฒะพะดะธั‚: Trueย โ€” ะตัะปะธ ั‡ะธัะปะพ ัะฒะปัะตั‚ัั ะฟะฐะปะธะฝะดั€ะพะผะพะผ, ะธะปะธ Falseย โ€” ะตัะปะธ ั‚ะฐะบะพะฒั‹ะผ ะฝะต ัะฒะปัะตั‚ัั. ะŸะฐะปะธะฝะดั€ะพะผ (https://ru.wikipedia.org/wiki/ะŸะฐะปะธะฝะดั€ะพะผ) โ€” ะพะดะธะฝะฐะบะพะฒะพ ั‡ะธั‚ะฐัŽั‰ะตะตัั ะฒ ะพะฑะพะธั… ะฝะฐะฟั€ะฐะฒะปะตะฝะธัั… ัะปะพะฒะพ, ั‡ะธัะปะพ ะธะปะธ ั„ั€ะฐะทะฐ. ะะฐะฟั€ะธะผะตั€, 8228, ABBA. """ var = input('ะ’ะฒะตะดะธั‚ะต ั‡ะธัะปะพ ะธะปะธ ัะปะพะฒะพ (ะฝะฐะฟั€ะธะผะตั€, "82822828" ะธะปะธ "ABCDFEkEFDCBA"): ') length = len(var) if length % 2 != 0: counter = int(length/2-0.5) else: counter = int(length/2) length = length-1 counter_begin = 0 counter_end = -1 while counter > 0: counter = counter-1 if var[counter_begin] == var[counter_end]: result = True else: result = False break counter_end -= 1 counter_begin += 1 print(result)
1e9280a0348b92f744031daf29de03db309de10e
dheerucr9/Gase-Search-Engine
/stack.py
507
3.90625
4
class stack: def __init__(self): self.s=[] def isempty(self): return len(self.s)==0 def push(self,a): self.s.append(a) def pop(self): if self.isempty(): print("Stack is empty") else: return self.s.pop() def top(self): if self.isempty(): print("Stack is empty") else: return self.s[-1] #Main a=stack() a.push(1) a.push(2) a.push(3) a.push(4) a.push(5)
a81743ac6e33cf9d26cdec0679f3e0f27b488f31
BhavaSuryaVamsiSrireddy/guvi
/wordpuzzle.py
1,031
3.75
4
import random sc=0 def puzzle(l,sc): le1=len(l)-1 i1=random.randint(0,le1) k=list(l[i1]) le2=len(k)-1 ri=[] for i in range(2): rig=random.randint(0,le2) if rig not in ri: ri.append(rig) for i in range(len(k)): if i in ri: k[i]='*' print(''.join(k)) ans=input() if ans in l: print('right \n') sc=sc+1 return sc else: print('wrong \n') print('answer is '+l[i1]) print('\nyour score is '+str(sc)) sc=-1 return sc print('WORD PUZZLE GAME') print('''1.fruits 2.vegetables 3.countries''') c=input('Enter your choice:') while(sc>=0): fruits=['apple','banana','pineapple','grapes','orange'] vegetables=['potato','peas','tomato','brinjal'] countries=['india','china','japan','korea'] if(c=='1'): sc=puzzle(fruits,sc) elif(c=='2'): sc=puzzle(vegetables,sc) elif(c=='3'): sc=puzzle(countries,sc) else: print('invalid choice') break
e1fc4db3f6240ed63e6dfc44c3b89d8f93ca2921
affinity96/2020PS-python
/Programmers/์™„์ „ํƒ์ƒ‰/์†Œ์ˆ˜์ฐพ๊ธฐ.py
593
3.796875
4
import itertools def isItSosu(number): if number < 2 : return False if number == 2 : return True if number % 2 == 0 : return False for i in range(3, number, 2) : if number % i == 0 : return False return True def solution(numbers): answer = 0 for length,_ in enumerate(numbers): numbers_list = list(set(map(''.join, itertools.permutations(numbers,length+1)))) for number in numbers_list: if number[0]!='0' : if isItSosu(int(number)): answer+=1 return answer
17e8c7a2ffb843d2405b22d77128de1a58f4a076
Techbanerg/TB-learn-Python
/Exercises/prompting.py
331
3.65625
4
#!/usr/bin/python def function1(): arg1 = input("\nNiger what's ur Name?\n") if (arg1!=""): arg2 = input("\nWhat's your age homie?\n") print("\nSon of a bitch " + arg1 +" does not look like aged\n"+arg2) else: print("\nThis Ahole aint gotta name") if __name__ == "__main__": function1()
25837b59993dfab08722726f5d723f16b422c448
tied/DevArtifacts
/master/Challenges-master/Challenges-master/level-1/calculateDistance/calculate_distance.py
679
3.5625
4
import sys import math import ast def main(input_file): output = [] with open(input_file, 'r') as data: for line in data: print get_distance(line.strip()) def get_distance(coordinates): coordinates = list(ast.literal_eval(coordinates.replace(')', '),'))) expression = (coordinates[1][0] - coordinates[0][0])**2 + (coordinates[1][1] - coordinates[0][1])**2 distance = int(math.sqrt(expression)) return distance if __name__ == "__main__": try: main(sys.argv[1]) except Exception as e: print 'First argument must be a text file!\nError: {0}'.format(e)
399fc64f6e8d7d79c57f3c278873cef9195becc2
rodrigo129/JuegoBulletHell
/juego/JEFE.py
4,505
3.71875
4
# -*- coding: latin-1 -*- """plantilla de objeto python""" from Armas import ArmaEstandarApuntada class Jefe1 : # recordar siempre declarar self en una funcion de objeto def __init__ ( self , pSpawn , velocidad , alturaAtaque ,info ) : """ :type info: list """ self.Vida = 500000 self.XY = pSpawn.copy ( ) self.AlturaAtaque = alturaAtaque self.C1 = ArmaEstandarApuntada ( 80 , "Enemigo" ) self.C2 = ArmaEstandarApuntada ( 80 + 60 , "Enemigo" ) self.C3 = ArmaEstandarApuntada ( 80 + 120 , "Enemigo" ) self.C4 = ArmaEstandarApuntada ( 80 + 180 , "Enemigo" ) self.C5 = ArmaEstandarApuntada ( 80 + 240 , "Enemigo" ) self.C6 = ArmaEstandarApuntada ( 80 + 300 , "Enemigo" ) self.C7 = ArmaEstandarApuntada ( 80 + 360 , "Enemigo" ) self.C8 = ArmaEstandarApuntada ( 80 + 420 , "Enemigo" ) self.Velocidad = velocidad self.AlturaAtaque = alturaAtaque self.Index = 0 self.Tipo = "JEFE" self.Alianza = "Enemigo" self.Tamao = "JEFE" self.InfoEntregada=False self.Info=info print(info) print(self.Info) def GetAlianza ( self ) -> str : return self.Alianza def GetTamao ( self ) : return self.Tamao """obtener tamao""" def GetX ( self ) : return self.XY[ 0 ] def GetCentro ( self ) : return (self.XY[ 0 ] + 32 , self.XY[ 1 ] + 37) def GetY ( self ) : return self.XY[ 1 ] def GetTipo ( self ) : return self.Tipo def Daar ( self , dao ) : self.Vida = self.Vida - dao pass def Fin ( self ) : # print (self.XY[0]==3000 and self.XY[1] == 3000,"destruir") return self.Vida < 0 and self.InfoEntregada def EntregarInfo( self ): if self.Vida < 0: self.InfoEntregada=True print(self.Info) return self.Info else: return [] #if def GetTodo ( self ) : return (self.XY[ 0 ] , self.XY[ 1 ]) def GetIndex ( self ) : return self.Index def Actualizar ( self , objetivo ) : # print("tiempo=",self.TExistencia,"\n") aux = [ ] if self.XY[ 1 ] < self.AlturaAtaque : self.XY[ 1 ] = self.AlturaAtaque + self.Velocidad else : self.C1.Apuntar ( [self.XY[0]+157,self.XY[1]+352] , objetivo ) self.C1.Actualizar ( ) self.C2.Apuntar ( [self.XY[0]+292,self.XY[1]+334] , objetivo ) self.C2.Actualizar ( ) self.C3.Apuntar ( [self.XY[0]+354,self.XY[1]+352] , objetivo ) self.C3.Actualizar ( ) self.C4.Apuntar ( [self.XY[0]+218,self.XY[1]+334] , objetivo ) self.C4.Actualizar ( ) self.C5.Apuntar ( [self.XY[0]+337,self.XY[1]+342] , objetivo ) self.C5.Actualizar ( ) self.C6.Apuntar ( [self.XY[0]+196,self.XY[1]+338] , objetivo ) self.C6.Actualizar ( ) self.C7.Apuntar ( [self.XY[0]+313,self.XY[1]+338], objetivo ) self.C7.Actualizar ( ) self.C8.Apuntar ( [self.XY[0]+174,self.XY[1]+342] , objetivo ) self.C8.Actualizar ( ) for disparo in self.C1.Disparar ( [self.XY[0]+157,self.XY[1]+352]) : aux.append ( disparo ) for disparo in self.C2.Disparar ( [self.XY[0]+292,self.XY[1]+334] ) : aux.append ( disparo ) for disparo in self.C3.Disparar ( [self.XY[0]+354,self.XY[1]+352] ) : aux.append ( disparo ) for disparo in self.C4.Disparar ( [self.XY[0]+218,self.XY[1]+334] ) : aux.append ( disparo ) for disparo in self.C5.Disparar ( [self.XY[0]+337,self.XY[1]+342] ) : aux.append ( disparo ) for disparo in self.C6.Disparar ( [self.XY[0]+196,self.XY[1]+338] ) : aux.append ( disparo ) for disparo in self.C7.Disparar ( [self.XY[0]+313,self.XY[1]+338] ) : aux.append ( disparo ) for disparo in self.C8.Disparar ( [self.XY[0]+174,self.XY[1]+342] ) : aux.append ( disparo ) return aux
4dc905bcc09344f838ab7b5c383603892c178bd5
horia94ro/python_fdm_15ianuarie
/day_2_part_2.py
3,602
4.03125
4
nume_utilizator = input("Introduceti userul: ") print(len(nume_utilizator)) nume_utilizator = nume_utilizator.strip(str(9)) print(len(nume_utilizator)) sir = input("Introduceti sirul: ") if len(sir) > 1: # rez = sir[:2] + sir[len(sir) - 2 : len(sir)] rez = sir[:2] + sir[-2:] print(rez) else: print("Lungime prea mica a sirului!") sir = input("Introduceti sirul: ") for i in range(0, len(sir), 2): print(sir[i], end = " ") print("") for i in range(0, len(sir)): if i % 2 == 0: print(sir[i], end = " ") lista = [1, 2, True] lista_mea = [10, 20, "sir", True, 'telecom', 'python'] lista_mea.append("valoare noua") #adaugare in lista lista_mea.append(10) #listele memoreaza/suporta elementele duplicate # lista_mea.sort() #va genera exceptie pentru ca am tipuri diferite de date lista_mea.reverse() print(lista_mea[1:5]) #slicing-ul merge identic ca la string-uri print(lista_mea[3]) # print(lista_mea[99]) #va genera IndexError - nu exista indexul in cadrul listei mele print(lista_mea.index('sir')) #prima aparitie a elementului cautat lista_mea.remove("telecom") #metoda nu returneaza nimic; exceptie daca nu elementul nu exista del lista_mea[3] #statement, diferit de apelul metodei remove de mai sus print(lista_mea.pop()) #cand pop() nu are argument, returneaza si elimina ultimul element print(lista_mea.pop(0)) #elimina elementul de pe pozitia 0 si il returneaza nr = int(input("Cate valori doriti introduse?")) lista_val = [] for i in range(0, nr): lista_val.append(int(input("Valoarea cu indexul {0}: ".format(i)))) print("Lista initiala este: ", lista_val) for i in range(0, nr): lista_val[i] = lista_val[i] ** 2 print("Lista finala este: ", lista_val) rez = [i ** 2 for i in lista_mea] lista_2 = ['rosu', 'verde', 'albastru', 'galben'] rez = [var.upper() for var in lista_2] print(rez) rez = [var for var in lista_2 if len(var) == 4] print(rez) # Cititi de la tastatura N elemente intr-o lista; intr-o lista secundara # pastrati doar valorile unice N = int(input("Cate valori adaugam in lista?")) lista_init =[] for i in range(0, N): lista_init.append(int(input("Valoarea {}: ".format(i)))) lista_unice = [] for i in lista_init: if i not in lista_unice: lista_unice.append(i) else: pass print(lista_unice) setul_meu = {10, 20, "sir", True, 10, 20, False, "sir"} setul_meu.add(47) setul_meu.add(47) setul_meu.add(50) setul_meu.add("sir") print(setul_meu) setul_meu.update([10, 11, 12, 13, 14, 15]) print(setul_meu) # print(setul_meu[4]) #set-urile NU se indexeaza asemanator tuplurilor/listelor setul_meu.remove(20) # setul_meu.remove(20) #KeyError daca incerc sa elimin ceva ce nu exista print(setul_meu) setul_meu.discard(20) #NU va mai arunca eroare la momentul rularii, chiar daca elementul nu exista # dictionar = {'cheie_1':10, 'cheie_2':30, 'cheie_3':45, 'cheie_4':True} # print(dictionar['cheie_1']) # dictionar['cheie_2'] = 44 # print(dictionar) persoana = {'nume':'', 'varsta': '', 'e-mail':"horia.calin@telacad.ro"} persoana.update({'nume':'Horia', 'varsta':25}) # print(persoana) # persoana['culoare_ochi'] = 'caprui' # print(persoana) # persoane_varsta = [ ('Tudor', 17), ('Laur', 29), ('Daniela', 27), ('Tudor', 28)] # dict_pers_varsta = dict(persoane_varsta) # print(dict_pers_varsta) print(list(persoana.keys())) print(list(persoana.values())) print(persoana.items()) for k, v in persoana.items(): print("Cheia este: {0}, valoarea: {1}".format(k, v))
b80b274f95b407ace8bf851914a89206d9dd1b5c
lizyang95/leetcode
/leetcode4/searchMatrix.py
1,099
3.5
4
class Solution(object): def searchMatrix(self, matrix, target): """ :type matrix: List[List[int]] :type target: int :rtype: bool """ if len(matrix) == 0: return False if len(matrix[0]) == 0: return False while(len(matrix)>=1): if matrix[-1][-1] < target: return False else: if matrix[-1].count(target) > 0: return True else: del matrix[-1] return False def searchMatrix(self, matrix, target): """ :type matrix: List[List[int]] :type target: int :rtype: bool """ if not matrix: return False nrow = len(matrix) ncol = len(matrix[0]) r = 0 c = ncol -1 while r < nrow and c >=0: if target < matrix[r][c]: c -= 1 elif target > matrix[r][c]: r += 1 else: return True return False
e8511a009295fdc16b92455e1483f1668606ff39
smtamh/oop_python_ex
/student_result/2019/01_number_baseball/baseball [2-3 ์–‘A].py
12,239
3.75
4
""" ์ˆซ์ž ์•ผ๊ตฌ ๊ฒŒ์ž„ 2019.09.23 made by 230* ์–‘** """ import random NUM_DIGITS = 3 # ์ •๋‹ต ์ˆซ์ž์˜ ์ž๋ฆฟ์ˆ˜๋ฅผ ๋‚˜ํƒ€๋‚ด๋Š” ์ƒ์ˆ˜ NUM_CHANCES = 10 # ๋ฌธ์ œ๋ฅผ ๋งž์ถ”๋Š” ์ „์ฒด ๊ธฐํšŒ์˜ ์ˆ˜๋ฅผ ๋‚˜ํƒ€๋‚ด๋Š” ์ƒ์ˆ˜ ANSWER = "" # ์ •๋‹ต ์ˆซ์ž๋ฅผ ๋ฌธ์ž์—ด๋กœ ์ €์žฅํ•˜๋Š” ์ƒ์ˆ˜ def start_notification(): """ ์ˆซ์ž ์•ผ๊ตฌ ๊ฒŒ์ž„์„ ์‹œ์ž‘ํ•˜๊ธฐ ์ „์— ์‹คํ–‰๋˜๋Š” ํ•จ์ˆ˜๋กœ์„œ, ํ”Œ๋ ˆ์ด์–ด์˜ ์š”๊ตฌ์— ๋”ฐ๋ผ ์ˆซ์ž ์•ผ๊ตฌ์˜ ๊ทœ์น™์— ๋Œ€ํ•ด ์„ค๋ช…ํ•˜๋Š” ํ•จ์ˆ˜. :return: ์—†์Œ. """ global NUM_DIGITS, NUM_CHANCES, ANSWER # ์ „์—ญ ๋ณ€์ˆ˜ ์‚ฌ์šฉ์„ ์œ„ํ•œ ์„ ์–ธ print('=' * 100) print("<์ˆซ์ž ์•ผ๊ตฌ ๊ฒŒ์ž„>์ด ์‹œ์ž‘๋˜์—ˆ์Šต๋‹ˆ๋‹ค.") print("โ”ปโ”ณ|\n" "โ”ณโ”ป|__โˆง ...์•ผ๊ตฌ?\n" "โ”ปโ”ณ|โ€ข๏นƒโ€ข)\n" "โ”ณโ”ป|โŠ‚๏พ‰\n" "โ”ปโ”ณ|๏ผช\n") print("<์ˆซ์ž ์•ผ๊ตฌ ๊ฒŒ์ž„>์˜ ๊ทœ์น™ ์„ค๋ช…์„ ๋“ค์œผ์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (y/(n))", end=' ') rule = input() # ๊ทœ์น™ ์„ค๋ช…์„ ๋“ฃ๋Š”์ง€ ์—ฌ๋ถ€์— ๋Œ€ํ•œ ๋Œ€๋‹ต ์ž…๋ ฅ. # if rule == 'y' or rule == 'yes': # y, ๋˜๋Š” yes๊ฐ€ ์ž…๋ ฅ๋  ๊ฒฝ์šฐ ๊ทœ์น™์— ๋Œ€ํ•œ ์„ค๋ช… ์ œ๊ณต if rule in "y yes".split(): # y, ๋˜๋Š” yes๊ฐ€ ์ž…๋ ฅ๋  ๊ฒฝ์šฐ ๊ทœ์น™์— ๋Œ€ํ•œ ์„ค๋ช… ์ œ๊ณต rule_explain() if rule == "developer": # ํŽธ๋ฆฌํ•œ ๋””๋ฒ„๊น…์„ ์œ„ํ•ด ์ œ์ž‘ํ•œ ๊ฐœ๋ฐœ์ž ๋ชจ๋“œ, ์œ„ ์งˆ๋ฌธ์— developer๋ฅผ ์ž…๋ ฅํ•˜๋ฉด ์ •๋‹ต ์ˆซ์ž์˜ ์ž๋ฆฟ์ˆ˜์™€ ์ •๋‹ต ๊ธฐํšŒ๋ฅผ ์„ค์ •ํ•  ์ˆ˜ ์žˆ๋‹ค. print("๊ฐœ๋ฐœ์ž ๋ชจ๋“œ๋กœ ์ „ํ™˜ํ•ฉ๋‹ˆ๋‹ค.") print("NUM_DIGITS =", end=' ') NUM_DIGITS = int(input()) # 1๋ถ€ํ„ฐ 10๊นŒ์ง€์˜ ์ •์ˆ˜๋ฅผ ์ž…๋ ฅ๋ฐ›์•„ ์ •๋‹ต ์ˆซ์ž์˜ ์ž๋ฆฟ์ˆ˜ NUM_DIGITS๋ฅผ ์žฌ์„ค์ • print("NUM_CHANCES =", end=' ') NUM_CHANCES = int(input()) # ์ž์—ฐ์ˆ˜๋ฅผ ์ž…๋ ฅ๋ฐ›์•„ ์ •๋‹ต ๊ธฐํšŒ NUM_CHANCES๋ฅผ ์žฌ์„ค์ • print("์ˆซ์ž์˜ ์ž๋ฆฟ์ˆ˜๋Š” %d, ์ •๋‹ต ์ž…๋ ฅ ๊ธฐํšŒ๋Š” %d(์œผ)๋กœ ์žฌ์„ค์ •๋˜์—ˆ์Šต๋‹ˆ๋‹ค." % (NUM_DIGITS, NUM_CHANCES)) print('\n' + '=' * 100) print("Enter ๋ฅผ ๋ˆ„๋ฅด๋ฉด ์‹œ์ž‘ํ•ฉ๋‹ˆ๋‹ค!", end=' ') input() # Enter ๋ฅผ ๋ˆ„๋ฅธ ํ›„์— ๊ฒŒ์ž„์ด ์‹œ์ž‘๋˜๋„๋ก ์ž„์˜์˜ ์ž…๋ ฅ์„ ๋ฐ›์Œ. def rule_explain(): """ ์ˆซ์ž ์•ผ๊ตฌ ๊ฒŒ์ž„์˜ ๊ทœ์น™์„ ์ถœ๋ ฅํ•˜๋Š” ํ•จ์ˆ˜. :return: ์—†์Œ. """ global NUM_DIGITS print('\n' + '=' * 100) print("|์ˆซ์ž ์•ผ๊ตฌ ๊ฒŒ์ž„ ๊ทœ์น™|") print("๊ฐ ์ž๋ฆฌ์ˆ˜๊ฐ€ ๋ชจ๋‘ ๋‹ค๋ฅธ %d์ž๋ฆฌ ์ˆซ์ž๊ฐ€ ๋žœ๋ค์œผ๋กœ ์ƒ์„ฑ๋ฉ๋‹ˆ๋‹ค." % NUM_DIGITS) print("๊ทธ %d์ž๋ฆฌ ์ˆซ์ž๋ฅผ %d๋ฒˆ ์•ˆ์— ๋งž์ถ”๋ฉด ์Šน๋ฆฌํ•˜๊ณ , ๊ทธ๋ ‡์ง€ ๋ชปํ•˜๋ฉด ํŒจ๋ฐฐํ•ฉ๋‹ˆ๋‹ค." % (NUM_DIGITS, NUM_CHANCES)) print("์ˆซ์ž๋ฅผ ์ž…๋ ฅํ•˜๋ฉด, ์ž…๋ ฅํ•œ ์ˆซ์ž๊ฐ€ ์ •๋‹ต๊ณผ ์–ผ๋งˆ๋‚˜ ์œ ์‚ฌํ•œ์ง€ '์ˆซ์ž ์•ผ๊ตฌ' ํ˜•์‹์œผ๋กœ ์•Œ๋ ค์ค๋‹ˆ๋‹ค.") print("๊ฐ '์ˆซ์ž ์•ผ๊ตฌ' ์ •๋ณด๊ฐ€ ์˜๋ฏธํ•˜๋Š” ๋ฐ”๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์Šต๋‹ˆ๋‹ค.") print("") print("Strike (S): ์ •๋‹ต์— ํฌํ•จ๋˜๊ณ , ์œ„์น˜๋„ ์ผ์น˜ํ•˜๋Š” ์ˆซ์ž์˜ ๊ฐœ์ˆ˜") print("Ball (B): ์ •๋‹ต์— ํฌํ•จ๋˜์ง€๋งŒ, ์œ„์น˜๋Š” ์ผ์น˜ํ•˜์ง€ ์•Š๋Š” ์ˆซ์ž์˜ ๊ฐœ์ˆ˜") print("Out (O): ์ •๋‹ต์— ํฌํ•จ๋˜์ง€ ์•Š๋Š” ์ˆซ์ž์˜ ๊ฐœ์ˆ˜") def random_number(): """ NUM_DIGITS ๋งŒํผ์˜ ์ž๋ฆฟ์ˆ˜๋ฅผ ๊ฐ€์ง„ ์ž„์˜์˜ ์ˆซ์ž๋ฅผ ๋ฌธ์ž์—ด์˜ ํ˜•ํƒœ๋กœ ๋žœ๋ค ๋ฐ˜ํ™˜ํ•˜๋Š” ํ•จ์ˆ˜. :return: ๋ฌธ์ž์—ด ํ˜•์‹์˜ ๋žœ๋ค์œผ๋กœ ๋งŒ๋“ค์–ด์ง„ ์ •๋‹ต ์ˆซ์ž """ global NUM_DIGITS # num_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # 0๋ถ€ํ„ฐ 9๊นŒ์ง€์˜ ์ •์ˆ˜ ๋ฆฌ์ŠคํŠธ ์„ ์–ธ num_list = list(range(10)) # 0๋ถ€ํ„ฐ 9๊นŒ์ง€์˜ ์ •์ˆ˜ ๋ฆฌ์ŠคํŠธ ์„ ์–ธ random.shuffle(num_list) # ๋žœ๋ค์œผ๋กœ ๋ฆฌ์ŠคํŠธ๋ฅผ ์„ž์Œ answer = "" # ์ •๋‹ต์„ ๋ฌธ์ž์—ด ํ˜•ํƒœ๋กœ ์„ ์–ธ for i in range(NUM_DIGITS): # ๋ฌธ์ œ ์ˆซ์ž ์ž๋ฆฟ์ˆ˜ ๋งŒํผ ๋ฐ˜๋ณต answer += str(num_list[i]) # ์ •๋‹ต ๋ฌธ์ž์—ด์˜ ๋’ท๋ถ€๋ถ„์— ๋žœ๋ค์œผ๋กœ ์„ž์€ ์ •์ˆ˜ ๋ฌธ์ž๋ฅผ ์ถ”๊ฐ€ return answer # ๋ฌธ์ž์—ด ํ˜•์‹์˜ ์ •๋‹ต ๋ฐ˜ํ™˜ def is_right_input(number): """ ํ”Œ๋ ˆ์ด์–ด๊ฐ€ ์ž…๋ ฅํ•œ ๋ฌธ์ž์—ด์ด ์˜ณ์€ ํ˜•์‹์ธ์ง€ ์—ฌ๋ถ€๋ฅผ ๋ฆฌํ„ดํ•˜๋Š” ํ•จ์ˆ˜. ์ž…๋ ฅ ๋ฌธ์ž์—ด์ด ์˜ณ์ง€ ์•Š์€ ํ˜•์‹์ผ ๊ฒฝ์šฐ, ์–ด๋– ํ•œ ๋ถ€๋ถ„์ด ์ž˜๋ชป๋˜์—ˆ๋Š”์ง€ ์•Œ๋ ค์คŒ. :param number: ๋ฌธ์ž์—ด ํ˜•ํƒœ์˜ ํ”Œ๋ ˆ์ด์–ด๊ฐ€ ์ž…๋ ฅํ•œ ์ˆซ์ž. :return: ์˜ณ์€ ํ˜•์‹์˜ ์ž…๋ ฅ์ผ ๊ฒฝ์šฐ True, ์˜ณ์ง€ ์•Š์€ ํ˜•์‹์˜ ์ž…๋ ฅ์ผ ๊ฒฝ์šฐ False ๋ฅผ ๋ฐ˜ํ™˜. """ global NUM_DIGITS, ANSWER digits = "0123456789" # 0~9์˜ ์ •์ˆ˜๋กœ ์ด๋ฃจ์–ด์ง„ ๋ฌธ์ž์—ด. ์ž…๋ ฅ๋œ ๋ฌธ์ž๊ฐ€ ์ˆซ์ž ๋ฌธ์ž์ธ์ง€ ํŒ๋‹จํ•  ๋•Œ ์‚ฌ์šฉ. check = [0] * 20 # 0~9์˜ ์ •์ˆ˜๊ฐ€ ์ž…๋ ฅ๋˜์—ˆ๋Š”์ง€ ๊ธฐ๋กํ•˜๋Š” ๋ฆฌ์ŠคํŠธ. ์ •์ˆ˜ k๊ฐ€ ์ด์ „์— ์ž…๋ ฅ๋œ ๊ฒฝ์šฐ, check[k]์˜ ๊ฐ’์€ 1, ๊ทธ๋ ‡์ง€ ์•Š์€ ๊ฒฝ์šฐ 0. for i in number: # number ์˜ ๋ชจ๋“  ๊ตฌ์„ฑ ๋ฌธ์ž์— ๋Œ€ํ•ด ํ™•์ธ. if i not in digits: # number ์˜ ๊ตฌ์„ฑ ๋ฌธ์ž๊ฐ€ ์ •์ˆ˜ ๋ฌธ์ž๊ฐ€ ์•„๋‹ ๋•Œ, print("์˜๋ฌธ, ํ•œ๊ธ€, ํŠน์ˆ˜๋ฌธ์ž, ๊ณต๋ฐฑ ๋“ฑ์˜ ์ˆซ์ž๊ฐ€ ์•„๋‹Œ ๋ฌธ์ž๋Š” ์ž…๋ ฅํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.\n") # ์ž…๋ ฅ ์˜ค๋ฅ˜ ์•ˆ๋‚ด return False # ์˜ณ์ง€ ์•Š์€ ์ž…๋ ฅ์ด๋ฏ€๋กœ False ๋ฐ˜ํ™˜. if len(number) < NUM_DIGITS: # number ์˜ ์ž๋ฆฟ์ˆ˜๊ฐ€ ์ •๋‹ต ์ˆซ์ž์˜ ์ž๋ฆฟ์ˆ˜๋ณด๋‹ค ์ž‘์„ ๋•Œ print("์ž…๋ ฅํ•˜์‹  ์ˆซ์ž์˜ ๊ฐœ์ˆ˜๊ฐ€ ๋„ˆ๋ฌด ์ ์Šต๋‹ˆ๋‹ค. %d๊ฐœ์˜ ์ˆซ์ž๋ฅผ ์ž…๋ ฅํ•ด ์ฃผ์‹ญ์‹œ์˜ค.\n" % NUM_DIGITS) # ์ž…๋ ฅ ์˜ค๋ฅ˜ ์•ˆ๋‚ด return False # ์˜ณ์ง€ ์•Š์€ ์ž…๋ ฅ์ด๋ฏ€๋กœ False ๋ฐ˜ํ™˜. if len(number) > NUM_DIGITS: # number ์˜ ์ž๋ฆฟ์ˆ˜๊ฐ€ ์ •๋‹ต ์ˆซ์ž์˜ ์ž๋ฆฟ์ˆ˜๋ณด๋‹ค ํด ๋•Œ print("์ž…๋ ฅํ•˜์‹  ์ˆซ์ž์˜ ๊ฐœ์ˆ˜๊ฐ€ ๋„ˆ๋ฌด ๋งŽ์Šต๋‹ˆ๋‹ค. %d๊ฐœ์˜ ์ˆซ์ž๋ฅผ ์ž…๋ ฅํ•ด ์ฃผ์‹ญ์‹œ์˜ค.\n" % NUM_DIGITS) # ์ž…๋ ฅ ์˜ค๋ฅ˜ ์•ˆ๋‚ด return False # ์˜ณ์ง€ ์•Š์€ ์ž…๋ ฅ์ด๋ฏ€๋กœ False ๋ฐ˜ํ™˜. for i in number: # number ์˜ ๋ชจ๋“  ๊ตฌ์„ฑ ๋ฌธ์ž์— ๋Œ€ํ•ด ํ™•์ธ. if check[int(i)] == 1: # ๊ฐ™์€ ์ˆซ์ž๊ฐ€ 2๋ฒˆ number ์— ๋‘ ๊ฐœ ์ด์ƒ ์กด์žฌํ•  ๋•Œ, print("๊ฐ™์€ ์ˆซ์ž๋Š” ์ž…๋ ฅํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.\n") # ์ž…๋ ฅ ์˜ค๋ฅ˜ ์•ˆ๋‚ด return False # ์˜ณ์ง€ ์•Š์€ ์ž…๋ ฅ์ด๋ฏ€๋กœ False ๋ฐ˜ํ™˜. check[int(i)] = 1 # ์ •์ˆ˜ i๊ฐ€ ์ž…๋ ฅ๋˜์—ˆ๋‹ค๋Š” ๊ฒƒ์„ ๊ธฐ๋ก. return True # ์œ„์˜ ๋ชจ๋“  ๊ฒฝ์šฐ์— ํ•ด๋‹นํ•˜์ง€ ์•Š๋Š” ๊ฒฝ์šฐ ์˜ณ์€ ์ž…๋ ฅ์ด๋ฏ€๋กœ True ๋ฐ˜ํ™˜. def baseball_information(number): """ ํ”Œ๋ ˆ์ด์–ด๊ฐ€ ์ž…๋ ฅํ•œ ์˜ณ์€ ํ˜•์‹์˜ ์ •์ˆ˜ ๋ฌธ์ž์—ด์ด ์ •๋‹ต ์ •์ˆ˜ ๋ฌธ์ž์—ด๊ณผ ์–ผ๋งˆ๋‚˜ ์œ ์‚ฌํ•œ์ง€ '์ˆซ์ž ์•ผ๊ตฌ' ํ˜•์‹์œผ๋กœ ์•Œ๋ ค์ฃผ๋Š” ํ•จ์ˆ˜. ํ”Œ๋ ˆ์ด์–ด๊ฐ€ ์ž…๋ ฅํ•œ ๋ฌธ์ž์—ด์˜ ์ •๋‹ต ์—ฌ๋ถ€๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค. :param number: ํ”Œ๋ ˆ์ด์–ด๊ฐ€ ์ž…๋ ฅํ•œ ์˜ณ์€ ํ˜•์‹์˜ ์ •์ˆ˜ ๋ฌธ์ž์—ด. :return: ํ”Œ๋ ˆ์ด์–ด๊ฐ€ ์ž…๋ ฅํ•œ ์ •์ˆ˜ ๋ฌธ์ž์—ด์ด ์ •๋‹ต๊ณผ ์ผ์น˜ํ•  ๊ฒฝ์šฐ True, ์ผ์น˜ํ•˜์ง€ ์•Š์„ ๊ฒฝ์šฐ False ๋ฅผ ๋ฐ˜ํ™˜. """ # strike, ball, out์˜ ๊ฐœ์ˆ˜๋ฅผ ์ €์žฅํ•  ๋ณ€์ˆ˜๋“ค ์„ ์–ธ. strike = 0 ball = 0 out = 0 for i in range(NUM_DIGITS): # 0 ~ NUM_DIGITS-1 ์˜ ์ธ๋ฑ์Šค, ์ฆ‰, ๋ฌธ์ž์—ด์˜ ๋ชจ๋“  ๋ฌธ์ž์— ๋Œ€ํ•ด ํ™•์ธ. if number[i] == ANSWER[i]: # number ์— ์†ํ•œ ๋ฌธ์ž์™€ ์ •๋‹ต ๋ฌธ์ž์˜ ์ข…๋ฅ˜์™€ ์œ„์น˜๊ฐ€ ๋ชจ๋‘ ๊ฐ™์€ ๊ฒฝ์šฐ, strike += 1 # strike ๊ฐœ์ˆ˜ ์ฆ๊ฐ€ elif number[i] in ANSWER: # number ์— ์†ํ•œ ๋ฌธ์ž์™€ ์ •๋‹ต ๋ฌธ์ž์˜ ์ข…๋ฅ˜๋Š” ๊ฐ™์ง€๋งŒ ์œ„์น˜๊ฐ€ ๋‹ค๋ฅธ ๊ฒฝ์šฐ, ball += 1 # ball ๊ฐœ์ˆ˜ ์ฆ๊ฐ€ else: # number ์— ์†ํ•œ ๋ฌธ์ž๊ฐ€ ์ •๋‹ต ๋ฌธ์ž์—ด์— ์กด์žฌํ•˜์ง€ ์•Š๋Š” ๊ฒฝ์šฐ, out += 1 # out ๊ฐœ์ˆ˜ ์ฆ๊ฐ€ print("\nStrike โ†’ %d | Ball โ†’ %d | Out โ†’ %d" % (strike, ball, out)) # '์ˆซ์ž ์•ผ๊ตฌ' ํ˜•์‹์˜ ์ •๋ณด ์•ˆ๋‚ด. if strike == NUM_DIGITS: # ์ŠคํŠธ๋ผ์ดํฌ์˜ ๊ฐœ์ˆ˜์™€ ์ •๋‹ต ์ˆซ์ž์˜ ์ž๋ฆฟ์ˆ˜๊ฐ€ ๊ฐ™์€ ๊ฒฝ์šฐ, ์ฆ‰, number ๊ฐ€ ์ •๋‹ต ๋ฌธ์ž์—ด์ธ ๊ฒฝ์šฐ, return True # number ๊ฐ€ ์ •๋‹ต์ด๋ฏ€๋กœ True ๋ฐ˜ํ™˜. else: # number ๊ฐ€ ์ •๋‹ต ๋ฌธ์ž์—ด์ด ์•„๋‹Œ ๊ฒฝ์šฐ, return False # number ๊ฐ€ ์˜ค๋‹ต์ด๋ฏ€๋กœ False ๋ฐ˜ํ™˜. def win(round): """ ์ฃผ์–ด์ง„ ๊ธฐํšŒ ๋‚ด์— ์ •๋‹ต์„ ๋งž์ถ˜ ๊ฒฝ์šฐ, ์ •๋‹ต์„ ๋งž์ถ˜ ๋ผ์šด๋“œ์™€ ์Šน๋ฆฌ ๋ฌธ๊ตฌ๋ฅผ ์ถœ๋ ฅํ•˜๋Š” ํ•จ์ˆ˜. :return: ์—†์Œ. """ print('\n' + '-' * 100) print("...ฮ›๏ผฟฮ›\n" "๏ผˆใ†ฯ‰ใ†)ใคโ”โ˜†*ใ€‚\n" "โŠ‚ใ€€ใ€€ ใƒŽ ใ€€ใ€€ใ€€.์ •\n" "ใ€€ใ—-๏ผชใ€€ใ€€ใ€€ยฐใ€‚๋‹ต *ยดยจ)\n" "ใ€€ใ€€ใ€€ใ€€ใ€€ใ€€..ใ€€.ยท ยดยธ.ยท์ด*ยดยจ) ยธ.ยท*ยจ)\n" "ใ€€ใ€€ใ€€ใ€€ใ€€ใ€€ใ€€ใ€€ใ€€ใ€€(ยธ.ยทยด (์—์š”!ยธ.'*\n") print("%d ๋ผ์šด๋“œ ๋งŒ์— ์ •๋‹ต์„ ๋งž์ถ”์–ด ์Šน๋ฆฌํ•˜์…จ์Šต๋‹ˆ๋‹ค!" % round) def lose(): """ ์ฃผ์–ด์ง„ ๊ธฐํšŒ ๋‚ด์— ์ •๋‹ต์„ ๋งž์ถ”์ง€ ๋ชปํ•œ ๊ฒฝ์šฐ, ํŒจ๋ฐฐ ๋ฌธ๊ตฌ๋ฅผ ์ถœ๋ ฅํ•˜๋Š” ํ•จ์ˆ˜. :return: ์—†์Œ. """ global NUM_CHANCES print('\n' + '-' * 100) print("โ•ญโ”ˆโ”ˆโ”ˆโ”ˆโ•ฏโ€ƒโ€ƒ โ•ฐโ”ˆโ”ˆโ”ˆโ•ฎ\n\n" "โ€ƒโ•ฐโ”ณโ”ณโ•ฏโ€ƒโ€ƒโ€ƒ โ•ฐโ”ณโ”ณโ•ฏ\n\n" "โ€ƒโ€ƒN ใ€€โ€ƒโ€ƒโ€ƒโ€ƒN\n\n" "โ€ƒโ—‹โ€ƒโ€ƒใ€€โ€ƒโ€ƒโ€ƒ โ—‹\n" "โ€ƒโ€ƒโ€ƒโ€ƒโ•ฐโ”ˆโ”ˆโ•ฏ\n" "โ€ƒ O โ•ญโ”โ”โ”โ”โ”โ•ฎใ€€ O\n" "โ€ƒ โ€ƒโ€ƒ โ”ˆโ”ˆโ”ˆโ”ˆ\n" "ใ€€ใ€€oโ€ƒโ€ƒโ€ƒโ€ƒโ€ƒใ€€ใ€€ o\n") print("%d ๋ผ์šด๋“œ ๋งŒ์— ์ •๋‹ต์„ ๋งž์ถ”์ง€ ๋ชปํ•ด ํŒจ๋ฐฐํ•˜์…จ์Šต๋‹ˆ๋‹ค..." % NUM_CHANCES) def play_game(): """ ํ•˜๋‚˜์˜ ๊ฒŒ์ž„์„ ์‹œ์ž‘ํ•˜๋Š” ํ•จ์ˆ˜. :return: ์—†์Œ """ global NUM_DIGITS, NUM_CHANCES, ANSWER ANSWER = random_number() # ์ •๋‹ต ๋ฌธ์ž์—ด์„ ๋žœ๋ค์œผ๋กœ ์ƒ์„ฑ. for i in range(1, NUM_CHANCES+1): # 1 ~ NUM_CHANCES ์˜ ๋ผ์šด๋“œ๋ฅผ ์ด NUM_CHANCES ํšŒ ์ง„ํ–‰. print('\n' + '-' * 100) print("%d ๋ผ์šด๋“œ์ž…๋‹ˆ๋‹ค. %d๋ฒˆ์˜ ๊ธฐํšŒ๊ฐ€ ๋‚จ์•„์žˆ์Šต๋‹ˆ๋‹ค\n" % (i, NUM_CHANCES - i + 1)) # ๋ผ์šด๋“œ์™€ ์ž”์—ฌ ๊ธฐํšŒ ์ •๋ณด ์•ˆ๋‚ด. while True: # ์˜ณ์€ ํ˜•์‹์˜ ๋ฌธ์ž์—ด์ด ์ž…๋ ฅ๋  ๋•Œ๊นŒ์ง€ ๋ฐ˜๋ณต. print("์ˆซ์ž๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”:", end=' ') number = input() # ํ”Œ๋ ˆ์ด์–ด์˜ ๋ฌธ์ž์—ด ์ž…๋ ฅ. if number == "exit": # ๋งŒ์•ฝ exit ๊ฐ€ ์ž…๋ ฅ๋˜๋ฉด, ๊ฒŒ์ž„์„ ์ค‘๋„ ์ข…๋ฃŒ. print('\n' + "=" * 100) print("๊ฒŒ์ž„์„ ์ข…๋ฃŒํ•ฉ๋‹ˆ๋‹ค.") return # ํ•จ์ˆ˜ ์ „์ฒด๋ฅผ ๋ฆฌํ„ดํ•จ์œผ๋กœ์จ ๊ฒŒ์ž„ ์ข…๋ฃŒ. if is_right_input(number): # ์˜ณ์€ ํ˜•์‹์˜ ๋ฌธ์ž์—ด์ด ์ž…๋ ฅ๋˜๋ฉด, ๋ฐ˜๋ณต๋ฌธ ํƒˆ์ถœ break is_answer = baseball_information(number) # ํ”Œ๋ ˆ์ด์–ด๊ฐ€ ์ž…๋ ฅํ•œ ๋ฌธ์ž์—ด์˜ '์ˆซ์ž ์•ผ๊ตฌ' ์ •๋ณด๋ฅผ ์•ˆ๋‚ดํ•˜๊ณ , ์ •๋‹ต ์—ฌ๋ถ€๋ฅผ ๋ฐ›์•„์˜ด. if is_answer: # ํ”Œ๋ ˆ์ด์–ด๊ฐ€ ์ž…๋ ฅํ•œ ๋ฌธ์ž์—ด์ด ์ •๋‹ต์ผ ๊ฒฝ์šฐ, win(i) # ์Šน๋ฆฌ ๋ฌธ๊ตฌ ์ถœ๋ ฅ. return # ํ•จ์ˆ˜ ์ „์ฒด๋ฅผ ๋ฆฌํ„ดํ•จ์œผ๋กœ์จ ๊ฒŒ์ž„ ์ข…๋ฃŒ. lose() # ํ”Œ๋ ˆ์ด์–ด๊ฐ€ ์ž…๋ ฅํ•œ ๋ฌธ์ž์—ด์ด ์ •๋‹ต์ด ์•„๋‹ˆ์–ด์„œ ํ•จ์ˆ˜๊ฐ€ ๋ฆฌํ„ด๋˜์ง€ ์•Š์€ ๊ฒฝ์šฐ, ํŒจ๋ฐฐ ๋ฌธ๊ตฌ๋ฅผ ์ถœ๋ ฅ. def play_again(): """ ๊ฒŒ์ž„์„ ๋‹ค์‹œ ํ”Œ๋ ˆ์ดํ• ์ง€ ๋ฌผ์–ด๋ณด๊ณ , ํ”Œ๋ ˆ์ด์–ด์˜ ๋Œ€๋‹ต์— ๋”ฐ๋ผ ์žฌ์‹œ์ž‘ ์—ฌ๋ถ€๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋Š” ํ•จ์ˆ˜. :return: ํ”Œ๋ ˆ์ด์–ด๊ฐ€ ๊ฒŒ์ž„์„ ๋‹ค์‹œ ํ”Œ๋ ˆ์ด ํ•˜๊ฒ ๋‹ค๊ณ  ๋‹ตํ•˜๋ฉด True, ๊ทธ๋ ‡์ง€ ์•Š๋‹ค๋ฉด False๋ฅผ ๋ฐ˜ํ™˜. """ print('\n' + '-' * 100) print("๋‹ค์‹œ ํ”Œ๋ ˆ์ด ํ•˜์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (y/(n))", end=' ') replay = input() # ์žฌ์‹œ์ž‘ ์—ฌ๋ถ€์— ๋Œ€ํ•œ ๋Œ€๋‹ต ์ž…๋ ฅ. if replay in "y yes".split(): # y ๋˜๋Š” yes๊ฐ€ ์ž…๋ ฅ๋  ๊ฒฝ์šฐ, ํ”Œ๋ ˆ์ด์–ด๊ฐ€ ์žฌ์‹œ์ž‘์„ ์›ํ•œ๋‹ค๋Š” ์˜๋ฏธ์˜ True ๋ฆฌํ„ด. return True else: # ๊ทธ๋ ‡์ง€ ์•Š์„ ๊ฒฝ์šฐ, ํ”Œ๋ ˆ์ด์–ด๊ฐ€ ์žฌ์‹œ์ž‘์„ ์›ํ•˜์ง€ ์•Š๋Š”๋‹ค๋Š” ์˜๋ฏธ์˜ False ๋ฆฌํ„ด. return False start_notification() # ์ˆซ์ž ์•ผ๊ตฌ ๊ฒŒ์ž„์— ๋Œ€ํ•œ ์„ค๋ช…์„ ์ œ๊ณตํ•จ์œผ๋กœ์จ ๊ฒŒ์ž„์˜ ์‹œ์ž‘์„ ์•Œ๋ฆผ. while True: # ์‚ฌ์šฉ์ž๊ฐ€ ์žฌ์‹œ์ž‘์„ ์›ํ•˜์ง€ ์•Š์„ ๋•Œ๊นŒ์ง€, play_game() # ๊ฒŒ์ž„์„ ์‹œ์ž‘. if not play_again(): # ๊ฒŒ์ž„์ด ๋๋‚˜๋ฉด ์žฌ์‹œ์ž‘ ์—ฌ๋ถ€์— ๊ด€ํ•ด ์งˆ๋ฌธ, ํ”Œ๋ ˆ์ด์–ด๊ฐ€ ์žฌ์‹œ์ž‘์„ ์›ํ•˜์ง€ ์•Š๋Š”๋‹ค๊ณ  ๋‹ตํ•˜๋ฉด ํ”„๋กœ๊ทธ๋žจ์„ ์ข…๋ฃŒ. break
57bdcfba21060783b32ef00d361f945576997114
marcoisgood/Leetcode
/0518. Coin Change 2.py
1,007
3.9375
4
""" 518. Coin Change 2 Medium 1513 54 Add to List Share You are given coins of different denominations and a total amount of money. Write a function to compute the number of combinations that make up that amount. You may assume that you have infinite number of each kind of coin. Example 1: Input: amount = 5, coins = [1, 2, 5] Output: 4 Explanation: there are four ways to make up the amount: 5=5 5=2+2+1 5=2+1+1+1 5=1+1+1+1+1 Example 2: Input: amount = 3, coins = [2] Output: 0 Explanation: the amount of 3 cannot be made up just with coins of 2. Example 3: Input: amount = 10, coins = [10] Output: 1 """ class Solution: def change(self,coins,amount): dp=[0]*(amount+1) dp[0] = 1 for coin in coins: for num in range(1,len(dp)): if coin <= num: dp[num] += dp[num-coin] return dp[-1] if __name__ == "__main__": amount = 6 coins = [1,5] result = Solution().change(coins,amount) print(result)
02829770542910b2814c5391e33c4c4c6fa4874f
Dominique-Cardon/digital-culture
/5_software/demo.py
342
3.921875
4
database = open("first-names.txt") all_names = database.read().split('\n') def checkIfName(username): for name in all_names: if username == name: print("Welcome, " + username + "!") return print("Error occured!") username = input("what is your first name? ") checkIfName(username) database.close()
0bef130fc89b654d9730fbc9a1b26e3530ee7352
charlesfranciscodev/codingame
/community-puzzles/horse-racing-hyperduals/horse_racing_hyperduals.py
468
3.671875
4
import math def distance(vector1, vector2): return abs(vector2[0] - vector1[0]) + abs(vector2[1] - vector1[1]) if __name__ == "__main__": n = int(input()) vectors = [] for i in range(n): vector = tuple(map(int, input().split())) vectors.append(vector) min_d = math.inf for i in range(n): for j in range(i + 1, n): d = distance(vectors[i], vectors[j]) min_d = min(min_d, d) print(min_d)
b917218609e8b2318d8a627bfd389c63dec9bca7
eledoro/FreeCodeCamp-Scientific-Computing-with-Python-Assignments
/polygon-area-calculator/shape_calculator.py
1,529
3.78125
4
# ====== class Rectangle ====== class Rectangle: def __init__(self, width, height): self.width = width self.height = height def get_perimeter(self): perimeter = 2 * self.width + 2 * self.height return perimeter def set_height(self, height): self.height = height def set_width(self, w): self.width = w def get_area(self): return self.width * self.height def get_diagonal(self): return (self.width ** 2 + self.height ** 2) ** .5 def get_picture(self): picture = '' if self.width > 50 or self.height > 50: return "Too big for picture." else: for i in range(self.height): picture += '*' * self.width + '\n' return picture def __str__(self): rectangle_as_str = f'Rectangle(width={self.width}, height={self.height})' return rectangle_as_str def get_amount_inside(self, rectangle): n_in_width = self.width // rectangle.width n_in_height = self.height // rectangle.height if n_in_width >= 1 and n_in_height >= 1: return n_in_width * n_in_height else: return 0 # ======= class Square ========= class Square(Rectangle): def __init__(self, side): super().__init__(side, side) def __str__(self): square_as_str = f'Square(side={self.width})' return square_as_str def set_side(self, side): self.width = side self.height = side
87d3e10b4f5b297bf12b1f64facfd934ef1bb13f
seeinger/OpenCollegePythonWebProject
/session3_20200111/session3-practice1.py
433
3.703125
4
# ์ฝ”๋”ฉํ•ด๋ณด๊ธฐ def calc(type, a, b): if type == '๋”ํ•˜๊ธฐ': return a+b elif type == '๋นผ๊ธฐ': return a-b elif type == '๋‚˜๋ˆ„๊ธฐ': return a/b elif type == '๊ณฑํ•˜๊ธฐ': return a*b a = input('๊ณ„์‚ฐ์ •๋ณด๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”: ') input_list = a.split() type = input_list[0] a = int(input_list[1]) b = int(input_list[2]) result = calc(type, a, b) print("๊ณ„์‚ฐ๊ฒฐ๊ณผ:" + str(result))