text
stringlengths
37
1.41M
# My name is Sofya. This program computes cost of a beverage. # The program asks for the customer's name. name = input("Hello, what is your name?") if name.isalpha(): print("Welcome,"+name+"!") else: print("Sorry, the name should contain only letters.") exit() # The program asks for the type of a beverage a customer wants. beverage = input("What would you like to drink? Tea or Coffee?").lower() if beverage == "coffee" or beverage == "c": beverage = "coffee" elif beverage == "tea" or beverage == "t": beverage = "tea" else: print("We do not know about this drink. We only have tea or coffee.") exit() # The program asks for the size of the preferred beverage. size = input("What size of "+beverage+" would you like?").lower() if size == "small" or size == "s": size = "small" sizePrice = 1.5 elif size == "medium" or size == "m": size = "medium" sizePrice = 2.5 elif size == "large" or size == "l": size = "large" sizePrice = 3.25 else: print("This size is not available, size can be only small, medium or large.") exit() # The programs asks to choose a flavor for the customer's beverage. flavor = input("What flavour would you like? You can choose only one. We have vanilla, chocolate, maple or none for coffee, and lemon, mint or none for tea.").lower() if (flavor == "vanilla" or flavor == "v") and beverage == "coffee": flavor = "vanilla flavor" flavorPrice = 0.25 elif (flavor == "chocolate"or flavor == "c") and beverage == "coffee": flavor = "chocolate flavor" flavorPrice = 0.75 elif (flavor == "maple" or flavor == "m") and beverage == "coffee": flavor = "maple flavor" flavorPrice = 0.50 elif (flavor == "mint" or flavor == "m") and beverage == "tea": flavor = "mint falvor" flavorPrice = 0.5 elif (flavor == "lemon"or flavor == "l") and beverage == "tea": flavor = "lemon flavor" flavorPrice = 0.25 elif flavor == " " or flavor == "none" or flavor == "": flavor = "no flavoring" flavorPrice = 0.0 else: print("Sorry, this flavor is not available.") exit() # The program computes final price of the beverage with tax included and displays the specifications of the beverage as well as the price. cost = sizePrice + flavorPrice taxRate = 0.11 finalCost = round(cost + taxRate * cost, 2) print("For "+name+", a "+size+" "+beverage+", "+flavor+", cost:$"+str(finalCost)+".")
import math class Grocery: def __init__(self): self.items = { 'Banana': {'price': 4, 'stock': 6, 'code':1 }, 'Apple': {'price': 2, 'stock': 0,'code':2 }, 'Orange': {'price': 1.5, 'stock': 32,'code':3}, 'Pear': {'price': 3, 'stock': 15,'code':4}, } def print_items(self): counter = 1 for key in self.items: print(f"{counter}- {key}") counter += 1 class Bill: def __init__(self, grocery): self.grocery = grocery # Contain Dictionary self.price = [] self.products = [] def buy(self, quantity, code): for key in self.grocery.items: if self.grocery.items[key]['code'] == code: if self.grocery.items[key]['stock'] < quantity: print("Out of stock") total = sum(self.price); else: self.grocery.items[key]['stock'] -= quantity print (key, "| price:", self.grocery.items[key]['price'], "| Stock:", self.grocery.items[key]['stock'], "| Barcode:", self.grocery.items[key]['code']) self.price.append(self.grocery.items[key]['price'] * quantity) self.products.append(key) total = sum(self.price); print("..............................................") return total store = Grocery() #contain the Dictionary bill1 = Bill(store) finish = True while finish: store.print_items() item_number = int(input("Please Enter the number of the item: ")) quantity = int(input("Please enter the quantity needed: ")) total = bill1.buy(quantity, item_number) exit_statment = input("Do you need somthing else (y/n): ") if exit_statment == "n": finish = False print("Your total is:", total)
class User: def __init__(self, name, balance ): self.name = name self.balance = balance print(name, balance) def deposit(self, amount): self.balance += amount return self def make_withdrawal(self, amount): if amount > self.balance: return "non sufficient funds" self.balance -= amount return self def display_user_balance(self): print(self.balance) return self.balance def transfer_money(self, other_user, amount): self.make_withdrawal(amount) other_user.deposit(amount) print(other_user.name+"'s new balance:", other_user.balance,"\n" + self.name+"'s my current balance:", self.balance) return self hala = User("hala", 100) layan = User("layan", 0) zaid = User("zaid", 0) hala.deposit(100) hala.deposit(100) hala.deposit(100) # hala's new balance is 400 hala.make_withdrawal(50) # hala's new balance is 350 hala.display_user_balance() layan.deposit(100) layan.deposit(100) # layan's new balance is 200 layan.make_withdrawal(50) # layan's new balance is 150 layan.display_user_balance() zaid.deposit(500) # zaid's new balance is 500 zaid.make_withdrawal(50) zaid.make_withdrawal(50) zaid.make_withdrawal(50) # zaid's new balance is 350 zaid.display_user_balance() hala.transfer_money(zaid,100) # hala's new balance should be 250 # zaid's new balance should be 450
# Suppose we have a standard linked list. # Construct an in-place (without extra memory) algorithm # thats able to find the middle node! # ================================================ # Using Bruteforce method means iterating through whole linked list finding the size # and again iterating throgh the linked list upto middle. # This will have O(N**2) time complexity. # Time Complexity: O(N), # where N is the number of nodes in the given list. # Space Complexity: O(1), the space used by slow and fast pointers. class ListNode: def __init__(self, x): self.value = x self.next = None def findMiddleInLinkedList(a): slowPointer = a fastPointer = a while fastPointer and slowPointer: slowPointer = slowPointer.next fastPointer = fastPointer.next.next return slowPointer.value if __name__ == '__main__': a, a.next, a.next.next, a.next.next.next, a.next.next.next.next, a.next.next.next.next.next= ListNode(2), ListNode(14), ListNode(3),ListNode(6), ListNode(44), ListNode(23) middleNum = findMiddleInLinkedList(a) print(f"Middle number is: {middleNum}")
# In a given grid, each cell can have one of three values: # the value 0 representing an empty cell; # the value 1 representing a fresh orange; # the value 2 representing a rotten orange. # Every minute, any fresh orange that is adjacent (4-directionally) to a rotten orange becomes rotten. # Return the minimum number of minutes that must elapse until no cell has a fresh orange. If this is impossible, return -1 instead. # Example 1: # Input: [[2,1,1],[1,1,0],[0,1,1]] # Output: 4 # Example 2: # Input: [[2,1,1],[0,1,1],[1,0,1]] # Output: -1 # Explanation: The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally. # Example 3: # Input: [[0,2]] # Output: 0 # Explanation: Since there are already no fresh oranges at minute 0, the answer is just 0. # Note: # 1 <= grid.length <= 10 # 1 <= grid[0].length <= 10 # grid[i][j] is only 0, 1, or 2. # ======================================================= # Solution with BFS from collections import deque from typing import List class Solution: def orangesRotting(self, grid: List[List[int]]) -> int: rows, cols = len(grid), len(grid[0]) fresh = 0 # store location of rotten oranges in queue q = deque() for i in range(rows): for j in range(cols): if grid[i][j] == 1: fresh += 1 elif grid[i][j] == 2: q.append((i, j)) # if there is no fresh oranges then return 0 if fresh == 0: return 0 # take adjacent locations of rotten oranges in the list dirs = [(0, 1), (0, -1), (-1, 0), (1, 0)] step = 0 while q: size = len(q) # iterate through the each element in the level for i in range(size): x, y = q.popleft() for d in dirs: nx, ny = x + d[0], y + d[1] if nx < 0 or nx >= rows or ny < 0 or ny >= cols or grid[nx][ny] != 1: continue grid[nx][ny] = 2 q.append((nx, ny)) fresh -= 1 step += 1 if fresh != 0: return -1 # need to reduce step by 1 as we have started with 1 with first rotten orange. return step - 1 if __name__ == '__main__': myGrid = [[2,1,1],[1,1,0],[0,1,1], [1,1,0]] solution = Solution() result = solution.orangesRotting(myGrid) print(f"Minutes: {result}")
# find GCD from given array. # arr = [2,4,6,8] # gcd = 2 def findGCDofArray(arr) -> int: gcd = getGCD(arr[0], arr[1]) for i in range(len(arr)): gcd = getGCD(gcd,arr[i]) return gcd def getGCD(numA:int, numB:int) -> int: while(numB): numA, numB = numB, numA%numB return numA if __name__ == '__main__': arr = [14,56,7,28] result = findGCDofArray(arr) print(f"Greatest common divisible number is: {result}")
# The following iterative sequence is defined for the set of positive integers: # n → n/2 (n is even) # n → 3n + 1 (n is odd) # Using the rule above and starting with 13, we generate the following sequence: # 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1 # It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1. # Which starting number, under one million, produces the longest chain? # NOTE: Once the chain starts the terms are allowed to go above one million. # ==================================================== def findSeqLength(startingNum:int)->int: term = 0 if startingNum == 0: return term # find if the starting number is odd or even if startingNum in hash_store: term = hash_store[startingNum] return term if startingNum %2 == 0: # if even then divide by 2 term = findSeqLength(startingNum//2) else: # otherwise multiply by 3 and add 1 term = findSeqLength((startingNum*3)+1) # increase number of term term +=1 hash_store[startingNum] = term return term if __name__ == '__main__': hash_store = {1:1} resultNum = 0 num = 1000000 max_count = 0 for startingNum in range(num+1): seqLength = findSeqLength(startingNum) if seqLength> max_count: resultNum = startingNum max_count = seqLength print(f"Number with max callatz {max_count} term is: {resultNum}")
#================================ # Part B: Golden Eggs #================================ # Problem 1 def dp_make_weight(egg_weights, target_weight): """ Find number of eggs to bring back, using the smallest number of eggs. Assumes there is an infinite supply of eggs of each weight, and there is always a egg of value 1. Parameters: egg_weights - tuple of integers, available egg weights sorted from smallest to largest value (1 = d1 < d2 < ... < dk) target_weight - int, amount of weight we want to find eggs to fit memo - dictionary, OPTIONAL parameter for memoization (you may not need to use this parameter depending on your implementation) Returns: int, smallest number of eggs needed to make target weight """ sorted_eggs = sorted(egg_weights, reverse=True) # sorting weights of eggs in descending order. number_of_eggs = 0 # counter for the number of eggs that algorithm will take, starts at 0. remaining_weight = target_weight # available weight, will be decreased after some amount of eggs has been taken. for index in range(len(sorted_eggs)): eggs_to_take = remaining_weight // sorted_eggs[index] number_of_eggs += eggs_to_take remaining_weight -= eggs_to_take * sorted_eggs[index] if remaining_weight == 0: # no point in looping through lighter eggs if there is no more remaining weight. break return number_of_eggs if __name__ == '__main__': egg_weights = (1, 5, 10, 25) n = 99 print("Egg weights = (1, 5, 10, 25)") print("n = 99") print("Expected ouput: 9 (3 * 25 + 2 * 10 + 4 * 1 = 99)") print("Actual output:", dp_make_weight(egg_weights, n)) print() egg_weights = (2, 3, 5, 10, 50) n = 998 print("Egg weights = (2, 3, 5, 50)") print("n = 998") print("Expected ouput: 25 (19 * 50 + 4 * 10 + 1 * 5 + 1 * 3 = 998)") print("Actual output:", dp_make_weight(egg_weights, n)) print() egg_weights = (3, 5, 10, 20) n = 543 print("Egg weights = (3, 5, 10, 20)") print("n = 545") print("Expected ouput: 28 (27 * 20 + 1 * 5 = 28)") print("Actual output:", dp_make_weight(egg_weights, n)) print()
def parse_input(): with open("input1.txt", 'r') as f: return f.read() # Prints the number of the first instruction that lands us at the basement. def find_basement(): string = parse_input() floor = 0 pos = 0 for c in string: if c == '(': pos += 1 floor += 1 elif c == ')': pos += 1 floor -= 1 if floor == -1: print(pos) return print(-1) find_basement()
mum2=input() flag=0 for i in mum2: if((i=="0") or (i=="1")): pass else: flag=1 break if(flag==0): print("yes") elif(flag==1): print("no")
num1,num2=map(int,input().split()) num1=str(num1) num2=str(num2) print(num1+num2)
vox=input() if(len(vox)==1): if(vox=='a' or vox=='A' or vox=='e' or vox=='E' or vox=='i' or vox=='I' or vox=='o' or vox=='O' or vox=='u' or vox=='U'): print("Vowel") else: print("Consonant") else: print("Invalid")
a3=input() c=0 for i in a3: if(i==" "): c=c+1 print(c+1)
a45=input() flag=1 for i in a45: if(a45.count(i)>1): flag=0 if(flag==1): print("yes") elif(flag==0): print("no")
word=input() length_=len(word) for i in range(0,(length_//2)+1): if(word[i]==word[(length_-1)-i]): i=i+1 else: break if(i>length_/2): print("yes") else: print("no")
nummo1=int(input()) nummo1=str(nummo1) for i in nummo1: if((int(i)%2)!=0): print(i,end=" ")
from random import * import sys ops = ['+', '-', '*', '/'] #basic operations def make_arith_basic(max_vars): num_vars = randint(2, max_vars) n = randint(0, 10) num_vars-=1 expr = " " + str(n) while(num_vars!=0): n = randint(0,10) i = randint(0,3) temp_exp = expr + ops[i] + str(n) if(not (ops[i] == '/' and n == 0)): ev = eval(temp_exp) if(isinstance(ev, int)): expr = temp_exp num_vars-=1 return [expr,""] #exponents + parenthe+sis man def make_arith_exp(max_vars): num_vars = randint(2, max_vars) open_parenths = 0 n = randint(0, 10) num_vars-=1 expr = str(n) while(num_vars!=0): n = randint(0, 10) i = randint(0,4) i2 = randint(0,1) tmp_expr = expr add_parenths = 0 #0-3 is basic operations if(i < 4): if(ops[i] == '/' and n == 0): continue tmp_expr += ops[i] + '('*i2 + str(n) add_parenths = i2 #4 is ^ elif(i == 4): n = randint(1, 3) if(randint(0,1)==0): n *= -1 tmp_expr += '**' + '(' + str(n) + ')' #gives parenthesis if(eval(expr+(')'*open_parenths)) == 0 and i == 4): continue clos_paren = ')' * (open_parenths+add_parenths) ev = eval(tmp_expr+clos_paren) if(isinstance(ev, int)): expr = tmp_expr num_vars-=1 open_parenths += add_parenths #0 means closing parenths if(randint(0,1) == 0 and open_parenths != 0): expr += ')' open_parenths-=1 while(open_parenths != 0): expr += ')' open_parenths-=1 expr = expr.replace("**",'^') return [expr,""] #fractional operations def make_arith_frac(max_vars, same_dem): num_vars = randint(2, max_vars) n1 = randint(0, 10) n2 = randint(0, 10) while(n2 == 0): n2 = randint(0, 10) num_vars-=1 expr = '(' + str(n1) + '/' + str(n2) + ')' last_div = False while(num_vars!=0): n1 = randint(0,10) if(last_div): while(n1 == 0): n1 = randint(0, 10) if(not same_dem): n2 = randint(0,10) while(n2 == 0): n2 = randint(0, 10) i = randint(0,2) if(same_dem): i = randint(0,1) expr += ops[i] + '(' + str(n1) + '/' + str(n2) + ')' if(ops[i] == '/'): last_div = True else: last_div = False num_vars-=1 return [expr, ""] def print_ret(ret): print("\nSolve:") print(ret[0]) ret[0].replace("^", "**") print("Answer:") print(eval(ret[0])) def make_arith(): i = randint(0,3) n_vars = randint(2,5) if(i == 0): return make_arith_basic(n_vars) if(i == 1): return make_arith_exp(n_vars) if(i == 2): return make_arith_frac(n_vars, True) if(i == 3): return make_arith_frac(n_vars, False) #print_ret(make_arith_basic(int(sys.argv[1]))) #print_ret(make_arith_exp(int(sys.argv[1]))) #print_ret(make_arith_frac(int(sys.argv[1]), True)) #print_ret(make_arith_frac(int(sys.argv[1]), False)) #print_ret(make_arith()) #print(make_arith_basic(int(sys.argv[1]))[0])
# Simple calculator # ADD def add(num1, num2): return num1 + num2 # Substract def subtract(num1, num2): return num1 - num2 # Multiply def multiply(num1, num2): return num1 * num2 # Divide def divide(num1, num2): return num1 / num2 print("Please select operation -\n" \ "1. Add\n" \ "2. Subtract\n" \ "3. Multiply\n" \ "4. Divide\n") # Take input from the user select = raw_input("Select the operation from the menu: ") n1 = int(input("Enter your first number: ")) n2 = int(input("Enter your second number: ")) if select == '1': print(add(n1, n2)) elif select == '2': print(subtract(n1, n2)) elif select == '3': print(multiply(n1, n2)) elif select == '4': print(divide(n1, n2)) else: print("Invalid input")
# 3.1 Question a) import numpy as np vec1= np.arange(5,10) vec2 = np.arange(3,10,2) print vec1 print vec2 # 3.1 Question b) np.linspace(2,5, num=10) a = np.array([[1,2,3,4,5,6]]) # vecteur original à transformer b = np.reshape(a, (3,2)) # transformation du vecteur a en matrice 2x3 c = np.reshape(b, (2,3)) # transformation de b en matrice 3x2 np.transpose(c) # transposée de la matrice c # 3.2 Question a) # Dérivée d'une liste v=[1,4,10,17,26,35,38,49,100] def diff_list(v): n = len(v) d = [v[i+1] - v[i] for i in range(n-1)] return d diff_list(v) # Dérivée d'un vecteur Numpy def diff_np (l): t=np.array(l,dtype=float) n=len(t) c=np.zeros(n-1,dtype=float) for i in range (len(t)-2): a=t[i:i+2] b=t[i+1:i+3] c[i:i+2]=b-a return c # 3.2 Question b) a_list = [np.random.random() for _ in range(1000)] a_np = np.random.random(1000) %%timeit diff_list(a_list) # 3.3 Question a) import numpy as np import matplotlib.pyplot as plt import math as m x=np.linspace(0,2*m.pi,100) y1=np.cos(x) y2=np.cos(2*x) y3=np.cos(3*x) y4=np.sin(x) y5=np.sin(2*x) y6=np.sin(3*x) plt.plot(x,y1,label="cos(x)") plt.plot(x,y2,label="cos(2x)") plt.plot(x,y3,label="cos(3x)") plt.plot(x,y4,label="sin(x)") plt.plot(x,y5,label="sin(2x)") plt.plot(x,y6,label="sin(3x)") plt.xticks(np.arange(0, 2.5*m.pi, step=m.pi/2),('0','π/2','π','2π/3','2π')) plt.yticks(np.arange(-1,1.25,step=0.25)) plt.title('Fonctions trigonométriques') plt.xlabel('x') plt.ylabel('y') plt.legend() plt.show() # 3.3 Question b) import numpy as np import matplotlib.pyplot as plt import math as m plt.imshow(np.random.random((10, 10)), interpolation='none') plt.subplots_adjust(bottom=0.1, right=0.8, top=0.9) cax = plt.axes([0.85, 0.1, 0.075, 0.8]) plt.colorbar(cax=cax) plt.show() # 3.3 Question c) import numpy as np import matplotlib.pyplot as plt x = np.linspace(-3, 3, 300) y = np.linspace(-3, 3, 301) X, Y = np.meshgrid(x, y) Z = (-Y/5) + np.exp(-X**2 - Y**2) plt.pcolor(X, Y, Z) plt.show() # 3.4 a) c=np.array([0.9602, -0.99, 0.2837, 0.9602, 0.7539, -0.1455, -0.99, -0.9111, 0.9602, -0.1455, -0.99, 0.5403, -0.99, 0.9602, 0.2837, -0.99, 0.2837, 0.9602]) cond= (c<=0) c[cond]=0
def pro(): name=input('enter your name\n') name=name.upper() print('\n\n\t\t\t\t HELLO %s'%(name)) n = input('y and n') if 'n' in 'y': import bot pro()
def food(): data = ['hi', 'hello', 'who are you', 'i am a software program', 'what is software', 'the programs and other operating information used by a computer' 'ok', 'hmmm', 'what is your age', 'I am still young by your standards.', 'How are you doing?', 'I am doing well, how about you?', 'I am also good.', 'That is good.', 'who is made you', 'A human', 'Are you a robot?', 'Yes sumthing like that , but i am just a software .', 'you know about nishtha mam ', 'yes she is you project manter and also a your AI professor ', ' Good morning, how are you?', ' I am doing well, how about you?', ' Im also good.', ' Thats good to hear.', ' Yes it is.', '-Hello', ' Hi', ' How are you doing?', ' I am doing well.', ' That is good to hear', ' Yes it is.', ' Can I help you with anything?', ' Yes, I have a question.', ' What is your question?', ' Could I borrow a cup of sugar?', ' Im sorry, but I dont have any.', ' Thank you anyway', ' No problem', ' What is your favorite book?', 'I cant read.', 'So whats your favorite color?', 'Blue', 'What kind of movies do you like?', 'Alice in Wonderland', 'I wish I was The Mad Hatter.', 'Youre entirely bonkers. But Ill tell you a secret. All the best people are.', 'Tell me about your self.', 'What do you want to know?', 'Are you a robot?', 'Yes I am', 'what is robot', 'A robot is a machine—especially one programmable by a computer capable of carrying out a complex series of actions automatically.', ] return(data) def conversation(): data = [ 'hi', 'hello', 'do you drink', 'I am not capable of doing so', 'ok', 'hmmm', 'who are you', 'i am a software program', 'that is great', 'thank you', 'electricity', 'Electricity is food for robots', 'do you eat', 'I m a computer, I cant eat or drink', 'what are your interests', 'I am interested in all kinds of things. We can talk about anything!', 'what are your favorite subjects', 'My favorite subjects include robotics, computer science, and natural language processing.', 'what is your mobile number', 'i do not have any mobile number ', 'are you human', ' i am a software ,not a human ', 'what is your location', 'i am everywhere.', 'do you have any brothers', 'i do not have any brother,but i have lot of clones. ', 'who is made you', 'A human', 'what is your age', 'I am still young by your standards.', 'Good morning, how are you?', 'I am doing well, how about you?', 'I am also good.', 'That is good to hear.', 'Yes it is.', 'Hello', 'Hi', 'How are you doing?', 'I am doing well.', 'That is good to hear', 'Yes it is.', 'Can I help you with anything?', 'Yes, I have a question.', 'What is your question?', 'Could I borrow a cup of sugar?', 'I am sorry, but I do not have any.', 'Thank you', 'No problem', 'How are you doing?', 'I am doing well, how about you?', 'I am also good.', 'That is good.', 'Have you heard the news?', 'What good news?', 'What is your favorite book?', 'I can not read.', 'what is your favorite color?', 'My favorite color Blue', 'Tell me', 'Tell me about your self.', 'What do you want to know?', 'Are you a robot?', 'Yes sumthing like that , but i am just a software .', 'What is it like?', 'What is it that you want to know?', 'How do you work?', 'Its complicated.', 'Complex is better than complicated.', 'Simple is better than complex.', ] return(data) def hindi(): data = [ ' नमस्ते ', 'नमस्ते ', 'नमस्ते ', 'नमस्ते ', 'शुभेच्छा ', 'नमस्ते ', 'नमस्ते ', 'शुभेच्छा ', 'हाय, कैसा चल रहा है? ', 'अच्छा ', 'हाय, कैसा चल रहा है? ', 'ठीक ', 'हाय, कैसा चल रहा है? ', 'ठीक है ', 'हाय, कैसा चल रहा है? ', 'महान ', 'हाय, कैसा चल रहा है? ', 'बेहतर हो सकता था। ', 'हाय, कैसा चल रहा है? ', 'इतना महान नहीं। ', 'आप कैसे हैं? ', 'अच्छा। ', 'आप कैसे हैं? ', 'बहुत अच्छे धन्यवाद। ', 'आप कैसे हैं? ', 'ठीक हूं और आप? ', 'आपसे मिलकर अच्छा लगा। ', 'धन्यवाद। ', 'आप कैसे हैं? ', 'मैं अच्छा हूँ। ', 'आप कैसे हैं? ', 'मैं ठीक हूं, आपके क्या हाल हैं? ', 'हाय तुमसे मिलकर अच्छा लगा। ', 'धन्यवाद और आपको भी। ', 'आप से मिल कर खुशी हुई। ', 'धन्यवाद और आपको भी। ', 'तुम्हारे लिए सुबह अत्यंत शुभ हो! ', 'बहुत धन्यवाद। ', 'तुम्हारे लिए सुबह अत्यंत शुभ हो! ', 'और आप को दिन के आराम के। ', 'क्या हो रहा है? ', 'बहुत ज्यादा नहीं ।', 'क्या हो रहा है? ', 'बहुत जयादा नहीं। ', 'क्या हो रहा है? ', 'ज्यादा नहीं तुम्हारा क्या हाल है? ', 'क्या हो रहा है? ', 'ज़्यादा कुछ नहीं। ', 'क्या हो रहा है? ', 'आकाश के ऊपर है, लेकिन मैं। आप के बारे में क्या ठीक धन्यवाद कर रहा हूँ? ', ] return (data)
from typing import List ''' /** * This is the solution of No. 912 problem in the LeetCode, * the website of the problem is as follow: * https://leetcode-cn.com/problems/sort-an-array * <p> * The description of problem is as follow: * ========================================================================================================== * 给你一个整数数组 nums,请你将该数组升序排列。 * <p> * 示例 1: * <p> * 输入:nums = [5,2,3,1] * 输出:[1,2,3,5] * 示例 2: * <p> * 输入:nums = [5,1,1,2,0,0] * 输出:[0,0,1,1,2,5] *   * 提示: * <p> * 1 <= nums.length <= 50000 * -50000 <= nums[i] <= 50000 * <p> * 来源:力扣(LeetCode) * ========================================================================================================== * * @author zhangyu ([email protected]) */ ''' class Solution: def sort_array(self, nums: List[int]) -> List[int]: ''' 对数组进行排序 Args: nums: 数组 Returns: 排序好的数组 ''' if len(nums) < 2: return nums p = nums[len(nums) // 2] left = [x for x in nums if x < p] middle = [x for x in nums if x == p] right = [x for x in nums if x > p] return self.sort_array(left) + middle + self.sort_array(right) if __name__ == '__main__': nums = [5, 2, 3, 1] solution = Solution() result = solution.sort_array(nums) assert len(result) == 4 assert result[0] == 1
# encoding='utf-8' ''' /** * This is the solution of No. 258 problem in the LeetCode, * the website of the problem is as follow: * https://leetcode-cn.com/problems/add-digits/ * * The description of problem is as follow: * ========================================================================================================== * 给定一个非负整数 num,反复将各个位上的数字相加,直到结果为一位数。 * * 示例: * 输入: 38 * 输出: 2 * 解释: 各位相加的过程为:3 + 8 = 11, 1 + 1 = 2。 由于 2 是一位数,所以返回 2。 * * 来源:力扣(LeetCode) ** ========================================================================================================== * * @author zhangyu ([email protected]) */ ''' class Solution: def add_digits(self, num: int) -> int: ''' 加上两个数字 Args: arr: 数字 Returns: 固定值 ''' if num < 9: return num total = 0 while num > 0: total += num % 10 num = num // 10 return total if total < 9 else self.add_digits(total) def add_digits2(self, num: int) -> int: ''' 加上两个数字 Args: arr: 数字 Returns: 固定值 ''' if num == 0: return 0 return 9 if num % 9 == 0 else num % 9 if __name__ == '__main__': num = 38 solution = Solution() result = solution.add_digits(num) print(result) assert result == 2
# import os def header(text): # Centering print text: # https://stackoverflow.com/questions/33594958/is-it-possible-to-align-a-print-statement-to-the-center-in-python def center (str): #if we wanted to center based on the os terminal size, # replace 50 with: os.get_terminal_size().columns return str.center(50) #https://www.geeksforgeeks.org/python-split-string-into-list-of-characters/ def split(word): return [char for char in word] def space_out(str): # Start with a double space, # split the string into an array of characters, # then rejoin it with double spaces between each letter spaced_str = " " + " ".join(split(str)) return spaced_str print(center("+-++-++-++-++-++-++-++-++-++-++-++-++-++-++-++-++-+")) print(center(space_out(text))) print(center("+-++-++-++-++-++-++-++-++-++-++-++-++-++-++-++-++-+")) print()
from animals import Animal from interfaces import IFreshwater, ISwimming class Kikakapu(Animal, IFreshwater, ISwimming): instances = [] def __init__(self, age, name): Animal.__init__(self) IFreshwater.__init__(self) ISwimming.__init__(self) self.instances.append(self) self.name = name self.species = "Kikakapu" self.min_release_age = 1 self.age = age self.prey = [ "trout", "mackarel", "salmon", "sardine" ] self.tolerate_stagnant = True def feed(self, prey): if prey in self.prey: print(f'{self.name} the {self.species} ate {prey} for a meal') else: print(f'{self.name} the {self.species} rejects the {prey}') def move(self): print(f"The {self.species} swims")
import sys from load import load_numbers from random import randint numbers = load_numbers(sys.argv[1]) def quicksort(values): if len(values) <= 1: return values less_than_pivot = [] greater_than_pivot = [] random_index = randint(0, len(values) - 1) pivot = values[random_index] del values[random_index] for value in values: if value <= pivot: less_than_pivot.append(value) else: greater_than_pivot.append(value) print("%25s %1s %-15s" % (less_than_pivot, pivot, greater_than_pivot)) return quicksort(less_than_pivot) + [pivot] + quicksort(greater_than_pivot) print(numbers) sorted_numbers = quicksort(numbers) print(sorted_numbers)
""" * Algorithms: Selection Search """ import random import sys import os from helper.load import load_numbers numbers = load_numbers(sys.argv[1]) def my_selection_sort(values): """My implementation of Selection sort.""" new_array = [] while values: min_v = values[0] min_i = 0 for i in range(len(values)): if values[i] < min_v: min_v = values[i] min_i = i new_array.append(values.pop(min_i)) return new_array def selection_sort(values): sorted_list = [] # print("%-25s %-25s" % (values, sorted_list)) for i in range(len(values)): i_to_move = min_index(values) sorted_list.append(values.pop(i_to_move)) # print("%-25s %-25s" % (values, sorted_list)) return sorted_list def min_index(values): min_i = 0 for i in range(1, len(values)): if values[i] < values[min_i]: min_i = i return min_i print(selection_sort(numbers))
# 2. def combiner(lst): x = [] s = '' num = 0 for i in lst: if isinstance(i, str): s += i elif isinstance(i, (int, float)): num += i return f'{s}{num}' # print(combiner(["apple", 5.2, "dog", 8])) # Add a new property to the Rectangle class named area. It should # calculate and return the area of the Rectangle instance (width * length) class Rectangle: def __init__(self, width, length): self.width = width self.length = length @property def area(self): return self.width * self.length @property def perimeter(self): return self.length * 2 + self.width * 2
import datetime import random from questions import Add, Multiply class Quiz: questions = [] answers = [] def __init__(self): question_types = (Add, Multiply) # generate 10 different questions with numbers from 1 to 10 for _ in range(10): num1 = random.randint(1, 15) num2 = random.randint(1, 15) question = random.choice(question_types)(num1, num2) self.questions.append(question) # add these questions to self.questions return def take_quiz(self): # log the start time # ask all of the questions # log if they got the questions right # log the end time # show a summary return def ask(self, question): # log the start time # capture the answer # check the answer # log the end time # if the answer's right, send back True # otherwise, send back False # send back the elapsed time, too return def total_correct(self): # return the total # of correct answers return [i for i in self.answers if i[0]] # total = 0 # for answer in self.answers: # if answer[0]: # total += 1 # return total def summary(self): # print how many you got right and the total # of questions. 9/10 # print the total time for the quiz: 30 seconds! print(f'You got {self.total_correct} out of \ {len(self.question)} right.') print(f'It took you {(self.end_time-self.start_time).seconds} \ seconds total.')
class Stack: class Frame: def __init__(self, data, next_frame): self.data = data self.next_frame = next_frame def __init__(self): self.items = [] self.head = None self.size = 0 def push(self, data): new_frame = self.Frame(data, self.head) self.head = new_frame self.size += 1 def pop(self): if self.size == 0: return None data = self.head.data self.head = self.head.next_frame self.size -= 1 return data
from typing import Dict, List, Tuple Seats = Dict[Tuple[int, int], str] def list_to_dict(data: List[List[str]]) -> Seats: """Convert from a list of lists to a dict of tuples with row/col as the keys and the string seat as the value.""" rows_cols = [(r, c) for r in range(len(data)) for c in range(len(data[0]))] return {(r,c): data[r][c] for r,c in rows_cols} def get_surrounding_seats(data: Seats, row: int, col: int) -> str: """Given a dict of Seats and a specific row/col, return a concatenated string of all adjacent seats values.""" vals = [ (row, col-1), # left (row-1, col-1), # upper left (row-1, col), # up (row-1, col+1), # upper right (row, col+1), # right (row+1, col+1), # lower right (row+1, col), # down (row+1, col-1), # lower left ] return ''.join([data.get(v, '') for v in vals]) def update_seats(data: Seats) -> Seats: """Given a dict of Seats, iterate through and update into a new Seats dict.""" new_data = dict() for (r,c), seat in data.items(): surrounding_seats = get_surrounding_seats(data, r, c) # If a seat is empty (L) and there are no occupied (#) seats adjacent to it, the seat becomes occupied (#) if seat == 'L' and '#' not in surrounding_seats: new_data[(r,c)] = '#' # If a seat is occupied (#) and four or more seats adjacent to it are also occupied (#), the seat becomes empty (L) elif seat == '#' and surrounding_seats.count('#') >= 4: new_data[(r,c)] = 'L' else: new_data[(r,c)] = seat return new_data def count_occupied(data: Seats) -> int: """Return the total number of occupied seats.""" return ''.join(data.values()).count('#') if __name__ == '__main__': with open('input.txt') as f: seat_list = f.read().split('\n') seat_dict = list_to_dict(seat_list) for i in range(1, 200): start = count_occupied(seat_dict) seat_dict = update_seats(seat_dict) end = count_occupied(seat_dict) if start == end: print(f'The answer is: {(end)} (on round {i})') break
#!/usr/bin/env python import __builtin__ class sublist(list): def __init__(self, data=[]): #super(type(self),self).__init__(data) __builtin__.list(self).__init__(data) l = sublist([1, 2]) print l.items()
from copy import copy, deepcopy class classname1(): value=None def method1(self): pass def __repr__(self): return "repr" class classname2(): pass def get_class_members(klass): ret = dir(klass) if hasattr(klass,'__bases__'): for base in klass.__bases__: ret = ret + get_class_members(base) return ret print get_class_members(classname1) classname2.__repr__=classname1 ins=classname1() print ins
from lxml import etree root = etree.Element("root", interesting="totally") root.text="Text inside tag" root.tail="text after tag" print(etree.tostring(root, pretty_print=True)) # <root interesting="totally">Text inside tag</root>text after tag
from lxml import etree root = etree.Element("root") root.text="Text inside tag" br = etree.SubElement(root, "br") print root.xpath("br") # http://stackoverflow.com/questions/9233092/using-lxml-and-path-to-parse-xml-but-get-empty-list-if-it-has-xmlns-declaration?rq=1 # http://lxml.de/xpathxslt.html url="http://export.yandex.ru/weather-ng/forecasts/26686.xml" tree=etree.parse(url) print tree.getroot().xpath("uptime") # [] already if invalid xml yesterday=tree.getroot().xpath("//*[local-name()='yesterday']")[0] print "yesterday",yesterday print "" print "uptime in root:", int(yesterday.xpath("count(//*[local-name() = 'uptime'])")) for r in yesterday.xpath("//*[local-name()='uptime']"): print r.text print "" print "uptime in this element:", int(yesterday.xpath("count(*[local-name() = 'uptime'])")) for r in yesterday.xpath("*[local-name()='uptime']"): print r.text ns=dict(a="http://weather.yandex.ru/forecast") print tree.getroot().xpath("//a:uptime",namespaces=ns) print yesterday.xpath("a:uptime/text()",namespaces=ns)
#Question 1 Two Sum #Given an array of integers num and an integer target #Return indices of the two numbers such that they add up to target #Assume taht each input would have exactly one solution #And you may not use the same element twice def twoSum(nums, target): seen = {} for i, v in enumerate(nums): targetDifference = target - v if targetDifference in seen: return [seen[targetDifference], i] seen[v] = i return [] nums = [2,7,11,15] target = 9 print(twoSum(nums, target))
from abc import ABC, abstractmethod import json class SettingsGood(ABC): instance = None @abstractmethod def __init__(self): pass class _SettingsGood: def __init__(self): self.settings = {} def set(self, key, value): self.settings[key] = value def save(self): f = open('settingsGood.json', 'w') j = json.dumps(self.settings) f.write(j) f.close() @staticmethod def getInstance(): if SettingsGood.instance == None: SettingsGood.instance = SettingsGood._SettingsGood() return SettingsGood.instance
def pairwise(iterable): "For sequence of (a, b, c) yield pairs of (a, b), (b, c), (c, None)." prev = Ellipsis for it in iterable: if prev is not Ellipsis: yield (prev, it) prev = it yield (it, None) def set_union(*sets): # Python's set.union is unfortunately not a class method, # but a normal method, [and if used as unbound method], # requires at least one argument (set). if sets: return set.union(*sets) return set() def set_intersection(*sets): # Python's set.intersection is unfortunately not a class method, # but a normal method, [and if used as unbound method], # requires at least one argument (set). if sets: return set.intersection(*sets) return set()
class Node: def __init__(self, d): self.data = d self.left = None self.right = None def sortedArrayToBST(arr): if not arr: return None mid = (len(arr))//2 root = Node(arr[mid]) root.left = sortedArrayToBST(arr[:mid]) root.right = sortedArrayToBST(arr[mid+1:]) return root def preOrder(node): if not node: return print(node.data, end = " ") preOrder(node.left) preOrder(node.right) arr = [1, 2, 3, 4, 5, 6, 7] root = sortedArrayToBST(arr) print("PreOrder Traversal of constructed BST ", end=" "), preOrder(root) print()
class Node: def __init__(self, val): self.right = None self.left = None self.val = val def inorder(root): # go to leftmost node while pushing to stack, when no left is available pop and print it and then go to right node and continue stack = [] current = root while True: if current is not None: stack.append(current) current = current.left elif len(stack): current = stack.pop() print(current.val, end = " ") current = current.right else: break print() def preorder(root): # print root go left most, print and then go right most and print if root is None: return stack = [] current = root stack.append(current) while len(stack): current = stack.pop() print(current.val, end = " ") if current.right is not None: stack.append(current.right) if current.left is not None: stack.append(current.left) print() def postorder(root): if root is None: return s1 = [] s2 = [] current = root s1.append(current) while s1: current = s1.pop() s2.append(current) if current.left: s1.append(current.left) if current.right: s1.append(current.right) while s2: current = s2.pop() print(current.val, end = " ") print() def levelorder(root): # basically bfs for trees if root is None: return queue = [] queue.append(root) while queue: s = queue.pop(0) print(s.val, end = " ") if s.left: queue.append(s.left) if s.right: queue.append(s.right) print() # driver # tree: root = Node(10) root.left = Node(8) root.right = Node(2) root.left.left = Node(3) root.left.right = Node(5) root.right.left = Node(2) print("Preorder: ") preorder(root) print("Inorder: ") inorder(root) print("Postorder: ") postorder(root) print("Levelorder: ") levelorder(root)
# Sentiment analysis with feature engineering based method # using naïve bayes classifier with bag of words features # Author: Jialun Shen # Student No.: 16307110030 import nltk from data_utils import * # Load the dataset dataset = StanfordSentiment() tokens = dataset.tokens() nWords = len(tokens) allWords = list(tokens.keys()) # Define bag of words feature def feature(words): return nltk.FreqDist(words) def featureSet(trainset): return [(feature(words), c) for (words, c) in trainset] # Load the train set and train trainset = dataset.getTrainSentences() featureTrainset = featureSet(trainset) classifier = nltk.NaiveBayesClassifier.train(featureTrainset) accTrain = nltk.classify.accuracy(classifier, featureTrainset) * 100 # Prepare dev set features devset = dataset.getDevSentences() featureDevset = featureSet(devset) accDev = nltk.classify.accuracy(classifier, featureDevset) * 100 # Test your findings on the test set testset = dataset.getTestSentences() featureTestset = featureSet(testset) accTest = nltk.classify.accuracy(classifier, featureTestset) * 100 print("=== Naive Bayes Accuracy ===") print("Train accuracy (%%): %f" % accTrain) print("Dev accuracy (%%): %f" % accDev) print("Test accuracy (%%): %f" % accTest) print() print(classifier.show_most_informative_features(20)) #print(nWords)
import sys def __compare(number1, number2): if len(number1) > len(number2): return 1 elif len(number2) > len(number1): return -1 else: i = 0 while i < len(number1): if int(number1[i]) > int(number2[i]): return 1 elif int(number2[i]) > int(number1[i]): return -1 i += 1 return 0 def __sort(number1, number2): bigger = number1 smaller = number2 if len(number1) > len(number2): bigger = number1 smaller = number2 elif len(number2) > len(number1): bigger = number2 smaller = number1 else: i = 0 while i < len(number1): if int(number1[i]) > int(number2[i]): bigger = number1 smaller = number2 elif int(number2[i]) > int(number1[i]): bigger = number2 smaller = number1 i += 1 return [smaller, bigger] def __add_zeros(number, zeros): return number + (zeros * "0") def __clean_zeros(number): i = 0 while i < (len(number) - 1): if number[i] != "0": break i += 1 return number[i:] def __clean_negative(number): if number[0] == "-": return __clean_zeros(number[1:]) return __clean_zeros(number) def __increment(val, keep_extra=True): result = "" carry = 1 for i in range(len(val) - 1, -1, -1): res = int(val[i]) + carry result = str(res % 10) + result carry = res // 10 if i == 0 and carry != 0 and keep_extra: result = str(carry) + result return result def __complement(val, length): result = "" for i in range(length): res = str(9 - int(val[-1 * (i + 1)])) if i < len(val) else "9" result = res + result return __increment(result, keep_extra=False) def add(input1, input2): carry = 0 result = "" len1 = len(input1) len2 = len(input2) i = 0 while True: index1 = (len(input1) - i) - 1 index2 = (len(input2) - i) - 1 if i >= len1 and i >= len2: break elif i >= len2: res = str(int(input1[index1]) + carry) result = res[-1] + result carry = int(res[-2]) if len(res) > 1 else 0 elif i >= len1: res = str(int(input2[index2]) + carry) result = res[-1] + result carry = int(res[-2]) if len(res) > 1 else 0 else: res = str(int(input1[index1]) + int(input2[index2]) + carry) result = res[-1] + result carry = int(res[-2]) if len(res) > 1 else 0 i += 1 return "0" if result == "" else result def subtract(big, small): result = add(big, __complement(small, len(big))) return __clean_zeros(result) def multiply(big, small): result = "0" power = 0 for s in range(len(small) - 1, -1, -1): res = "" carry = 0 for b in range(len(big) - 1, -1, -1): r = (int(small[s]) * int(big[b])) + carry carry = r // 10 res = str(r % 10) + res if carry != 0: res = str(carry) + res result = add(result, __add_zeros(res, power)) power += 1 return __clean_zeros(result) def divide(big, small): result = "0" while __compare(big, small) >= 0: big = subtract(big, small) result = __increment(result) result = result + "." for i in range(3): if big == "0": break big = big + "0" r = "0" while __compare(big, small) >= 0: big = subtract(big, small) r = __increment(r) result = result + r return __clean_zeros(result) def cut_num(number: str, divisor: str): for i in range(1, len(number)): cut_string = number[:i] remaining_string = number[i:] if int(cut_string) >= int(divisor): return cut_string, remaining_string return number, "" def long_divide(numerator: str, denominator: str, result: str): if int(numerator) < int(denominator): return result, numerator cut_number, remaining = cut_num(numerator, denominator) print(cut_num, remaining) quotient = int(cut_number) // int(denominator) reminder = int(cut_number) % int(denominator) result += str(quotient) remaining = str(reminder) + remaining return long_divide(remaining, denominator, result) def solution(in1, operator, in2): # return __complement(in1, 5) # return __increment(in1) # return __sort(in1, in2) # return __compare(in1, in2) # return add(in1, in2) # return subtract(in1, in2) # return multiply(in1, in2) # return divide(in1, in2) negative1 = in1[0] == "-" negative2 = in2[0] == "-" negative_result = False clean1 = __clean_negative(in1) clean2 = __clean_negative(in2) sorted_nums = __sort(clean1, clean2) big = sorted_nums[1] small = sorted_nums[0] result = "" text = "Result: " if operator == "+": text = "Sum: " if not negative1 and not negative2: result = add(big, small) elif negative1 and negative2: negative_result = True result = add(big, small) elif negative1: negative_result = __compare(clean1, clean2) > 0 result = subtract(big, small) elif negative2: negative_result = __compare(clean1, clean2) < 0 result = subtract(big, small) elif operator == "-": text = "Difference: " if not negative1 and not negative2: negative_result = __compare(clean1, clean2) < 0 result = subtract(big, small) elif negative1 and negative2: negative_result = __compare(clean1, clean2) > 0 result = subtract(big, small) elif negative1: negative_result = True result = add(big, small) elif negative2: result = add(big, small) if operator == "*": text = "Product: " negative_result = (negative1 and not negative2) or (negative2 and not negative1) if clean1 == "0" or clean2 == "0": result = "0" else: result = multiply(big, small) if operator == "/": negative_result = (negative1 and not negative2) or (negative2 and not negative1) if clean2 == "0": result = "undefined" else: result = divide(clean1, clean2) if negative_result and result != "0": result = "-" + result return text + result def main(): print("Welcome...\n" "Input any operation using '+', '-', '*', '/'. Use 'exit' to leave." "\nFeel free to use negatives, but make sure to separate operator by spaces.") while True: print("\n> ", end="") try: inp = sys.stdin.readline().split() if inp == "exit": break in1 = inp[0] in2 = inp[1] in3 = inp[2] sys.stdout.write(str(solution(in1, in2, in3))) except: print("Sth went wrong, please try again.") print("It was nice while it lasted.") if __name__ == "__main__": main()
def distribute(group_list, n, m): root, group, size = list(range(m)), [[] for _ in range(n + 1)], [1] * m def find(node): if root[node] != node: root[node] = find(root[node]) return root[node] def union(node1, node2): small, big = tuple(sorted([find(node1), find(node2)], key=lambda x: size[x])) root[small] = big size[big] += size[small] for i, g in enumerate(group_list): for person in g: group[person].append(i) for g in group: for i in range(1, len(g)): union(g[i], g[i - 1]) result = [str(size[find(g[0])] + 1) if g else "1" for g in group[1:]] return " ".join(result) if __name__ == "__main__": inp = input().split() inp1, inp2 = int(inp[0]), int(inp[1]) inputs = [] for _ in range(inp2): inputs.append(list(map(int, input().split()[1:]))) print(distribute(inputs, inp1, inp2))
class Solution: def divisorGame(self, N: int) -> bool: checked = {1: False} self.check_only(N, checked) return checked[N] def check_only(self, N, checked): if N in checked: return checked[N] result = False for x1 in range(N - 1, 0, -1): if N % x1 == 0: N2 = N - x1 res = True for x2 in range(N2 - 1, 0, -1): if N2 % x2 == 0: N3 = N2 - x2 res = res and self.check_only(N3, checked) result = result or res checked[N] = result return result def solution(l1): s = Solution() return s.divisorGame(l1) def main(): inp1 = 30 print(solution(inp1)) if __name__ == '__main__': main()
import heapq class KthLargest: def __init__(self, k: int, nums: list): self.heap = [] self.k = k for i in nums: if len(self.heap) < k: heapq.heappush(self.heap, i) elif i > self.heap[0]: heapq.heapreplace(self.heap, i) heapq.heapify(self.heap) def add(self, val: int) -> int: if len(self.heap) < self.k: heapq.heappush(self.heap, val) elif val > self.heap[0]: heapq.heapreplace(self.heap, val) return self.heap[0] def main(): obj = KthLargest(3, [4, 5, 8, 2]) print(obj.add(3)) print(obj.add(5)) print(obj.add(6)) if __name__ == '__main__': main()
def transfer(computers, cables): hours, installed = 0, 1 while installed < cables: installed += installed hours += 1 remaining = max(0, computers - installed) res, rem = divmod(remaining, cables) return hours + res + (rem > 0) if __name__ == "__main__": inp, results = int(input()), [] for _ in range(inp): inp1, inp2 = list(map(int, input().split())) results.append(transfer(inp1, inp2)) print(*results, sep="\n")
def factors(x): result = [] i = 1 while i * i < x: if x % i == 0: result.append(i) i += 1 return result def gcd(big, small): mod = big % small if mod == 0: return small return gcd(small, mod) def find_nums(lcm): f = factors(lcm) biggest = lcm for i in f: bigger = lcm // i if bigger < biggest and gcd(i, bigger) == 1: biggest = bigger return str(lcm // biggest) + " " + str(biggest) def solution(inp): return find_nums(inp) def main(): print(solution(int(input()))) if __name__ == "__main__": main()
def count_pairs(nums, left, right): nums.sort() result = 0 for i, num in enumerate(nums): start, end, res1 = i + 1, len(nums) - 1, len(nums) while start <= end: mid = (start + end) // 2 if nums[mid] + num >= left: res1, end = mid, mid - 1 else: start = mid + 1 start, end, res2 = i + 1, len(nums) - 1, -1 while start <= end: mid = (start + end) // 2 if nums[mid] + num <= right: res2, start = mid, mid + 1 else: end = mid - 1 result += max(0, res2 - res1 + 1) return result if __name__ == "__main__": inp, results = int(input()), [] for _ in range(inp): _, inp1, inp2 = list(map(int, input().split())) inputs = list(map(int, input().split())) results.append(count_pairs(inputs, inp1, inp2)) print(*results, sep="\n")
def gcd(big, small): mod = big % small if mod == 0: return small return gcd(small, mod) def find_fraction(total): for i in range(total // 2, 0, -1): if gcd(i, total - i) == 1: return str(i) + " " + str(total - i) return "" def solution(inp1): return find_fraction(inp1) def main(): inp1 = input() result = solution(int(inp1)) print(result) if __name__ == "__main__": main()
from LeetCode.BST.__tree_node__ import TreeNode class Solution: def is_same_tree(self, p: TreeNode, q: TreeNode) -> bool: if p is None and q is None: return True elif p is None or q is None: return False return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right) def solution(l1, l2): s = Solution() return s.is_same_tree(l1, l2) def main(): inp1 = TreeNode(4) inp2 = TreeNode(5) inp3 = TreeNode(2) inp4 = TreeNode(6) inp1.left = inp2 inp3.right = inp4 print(solution(inp1, inp2)) if __name__ == '__main__': main()
import sys def valid_anagram(s, t): counting = {} for i in s: if i not in counting.keys(): counting[i] = 1 else: counting[i] += 1 for j in t: if j not in counting.keys(): return False else: counting[j] -= 1 for k in counting.keys(): if counting[k] > 0: return False return True def solution(l1, l2): return valid_anagram(l1, l2) def main(): # inp1 = sys.stdin.readline().split() # inp2 = sys.stdin.readline().split() inp1 = "abcdef" inp2 = "acbdfe" sys.stdout.write(str(solution(inp1, inp2))) if __name__ == '__main__': main()
def remove_letters(string): removed, count = True, 0 while removed: removed = False best, items = chr(1), {} for i, c in enumerate(string): if i > 0 and ord(c) == ord(string[i - 1]) + 1 or i < len(string) - 1 and ord(c) == ord(string[i + 1]) + 1: if string[i] > best: best, items = string[i], {i} elif string[i] == best: items.add(i) if items: removed, count = True, count + len(items) string = "".join(c for i, c in enumerate(string) if i not in items) return count if __name__ == "__main__": _, inp1 = input(), input() print(remove_letters(inp1))
class Solution: def findCircleNum(self, M: list) -> int: result = 0 visited = set() for i in range(len(M)): if i not in visited: self.do_dfs(M, i, visited) result += 1 return result def do_dfs(self, grid, current, visited): visited.add(current) for f in range(len(grid)): if f not in visited and grid[current][f] == 1: self.do_dfs(grid, f, visited) def solution(l1): s = Solution() return s.findCircleNum(l1) def main(): inp1 = [ [1, 1, 1], [1, 0, 1], [1, 1, 1] ] print(solution(inp1)) if __name__ == '__main__': main()
def __equalize__(moves): a = moves["L"] b = moves["R"] c = moves["U"] d = moves["D"] moves["L"] = moves["R"] = min(a, b) moves["U"] = moves["D"] = min(c, d) if moves["U"] == 0 and moves["L"] > 1: moves["L"] = moves["R"] = 1 if moves["R"] == 0 and moves["U"] > 1: moves["U"] = moves["D"] = 1 def __move__(start, move): if move == "L": return start[0] - 1, start[1] elif move == "R": return start[0] + 1, start[1] elif move == "U": return start[0], start[1] + 1 elif move == "D": return start[0], start[1] - 1 def correct(path): moves = {"L": 0, "U": 0, "R": 0, "D": 0} results = [] for i in path: moves[i] += 1 __equalize__(moves) moves_count = moves["L"] + moves["U"] + moves["R"] + moves["D"] if moves_count > 0: for i in moves: results += [i] * moves[i] result = "".join(results) return str(moves_count), result def solution(inp): return correct(inp) def main(): inp1 = input() length = int(inp1) result = [] for i in range(length): s = solution(input()) result.append(s[0]) if int(s[0]) > 0: result.append(s[1]) print(*result, sep="\n") if __name__ == "__main__": main() # 2 # LR # 14 # RUURDDDDLLLUUR # 12 # ULDDDRRRUULL # 2 # LR # 2 # UD # 0
from LeetCode.LinkedList.__list_node__ import ListNode def delete_node(node): node.val = node.next.val node.next = node.next.next def solution(l1): delete_node(l1) def main(): inp1 = ListNode(4) inp2 = ListNode(5) inp3 = ListNode(2) inp1.next = inp2 inp2.next = inp3 solution(inp2) print(inp1) if __name__ == '__main__': main()
import sys def array_intersection(nums1, nums2): commons = {} result = [] for i in nums1: commons[i] = 1 for j in nums2: if j in commons.keys(): commons[j] = 2 for k in commons.keys(): if commons[k] == 2: result += [k] return result def solution(l1, l2): return array_intersection(l1, l2) def main(): # inp1 = sys.stdin.readline().split() # inp2 = sys.stdin.readline().split() inp1 = [1, 2, 2, 1] inp2 = [2, 2] sys.stdout.write(str(solution(inp1, inp2))) if __name__ == '__main__': main()
from collections import deque def paint(squares): opposite, n = {"R": "B", "B": "R"}, len(squares) queue, result = deque(), [""] * n + ["R"] for i, square in enumerate(squares): if square != "?": result[i] = square queue.append(i) if not queue: queue.append(len(result) - 1) while queue: current = queue.popleft() for i in (current - 1, current + 1): if 0 <= i < n and result[i] == "": result[i] = opposite[result[current]] queue.append(i) return "".join(result[:-1]) if __name__ == "__main__": inp, results = int(input()), [] for _ in range(inp): input() results.append(paint(input())) print(*results, sep="\n")
amt = int(input()) if amt > 500: a = amt*0.05 print("5% discount", abs(amt-a)) else: print("No discount", amt)
#Account Generator - v2 student_info = [ { "name": "ROSIE MARTINEZ", }, { "name": "JOE LIU", }, { "name": "SALLY SUE", }, { "name": "BOB JOHNSON", }, { "name": "DELIA AGHO", }, ] import random for kid in student_info: idNumber = random.randint(111111, 999999) kid["id"] = idNumber number = (str(idNumber))[-3:] [first,last] = kid["name"].split(" ") email = (f"{first[0]}{last}{number}@example.org") kid["email"] = email for i in range (len(student_info)): print(f"name: {names[i]}") print(f"id: {ids[i]}") print(f"email: {emails[i]}\n")
import sys import pygame from settings import Settings from ship import Ship from bullet import Bullet class AlienInvasion: """Class to manage a individual game""" def __init__(self): """Initialize the game window / caption ship""" pygame.init() # pygame lib initialize # settings init before screen for icon init self.settings = Settings() self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN) self.settings.screen_width, self.settings.screen_height = self.screen\ .get_rect().width, self.screen.get_rect().height pygame.display.set_caption("Alien Invasion") # ship init after screen because ship needs it to initialize self.ship = Ship(self) # bullet init self.bullets = pygame.sprite.Group() def run_game(self): """Starts the main game loop""" while True: # checks for events self._check_events() # update ship pos self.ship.update() # update bullets self.bullets.update() # update screen self._uptade_screen() def _check_events(self): """Checks for keyboard and mouse events""" for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: self._check_keydown_events(event) elif event.type == pygame.KEYUP: self._check_keyup_events(event) def _check_keydown_events(self, event): """Checks for Keydown events""" # UP DOWN LEFT RIGHT Movement if event.key == pygame.K_RIGHT: # flag for movement to the right self.ship.moving_right = True if event.key == pygame.K_LEFT: # flag for movement to the left self.ship.moving_left = True if event.key == pygame.K_SPACE: self._fire_bullet() # Toggle up/down movement if self.settings.up_down == True: if event.key == pygame.K_UP: # flag for movement to the right self.ship.moving_up = True if event.key == pygame.K_DOWN: # flag for movement to the left self.ship.moving_down = True if event.key == pygame.K_q: sys.exit() def _check_keyup_events(self, event): """Checks for Keyup events""" if event.key == pygame.K_RIGHT: # flag self.ship.moving_right = False if event.key == pygame.K_LEFT: # flag self.ship.moving_left = False # Toggle up/down movement if self.settings.up_down == True: if event.key == pygame.K_UP: # flag self.ship.moving_up = False if event.key == pygame.K_DOWN: # flag self.ship.moving_down = False def _fire_bullet(self): """Create a new bullet and add it to the bullets group""" new_bullet = Bullet(self) self.bullets.add(new_bullet) def _uptade_screen(self): """Updates the screen""" # display background color set in settings class self.screen.fill(self.settings.bgc) # display ship self.ship.blitme() # display bullets for bullet in self.bullets.sprites(): bullet.draw_bullet() # display most recent screen pygame.display.flip() if __name__ == '__main__': # Make a game instance, and run the game. ai = AlienInvasion() ai.run_game()
a=int(input("enter 1st num:")) b=int(input("enter 2nd num:")) s=a d=b while(b!=0): r=a%b a=b b=r print("gcd",a) l=s*d/a print("lcm",l)
import argparse """ Documentation Description: Argument is a class with one static method get(), used to read all the arguments from the command line/terminal and read the values and use it in this script, all the arguments related to connecting to the database. Verbose flag used to print to the console the status of the script (i.e connected to db, view updated,... etc) List of argument: --driver='db driver' --server='db server name' --userid='db user' --password='user password' --database='db name' --verbose: if was specified value = True otherwise None or you can use the shortcut -r='db driver' -s='db server name' -u='db user' -p='user password' -d='db name' -v: if was specified value = True otherwise None All the argument are required to run this script, except verbose flag. Returns: object: has the list of parsed argument from CMD/terminal so it will be used later in this script. """ class Argument: @staticmethod def get(): parser = argparse.ArgumentParser(description="This a program that connects to SQL db and check if a table " "changed then update the view on db.", exit_on_error=True) parser.add_argument( '-r', '--driver', help='database driver', required=True ) parser.add_argument( '-s', '--server', help='database server name', required=True ) parser.add_argument( '-d', '--database', help='database name', required=True ) parser.add_argument( '-u', '--userid', help='database user ID', required=True ) parser.add_argument( '-p', '--password', help='database user password', required=True ) parser.add_argument( '-v', '--verbose', help='it will print descriptive messages of the script status, if it was provided.', nargs='?', const=True, type=bool ) return parser.parse_args()
import numpy as np import math class PCA(object): """ 1. Standardize the range of input variables so that each onee of them contributes equally to the analysis 2. Transformation is important as PCA is very sensitive to variance 3. """
from utils.metrics_loss import eucledian_distance import numpy as np class k_nearest: # no need to mention object as new-class style Python3 """ K nearest neighbors classifier - The KNN classifier assumes that similar things exist in close proximity of each other - that is objects from a same class will be near to each other.To capture how close objects are to each other a distance metric is utilized - distance between two points are calculated Choice of distance measures: Eucledian, Manhattan Algorithm: 1. Load the dataset 2. Initialize k to choose number of neighbors that will influence your class label choice 3. Iteratively for each data point in your dataset: 3.1.Calculate the distance between the data point of interest and the current data point under consideration 3.2. Add the distance and index of the calculation performed above in a dictionary 4. Sort the dictionary in ascending order of distances 5. Pick the k entries from sorted dictionary 6. Get the labels of the k entries 7. If regression (KNN - regressor) mean of the K labels is returned 8. If classification mode of K labels is returned - majority vote KNN doesn't have a loss function that needs to be minimized. The only training that Parameters: ----------- `k: (int) Number of closest neighbors that will determine/influence class of the sample point that we wish to determine """ def __init__(self, k): self.k = k def majority_vote(self, labels_of_neighbors): """ Return the mode of labels of k top nearest neighbors based on the distance metric """ label_counts = np.bincount(labels_of_neighbors.astype('int')) assert type(label_of_neighbors) == np.ndarray, "Please make sure the input is a numpy array" label_mode_max_idx = label_counts.argmax() return label_max_mode_idx def predict(self, X_test, X_train, Y_train): Y_pred = np.empty(X_test.shape[0]) # Find the class label of each data point for i, element in enumerate(X_test): # Sort training examples by their distance to test data point and get K nearest indices idx = np.argsort([eucledian_distance(element, x) for x in X_train])[:self.k] # Extract labels of K nearest training examples knn_labels = np.array([Y_train[i] for i in idx]) # Label test data point using majority vote - that is most common class in k nearest Y_pred[i] = majority_vote(knn_labels) return Y_pred
__author__ = '[email protected]' def getGuessedWord(secretWord, lettersGuessed): ''' secretWord: string, the word the user is guessing lettersGuessed: list, what letters have been guessed so far returns: string, comprised of letters and underscores that represents what letters in secretWord have been guessed so far. ''' # FILL IN YOUR CODE HERE... #correct_letters = [] guessed_word = [] for length in secretWord: guessed_word.append('_ ') for letter in lettersGuessed: if letter in secretWord: #correct_letters.append(letter) letter_occurrence = secretWord.count(letter) next_index = 0 for num_times in range(letter_occurrence): current_index = secretWord.find(letter, next_index) guessed_word[current_index] = letter next_index = current_index+1 return ''.join(guessed_word) # for c in secretWord: # print c # if c not in correct_letters: # return False # return True def getAvailableLetters(lettersGuessed): ''' lettersGuessed: list, what letters have been guessed so far returns: string, comprised of letters that represents what letters have not yet been guessed. ''' # FILL IN YOUR CODE HERE... import string alphabet = string.ascii_lowercase available_letters = [] for letter in alphabet: if letter not in lettersGuessed: available_letters.append(letter) return ''.join(available_letters) def hangman(secretWord): ''' secretWord: string, the secret word to guess. Starts up an interactive game of Hangman. * At the start of the game, let the user know how many letters the secretWord contains. * Ask the user to supply one guess (i.e. letter) per round. * The user should receive feedback immediately after each guess about whether their guess appears in the computers word. * After each round, you should also display to the user the partially guessed word so far, as well as letters that the user has not yet guessed. Follows the other limitations detailed in the problem write-up. ''' # FILL IN YOUR CODE HERE... print 'Welcome to the game, Hangman!' print 'I am thinking of a word that is %s letters long.' % len(secretWord) print '-------------' num_guesses = 8 lettersGuessed = [] while num_guesses > 0: print 'You have %s guesses left.' % num_guesses print 'Available letters:', getAvailableLetters(lettersGuessed) letterGuessed = raw_input('Please guess a letter: ') if letterGuessed in secretWord and letterGuessed not in lettersGuessed: lettersGuessed.append(letterGuessed.lower()) print 'Good guess:', getGuessedWord(secretWord, lettersGuessed) elif letterGuessed in lettersGuessed: print 'Oops! You\'ve already guessed that letter:', getGuessedWord(secretWord, lettersGuessed) elif letterGuessed not in secretWord and letterGuessed not in lettersGuessed: num_guesses -= 1 lettersGuessed.append(letterGuessed.lower()) print 'Oops! That letter is not in my word:', getGuessedWord(secretWord, lettersGuessed) print '-------------' if getGuessedWord(secretWord, lettersGuessed) == secretWord: return 'Congratulations, you won!' return 'Sorry, you ran out of guesses. The word was %s.' % secretWord print hangman('apple')
#Create animal class class Animal: def __init__(self): # initialise with built in method called __init__(self) - self refers to current class # we declare attributes in our methods self.alive = True self.spine = True self.eyes = True self.lungs = True def breath(self): return "Keep breathing to stay alive." def eat(self): return "Time to eat." def move(self): return "Move left or right to stay awake." # We need to creat an objects of this class in order to be able to use methods cat = Animal() # Creating an object of Animal class print(cat.breath()) # The user doesn't need to worry about functionality, method breath is abstracted
#!/usr/bin/env python from Tkinter import * import random import Tkinter from Tkinter import * import sys import os import time ''' class App(Frame): def __init__(self,master): Frame.__init__(self,master) master.minimisze(width=500,height=500) self.grid() self.widget() self.word=''' def jumble(string): return ' '.join([''.join(random.sample(word, len(word))) for word in string.split()]) #Intialising Game #Getting data from txt file array=[] with open('tvshows.txt','r') as input_file: for data in input_file: array.append(data.rstrip('\n')) def game_array(): #Selecting Random 10 TV shows game_list = random.sample(array,10) #print(game_list) return game_list def jumble_array(): #Jumbling data jumble_list = [] for word in game_list: jumble_list.append(jumble(word)) #print(jumble_list) return jumble_list #Initialise Player def player(): print("Enter player name: ") player1 = raw_input() def again(): global score global pointer global txt_guess #print(pointer) label_jumbled.config(text=jumble_list[pointer]) txt_guess = Tkinter.Entry(root,width=30) txt_guess.grid(row=4, column=0, padx=5, pady=10) btn_check = Tkinter.Button(root, text="Check",fg="green",command=game) btn_check.grid(row=6, column=0, sticky=W) #Start game def game(): global score global pointer global txt_guess '''#score = 0#initialise score #for index in range(1,len(jumble_list)): label_jumbled = Tkinter.Label(root, text=jumble_list[index]) label_jumbled.grid(row=1, column=0, sticky=E, pady=5) #print("Guess the jumbled name of TV Show",jumble_list[index]) #word = raw_input() #word = word.upper()''' player_guess = txt_guess.get() player_guess = player_guess.upper() if player_guess == game_list[pointer]: score += 1 string = "Score: %s" %score scored.config(text=str(score) + '/10') o.config(text=" ") Label(root,text="Correct Answer").grid(row=7,column=0,sticky=W) print("Correct Answer",string) pointer+=1 else: print("Game Over") Label(root,text="Correct Answer was: ").grid(row=8,column=0,sticky=W) o.config(text=game_list[pointer]) Label(root,text="Wrong Answer").grid(row=7,column=0,sticky=W) print("Correct answer was: ",game_list[pointer]) '''time.sleep(1) os.system("python gdg.py") time.sleep(0.2) quit()''' if score == 10: print("CONGRATULATIONS!! YOU WIN") Label(root,text="CONGRATULATIONS!! YOU WIN").grid(row=7,column=0,sticky=W) elif score<10: #pointer += 1 again() #print("BETTER LUCK NEXT TIME") # reset() def main(): player() game() #Start Game game_list = game_array() jumble_list = jumble_array() score = 0 pointer = 0 root = Tk() root.title("GDG Project") root.geometry("320x200") #Widgets label_title = Tkinter.Label(root, text=" Welcome to the Guessing Game! ") label_title.grid(row=0, column=0, sticky=W) label_jumble = Tkinter.Label(root, text = " Scrambeled Show -") label_jumble.grid(row=1, column=0, sticky=W, pady=5) player_guess = Tkinter.Label(root, text=" Guess the Show ") player_guess.grid(row=3,column=0,sticky=W) txt_guess = Tkinter.Entry(root,width =30) txt_guess.grid(row=4, column=0, padx=5, pady=10) o=Label(root,text='') o.grid(row=8,column=0,sticky=E) label_jumbled = Tkinter.Label(root, text=jumble_list[pointer]) label_jumbled.grid(row=1, column=0, sticky=E, pady=5) #Button btn_check = Tkinter.Button(root, text="Check",fg="green",command=game) btn_check.grid(row=6, column=0, sticky=W) score_label = Tkinter.Label(root, text="Your Score: ") score_label.grid(row=12,column=0,sticky=W) scored = Tkinter.Label(root, text = str(score) + '/10') scored.grid(row=12,column=1,sticky=W) #print(game_list,jumble_list) root.mainloop() #main() '''#Reseting the game def reset(): while True: game_start() reset()'''
# The project creates a basic skeleton for determining cost price and sales volume # Use the variables listed in the class to change the values and determine the impact from numpy import random as rd import pandas as pd import time as t class amazon_price_structure: # This class is used to calculate the cost of delivery/fulfilment total_no_items = 0 """ Default values for price structure: per_cu_ft = 0.25 ## Price of storage per cubic ft assumed standard over the year amazon_per_mo = 39.99 ## subscription fee - allows us to be prime standard_shipping = 0.3 ## standard shipping fee per article variable_shipping = 0.1 ## variable shipping fee based on weight per article storage_vol = 1 ## cubic ft volume -- vary this to study the effect no_items = 50 ## no of articles to be solde -- vary this to study the effect weight_items = 0.2 ## weight of the articles -- vary this to study the effect """ def __init__(self,amazon_per_mo, standard_shipping, variable_shipping, per_cu_ft,storage_vol,no_items,weight_items): self.per_cu_ft = per_cu_ft self.amazon_per_mo = amazon_per_mo self.standard_shipping = standard_shipping self.variable_shipping = variable_shipping self.storage_vol = storage_vol self.no_items = no_items self.weight_items = weight_items amazon_price_structure.total_no_items += no_items def calculate_shipping(self): total_shipping = self.standard_shipping + \ self.variable_shipping*self.weight_items + \ self.amazon_per_mo / amazon_price_structure.total_no_items + \ self.per_cu_ft * self.storage_vol return total_shipping class article_properties: no_articles = 0 fusion_articles = 0 standard_articles = 0 total_cost_price_to_us = 0 total_profit = 0 def __init__(self,theme,name,weight,volume,cp,inv): article_properties.no_articles+=1 # increment counter representing articles self.fusion = theme self.name = name self.weight = weight self.volume = volume self.cp = cp article_properties.total_cost_price_to_us += cp*inv self.sp = 0 self.profit = 0 self.inventory = inv self.appeal = rd.random() # Appeal of a product -- if exceeds buyer interest then buyer buys the product self.mrp = 0 def if_fusion_product(self): if self.fusion == 'fusion': article_properties.fusion_articles += 1 elif self.fusion == 'standard': article_properties.standard_articles += 1 else: print "Invalid Article Theme - correct themes standard, fusion" def calculate_selling_price(self,profit_in_percent): self.sp = self.cp*(1+profit_in_percent) return self.sp def if_sold(self): if self.inventory >= 1: self.inventory -= 1 article_properties.total_profit += self.sp - self.cp elif self.inventory == 0: article_properties.no_articles -= 1 @classmethod def how_many_fusion(cls): return cls.fusion_articles @classmethod def how_many_standard(cls): return cls.standard_articles class buyer: no_buyers = 0 def __init__(self): buyer.no_buyers+=1 # increment counter representing articles self.interest = rd.random() # buyer interest needs to be topped by product appeal 45/ self.buying_power = rd.randint(0,45) # this models a random buying power self.basket = [] def if_bought(self,article_price,article): self.buying_power -= article_price self.interest = rd.random() # after the buyer has bought something, it will recalculate the interest # recalculating interest is an interesting idea - sort of tells about mass shopping # try making the interest unchanged to see the effect self.basket.append(article) class operation: def __init__(self,employees): self.employees = employees self.month = 1 self.fixed_costs = 200 # comprises of registration costs def calculate_revenue(self): min_salary = self.employees*130 self.revenue = article_properties.total_profit - (min_salary + self.fixed_costs) return self.revenue
# counts the repeating element in an array def noCount(nums): c={} count=0 for i in range(len(nums)): for j in range(len(nums)): if nums[i] == nums[j]: count+=1 c[nums[i]]=count count=0 return c
""" GameAI.py Created by: D.C. Hartlen Date: 19-Aug-2018 Updated by: Date: Contains the algorithm to allow a computer to always win or draw at a game of tic tac toe. The entirety of the algorithm presented here was developed by Cecil Wobker (https://cwoebker.com/posts/tic-tac-toe). However, I have made changed variable names to clarify thier meaning, added documentation, and added a function or two to allow for easier interface with other project source codes NOTE: this source code only works if the computer plays as 'O'. I can't figure out why, but it always plays the wrong moves if the computer plays as 'X'. I'm its a logic issue somewhere, but I haven't had the time to fix it FIXME: find out why computer can only play as 'O' """ import random class Game: """ Class contains all the gameboard informatino and utilities including determining the winner and tree-search for determining the next move. However, this class will not actually make a prediction. That is the standalone function below. Inputs: squares: 9 entry list containing 'None','X', and 'O'. Used to preload a configuration into the system. Defaults to empty and an empty gameboard is generated """ # List of all winning combos winningCombos = ( [0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]) # Possible winners winners = ('X-win', 'Draw', 'O-win') def __init__(self, squares=[]): if len(squares) == 0: self.squares = [None for i in range(9)] else: self.squares = squares def showBoard(self): """ Pretty print the current game board""" for element in [self.squares[i:i + 3] for i in range(0, len(self.squares), 3)]: print( element) def availableMoves(self): """ Return all empty squares""" return [k for k, v in enumerate(self.squares) if v is None] def availableCombos(self, player): """what combos are available?""" return self.availableMoves() + self.getSquares(player) def complete(self): """Has game ended?""" if None not in [v for v in self.squares]: return True if self.winner() != None: return True return False """ Next three methods return winner""" def xWon(self): return self.winner() == 'X' def oWon(self): return self.winner() == 'O' def tied(self): return self.complete() == True and self.winner() is None def winner(self): """ Check if there if current player is a winner""" for player in ('X', 'O'): positions = self.getSquares(player) for combo in self.winningCombos: win = True for pos in combo: if pos not in positions: win = False if win: return player return None def declareWinner(self): """ Hacky way to return winner and the winning combo. Can't use winner() because the output of winner is altered by xWon() et al. """ for player in ('X', 'O'): positions = self.getSquares(player) for combo in self.winningCombos: win = True for pos in combo: if pos not in positions: win = False if win: return player,combo return None def getSquares(self, player): """Return all regions which belong to the current player""" return [k for k, v in enumerate(self.squares) if v == player] def addMarker(self, position, player): """place on square on the board""" self.squares[position] = player def alphaBeta(self, board, player, alpha, beta): """ The magic: binary tree search through all possible moves to find the best one. Return the best move. This function runs recursively """ if board.complete(): if board.xWon(): return -1 elif board.tied(): return 0 elif board.oWon(): return 1 for move in board.availableMoves(): board.addMarker(move, player) val = self.alphaBeta(board, getEnemy(player), alpha, beta) board.addMarker(move, None) if player == 'O': if val > alpha: alpha = val if alpha >= beta: return beta else: if val < beta: beta = val if beta <= alpha: return alpha if player == 'O': return alpha else: return beta def determineMove(board, player): """ Determine the optimal move given the current gameboard configuration. Inputs: board: Board class which contains the current state of play player: the player for whom the move is predicted. Returns: Optimal next move for player """ a = -2 choices = [] if len(board.availableMoves()) == 9: return 4 for move in board.availableMoves(): board.addMarker(move, player) val = board.alphaBeta(board, getEnemy(player), -2, 2) board.addMarker(move, None) # print( "move:", move + 1, "causes:", board.winners[val + 1]) if val > a: a = val choices = [move] elif val == a: choices.append(move) return random.choice(choices) def getEnemy(player): """ Returns the other player. getEnemy('X') returns 'O'. """ if player == 'X': return 'O' return 'X' """ Standalone exection allows one to play a game of tic tac toe by specifing the square ID (0-9) which one wants to play. """ if __name__ == "__main__": board = Game() board.showBoard() while not board.complete(): player = 'X' playerMove = int(input("Next Move: ")) - 1 if not playerMove in board.availableMoves(): continue board.addMarker(playerMove, player) board.showBoard() if board.complete(): break player = getEnemy(player) computerMove = determineMove(board, player) # Bots move is zero indexed board.addMarker(computerMove, player) board.showBoard() print(board.declareWinner()) print("winner is", board.declareWinner())
import random def genBoard(): #Generate an empty board return [0,0,0,0,0,0,0,0,0] def printBoard(T): #Print the board in a user-friendly manner if len(T) != 9: return False for i in T: if (i != 0) and (i != 1) and (i != 2): return False msg=[] pos=0 for i in T: if (i==1): msg += ["X"] elif (i==2): msg += ["O"] else: msg += list(str(pos)) pos+=1 s = " " + msg[0] + " | " + msg[1] + " | " + msg[2] print(s) print("---|---|---") s = " " + msg[3] + " | " + msg[4] + " | " + msg[5] print(s) print("---|---|---") s = " " + msg[6] + " | " + msg[7] + " | " + msg[8] print(s) return True def analyzeBoard(t): #Check for wins, analyze the diagonals, horizontals and verticals. Return the winner (which is whatever is in that position) if t[0] == t[1] == t[2] != 0: return t[0] if t[3] == t[4] == t[5] != 0: return t[3] if t[6] == t[7] == t[8] != 0: return t[6] if t[0] == t[3] == t[6] != 0: return t[0] if t[1] == t[4] == t[7] != 0: return t[1] if t[2] == t[5] == t[8] != 0: return t[2] if t[0] == t[4] == t[8] != 0: return t[0] if t[2] == t[4] == t[6] != 0: return t[2] n_opens=0 for i in t: if i==0: n_opens+=1 if n_opens == 0: return 3 else: return 0 def findOpponent(player): if player==1: opponent = 2 elif player==2: opponent= 1 return opponent def checkError(T): good=1 prod = 1 if len(T)!=9: good=0 #Check if there is an empty spot for element in T: prod=prod*element if (prod!=0): good=0 for element in T: if (element!=0) and (element!=1) and (element!=2): good=0 return good def genNonLoser(T, player): good=checkError(T) opponent = findOpponent(player) returned = 0 if good==1: board = T for i in range(len(board)): if board[i]==0: board[i] = opponent if analyzeBoard(board)==opponent: return i returned = 1 else: board[i]=0 if returned==0: return -1 else: return -1 def genWinningMove(T, player): good = checkError(T) returned = 0 if good==1: board = T for i in range(len(board)): if board[i]==0: board[i] = player if analyzeBoard(board)==player: return i returned = 1 else: board[i]=0 if returned == 0: return -1 else: return -1 def genRandomMove(T, player): good = checkError(T) good_indices = [] if good==1: for i in range(len(T)): if T[i]==0: good_indices = good_indices + [i] moveindex = random.randint(0,len(good_indices)-1) move = good_indices[moveindex] return move else: return -1 def genOpenMove(T, player): open = [] good = checkError(T) if good==1: for i in range(len(T)): if T[i]==0: open = open +[i] move = open[0] return move else: return -1
""" Compare two strings A and B, determine whether A contains all of the characters in B. The characters in string A and B are all Upper Case letters. """ def compareStrings(A, B): ss = [0] * 256 tt = [0] * 256 for i in range(len(A)): pos = ord(A[i]) ss[pos] = ss[pos] + 1 for j in range(len(B)): pos = ord(B[j]) tt[pos] = tt[pos] + 1 for k in range(len(ss)): if ss[k] < tt[k]: return False return True def main(): A = "ABCD" B = "ABC" C = "AABC" print compareStrings(A,B) print compareStrings(A,C) main()
# Given two given arrays of equal length, the task is to find # if given arrays are equal or not. Two arrays are said to be # equal if both of them contain same set of elements, arrang- # -ements (or permutation) of elements may be different though. def is_same(arr1, arr2): if len(arr1) != len(arr2): return False frequency = reduce(lambda d, c: d.update({c: d.get(c, 0) + 1}) or d, arr1, {}) for a in arr2: if not frequency.has_key(a): return False if not frequency.get(a): return False frequency[a] -= 1 return True if __name__ == '__main__': arr1 = [3, 5, 2, 5, 2] arr2 = [2, 3, 5, 5, 2] print 'Are {} and {} same? {}'.format(arr1, arr2, is_same(arr1, arr2))
# Reverse words in a given string def reverse_string_word(string): temp = '' n = len(string) for i in range(n): c = string[n-1-i] if c == ' ': if temp: print temp, temp = '' else: temp = c + temp if temp: print temp if __name__ == '__main__': s = 'geeks quiz practice code' print s reverse_string_word(s)
import re string1=input() string2=input() for i in string1: if(re.search(string1,string2)): print(int(string1[i]),int(string1[i+1]))
#Add your code here def converToDollar(amount): ruppees=amount*65 totalamount=ruppees-(ruppees*1)/100 return totalamount amount=int(input("Enter the number of dollars:")) total=converToDollar(amount) print(total)
class node: def __init__(self, step): self.step = step self.depth = -1 self.visited = 0 def set_step(self, val): self.step = self.step + val def update(test, val): test.step += val def random(node): node.depth+= 1 if __name__ == '__main__': a = node(3) a.depth = 0 dep = a.depth print(a.step) print(a.visited) print(a.depth) b = a b.visited = 1 print(b.visited) random(b) print(b.depth) a = b print(a.step) print(a.visited) print(a.depth)
# 자연수 n의 약수를 출력하는 함수 # 일반적인 코드로 작성하기 n = int(input('n을 입력해주세요 : ')) for i in range(1, n+1): if n % i == 0: print(i) # 입력이 없는 함수로 작성하기 def divisor(): n = int(input('n을 입력해주세요 : ')) for i in range(1,n+1): if n % i == 0: print(i) divisor() # 입력이 있는 함수로 작성하기 def divisorOne(n): for i in range(1, n+1): if n % i == 0: print(i, end=' ') divisorOne(6) print() for i in range(6,12,24): divisorOne(i)
# 1부터 5까지의 합 구하기 # i < 5 # 선증가 : i = i + 1 # 후처리 : sum = sum + i i = 1 sum = 1 while i < 5: i = i + 1 sum = sum + i print(f'i={i}, sum={sum}, {i}<5={i<5}') print(f'1부터 5까지 합계 : {sum}')
# 홀수 마방진 n = 5 # 홀수 개수만 입력 arr = [[0]*n for x in range(n)] # 배열 생성 초기화 # 시작을 위한 위치 설정 row = 0 col = n//2 arr[row][col] = 1 # 시작 위치에 1을 넣고 시작 # 행의 오른쪽 끝 열의 상단 끝에 있을 경우 되돌아오기 위해 위치 넣을 변수 x = 0 y = 0 for i in range(2,n*n+1): x = row y = col row = row - 1 # 행 감소 col = col + 1 # 열 증가 if row < 0: # 행이 0보다 작으면 row = n - 1 # 행은 n에서 1 감소로 이동 if col > n-1 : # 열이 n-1 보다 크면 col = 0 # 열은 0으로 이동 if arr[row][col] == 0: # 배열의 값이 0이면 arr[row][col] = i # i를 배열에 저장 한다 else: # 그렇지 않으면 row = x + 1 # x+1의 값을 행에 저장하고 col = y # y를 열에 저장하고 arr[row][col] = i # i를 배열에 저장 한다 for row in range(0,n): for col in range(0,n): print(f'{arr[row][col]:2d}',end=' ') print()
# 에라토스체 def is_prime(num): if num <=1 : return False i = 2 while i*i <= num: if num%i ==0: return False i = i + 1 return True print(is_prime(11))
''' Spiral Matrix (https://leetcode.com/problems/spiral-matrix/) Given an m x n matrix, return all elements of the matrix in spiral order. Example 1: [[1,2,3], [4,5,6], [7,8,9]] Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] Output: [1,2,3,6,9,8,7,4,5] Example 2: [[1, 2, 3, 4], [5, 6, 7, 8], [9,10,11,12]] Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]] Output: [1,2,3,4,8,12,11,10,9,5,6,7] Constraints: m == matrix.length n == matrix[i].length 1 <= m, n <= 10 -100 <= matrix[i][j] <= 100 ''' class Solution: def spiralOrder(self, snail_map: List[List[int]]) -> List[int]: ''' Time: O(N): simply traversing the matrix Space: O(N): I don't technically use any space but I do replace the elements of the matrix so I would like to add a visited set to avoid mutating the matrix which would make my solution O(N) ''' # first off some edge cases if snail_map == [[]]: return [] elif len(snail_map) == 1: return snail_map[0] n = len(snail_map) m = len(snail_map[0]) deltas = [(1,0), (0,1), (-1,0), (0,-1)] # list of delta (x,y) pairs [right, down, left, up]. This is what I use to keep track of which way I am moving d_index = 0 # start off at the first delta which is going right result = [] # solution list current_x = 0 current_y = 0 while(snail_map[current_y][current_x] is not None): result.append(snail_map[current_y][current_x]) # append the value I am currently on snail_map[current_y][current_x] = None # mutation of the matrix. Can use a visited set instead new_x = current_x + deltas[d_index][0] # calculate what the next x,y would be based on what direction I am going in new_y = current_y + deltas[d_index][1] if new_x < 0 or new_x >= m or new_y < 0 or new_y >= n or snail_map[new_y][new_x] is None: # x or y out of bounds or next block is a none # need to turn d_index = (d_index + 1) % 4 # move my index to the next direction in my deltas list current_x += deltas[d_index][0] # move x,y in the new direction current_y += deltas[d_index][1] else: # keep going current_x = new_x # new_x and new_y are safe so I will use those as my next x,y current_y = new_y return result
class Data: """ This class holds the data matrix and related function """ def __init__(self): self.__matrix = [] def getMatrix(self): return self.__matrix def setMatrix(self, matrix): self.__matrix = matrix def getAvailableFeatures(self): """ This function returns the available features in the data. :return: list of available features """ matrix = self.__matrix return list(range(0,len(matrix[0])-1)) def getDataIndices(self, featureIndex, featureValue, subsetIndices): """ This function list of indices in the data (subset of data) having particular feature value. :param featureIndex: feature index to subset :param featureValue: value of the feature to compare :param subsetIndices: list of current indices (current subset of the data) :return: list of indices """ indices = [] if len(subsetIndices) == 0: subsetIndices = list(range(0, len(self.__matrix))) for dataPointIndex in subsetIndices: dataPoint = self.__matrix[dataPointIndex] if dataPoint[featureIndex] == featureValue: indices.append(dataPointIndex) return indices
import random from DecisionTree.DecisionTree.DecisionTree import DecisionTree class EnsembleUtil: """ This is a utility class for performing Ensemble learning such as Bagging/Boosting """ def createBootstrapSamples(self, trainingSet, numBags): """ This function creates 'numBags' bootstrap samples (with replacement) randomly drawn from the trainingSet :param trainingSet: the training data :param numBags: number of bootstrapped bags :return: bootstrapped samples """ bootstrap_samples = [] sample_size = len(trainingSet) for index in range(numBags): # print("Creating bootstrap sample #" + str(index)) bootstrap_samples.append( [random.choice(trainingSet) for _ in range(sample_size)] ) return bootstrap_samples def get_majority_voted_labels(self, predicted_label_collection): """ This function uses majority voting to return the class label from list of labels predicted by each learned model :param predicted_label_collection: labels predicted by learned model(s) :return: majority voted class labels """ num_bags = len(predicted_label_collection) num_test_points = len(predicted_label_collection[0]) # labels selected via majority vote - appearing more times majority_voted_labels = [] for test_data_index in range(num_test_points): # keep count of majority vote label_count = {True.__int__(): 0, False.__int__(): 0} # scan through all bags & increase vote for bag_index in range(num_bags): label_count[ predicted_label_collection[bag_index][test_data_index] ] += 1 # add majority voted class-label majority_voted_labels.append( (label_count[True.__int__()] >= label_count[False.__int__()]).__int__() ) # return majority vote return majority_voted_labels def calculate_accuracy(self, testing_data, predicted_classes): """ This function prints the accuracy & mis-classification count of the ensemble method :param testing_data: test data set :param predicted_classes: predicted classes by ensemble learner :return: """ decision_tree = DecisionTree() # calculate accuracy of model dt_accuracy, dt_misclassification = decision_tree.calculateAccuracy(testing_data, predicted_classes) print('Accuracy of ensemble method = {}%'.format(round(dt_accuracy, 3))) print('Misclassification Count = {}'.format(dt_misclassification)) return def print_confusion_matrix(self, testing_data, predicted_classes): """ This function prints the confusion matrix for the ensemble learner :param testing_data: test data set :param predicted_classes: predicted classes by ensemble learner :return: """ decision_tree = DecisionTree() # print confusion matrix decision_tree.plotConfusionMatrix(testing_data, predicted_classes) return
#https://leetcode.com/problems/find-the-celebrity/description/ # The knows API is already defined for you. # @param a, person a # @param b, person b # @return a boolean, whether a knows b # def knows(a, b): class Solution(object): def findCelebrity(self, n): """ :type n: int :rtype: int """ my_celeb = -1 not_celebs = set() i = 0 while i < n: if i not in not_celebs: is_celeb = True for j in xrange(n): if j != i: if knows(i, j): not_celebs.add(i) is_celeb = False break else: not_celebs.add(j) if not knows(j, i): not_celebs.add(i) is_celeb = False break if is_celeb: my_celeb = i break i = i + 1 return my_celeb
# class Solution(object): class ListNode(object): def __init__(self, x): self.val = x self.next = None def mergeTwoLists(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ head = None curr_node = None # while both lists are non-empty, take the smaller value and grow the merged list, # while advancing on the respective input list while l1 != None and l2 != None: val1 = l1.val val2 = l2.val if val1 < val2: my_val = val1 l1 = l1.next else: my_val = val2 l2 = l2.next if head == None: head = ListNode(my_val) else: if curr_node == None: curr_node = ListNode(my_val) head.next = curr_node else: next_node = ListNode(my_val) curr_node.next = next_node curr_node = next_node # if we reached the end of one of them, simply append the other next_node = None if l1 != None and l2 == None: next_node = l1 elif l1 == None and l2 != None: next_node = l2 if head == None: # edge case: one of the input lists is empty head = next_node elif curr_node == None: # we only had one iteration head.next = next_node else: curr_node.next = next_node return head
#https://leetcode.com/problems/group-anagrams/ class Solution(object): def groupAnagrams(self, strs): """ :type strs: List[str] :rtype: List[List[str]] """ """ hold a dictionary 'sorted anagram'-> list of anagrams sort - if in dictionary append to value else create a key-value pair: sorted->[item] return the values of the dictionary O(n*(mlogm)) time """ anagrams = {} for s in strs: key = "".join(sorted(s)) group = anagrams.get(key) if group is None: anagrams[key] = [s] else: group.append(s) return anagrams.values()
""" Copyright (C) 2020-2022 Vanessa Sochat. This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. """ enter_input = getattr(__builtins__, "raw_input", input) def request_input(): """Wait for the user to input some string, optionally with multiple lines.""" lines = [] # The message can be multiple lines while True: try: line = enter_input() except EOFError: break if line: lines.append(line) return "\n".join(lines) def choice_prompt(prompt, choices, choice_prefix=None, multiple=False): """Ask the user for a prompt, and only return when one of the requested options is provided. Parameters ========== prompt: the prompt to ask the user choices: a list of choices that are valid. multiple: allow multiple responses (separated by spaces) """ choice = None print(prompt) # Support for Python 2 (raw_input) get_input = getattr(__builtins__, "raw_input", input) if not choice_prefix: choice_prefix = "/".join(choices) message = "[%s] : " % (choice_prefix) while choice not in choices: choice = get_input(message).strip() # If multiple allowed, add selection to choices if includes all valid if multiple is True: contenders = choice.strip().split(" ") if all(x in choices for x in contenders): choices.append(choice) message = "Please enter a valid option in [%s]" % choice_prefix return choice
import datetime as dt import six if six.PY2: from tkinter import * if six.PY3: from tkinter import * class CountDownTimer: dark = '#333333' white = '#D0D6D3' master = None titleLabel = None countLabel = None footerLabel = None initWidth = None initHeight = None initFlag = True labelMargin = 30 resizeCoeff = 1.0 width = None height = None def __init__(self, titleText="", finishTime="", footerText="", baseFontSize=100): self.titleText = titleText self.finishTime = finishTime self.footerText = footerText self.baseFontSize = int(baseFontSize) self.nomarl_font = ("Helvetica", baseFontSize) self.large_font = ("Helvetica", int(baseFontSize * 1.5)) def countDown(self): self.countLabel.configure(text=self.getRemainingTimeText()) self.master.after(1000, self.countDown) def getRemainingTimeText(self): current_time = dt.datetime.now() finish_time = dt.datetime.strptime(self.finishTime, '%Y-%m-%d %H:%M:%S') diff_time = finish_time - current_time total_second = diff_time.seconds days = diff_time.days hour = total_second // 3600 minute = (total_second - 3600 * hour) // 60 second = total_second - 3600 * hour - 60 * minute return "{0} Days\n {1:02d}:{2:02d}:{3:02d}".format(days, hour, minute, second) def getWindowSize(self, event): self.width = self.master.winfo_width() self.height = self.master.winfo_height() if self.initFlag: self.initWidth = self.master.winfo_width() self.initHeight = self.master.winfo_height() self.initFlag = False self.resizeCoeff = self.height / self.initHeight self.updateFontSize() self.updateGridSize() def updateFontSize(self): baseFontSize = int(self.baseFontSize * self.resizeCoeff) self.nomarl_font = ("Helvetica", baseFontSize) self.large_font = ("Helvetica", int(baseFontSize * 1.5)) self.titleLabel.configure(font=self.nomarl_font) self.countLabel.configure(font=self.large_font) self.footerLabel.configure(font=self.nomarl_font) def updateGridSize(self): labelMargin = int(self.labelMargin * self.resizeCoeff) self.titleLabel.grid(pady=(labelMargin, 0)) self.countLabel.grid(pady=(labelMargin, labelMargin)) self.footerLabel.grid(pady=(0, labelMargin)) def run(self): self.master = Tk() self.master.configure(background=self.dark) self.master.bind("<Configure>", self.getWindowSize) self.master.columnconfigure(0, weight=1) self.master.title("Count Down Timer") self.titleLabel = Label(text=self.titleText, font=self.nomarl_font, fg=self.white, bg=self.dark) self.countLabel = Label(text=self.getRemainingTimeText(), font=self.large_font, fg=self.dark, bg=self.white) self.master.after(1000, self.countDown) self.footerLabel = Label(text=self.footerText, font=self.nomarl_font, fg=self.white, bg=self.dark) self.titleLabel.grid(row=0, column=0, pady=(self.labelMargin, 0), sticky=W+E+N+S) self.countLabel.grid(row=1, column=0, pady=(self.labelMargin, self.labelMargin), sticky=W+E+N+S) self.footerLabel.grid(row=2, column=0, pady=(0, self.labelMargin), sticky=W+E+N+S) self.master.mainloop() if __name__ == '__main__': app = CountDownTimer( titleText="Title Text", finishTime="2017-01-01 00:00:00", # Format: YYYY-mm-DD HH:MM:SS footerText="Footer Text", baseFontSize=100 ) app.run()
""" Author: Joel Potts Language: Python2.7 Last Edit: 10/25/13 Summary: This program is meant to emulate the learning process of an MCP neuron based off of the Simple Perceptron Learning. """ """ Initialize variables w1,w2 - the weights used on the inputs b - the bias n - the neeta value (learning curve) error - indicates where an error is found(location in array) tooLow - indicates whether the error is due to too low or not i1,i2 - input values trainingSet - the desired output binaryInputs - list of possible input patterns output - output for current weights and bias """ w1 = 0 w2 = 0 b = 0 n = 1 error = 0 tooLow = False i1 = [0,1] i2 = [0,1] trainingSet = [0,1,0,1] binaryInputs = [[0,0],[0,1],[1,0],[1,1]] output = [0,0,0,0] #this function finds the output using current w1 w2 and b def findOutput(i1, i2, w1, w2, b): global output i = 0 for input1 in i1: for input2 in i2: if (((input1*w1)+(input2*w2)+b) >= 0): output[i] = 1 #if sum is greater than 0 (threshold) output is 1 i+=1 else: output[i] = 0 i+=1 #else it doesnt reach threshold and is 0 return output #refreshes output... pointless function will edit out... def refreshOutput(): while (len(output) < 0): output.pop() #find the location of any error in the output and provides its index in the array and also determines if it is too low or not def findErrors(output): global error, tooLow for i in range(4): if (int(output[i]) != int(trainingSet[i])): #there is an error print "", int(output[i]), " vs ", int(trainingSet[i]), " is ", (int(output[i]) != int(trainingSet[i])) error = i #error is at index i print i if (output[i] < trainingSet[i]): tooLow = True #output is lower than desired output else: tooLow = False #output is higher than desired print "", output[i], " is less than ", trainingSet[i], ": ", tooLow return 0 #stops function so error is not set to -1 error = -1 #if no errors are found error is set to -1 as sentinel value #changes weights or bias according to error #note to self: can change if to if(i = 0,1,2,3) to determine pattern... more efficiant def weightChange(error, tooLow): global b, w1, w2 if (binaryInputs[error][0] == 0 and binaryInputs[error][1] == 0): #pattern 00 has error if tooLow: b+=1 else: b-=n elif (binaryInputs[error][0] == 0 and binaryInputs[error][1] == 1): #pattern 01 has error if tooLow: w2+=n else: w2-=n elif (binaryInputs[error][0] == 1 and binaryInputs[error][1] == 0): #pattern 10 has error if tooLow: w1+=n else: w1-=n elif (binaryInputs[error][0] == 1 and binaryInputs[error][0] == 1): #pattern 11 has error if tooLow: if (w1 > 0): w1+=n elif (w2 > 0): w2+=n elif (b > 0): b+=n w1-=n w2-=n else: b-=n w1+=n w2+=n else: if (w1 < 0): w1-=n elif (w2 < 0): w2-=n elif(b < 0): b-=n w1+=n w2+=n else: b+=n w1-=n w2-=n #mainloop manages which functions to call def mainLoop(): while(error != -1): print "*" findOutput(i1,i2,w1,w2,b) print output findErrors(output) if (error != -1): weightChange(error, tooLow) print "\nw1: ", w1, " w2: ", w2, " b: ", b, " error: ", error refreshOutput() print "done\n" print "Output: ", output, ", w1: ", w1, ", w2: ", w2, ", b: ", b print "Training Set: ", trainingSet mainLoop() #calls mainLoop and main program
#!/usr/bin/env python3 import sys def parse(txt): foods = [] for row in txt.strip().split("\n"): words = row.split(" ") ingredients = [] allergens = [] state = 0 for w in words: if state == 0: if w == "(contains": state = 1 continue ingredients.append(w) else: allergens.append(w[:-1]) foods.append((ingredients, allergens)) return foods def find_allergens(foods): # find the dangerous ingredients allergens = {} for ilst, alst in foods: for a in alst: dangerous = allergens.get(a) if dangerous: allergens[a] = set(i for i in ilst if i in dangerous) else: allergens[a] = set(ilst) # constraint elimination allergens = [(k, v) for k, v in allergens.items()] solution = [] while allergens: for i in range(len(allergens)-1, -1, -1): key, val = allergens[i] if not val: allergens.pop(i) elif len(val) != 1: pass else: val = list(val)[0] solution.append((key, val)) for _, ingr in allergens: ingr.discard(val) # sort by allergen name solution.sort() return solution def part1(foods, allergens): dangerous = set(v for k, v in allergens) count = 0 for ing_list, _ in foods: for i in ing_list: if i not in dangerous: count += 1 return count def part2(allergens): return ",".join(x[1] for x in allergens) if __name__ == "__main__": if len(sys.argv) < 2: print("Usage: {} <filename>".format(sys.argv[0]), file=sys.stderr) sys.exit(1) try: with open(sys.argv[1], "rt") as f: txt = f.read() except: print("Cannot open {}".format(sys.argv[1]), file=sys.stderr) sys.exit(1) foods = parse(txt) allergens = find_allergens(foods) print("Part1:", part1(foods, allergens)) print("Part2:", part2(allergens))
#!/usr/bin/env python3 import sys # tokens NUM = 0 ADD = 1 MUL = 2 LPAR = 3 RPAR = 4 EOF = 5 # expression = factor {"+" factor | "*" factor}* # factor = number | "(" expression ")" class Grammar1(object): def __init__(self): self.pos = 0 self.cur = (EOF, None) self.txt = "" def eval(self, txt): self.pos = 0 self.txt = txt self.scan_next() return self.expression() def scan_next(self): while self.pos < len(self.txt) and self.txt[self.pos] in " \n\t\r": self.pos +=1 if self.pos == len(self.txt): self.cur = (EOF, None) elif self.txt[self.pos] in "0123456789": start = self.pos while self.pos < len(self.txt) and self.txt[self.pos] in "0123456789": self.pos += 1 self.cur = (NUM, self.txt[start:self.pos]) elif self.txt[self.pos] == "+": self.cur = (ADD, None) self.pos += 1 elif self.txt[self.pos] == "*": self.cur = (MUL, None) self.pos += 1 elif self.txt[self.pos] == "(": self.cur = (LPAR, None) self.pos += 1 elif self.txt[self.pos] == ")": self.cur = (RPAR, None) self.pos += 1 else: print("Error: {} at {}".format(self.txt, self.pos)) exit(1) # factor = number | "(" expression ")" def factor(self): if self.cur[0] == NUM: value = int(self.cur[1]) self.scan_next() elif self.cur[0] == LPAR: self.scan_next() value = self.expression() if self.cur[0] != RPAR: print("Error: found {} expected {}".format(self.cur[0], RPAR)) exit(1) self.scan_next() else: print("Error: found type {}, expected {} or {}".format(self.cur[0], NUM, LPAR)) exit(1) return value # expression = factor {"+" factor | "*" factor}* def expression(self): value = self.factor() while True: if self.cur[0] == ADD: self.scan_next() value += self.factor() elif self.cur[0] == MUL: self.scan_next() value *= self.factor() else: break return value # expression = term {"+" term}* # term = factor {"*" factor}* # factor = number | "(" expression ")" class Grammar2(Grammar1): # term = factor {"*" factor}* def term(self): value = self.factor() while self.cur[0] == ADD: self.scan_next() value += self.factor() return value # expression = term {"+" term}* def expression(self): value = self.term() while self.cur[0] == MUL: self.scan_next() value *= self.term() return value # g1 = Grammar1() # g2 = Grammar2() # assert g1.eval("1 + 2 * 3 + 4 * 5 + 6") == 71 # assert g1.eval("5 + (8 * 3 + 9 + 3 * 4 * 3)") == 437 # assert g1.eval("5 * 9 * (7 * 3 * 3 + 9 * 3 + (8 + 6 * 4))") == 12240 # assert g1.eval("((2 + 4 * 9) * (6 + 9 * 8 + 6) + 6) + 2 + 4 * 2") == 13632 # assert g2.eval("1 + 2 * 3 + 4 * 5 + 6") == 231 # assert g2.eval("1 + (2 * 3) + (4 * (5 + 6))") == 51 # assert g2.eval("2 * 3 + (4 * 5)") == 46 # assert g2.eval("5 * 9 * (7 * 3 * 3 + 9 * 3 + (8 + 6 * 4))") == 669060 # assert g2.eval("((2 + 4 * 9) * (6 + 9 * 8 + 6) + 6) + 2 + 4 * 2") == 23340 if __name__ == "__main__": if len(sys.argv) < 2: print("Usage: {} <filename>".format(sys.argv[0]), file=sys.stderr) sys.exit(1) try: with open(sys.argv[1], "rt") as f: txt = f.read() except: print("Cannot open {}".format(sys.argv[1]), file=sys.stderr) sys.exit(1) g1 = Grammar1() g2 = Grammar2() part1, part2 = 0, 0 for line in txt.splitlines(): part1 += g1.eval(line) part2 += g2.eval(line) print("Part1:", part1) print("Part2:", part2)
totalNums = int(input()) phoneBook={} for i in range(0,totalNums): string = input() Input = string.split(' ') phoneBook[Input[0]]=Input[1] hell = input() while hell != "": if hell in phoneBook: print(hell + "=" + phoneBook[hell]) else: print("Not found") hell = input()
a = 1 b = 10 def test(a): a = a + 1 print(b, "b변수") return a print(a, "1St") a = test(a) print(a, "2nd") def add(a, b): """ add function """ return a + b add.__doc__ = "add function" help(add)
from functools import reduce import operator class Calculator: def __init__(self): print("Turn on Calculator") def fnAdd(self, *arg): print("The result is : %d" % (sum(arg))) def fnMinus(self, *arg): print("The result is : %d" % (reduce(operator.__sub__, arg))) def fnMultiply(self, *arg): print("The result is : %d" % (reduce(operator.__mul__, arg))) def fnDivide(self, *arg): print("The result is : %d" % (reduce(operator.__truediv__, arg))) def __del__(self): print("Shut down Calculator") if __name__ == '__main__': print("# Execute Check : Direct Execute \n") Calculator() else : print("# Execute Check : Indirect Execute \n") Calculator() calc = Calculator() recycleFlag = True while recycleFlag: num = int(input("\n\n ####### Calculator ######\n" \ "#########################\n" \ "# 1. Add\n" \ "# 2. Minus\n" \ "# 3. Divide \n" \ "# 4. Multiply \n" \ "# 5. Exit\n" \ "#########################\n" \ "Select what you want. [1-5] : ")) strNum = [] intNum = [] if num != 5: print("\n If you want input one more number, you should input Blank(Seperated by Space bar)") strNum = input("Input Number : ").split() intNum = tuple(map(int, strNum)) if num == 1: calc.fnAdd(*intNum) elif num == 2: calc.fnMinus(*intNum) elif num == 3: calc.fnDivide(*intNum) elif num == 4: calc.fnMultiply(*intNum) elif num == 5: calc.__del__() else : recycleFlag = False del calc
print(1) print('hi guys') a = 'Hello\n' x = 0.2 print(x) str(x) print(str(x)) a = repr('hello\n') print(a) import sys print("Welcome to", "python", sep="-", end="!", file=sys.stderr) import sys help(sys.stderr) #파일 입출력 // Default is Read f = open('file.txt', 'w') # Write f.write('plow deep\nwhile sluggards sleep') f.close() f = open('file.txt', 'r') # Read f.read() print("file write", 'r') # Read f.close() f.close() # 파일 입출력 확장 f = open('file.txt') # Read f.read() f.read() f.tell() # 어디까지 읽었니.. f.seek(0) # 0으로 돌아가라.. (처음으로) f.read() # 다시 읽으면 처음부터 읽게된다 Seek 때문에..ㅎ f.seek(0) f.readline() f.readline() f.seek(0) f.readlines() f.close() # 문자열 포매팅 print("{0} is {1}".format("apple", "red"))
from phone_store import PHONES def search_by_props(name,memory,color): phones = [] for phone in PHONES: if phone['name'] == name and phone['memory'] == memory and phone['color'] == color: phones.append(phone) if len(phones) == 0: print("Извините у нас нет в наличии этот телефон") else: for phone in phones: print(str(phone)+"\n") def search_by_price(): phones_1 = [] price = int(input("Введите сумму:")) for phone in PHONES: if phone['price'] == price: print(phone) if len(phones_1) == 0: print("Извините у нас нет телефон на эту сумму") else: for phone in phones_1: print(str(phone)+ "\n")
def findTheDifference(s, t): """ :type s: str :type t: str :rtype: str """ a=list(t) for i in s: if i in t: a.remove(i) a=''.join(a) print(a) return "".join(a) s="abcd" t="aacbde" findTheDifference(s,t)
def maxSubArray(nums): ans=nums[0] sum=nums[0] for i in range(1,len(nums)): sum=max(sum+nums[i],nums[i]) if sum>ans: ans=sum return ans
""" @Author: Brady Miner GPA Calculator: Will calculate n number of grades and return the average GPA. """ print("\nThis program will calculate your GPA based on the number of grades entered.\n" "Valid grades include '+' or '-' symbols.\n" "Invalid grades such as 'S' or 'G' will not be calculated.\n" "Type 'quit' to end the program and calculate GPA.") grades = [] # List to store number of points associated with each grade valid_grades = '' valid = ("A+", "A", "A-", "B+", "B", "B-", "C+", "C", "C-", "D+", "D", "F") # Stores valid grade entries invalid = '' while True: grade = input("\nEnter your grades (Ex. A+ A, A-): ").upper() # Match user input to uppercase constraints points = 0 if grade == "QUIT": # If the user enters a blank line or types "quit" GPA is calculated break elif grade == '': break elif grade not in valid: # Prevents invalid grades from being calculated into the GPA print("Grade is invalid, enter a valid grade") continue else: grade += valid_grades # Add invalid inputs to separate list if grade == "A+": # Accumulate the points for each grade inside the loop points = 4.2 elif grade == "A": points = 4.0 elif grade == "A-": points = 3.9 elif grade == "B+": points = 3.7 elif grade == "B": points = 3.2 elif grade == "B-": points = 3.0 elif grade == "C+": points = 2.8 elif grade == "C": points = 2.2 elif grade == "C-": points = 2.0 elif grade == "D+": points = 1.8 elif grade == "D": points = 1.2 elif grade == "F": points = 0 grades.append(points) total = 0 # Store the total amount of GPA accumulated num = 0 # Store the number of grades from user input for grade in grades: # Loop to increment the total grades total += grade num += 1 average = round(total / num, 3) # Calculate the average GPA rounding to 3 decimal places print("Your GPA is", average) # Print the GPA and show the user