text
stringlengths
37
1.41M
def count_words(s, n): """Return the n most frequently occuring words in s.""" # TODO: Count the number of occurences of each word in s a = dict() split_s = s.split() for sp in split_s: a[sp] = a.get(sp,0) + 1 # TODO: Sort the occurences in descending order (alphabetically in case of ties) tup = [(v[0],v[1]) for v in sorted(a.iteritems(), key=lambda(k, v): (-v, k))] # TODO: Return the top n words as a list of tuples (<word>, <count>) #top_n = tup[:n] return tup def test_run(): """Test count_words() with some inputs.""" print count_words("cat bat mat cat bat cat", 3) print count_words("betty bought a bit of butter but the butter was bitter", 3) if __name__ == '__main__': test_run()
num1=int(input("enter the first number")) num2=int(input("enter the second number")) num3=int(input("enter the third number")) sum=num1+num2+num3 print(sum)
# Parent Class class User: name = "Bill" email = "[email protected]" phone = "321-456-7544" password = "abcde1234" def getLoginInfo(self): entry_name = input("Enter your name: ") entry_email = input("Enter your email: ") entry_phone = input("Enter your Phone Number: ") entry_password = input("Enter your password: ") if (entry_email == self.email and entry_password == self.password): print("Welcome back, {}!".format(entry_name)) else: print("The password or email is incorrect.") #Child Class Employee class Employee(User): base_pay = 11.00 department = "General" pin_number = "3980" def getLoginInfo(self): entry_name = input("Enter your name: ") entry_email = input("Enter your email: ") entry_phone = input("Enter your Phone Number: ") entry_pin = input("Enter your pin: ") if (entry_email == self.email and entry_pin == self.pin_number): print("Welcome back, {}!".format(entry_name)) else: print("The pin or email is incorrect.") #Child Class Employee class Manager(User): position = "Senior" department = "Operations" manager_password = "special_level" def getLoginInfo(self): entry_name = input("Enter your name: ") entry_email = input("Enter your email: ") entry_phone = input("Enter your Phone Number: ") entry_password = input("Enter your password: ") entry_man_pswd = input("Enter your Manager Password: ") if (entry_password == self.password and entry_man_pswd == self.manager_password): print("Welcome back, {}!".format(entry_name)) else: print("The Password or Manager Password is incorrect.") # The following code invokes the methods inside each class for User and Employee customer = User() customer.getLoginInfo() employee = Employee() employee.getLoginInfo() manager = Manager() manager.getLoginInfo()
#Written by: Adrian Sanchez #Prof: Diego Aguirre #Class: Data Structures 2302 #Lab: 1 #Date completed: 9/12/19 import hashlib def hash_with_sha256(str): hash_object = hashlib.sha256(str.encode('utf-8')) hex_dig = hash_object.hexdigest() return hex_dig #compares generated string after being hashed def compare(cur_perm): filename = "password_file.txt" f = open(filename, 'r') line = f.readline() while line: currentline = line.split(",") salt = str(currentline[1]) #salt value, hashed password and user taken from file hash_p = str(currentline[2]) user = str(currentline[0]) s_salt = cur_perm + salt #string to pass into hashing method attempt = hash_with_sha256(s_salt) #hashed number to compare if(hash_p == attempt): print("Matched " + attempt + " with " + hash_p + " for user " + user ) print("Password is: " + cur_perm) line = f.readline() f.close() def brutus(s, unusedlist, length): if len(s) == length: #checks if length matches the one required return compare(s) #return s for j in range(0,10): brutus(s + str(j),unusedlist, length) #recursively calls the method with an increased string #needed range fed into for loop, then into the method call for x in range(3,8): s = "" brutus(s, ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], x)
def max_num(num1, num2, num3): if num1>= num2 and num1>= num3: return num1 elif num2>= num1 and num2>= num3: return num2 else: return num3 print(max_num(30, 4, 57)) # new code starts here # float immediately converts into a number instead of the conventional string num1 = float(input("Enter first no: ")) op = input("Enter operator: ") num2 = float(input("Enter second number: ")) if op == "+": print(num1 + num2) elif op == "-": print(num1 - num2) elif op == "*": print(num1 * num2) elif op == "/": print(num1 / num2) else: print("Invalid Operator")
""" DYNAMIC Dynamic programming stuff Stefan Wong 2019 """ from pylc import stack # debug #from pudb import set_trace; set_trace() # ======== Compute Fibonacci Sequence ======== # def fibonacci(i:int) -> int: if i == 0 or i == 1: return i return fibonacci(i - 1) + fibonacci(i - 2) # ---- Memoized implementation def fibonacci_memo(i:int) -> int: memo = [0 for _ in range(i+2)] return _fibonacci_memo_inner(i, memo) def _fibonacci_memo_inner(i:int, memo:list) -> int: if i == 0 or i == 1: return i if memo[i] == 0: memo[i] = _fibonacci_memo_inner(i - 1, memo) + _fibonacci_memo_inner(i - 2, memo) return memo[i] # --- Iterative implementation def fibonacci_iter(i:int) -> int: if i == 0 or i == 1: return i fib = [0 for _ in range(i+1)] fib[1] = 1 for n in range(2, i+1): fib[n] = fib[n-1] + fib[n-2] return fib[i] def fibonacci_iter_const_space(i:int) -> int: # We can do this in constant space since we don't need # to store all the previous sums if i == 0 or i == 1: return i f_oldest = 0 f_old = 1 f_cur = 0 for f in range(2, i+1): f_cur = f_old + f_oldest f_oldest = f_old f_old = f_cur return f_cur # Fastest would be a direct form - not going to bother for now # ======== COIN CHANGE ======== # # ======== TOWERS OF HANOI ======== # def hanoi_simple(num_towers:int=3, num_disks:int=4, verbose:bool=False) -> list: towers = [stack.Stack() for _ in range(num_towers)] # Init the first tower with disks for n in reversed(range(num_disks)): towers[0].push(n) if verbose: print('Tower[0] :') print(towers[0]) print('Moving disks....') hanoi_calc(towers, num_disks, 0, 2, 1) return towers def hanoi_calc(towers:list, n:int, src:int, dst:int, buf:int) -> None: if n == 1: hanoi_move(towers, src, dst) else: # here we implement the logic to reduce the movement problem down # to a single disk hanoi_calc(towers, n-1, src, buf, dst) # buffer the disk below hanoi_calc(towers, 1, src, dst, buf) # move the disk below from src->dst hanoi_calc(towers, n-1, buf, dst, src) # move disks off the buffer and towards the dst def hanoi_move(towers:list, src:int, dst:int) -> None: disk = towers[src].pop() towers[dst].push(disk) print('Moving disk from %d -> %d' % (src, dst))
""" QUESTIONS Answers to specific Leetcode questions Stefan Wong 2019 """ from typing import List, Optional from pylc.tree import TreeNode, BinaryTreeNode # debug #from pudb import set_trace; set_trace() # leetcode 3 # https://leetcode.com/problems/longest-substring-without-repeating-characters/ def longest_unique_substring_3(s:str) -> int: # Lets try a sliding window. We keep incrementing a pointer along the # string checking if we have seen a character before. If not, we expand the # window start = 0 end = 0 max_ever = 0 # Keep a map of any character that we have seen seen_chars = dict() while(end < len(s)): if s[end] not in seen_chars: seen_chars[s[end]] = True end += 1 max_ever = max(max_ever, len(seen_chars)) else: del seen_chars[s[start]] start += 1 return max_ever # leetcode 14 #https://leetcode.com/problems/longest-common-prefix/ def longest_common_prefix_14(strs:List[str]) -> str: # It turns out that scanning ahead to find the maximum length # the prefix could be is slightly faster on average. The reason # for this is that we don't know what order the strings will be # in the input, and therefore we might end uo checking more # characters than we need to. For example, if the shortest string # comes last and we test the string lengths as we go, we will have # checked all the characters in the longer strings when it wasn't # required prefix = "" if len(strs) == 0: return prefix max_prefix = 9999999 for s in strs: if len(s) < max_prefix: max_prefix = len(s) # Now check each character at position n of string 0 against the # character in position n of all other strings (vertical scan) for n in range(max_prefix): for s in range(len(strs)-1): if strs[0][n] != strs[s+1][n]: return prefix prefix += strs[0][n] return prefix # leetcode 53 # https://leetcode.com/problems/maximum-subarray/ def maximum_subarray_53(nums:list) -> int: if len(nums) == 0: return 0 max_ever = nums[0] max_here = 0 for elem in nums: max_here = max_here + elem # Ints may be positive or negative if(max_here > max_ever): max_ever = max_here if(max_here < 0): max_here = 0 return max_ever # leetcode 55 # https://leetcode.com/problems/jump-game/ # The key insight of this question is to note that a good jump is one # that allows you to land on position len(nums)-1. Therefore, if we are # walking towards the end (right hand side) of the array, we can only # terminate with a True (can reach) if the current position is at # len(nums) - 1. If we terminate elsewhere, we must return False def jump_game_55(nums:list) -> bool: print('input : %s' % str(nums)) return jump_game_can_jump_basic(0, nums) # Inner function - determine if we can jump to the end from here # NOTE: This function is much too slow. def jump_game_can_jump_basic(cur_pos:int, nums:list) -> bool: if cur_pos == len(nums)-1: return True if (cur_pos + nums[cur_pos]) > (len(nums)-1): max_jump = len(nums) - 1 else: max_jump = cur_pos + nums[cur_pos] next_pos = cur_pos + 1 while(next_pos <= max_jump): can_jump = jump_game_can_jump_basic(next_pos, nums) if can_jump: return True next_pos += 1 return False # The above solution is expensive, because we have to try every possible # jump from index zero and backtracking down # Question 62 # Unique paths # https://leetcode.com/problems/unique-paths/ def unique_paths_62_brute_force(m: int, n:int) -> int: """ Worst implementation. Each call generates 2 calls where one of row or col are decremented by one. Therefore, time complexity is O(2^(n+m)). Space complexity is O(n+m) via implied stack space. """ def unique_paths(m:int, n:int, row:int, col:int) -> int: if row >= m or col >= n: return 0 if row == m-1 and col == n-1: return 1 return unique_paths(m, n, row+1, col) + unique_paths(m, n, row, col+1) return unique_paths(m, n, 0, 0) # Question 62 # Unique paths # https://leetcode.com/problems/unique-paths/ def unique_paths_62_memo(m:int, n:int) -> int: """ Same as above but we memoize. We only gain in time complexity as we don't recalculate redundant values. Time: O(m*n) Space: O(m*n) <- this is the final/worst case size of the cache. """ cache = [[1 for _ in range(n)] for _ in range(m)] def unique_paths(m:int, n:int, row:int, col:int, cache:List[List[int]]) -> int: if row >= m or col >= n: return 0 if row == m-1 and col == n-1: return 1 cache[row][col] = unique_paths(m, n, row+1, col, cache) + unique_paths(m, n, row, col+1, cache) return cache[row][col] return unique_paths(m, n, 0, 0, cache) # Question 64 # Minimum path sum # https://leetcode.com/problems/minimum-path-sum/ def min_path_sum_64(grid: List[List[int]]) -> int: """ Tabulation solution. Time complexity: O(N*M) where N and M are dimensions of grid. Space Complexity = O(N*M) to store the cost array, O(N*M) to store the grid. """ MAX_COST = 1000 num_rows = len(grid) num_cols = len(grid[0]) cost = [[0 for _ in range(num_cols)] for _ in range(num_rows)] cost[0][0] = grid[0][0] for row in range(num_rows): for col in range(num_cols): if row == 0 and col == 0: cost[0][0] = grid[0][0] continue col_cost = cost[row][col-1] if col > 0 else MAX_COST row_cost = cost[row-1][col] if row > 0 else MAX_COST cost[row][col] = grid[row][col] + min(row_cost, col_cost) return cost[num_rows-1][num_cols-1] def min_path_sum_64_top_down(grid: List[List[int]]) -> int: """ For the sake of completness, here is a top-down solution to the same problem. TODO: add memoization. Time Complexity: O(2^(n+m)) Space Complexity: O(n+m) """ MAX_COST = 1000 num_rows = len(grid) num_cols = len(grid[0]) def sp(grid:List[List[int]], row:int, col:int) -> int: # re-use the grid size from the outer scope if row == 0 and col == 0: return grid[0][0] if row >= num_rows or col >= num_cols: return MAX_COST #if row == (num_rows-1) and col == (num_cols-1): # return grid[row][col] # Wrong index here.... row_cost = sp(grid, row-1, col) + grid[row][col] if row > 0 else MAX_COST col_cost = sp(grid, row, col-1) + grid[row][col] if col > 0 else MAX_COST return min(row_cost, col_cost) return sp(grid, num_rows-1, num_cols-1) # Question 102 # Binary Tree Level Order Traversal # https://leetcode.com/problems/binary-tree-level-order-traversal/ def level_order_traversal_102(root: Optional[BinaryTreeNode]) -> List[List[int]]: """ Return a level-order traversal of some BinaryTreeNode. We want to the traversal returned as a List, where each element is a List of all the values at a given level. """ if not root: return [] q = [root] traversal = [] #from pudb import set_trace; set_trace() while q: # Get any nodes from the queue. The nodes will have been added in "level" order # since we add all children to the queue at the end of the loop. In other words # we expect the length of the queue to double on each level, assuming that all # nodes are populated. level = [] for _ in range(len(q)): # Add the value from this node to the traversal of this level cur_node = q.pop(0) if cur_node: level.append(cur_node.val) # Add any children to the queue, on the subsequent loop we will visit them # and their children in turn. if cur_node.left: q.append(cur_node.left) if cur_node.right: q.append(cur_node.right) traversal.append(level) return traversal # Question 103 # Binary Tree ZigZag Level Order Traversal # https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/ def level_order_zigzag_traversal_103(root:Optional[BinaryTreeNode]) -> List[List[int]]: """ The zig-zag level order traversal is the traversal that goes in level order from left to right, then on the subsequent level right-to-left, then left-to-right and so on. """ if not root: return [] left_first = False q = [root] traversal = [] while q: level = [] for _ in range(len(q)): cur_node = q.pop(0) if cur_node: level.append(cur_node.val) if left_first: nodes = [cur_node.left, cur_node.right] else: nodes = [cur_node.right, cur_node.left] q.extend(nodes) left_first = ~left_first if level: traversal.append(level) return traversal # Question 300 # Longest increasing subsequence # https://leetcode.com/problems/longest-increasing-subsequence/ def lis_300(nums: List[int]) -> int: """ This is the shitty solution Time complexity: O(n^2) Space complexity: O(n) (for d array) """ N = len(nums) # This is the array that tells us how long each subsequence is. The element d[i] # represents the length of the longest subsequence ENDING at nums[i]. d = [1 for _ in range(N)] # Construct d #from pudb import set_trace; set_trace() ans = d[0] for i in range(N): for j in range(i): if nums[j] < nums[i]: d[i] = max(d[i], d[j]+1) ans = max(ans, d[i]) return ans def lis_300_recursive(nums: List[int]) -> int: """ A recursive solution. This one looks at all pairs of elements in nums. Time Complexity: O(n^2) Space Complexity: O(n) (stack) """ MIN_VAL = int(-1e4) def solve(nums: List[int], idx: int, prev: int) -> int: # Base case - there are no more numbers to pick if idx >= len(nums): return 0 dont_take = solve(nums, idx+1, prev) # value if we don't include this value in the subsequence if nums[idx] > prev: take = 1 + solve(nums, idx+1, nums[idx]) # value if we include this value in the subsequence else: take = 0 return max(take, dont_take) return solve(nums, 0, MIN_VAL) # TODO: do a proper DP version def lis_300_alt(nums: List[int]) -> int: """ This is version where the d array holds the element at which a subsequence of length i terminates. This version still has a runtime complexity of O(n^2). """ from pudb import set_trace; set_trace() MAX = 100000 N = len(nums) d = [MAX for _ in range(N+1)] d[0] = -MAX for i in range(N): for j in range(1, N+1): if (d[j-1] < nums[i]) and (nums[i] < d[j]): d[j] = nums[i] ans = 0 for elem in d: if elem < MAX: ans = elem return ans # Question 322 # https://leetcode.com/problems/coin-change/ # You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money. # # Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1. # #You may assume that you have an infinite number of each kind of coin def coin_change_322(coins:List[int], amount:int) -> int: # Time complexity here is O(C * A) where C is the number of elements in coins # and A is the amount. # # Space complexity is O(A) as we are storing the min value for each value between # 0 -> amount in num_ways[]. # # In this case amount+1 is effectively MAX_INT num_ways = [(amount+1) for _ in range(amount+1)] num_ways[0] = 0 # Find values for each element in the cache ways for k in range(1, amount+1): for c in coins: if (k - c) >= 0: num_ways[k] = min(num_ways[k], num_ways[k - c] + 1) if num_ways[amount] < (amount + 1): return num_ways[amount] return -1 # question 322 # https://leetcode.com/problems/coin-change/ # # an implementation using a depth-first search. def coin_change_dfs_322(coins: List[int], amount:int) -> int: pass # Question 416 # https://leetcode.com/problems/partition-equal-subset-sum/ # Question 714 # https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/ def time_to_buy_stock_714(prices: List[int], fee: int) -> int: pass # Question 842 # https://leetcode.com/problems/split-array-into-fibonacci-sequence/ def split_into_fib_seq_842(num:str) -> List[int]: """ You are given a string of digits num, such as "123456579". We can split it into a Fibonacci-like sequence [123, 456, 579]. Formally, a Fibonacci-like sequence is a list f of non-negative integers such that: 0 <= f[i] < 231, (that is, each integer fits in a 32-bit signed integer type), f.length >= 3, and f[i] + f[i + 1] == f[i + 2] for all 0 <= i < f.length - 2. Note that when splitting the string into pieces, each piece must not have extra leading zeroes, except if the piece is the number 0 itself. Return any Fibonacci-like sequence split from num, or return [] if it cannot be done. """ # # "1101111" # ^ <- pointer to left-most digit (i) # ^ <- pointer to current right-most digit (j) # ^ <- pointer to next digit (k) # # "1101111" # ^ <- pointer to left-most digit (i) # ^ <- pointer to current right-most digit (j) # ^ <- pointer to next digit (k) # # # "1101111" # ^ <- pointer to left-most digit # ^ <- pointer to current right-most digit # ^ <- pointer to next digit. # 1, 1, 0 <- fails #
# python3 def linear_search(keys, query): for i in range(len(keys)): if keys[i] == query: return i return -1 def binary_search(keys, query, final_position, checker): checker_position = len(keys) // 2 checker_value = keys[checker_position] #print('Query:', query) #print('Checker Position:', checker_position) #print('Checker Value:', checker_value) #print('Final Position:', final_position) if query == checker_value: if len(keys) <= 2 and checker == 1: final_position += 1 return final_position elif len(keys) <= 1 or len(keys) <= 2 and query > checker_value: return -1 elif query > checker_value: keys = keys[checker_position + 1:] final_position += len(keys) // 2 + 1 return binary_search(keys, query, final_position, checker) elif query < checker_value: keys = keys[:checker_position] if len(keys) == 2: checker = 1 final_position -= len(keys) // 2 + 1 return binary_search(keys, query, final_position, checker) if __name__ == '__main__': input_keys = list(map(int, input().split()))[1:] input_queries = list(map(int, input().split()))[1:] final_position = len(input_keys) // 2 checker = 0 for q in input_queries: print(binary_search(input_keys, q, final_position, checker), end=' ')
import tkinter as tk from tkinter import * from tkinter import messagebox from googletrans import Translator import pyperclip #Creating the Frontend by using Tkinter app = tk.Tk() app.title('Tanslator') app.geometry('500x350') app.configure(bg="#eaeaea") #String Variables ent_var = StringVar() out_var = StringVar() lang_selec = StringVar() #Class for Translation class Trans(): def trans(self): inn=ent_var.get() if inn!="": selected_language=lang_selec.get() if selected_language=="Arabic": out=Translator().translate(inn, dest='ar') out_var.set(out.text) self.show() elif selected_language == "Chinese": out = Translator().translate(inn, dest='zh-TW') out_var.set(out.text) self.show() elif selected_language == "French": out = Translator().translate(inn, dest='fr') out_var.set(out.text) self.show() elif selected_language=="English": out=Translator().translate(inn, dest='en') out_var.set(out.text) self.show() elif selected_language=="German": out=Translator().translate(inn, dest='de') out_var.set(out.text) self.show() elif selected_language == "Gujarati": out = Translator().translate(inn, dest='gu') out_var.set(out.text) self.show() elif selected_language == "Hindi": out = Translator().translate(inn, dest='hi') out_var.set(out.text) self.show() elif selected_language == "Japanese": out = Translator().translate(inn, dest='ja') out_var.set(out.text) self.show() elif selected_language == "Kannada": out = Translator().translate(inn, dest='Kn') out_var.set(out.text) self.show() elif selected_language == "Korean": out = Translator().translate(inn, dest='Kn') out_var.set(out.text) self.show() elif selected_language == "Latin": out = Translator().translate(inn, dest='la') out_var.set(out.text) self.show() elif selected_language == "Marathi": out = Translator().translate(inn, dest='mr') out_var.set(out.text) self.show() elif selected_language=="Punjabi": out=Translator().translate(inn, dest='pa') out_var.set(out.text) self.show() elif selected_language=="Russian": out=Translator().translate(inn, dest='ru') out_var.set(out.text) self.show() elif selected_language == "Spanish": out = Translator().translate(inn, dest='es') out_var.set(out.text) self.show() elif selected_language == "Tamil": out = Translator().translate(inn, dest='ta') out_var.set(out.text) self.show() elif selected_language == "Telugu": out = Translator().translate(inn, dest='te') out_var.set(out.text) self.show() else: messagebox.showerror("Error", "Language not available Currently. Please select from the given list") else: messagebox.showerror("Error", "Input Text Can't Be Empty") def show(self): #Toplayer for the output. top =Toplevel() top.title('Tanslator') top.geometry('500x350') top.configure(bg="#eaeaea") def copy(): pyperclip.copy(out_var.get()) #To copy the output directly to the clipboad. button = tk.Button(top, text='Copy', width=35, height=3, command=copy, activebackground="dark grey", activeforeground="red") button.place(relx=0.5, rely=0.7, anchor=CENTER) msg1 = tk.Label(top, text='Translation', ) msg1.place(relx=0.5, rely=0.4, anchor=CENTER) user_pass = Entry(top, textvariable=out_var, ) user_pass.place(relx=0.5, rely=0.5, anchor=CENTER, width=400,height=50) #Creating the object for the Trans Class obj=Trans() msg1 = tk.Label(app, text='Input text', ) msg1.place(relx=0.5, rely=0.1, anchor=S) in_text = Entry(app, textvariable=ent_var) in_text.place(relx=0.5, rely=0.2, anchor=CENTER, width=350, height=30) msg2 = tk.Label(app, text='Language') msg2.place(relx=0.5, rely=0.4, anchor=S) #Creating the language selection. languages = ["Tamil","Telugu","Spanish", "Russian", "Punjabi", "Marathi", "Latin", "Korean", "Kannada", "Japanese", "Hindi", "Gujarati", "German", "English", "French", "Chinese", "Arabic"] #SpinBox to select the choice of the language. lang_selec_box=Spinbox(app, values=languages,textvariable=lang_selec) lang_selec_box.place(relx=0.5, rely=0.5, anchor=CENTER, width=350, height=30) #Button to start the Trans function. translate_button = tk.Button(app, text='Translate', width=35, height=3, command=obj.trans, activebackground="dark grey", activeforeground="red") translate_button.place(relx=0.5, rely=0.7, anchor=CENTER) app.mainloop()
"""The interface used by user""" from tkinter import * class Interface: """The main interface""" def __init__(self): global root root = Tk() root.title("Expense Tracker") mybutton1 = Button(root,text="Start", command = self.mybutton,width = 25, height = 5) mybutton1.pack() root.mainloop() def mybutton(self): """Create a button to let user interact with""" mybutton2 = Button(root,text="Company and Acount Type", command = self.mycompany,width = 25, height = 5) mybutton2.pack() mybutton3 = Button(root,text="Sum of The Total Amount Due", command = self.mytotal,width = 25, height = 5) mybutton3.pack() mybutton4 = Button(root,text="Sum of The Monthly Budget", command = self.mybudget,width = 25, height = 5) mybutton4.pack() def mycompany(self): mylabel = Label(root,text = "Companies and account types are: ") mylabel.pack() def mytotal(self): mylabe2 = Label(root,text = "Sum of the total amount is: ") mylabe2.pack() def mybudget(self): mylabe3 = Label(root,text = "Sum of monthly budget is: ") mylabe3.pack() if __name__ == '__main__': myInterface = Interface()
#add any 2 numbers a=int(input("enter value of a")) b=int(input("enter value of b")) sum=a+b print(sum)
def tree(tpl): dct = {} # словарь, где ключ - родитель, значение - множество детей for index, apex in enumerate(tpl): if apex not in dct: dct.update({ apex: {index}, }) else: dct[apex].add(index) return dct def height_tree(dct): height = 0 # высота дерева # проверяем, что на вход поступило не пустое дерево try: stack = dct.get(-1).copy() # корень дерева не имеет родителя # обходим дерево по уровням от родителей к детям while stack: height += 1 # собираем детей со следующего уровня new_stack = set() for num in stack: apex = dct.get(num) if apex: new_stack.update(apex) stack = new_stack.copy() finally: return height n = int(input()) parents = tuple(map(int, input().split())) print(height_tree(tree(parents)))
A = int(input ("Could I ask you for a number? ")) k = 0 for i in range(A//2, 0, -1): if A % i == 0: k = k + i if A == k: print ("It is a perfect number") else: print ("It is not a perfect number")
# У меня большие проблемы с тем, чтобы сосолаться на функцию из другого модуля! # Я умею импортировать модуль, но он у меня тогда его начинает запускать полностью! # А если я ему пишу так: from Task_1 import factorial () # он меня не понимает! Поэтому пришлось копировать! def factorial(x): mult = 1 for i in range (2,x+1): mult = mult * i return mult x = int(input("Hello! We are goig to print out the first n rows of Pascal's triangle! Input the x: ")) def C(n, k): t = factorial(n) // (factorial(n-k) * factorial(k)) return t for n in range (0, x + 1): print("\n", end=" " * (x - n + 1)) for k in range (0, n + 1): print(C(n, k), end=' ')
import csv def list_to_dict(l1: list, l2: list) -> dict: result = {} for index in range(len(l2)): result[l2[index]] = l1[index] return result def csv_to_dict(file: str, dictKeyList: list) -> dict: result = {} open_file = open(file, 'r') read_file = csv.reader(open_file) csv_format = next(read_file) #skips first line (header) in a .csv file if csv_format[1] in ['gender', 'ethnicity', 'major']: for line in read_file: if line[0] not in result: result[line[0]] = {} result[line[0]][line[1]] = list_to_dict(line[2:], dictKeyList) else: result[line[0]][line[1]] = list_to_dict(line[2:], dictKeyList) else: for line in read_file: if line[0] not in result: result[line[0]] = {} result[line[0]] = list_to_dict(line[1:], dictKeyList) else: result[line[0]] = list_to_dict(line[1:], dictKeyList) return result
import math func = lambda x: 2*math.sin(x) - x**2 fp = lambda x : 2*math.cos(x)-2*x g = lambda x: math.sqrt(2*math.sin(x)) X = 1.3 root = 1.404418240924343641 def biseccion(a,b,n): print("Bisección") aN = a bN = b for i in range(1,n+1): m_n = (aN+bN)/2 f = func(m_n) print("a_N: "+str(aN),"b_N: "+str(bN),"m_N: "+str(m_n), "error: "+"{:3e}".format(abs(root-(aN+bN)/2 ))) if func(aN)*f < 0: bN = m_n elif func(bN)*f < 0: aN = m_n elif f == 0: return m_n else: return None raiz = (aN+bN)/2 if raiz != None: print("iteraciones: ", n) print(raiz, 'con un error absoluto de: ', "{:3e}".format(abs(root-raiz))) print("\n") def newton(x_not, n): print("Newton-Raphson") for i in range(n): x = x_not - (func(x_not)/fp(x_not)) print("x_i: "+str(x_not),"x: "+ str(x), "error: "+"{:3e}".format(abs(root-x))) x_not = x print("iteraciones: ", n) print(x,"con un error absoluto de: "+"{:3e}".format(abs(root-x))) print("\n") def fixedPoint(x_i, n): print("Punto Fijo") print("función g(x)=(2*sin(x))^(1/2)") for i in range(n): x = x_i print("x: "+ str(x), "error: "+"{:3e}".format(abs(root-x))) x_i = g(x) print("iteraciones: ", n) print(x,"con un error absoluto de: "+"{:3e}".format(abs(root-x))) biseccion(float(input('a: ')),float(input('b: ')), int(input('n: '))) newton(1, 4) fixedPoint(1, 5)
import math root1 = 0.22849140 root2 = 2.69682 def serie(): print('Serie de MacLaurin para ln((1+x)/(1-x)), evaluada en 0.75 para obtener ln(7)') S = 0 x = .75 real = 1.94591014906 i = 0 while abs(S-real)>=0.00001: S += 2*(x)**(2*i + 1) / (2*i +1) print("S:", S, "error: "+"{:3e}".format(abs(S-real))) i+=1 print("iteraciones: ", i) print(S, 'con un error absoluto de: ', "{:3e}".format(abs(S-real))) print('\n') serie() def raiz(a,b, a2,b2): print('Calculo de raices para 11x-2e^x mediante método de bisección \nRaíz 1: ') x = lambda s : 11*s - 2*(math.e)**s aN = a bN = b i = 0 while abs((aN+bN)/2 - root1)>=0.00001: m_n = (aN+bN)/2 f = x(m_n) print("a_N: "+str(aN),"b_N: "+str(bN),"m_N: "+str(m_n), "error: "+"{:3e}".format(abs(root1-(aN+bN)/2 ))) if x(aN)*f < 0: bN = m_n elif x(bN)*f < 0: aN = m_n elif f == 0: return m_n else: return None i+=1 print("iteraciones: ", i) print((aN+bN)/2, 'con un error absoluto de: ', "{:3e}".format(abs((aN+bN)/2-root1))) print('\nRaíz 2:') i = 0 aN = a2 bN = b2 while abs((aN+bN)/2 - root2)>=0.00001: m_n = (aN+bN)/2 f = x(m_n) print("a_N: "+str(aN),"b_N: "+str(bN),"m_N: "+str(m_n), "error: "+"{:3e}".format(abs(root2-(aN+bN)/2 ))) if x(aN)*f < 0: bN = m_n elif x(bN)*f < 0: aN = m_n elif f == 0: return m_n else: return None i+=1 print("iteraciones: ", i) print((aN+bN)/2, 'con un error absoluto de: ', "{:3e}".format(abs((aN+bN)/2-root2))) print('\n') raiz(0,1,2,3) def newton(x_0, x_0_2): print('Calculo de raices para 11x-2e^x mediante método de Nexton \nRaíz 1:') f = lambda x: 11*x - 2*(math.e)**x fp = lambda x : 11 - 2*(math.e)**x i=0 x=0 while abs(x-root1)>=0.00001: x = x_0 - (f(x_0)/fp(x_0)) print("x_0: ",x_0,"x: ", x) x_0 = x i+=1 print("iteraciones: ", i) print(x, 'con un error absoluto de: ', "{:3e}".format(abs(x-root1))) print('\nRaíz 2:') x_0 = x_0_2 i=0 x=0 while abs(x-root2)>=0.00001: x = x_0 - (f(x_0)/fp(x_0)) print("x_0: ",x_0,"x: ", x) x_0 = x i+=1 print("iteraciones: ", i) print(x, 'con un error absoluto de: ', "{:3e}".format(abs(x-root2))) newton(0,2) def fixedPoint(x_0, x_0_2): print('Calculo de raices para 11x-2e^x mediante método de Punto Fijo \nRaíz 1:') print("g(x) = 2e^x/11") g = lambda x: 2*(math.e)**x / 11 i=0 x=0 while abs(x-root1)>=0.00001: x = x_0 print("x_0: ",x_0,"x: ", x) x_0 = g(x) i+=1 print("iteraciones: ", i) print(x, 'con un error absoluto de: ', "{:3e}".format(abs(x-root1))) print('\nRaíz 2:') print("g(x)=ln(11x/2e)+1") g = lambda a: math.log1p(-1+(11/2)*(a/math.e))+1 x_0 = x_0_2 i=0 x=0 while abs(x-root2)>=0.00001: x = x_0 print("x_0: ",x_0,"x: ", x) #if abs(g(x))>1: # break x_0 = g(x) i+=1 print("iteraciones: ", i) print(x, 'con un error absoluto de: ', "{:3e}".format(abs(x-root2))) fixedPoint(.2, 2.7)
""" Math 560 Project 3 Fall 2020 Partner 1: George Lindner (dgl12) Partner 2: Ezinne Nwankwo (esn11) Date: October 28, 2020 """ # Import math and p3tests. import math from p3tests import * ################################################################################ """ detectArbitrage """ def detectArbitrage(adjList, adjMat, tol=1e-15): """ The detectArbitrage function detects negative cost cycles in graphs using an implementation of the Bellman-Ford algorithm. :param adjList: Adjacency list representing currencies graph. :param adjMat: the adjacency matrix representing the exchange rates, as generated by the rates2mat function. :param tol: this is a value that is set at 1e-15 as default to account for any small system error. :return: list of nodes involved in negative cost cycles or arbitrage. """ # Set initial distances and previous nodes. for vertex in adjList: vertex.dist = math.inf vertex.prev = None # Initialize start distance to 0 # Choose starting node as first node in adjacency list adjList[0].dist = 0 # iterate |V| - 1 times for i in range(len(adjList) - 1): # iterate over each vertex in adjacency list for vertex in adjList: # Check each neighbor of the vertex for neighbor in vertex.neigh: # only update if new node distance gives better offer # meaning the distance is shorter if neighbor.dist > vertex.dist + adjMat[vertex.rank][neighbor.rank] + tol: neighbor.dist = vertex.dist + adjMat[vertex.rank][neighbor.rank] neighbor.prev = vertex # Run extra iteration to check if any distances changed # If the optimal value is changed, this implies that there is a cycle # Thus, we note which node is changed. And we start from that node # That node is called 'cycle' cycle = None for vertex in adjList: for neighbor in vertex.neigh: # This if statement only will be true if a distance is updated! if neighbor.dist > vertex.dist + adjMat[vertex.rank][neighbor.rank] + tol: # This means that there is a cycle neighbor.dist = vertex.dist + adjMat[vertex.rank][neighbor.rank] neighbor.prev = vertex cycle = neighbor break # As soon as the cycle is not empty, meaning a node was updated, indicating arbitrage if cycle is not None: break # If cycle is none, then no arbitrage and return empty list if cycle is None: return [] # If cycle is not none, then we need to traceback the cycle of nodes that had arbitrage path = [] # While the current vertex is not already in the path # append the previous nodes to path # this returns list of the nodes that were updated after extra iteration while cycle.rank not in path: path.append(cycle.rank) cycle = cycle.prev # Now we need to work back to get actual arbitrage cycle # and remove any extra nodes not in arbitrage cycle cycle = cycle.prev path = [] while cycle.rank not in path: path.append(cycle.rank) cycle = cycle.prev path.append(cycle.rank) return path[::-1] ################################################################################ """ rates2mat """ def rates2mat(rates): """ The rates2mat function generates a matrix of exchange rates that will be used as weights in the currencies graph. :param rates: a 2D array representing the exchange rates. :return: a matrix of the negative log of each exchange rate. """ # Return the adjacency matrix with the correctly weighted edges using properties of logarithms return [[-math.log(R) for R in row] for row in rates] """ Main function. """ if __name__ == "__main__": testRates()
l1=[10,20,30,40] l1.append(40) print(l1) print("appending one list to another list") l2=[300,400,500] l1.append(l2) print("append=",l1) print("----------------------","ExtendMethod","----------------") l2=[300,400,500] l1.extend(l2) print(l1) l3=[10,20] l2.extend(l3) print(l2) print("-------------","Insert Method ","-----------") l4=[324,675,-1,-2] l4.insert(4,30) print("Inserting ", l4) print("Index of -2 number =",l4.index(-2)) print("============== sorting l1 ==========") l4.sort() print(l4) l4[0]=35 print(l4)
# Fitness Data Class. # Create a class that has the properties: # 1.) name (Constructor set) # 2.) step count # 3.) height (Constructor set) # 4.) miles walked. # class FitnessData: def __init__(self, name, height): self.name = name self.stepCount = 0 self.height = height self.mileWalked = 0 def addSteps(self, moreSteps): self.stepCount = self.stepCount + moreSteps #print("currentSteps==", self.stepCount) def getMiles(self): # m = 1/2 height * stepCount self.miles = self.stepCount / (1/4 * self.height) return self.miles #END CLASS #object1 object1 = FitnessData("Joe", 6.0) # add 500 steps to object1 using the addSteps class function object1.addSteps(500) # print the current number of steps print("object1--step count: ", object1.stepCount ) #object2 object2 = FitnessData("Tom", 8.0) object2.addSteps(1000) print( "object2-- getMiles(): ", object2.getMiles() )
def RenjieWen(): print("he is cool") def printLess100(n): for x in n: if x < 100: print(x) else: print("something larger than 100") def defineRange(n): for x in n: if x < 0: print(x,'is a negative number') elif x >= 43 and x < 100: print(x , 'is inside the range') else: print(x, 'is outside the range') def ifItemInList(instruments,inventory): for item in instruments: if item in inventory.keys(): print(item,'is in the dictionary, the value is', inventory[item]) else: print(item, 'is not in the dictionary') def write_bottle_song(): file = open('./!0GreenBottles.txt', 'w') for numBottle in range(10): s = str(10-numBottle) + " green bottles hanging on the wall, but if one bottle should accidentally fall. There will be " + str(9-numBottle) + " green bottles hanging on the wall\n" file.write(s) file.close()
#Proyecto final - Minijuego TATETI (Grupo: Juan Cruz - Mirko) '''Reglamento: 1. Cantidad de jugadores: 2. 2. Objetivo: Formar TA-TE-TI en el tablero de juego. 3. El jugador que inicia el juego lo define el sistema en forma aleatoria. Como jugar: - Al inicio el sistema define en forma aleatoria cual de los 2 jugadores comienza la partida. - Inicialmente, cada jugador podrá elegir 3 posiciones del tablero (que estén vacías), según se desarrolla la partida. - El jugador que comienza podrá elegir cualquier posición del tablero (incuida la del centro). - Luego de la primer jugada, continua el otro jugador y así sucesivamente de forma alternada. - Si no hay un ganador luego de elegidas las 3 posiciones del tablero por cada jugador, el juego puede continuar dejando libre una posición del tablero y seleccionar otra distinta a esta, pero libre. - La selección de nuevas posiciones por parte de ambos jugadores, será en función a como se desarrolle la partida y finalizará cuando un de los jugadores logre formar TA-TE-TI. ''' #Función de inicio - Define de forma aleatoria quien es "X" y "O" y quien comienza jugando en la partida. import random simbolos=["X","O"] jug1=str(input('Ingresar nombre del jugador 1: ')) jug2=str(input('Ingresar nombre del jugador 2: ')) def ini_partida(x,y): jugadores=[jug1,jug2] asig1=(random.choice(simbolos)) if asig1=='X': asig2='O' else: asig2='X' print('La asignación de letras es: ', jug1,'=',asig1, '|', jug2, '=', asig2) print('Inicia la partida:',random.choice(jugadores)) return () ini_partida(jug1,jug2) def mostrar_tablero(tablero): # se crea función para crear el tablero e imprimirlo en pantalla for fila in tablero: for i in range (len (fila)): # recorre cada elemento de la fila if i==len(fila)-1: # representa el último elemento de cada lista,ya que el largo de cada sublista es de 5 elementos(len=4),ya que se cuenta desde subindice 0 a 4. print(fila[i],end='\n') # se muestra en pantalla sólo el último elemento de cada lista y con '\n' se baja al siguiente renglón, para armar el tablero else: # si no es el último elemento, se lo imprime en pantalla y no se baja a siguiente renglón print(fila[i], end=' ') tablero= [ [' ', '|', ' ', '|', ' '], # posición 0,1,2,3,4 de la lista 0 [0:0,0:1,0:2,0:3,0:4] ['-', '+', '-', '+', '-'], # posición 0,1,2,3,4 de la lista 1 [1:0,1:1,1:2,1:3,1:4] [' ', '|', ' ', '|', ' '], # posición 0,1,2,3,4 de la lista 2 [2:0,2:1,2:2,2:3,2:4] ['-', '+', '-', '+', '-'], # posición 0,1,2,3,4 de la lista 3 [3:0,3:1,3:2,3:3,3:4] [' ', '|', ' ', '|', ' '] # posición 0,1,2,3,4 de la lista 4 [4:0,4:1,4:2,4:3,4:4] ] mostrar_tablero(tablero)
''' A suite of functions to make eda plots with baseball data ''' import matplotlib.pyplot as plt import pandas as pd from pymongo import MongoClient def plot_stats_over_time(year_index, df, stats_to_plot, games_per_year): ''' Parameters: ---------- Input: year_index {list-like}: list of years covered by plot, generally 1871-2018 df {dataframe}: Pandas dataframe with data to plot stats_to_plot {list}: list of stats (columns) to plot games_per_year {list-like}: list of the total number of mlb games played for each year described in plot Output: Plot ''' fig, ax = plt.subplots(figsize=(20,10)) for stat in stats_to_plot: ax.plot(year_index, df[stat]/ games_per_year, label=stat, lw=3) ax.legend(prop={'size': 20}) ax.set_title("Yearly Totals Per Game Over Time", fontsize=20) ax.set_xlabel("Year") plt.show def _connect_mongo(host, port, username, password, db): """ A util for making a connection to mongo """ if username and password: mongo_uri = 'mongodb://%s:%s@%s:%s/%s' % (username, password, host, port, db) conn = MongoClient(mongo_uri) else: conn = MongoClient(host, port) return conn[db] def read_database(db, query={}, host='localhost', port=27018, username=None, password=None, no_id=True): """ Read from Mongo and Store into DataFrame Typically port 27017 is used""" # Connect to MongoDB db = _connect_mongo(host=host, port=port, username=username, password=password, db=db) dfs = [] # Get list of collections for name in db.list_collection_names(): # Make a query to the specific DB and Collection cursor = db[name].find(query) # Expand the cursor and construct the DataFrame df = pd.DataFrame(list(cursor)) # Delete the _id if no_id: del df['_id'] dfs.append(df) return pd.concat(dfs) def read_collection(db, collection, query={}, host='localhost', port=27018, username=None, password=None, no_id=True): """ Read from Mongo and Store into DataFrame Typically port 27017 is used""" # Connect to MongoDB db = _connect_mongo(host=host, port=port, username=username, password=password, db=db) # Make a query to the specific DB and Collection cursor = db[collection].find(query) # Expand the cursor and construct the DataFrame df = pd.DataFrame(list(cursor)) # Delete the _id if no_id: del df['_id'] return df
#!/usr/bin/python3 # -*- coding:utf-8 -*- import numpy as np def sigmoid(z): p = 1 / (1 + np.exp(-z)) return p def predict(x, theta): m, n = x.shape theta = theta.reshape((n, 1)) z = x * theta a = sigmoid(z) > 0.5 return a
def guess(num, k): if num < k: return -1 elif num > k: return 1 else: return 0 class Solution(object): def guessNumber(self, n, k): """ :type n: int :rtype: int """ l, r = 0, n while l <= n: mid = (l + r + 1) >> 1 print(l, mid, n) res = guess(mid, k) if res == -1: l = mid + 1 elif res == 1: r = mid - 1 else: return mid print(Solution().guessNumber(2, 2))
# -*- coding:utf-8 -*- class Solution: # array 二维列表 def binary_search(self, array, target): length = len(array) l, h = 0, length - 1 while l <= h: mid = l + (h - l) // 2 print(l, mid, h) if array[mid] < target: l = mid + 1 elif array[mid] > target: h = mid - 1 else: return True return False def Find(self, target, array): # write code here for sub_array in array: if not sub_array: continue if target < sub_array[0]: return False exists = self.binary_search(sub_array, target) if exists: return True return False nums = [[1,2,8,9],[2,4,9,12],[4,7,10,13],[6,8,11,15]] result = Solution().Find(15, nums) print(result)
#!/usr/bin/python import socket #from Tkinter import * class player: def __init__(self, n): self.name = n port = int(raw_input("define port: ")) conn = socket.socket() host = socket.gethostname() #port = 12345 conn.connect((host,port)) while True: print "***MENU***" print "1 - Enter names" print "2 - Get names" print "3 - Show Board" print "4 - Make move" print "0 - Exit" choice = int(raw_input("> ")) if choice == 1: p1name = raw_input("What is player one's name: ") p1 = player(p1name) p2name = raw_input("What is player two's name: ") p2 = player(p2name) elif choice == 2: print "Player one's name is " + p1.name + " and player two's name is " + p2.name elif choice == 3: conn.send("Print") print conn.recv(1024) elif choice == 4: conn.send("Update") letter = raw_input("Send which letter?") x = raw_input("To which X coord?") y = raw_input("To which Y coord?") conn.send(letter + x + y) print conn.recv(1024) #success or fail message elif choice == 0: break print "Thanks for playing!" conn.close
import math class SolutionTest(object): def reverse(self, x): ret = 0 mul = 1 sign = x/abs(x) if x is not 0 else 0 log = int(math.log(abs(x))/math.log(10)) if x is not 0 else 0 #maxmul = 10**log if x is not 0 else 0 for mul in [10**d for d in range(log + 1)]: ret += (10**log)*(sign*((abs(x)/mul)%10)) log -= 1 return ret if ret<=2**31-1 and ret >= -(2**31) else 0 """ :type x: int :rtype: int """ solutionTest = SolutionTest() print(solutionTest.reverse(123))
def get_indices_of_item_weights(weights, length, limit): """ YOUR CODE HERE """ # Add all items to a hash table with weight: index table = {} for i in range(len(weights)): # store indices in arrays so that we can handle duplicate weights if weights[i] in table: table[weights[i]].append(i) else: table[weights[i]] = [i] # Check each item to see if there is a matching weight # (i is descending so that we get the highest index solution possible) for i in range(len(weights)-1, -1, -1): w = limit - weights[i] # matching weight if w in table: # found a match if len(table[w]) == 1: # only 1 item with that weight return (i, table[w][0]) else: # multiple items, find highest matching index that isn't i idx = table[w][0] for j in table[w]: if j > idx and j != i: idx = j return (i, idx) # No match found, return None return None
import sqlite3 as sq db = sq.connect('data/mydb') cursor = db.cursor() rowNumbers = 32 def createTable(headers): #headers = [ "name" , "phone", "email" , "password" ] try: ## connects to the database #db = sq.connect('data/mydb') # get a cursor object #cursor = db.cursor() # check if the table exists #dropTableStatement = "DROP TABLE users1" #cursor.execute(dropTableStatement) #db.commit() #print("table deleted") print(headers[:rowNumbers]) insertStatement = "CREATE TABLE IF NOT EXISTS users1 %s " % (tuple(headers[:rowNumbers]),) #insertStatement = insertStatement + " VALUES %s" % (tuple(headers),) #cursor.execute('''CREATE TABLE IF NOT EXISTS # users(id INTEGER PRIMARY KEY , name TEXT, phone TEXT, email TEXT, password TEXT)''') cursor.execute(insertStatement) db.commit() print("table created") except Exception as e: db.rollback() print(e) raise e #finally: #db.close() def inputValue(): name = "andreas" phone = "123" email = "[email protected]" password = "123" playerValues = ["one", "two", "three", "four"] try: ## connects to the database db = sq.connect('data/mydb') with db: #db.execute(''' INSERT INTO users(name, phone, email, password) #VALUES(?,?,?,?)''', (name, phone, email,password)) db.execute(''' INSERT INTO users4(name, phone, email, password) VALUES(?,?,?,?)''', tuple(playerValues)) print("input proceseed") except sq.IntegrityError: print("record already exists") finally: db.close() def dynamicTableCreation(): global db tableName = "stat1" data_list = ['id', 'url', 'name', 'number', 'position', 'captain', 'subbed', 'homeAway', 'subToolTip', 'eventTimes', 'onPitch', 'wasActive', 'tries', 'tryassists', 'points', 'kicks', 'passes', 'runs', 'metres', 'cleanbreaks', 'defendersbeaten', 'offload', 'lineoutwonsteal', 'turnoversconceded', 'tackles', 'missedtackles', 'lineoutswon', 'penaltiesconceded', 'yellowcards', 'redcards', 'penalties', 'penaltygoals', 'conversiongoals', 'dropgoalsconverted'] db = sq.connect("data/mydb") commie = "CREATE TABLE IF NOT EXISTS users2(" for data in data_list: commie = commie + data + " , " + "TEXT " commie = commie + ")" #print(commie) db.execute(commie) cursor = db.cursor() cursor.execute("PRAGMA table_info(users2)") heads = list(cursor.fetchall()) print(heads) #db.execute("CREATE TABLE IF NOT EXISTS " + tableName +" VALUES(" + ('?,' * len(data_list))[:-1] + ")", data_list) def dynamicTableCreation2(): createStatment = "CREATE TABLE IF NOT EXISTS users3" #dynamicTableCreation() def sanitiseList(liste): strList = [] for item in liste: print(type(item)) if type(item) is list: #item = item.replace('""', " ") item = item[0] strList.append(str(item)) return strList def insertPlayerData(colheads, list): #headers = [ "name" , "phone", "email" , "password" ] print(colheads[:rowNumbers]) print(list[:rowNumbers]) print(10*"^") ## sanitise the list list = sanitiseList(list) insertStatement = "INSERT INTO users1 %s " % (tuple(colheads[:rowNumbers]),) insertStatement = insertStatement + " VALUES %s " % (tuple(list[:rowNumbers]),) #db.execute(''' INSERT INTO users(name, phone, email, password) #VALUES(?,?,?,?)''', tuple(list)) #print(insertStatement) cursor.execute(insertStatement) db.commit() #db.close() def readDB(): print("read table") db = sq.connect("data/mydb") db.row_factory = sq.Row cursor = db.cursor() cursor.execute(''' SELECT * FROM users1 ''') data = cursor.fetchall() print(type(data)) ''' for row in data: print(row.keys()) for r in row: print(r) #print(row.values()) #print('{0} : {1}, {2}'.format(row['id'], row['name'], row['number'])) #db.close() ''' print(len(data))
# Second Engeto project Bulls and Cows import random def welcome() -> None: print("Hi there!") separator() print("I've generated a random 4 digit number for you. \nLet's play a bulls and cows game.") separator() def generate_number() -> (list, int): number = [random.randint(1, 9)] for i in range(3): number.append(random.randint(0, 9)) while number[-1] in number[:-1]: number[-1] = random.randint(0, 9) return number def make_a_guess() -> (list, int): while True: guess = input('Enter a number: ') if not guess.isnumeric(): print("Only numbers are allowed") continue elif len(guess) != 4: print("Number must be 4 digit long") continue elif guess[0] == str(0): print("Number cannot start with zero") continue elif len(guess) != len(set(guess)): print("Digits must be unique") continue else: guess = num_to_list(int(guess)) break return guess def separator() -> None: print('-' * 47) def num_to_list(number: int) -> (list, int): return [int(x) for x in str(number)] def list_to_num(number: (list, int)) -> int: return int("".join([str(x) for x in number])) def evaluate_guess(number: (list, int), guess: (list, int)) -> dict: score = {"bulls": 0, "cows": 0} for pos, num in enumerate(guess): if num == number[pos]: score["bulls"] += 1 elif num in set(number): score["cows"] += 1 return score def print_evaluation(score: dict) -> None: print(f"{score['bulls']} bulls, {score['cows']} cows") separator() def goodbye(guesses: int) -> None: if guesses <= 3: message = "amazing" elif guesses <= 6: message = "average" elif guesses <= 8: message = "not so good" else: message = "terrible" print(f"Correct, you've guessed the right number in {guesses} guesses! That's {message}.") def main(): welcome() guesses = 0 guess = [] number = generate_number() while number != guess: guess = make_a_guess() guesses += 1 score = evaluate_guess(number, guess) if score['bulls'] < 4: print_evaluation(score) goodbye(guesses) if __name__ == '__main__': main()
""" False 包括: 1) None 2) 数值中的0(包括0.0) 3) 空序列,包括空字符串(""),空元组(()),空列表[] 4) 空字典{} """ # and - 与,or - 或,not - 非 user_gender = input("请输入您的性别(F/M): ") user_is_student = input("您是学生吗?(Y/N): ") if user_gender == 'F': if user_is_student == 'Y': print("你是萌妹子学生") elif user_is_student == 'N': print('你是萌妹子') else: print("输入不正确") elif user_gender == 'M': print("你是糙汉子") else: print("输入不正确,请输入F或M")
# 自己实现链表 class IntList(object): def __init__(self, f, r): self.first = f self.rest = r #获取链表长度,通过递归实现 """ def size(self): if self.rest is None: return 1 else: return 1 + self.rest.size() """ #获取链表长度,通过循环实现 def size(self): p = self total_size = 0 while p is not None: total_size += 1 p = p.rest return total_size #获取链表元素 def get(self, n): list_size = self.size() - 1 p = self while n < list_size: p = p.rest n += 1 return p.first """ if n == self.size() - 1: return self.first else: return self.rest.get(n) """ l = IntList(5, None) l = IntList(10, l) l = IntList(15, l) l = IntList(20, l) # print(l.rest.rest.first) print(l.size()) print(l.get(1))
#字典(无序),可变的 #字典中的key类型必须是不可变的,例如数值,字符串或元组 #dict查找和插入的速度极快,不会随着key的增加而变慢。但其需要占用大量的内存,内存浪费多 #如果key重复,以最后一个的数据为准 user1 = {'name':'李雷','numbers':'1234',"name":'李四'} print(user1['name']) #使用列表和元组的组合,创建字典 message = [('lilei',98),('hanmeimei',99)] d = dict(message) print(d) #根据关键字参数新建字典 d1 = dict(lilei = 98, hanmeimei = 99) d1['hanmeimei'] = 100 d1['madongmei'] = 90 print(d1) #get方法获取某个key对应的值,如果该值不存在则返回指定的值 print(d1.get('123',0)) #删除字典某某个值 del d1['lilei'] d1.pop('hanmeimei') print(d1) #删除字典中所有值 d1.clear() print(d1) #删除字典本身 del d1 #由字典构成的列表 student1 = {'name':'李雷','age':'18','grade':98} student2 = {'name':'韩信','age':'22','grade':80} student3 = {'name':'李白','age':'28','grade':100} student = [student1,student2,student3] print(student) #字典中存储列表 favorite_class = {'李雷':['数学','英语'], '韩信':['语文'], '李白':['语文','数学','地理']} print(favorite_class) print(favorite_class['李白'][0]) #字典中存储字典 class1 = {'No1':student1,'No2':student2,'No3':student3} print(class1) print(class1['No3']['name'])
#给定一组数字,将他们用链表的形式进行存储。另外再给一个数字,将它插入到链表的末尾。输出这个链表 #创建一个节点元素类 class IntNode(object): def __init__(self, i, n): self.item = i self.next = n #创建一个列表类 class SLList(object): def __init__(self, x): #两个下划线表示把变量或者方法设置成私有 self.__first = IntNode(x, None) self.__last = self.__first self.__second_last = None self.__count = 1 def add_last(self, x): self.__second_last = self.__last self.__last = IntNode(x, None) self.__second_last.next = self.__last self.__count += 1 def size(self): return self.__count def revert(self, m, n): count = 0 current = self.__first left_tmp, head_tmp = None, None while count<m-1: current = current.next count += 1 if m == 0: #left_tmp = current head_tmp = current last_tmp = current else: left_tmp = current head_tmp = current.next current = current.next last_tmp = current count +=1 current = current.next count += 1 while count<=n: tmp_next = current.next current.next = last_tmp if count == n and left_tmp is not None: left_tmp.next = current last_tmp = current current = tmp_next count += 1 head_tmp.next = current if m == 0: self.__first = last_tmp def to_str(self): tmp = self.__first list_str = str(tmp.item) while tmp.next: tmp = tmp.next list_str += '->' + str(tmp.item) return list_str list_str = input() revert_indexes = input() lis = list_str.split(' ') revert_list = revert_indexes.split(' ') result_list = SLList(lis[0]) for item in lis[1:]: result_list.add_last(item) result_list.revert(int(revert_list[0]), int(revert_list[1])) print(result_list.to_str())
import numpy as np import matplotlib.pyplot as plt # Load the data in format (energy,frequency) data = np.loadtxt('results.csv',delimiter=',') """ We produce a plot of the hamming distance from our initial state against the frequency with which we measure these states This is to demonstrate that we can measure states separated by large hamming distances from the initial state """ # computes the hamming distance between integers a and b def hamming_distance(a,b): if a==b: return 0 # include some debug if type(a)!=int: return "input a not an integer" if type(b)!=int: return "input b not an integer" # Compute bit strings for a and b which are of the same length a_bit = bin(a) b_bit = bin(b) a_bit = a_bit[2:] # remove leading bits b_bit = b_bit[2:] # remove leading bits n = len(b_bit)-len(a_bit) if n>0: # b_bit longer than a_bit pad a_bit with zeros a_bit = '0'*n + a_bit elif n<0: # a_bit longer than b_bit pad b_bit with zeros b_bit = '0' * (-n) + b_bit count = 0 for i in range(0,len(a_bit)): if a_bit[i]!=b_bit[i]: count+=1 return count # these two lines get altered by a sed command num_qubits=3 start_state=0 len_data = data.shape len_data = len_data[0] hamming_distances_frequencies = np.zeros(num_qubits+1) # Compute the total frequency of measuring a state at each given hamming distance for i in range(1, len_data): # the indexing is offset by one because we print the initial state twice once at the start of the results file. hamming_distances_frequencies[hamming_distance(i-1,start_state)] += data[i,1] for i in range(0,num_qubits+1): print('('+str(i)+','+str(hamming_distances_frequencies[i])+')') plt.bar(range(num_qubits+1), hamming_distances_frequencies) plt.xlabel("Hamming Distance from initial state") plt.ylabel("Frequency") plt.show()
print("WELCOME TO MY CALCULATOR") while True: welcome_input = str(input("TO ENTER PROGRAMMING MODE 1 ENTER P. \nTO ENTER PROGRAMMING MODE 2 ENTER M \nTO ENTER SCIENTIFIC MODE ENTER S \nOR press any key TO EXIT: ").capitalize()) if (welcome_input == "P"): print("You have entered programming mode 1. You can convert from decimal to binary here.") # Proramming Mode 1 input_number = int(input("Enter your number ")) bits = [] if input_number < 0: print("Number must be greater than zero!") else: # Running Progamming... while input_number != 0: bits.append(int(input_number % 2)) input_number = int(input_number // 2 ) bits.reverse() print (''.join(map(str, bits))) # print(bits) # --end Programming mode 1 # --start Programming mode 2 elif (welcome_input == "M"): print("You have entered programming mode 2. You can convert from binary to decimal here.") print("Enter your binary number below: ") Digit1 = int(input("Digit 1: "),2) Digit2 = int(input("Digit 2: "),2) Digit3 = int(input("Digit 3: "),2) Digit4 = int(input("Digit 4: "),2) Digit5 = int(input("Digit 5: "),2) Digit6 = int(input("Digit 6: "),2) Digit7 = int(input("Digit 7: "),2) Digit8 = int(input("Digit 8: "),2) D1 = Digit1 * 2**7 D2 = Digit2 * 2**6 D3= Digit3 * 2**5 D4 = Digit4 * 2**4 D5 = Digit5 * 2**3 D6 = Digit6 * 2**2 D7 = Digit7 * 2**1 D8 = Digit8 * 2**0 print(D1 + D2 + D3 + D4 + D5 + D6 + D7 + D8) # --end Programming mode 2 # --start Scientific mode elif (welcome_input == "S"): print("You have entered scientific mode.") num1 = float(input("Enter number: ")) oper = input("choose an operand: + - * / **: ") num2 = float(input("Enter number: ")) if (oper == "+"): print(num1 + num2) elif (oper == "-"): print(num1 - num2) elif (oper == "*"): print(num1 * num2) elif (oper == "/"): print(num1 / num2) elif (oper =="**"): print(num1 ** num2) else: print("Invalid selection") # --end Scientific mode else: print("GOODBYE") break
import logging def add (num1, num2): return num1 + num2 def substr (num1, num2): return num1 - num2 def multip (num1,num2): return num1 * num2 def divid (num1, num2): return num1/num2 print ("Podaj działanie, posługując się odpowiednią liczbą:") print ("1 Dodawanie, 2 Odejmowanie, 3 Mnożenie, 4 Dzielenie:") operation = input ("Podaj numer działania (1,2,3 lub 4) : ") if __name__ == "__main__": if operation in ('1', '2', '3', '4' ): #if operation in range (1:4) print ("podaj liczby na których dokonamy działania") num1 = float(input ("podaj liczbę nr 1 : ")) num2 = float (input ("podaj liczbę nr 2 : ")) if operation == '1': logging.info(f"Dodaję liczby {num1} i {num2}") print(num1, "+", num2, "=", add(num1, num2)) elif operation == '2': logging.info(f"Odejmuję liczby {num1} i {num2}") print(num1, "-", num2, "=", substr(num1, num2)) elif operation == '3': logging.info(f"Mnożę liczby {num1} i {num2}") print(num1, "*", num2, "=", multip(num1, num2)) elif operation == '4': logging.info(f"Dzielę liczby {num1} i {num2}") roundup = int(input("Ile zer po przecinku ? : ")) print(num1, "/", num2, "=", round(divid(num1, num2),roundup) ) else : print ("Nieprawidłowy numer działania")
""" Tests the add() function of the calculator """ from calculator import add def test_two_plus_two(): """ If given 2 and 2 as parameters, 4 should be returned """ assert add(2, 2) == 4 def test_three_plus_three(): assert add(3, 3) == 6 def test_no_parameter(): assert add() == 0 def test_one_two_three(): """ Given the values 1, 2, and 3 as parameters 6 should be returned """ assert add(1, 2, 3) == 6
def is_palindrome(s, lo, hi): while lo < hi: if s[lo] != s[hi]: return False lo += 1 hi -= 1 return True def solve(s): lo, hi = 0, len(s) - 1 while lo < hi: if s[lo] != s[hi]: return is_palindrome(s, lo + 1, hi) or is_palindrome(s, lo, hi - 1) lo += 1 hi -= 1 return True class Solution: def validPalindrome(self, s): """ :type s: str :rtype: bool """ return solve(s)
#!/usr/bin/env python3 #-*- coding: utf-8 -*- # File Name: test_sql2.py # Author: Feng # Created Time: Tue 30 Oct 2018 05:37:06 PM CST # Content: import sqlite3, os db_file = os.path.join(os.path.dirname(__file__), 'test.db') if os.path.isfile(db_file): os.remove(db_file) #初始数据 conn = sqlite3.connect(db_file) cursor = conn.cursor() cursor.execute('create table user(id varchar(20) primary key, name varchar(20), score int)') cursor.execute(r"insert into user values('A-001', 'Adam', 95)") cursor.execute(r"insert into user values('A-002', 'Bart', 62)") cursor.execute(r"insert into user values('A-003', 'Lisa', 78)") cursor.close() conn.commit() conn.close() def get_score_in(low, high): ' 返回指定分数区间的名字,按分数从低到高排序 ' with sqlite3.connect(db_file) as conn: cursor = conn.cursor() cursor.execute('select * from user where score >= ? and score <= ?', (low, high)) values = cursor.fetchall() cursor.close() users = [] for data in values: users.append(data[1]) return users print(get_score_in(60, 80)) assert get_score_in(80, 95) == ['Adam'], get_score_in(80, 95) os.remove(db_file) print('Pass')
#!/usr/bin/env python3 #-*- coding: utf-8 -*- # File Name: test2.py # Author: Feng # Created Time: Tue May 8 19:40:17 2018 # Content: https://www.w3cschool.cn/python/python-exercise-example2.html total = int(input("Enter a number: ")) arr = [1000000, 600000, 400000, 200000, 100000, 0] rat = [0.01, 0.015, 0.03, 0.05, 0.075, 0.1] r = 0 for i in range(0, 6): if (total > arr[i]): r += (total - arr[i]) * rat[i] print((total - arr[i]) * rat[i]) total = arr[i] print(r)
''' Created on Aug 27, 2016 @author: Sudeep ''' #Normal print function print ("Hello World") #print using a custom function def print_function(string): print(string) print_function("What a day") #Perform normal numerical functions a = 8 print(a*10) #Multiplication print(a**10) #Exponential
import math as mt from operator import itemgetter # Report functions def insertion_sort(lst): for i in range(1, len(lst)): current = lst[i] j = i - 1 while j >= 0 and current < lst[j]: lst[j + 1] = lst[j] j -= 1 lst[j + 1] = current return lst def selection_sort(lst): for i in range(len(lst)): index_min = i for j in range(i + 1, len(lst)): if lst[index_min] > lst[j]: index_min = j lst[i], lst[index_min] = lst[index_min], lst[i] return lst def open_file(filename): with open(filename) as game_text: games_db = game_text.readlines() for line in range(len(games_db)): games_db[line] = games_db[line].rstrip('\n').split('\t') return games_db def count_games(filename): lst = open_file(filename) return len(lst) def decide(filename, year): GAME_YEAR = 2 lst = open_file(filename) for sublist in range(len(lst)): if lst[sublist][GAME_YEAR] == str(year): return True return False def get_latest(filename): GAME_YEAR = 2 GAME_TITLE = 0 lst = open_file(filename) late_year = -1 for sublist in range(len(lst)): if int(lst[sublist][GAME_YEAR]) > late_year: late_year = int(lst[sublist][GAME_YEAR]) title = lst[sublist][GAME_TITLE] return title def count_by_genre(filename, genre): GAME_GENRE = 3 lst = open_file(filename) current_genre_count = 0 for sublist in range(len(lst)): if lst[sublist][GAME_GENRE] == str(genre): current_genre_count += 1 return current_genre_count def get_line_number_by_title(filename, title): GAME_TITLE = 0 lst = open_file(filename) for sublist in range(len(lst)): if lst[sublist][GAME_TITLE] == str(title): return sublist + 1 raise ValueError('Non-existing game') def sort_abc(filename): GAME_TITLE = 0 lst = open_file(filename) titles = [] for sublist in range(len(lst)): titles.append(lst[sublist][GAME_TITLE]) titles = selection_sort(titles) return titles def get_genres(filename): lst = open_file(filename) GAME_GENRE = 3 genres = [] for sublist in range(len(lst)): if lst[sublist][GAME_GENRE] not in genres: genres.append(lst[sublist][GAME_GENRE]) genres = selection_sort(genres) return genres def when_was_top_sold_fps(filename): lst = open_file(filename) GAME_YEAR = 2 GAME_SALES = 1 GAME_GENRE = 3 SEARCH_GENRE = 'First-person shooter' if SEARCH_GENRE not in get_genres(filename): raise ValueError year = -1 sales = -1 for sublist in range(len(lst)): if lst[sublist][GAME_GENRE] == SEARCH_GENRE: if float(lst[sublist][GAME_SALES]) > sales: sales = float(lst[sublist][GAME_SALES]) year = lst[sublist][GAME_YEAR] return float(year) def get_most_played(filename): lst = open_file(filename) GAME_TITLE = 0 GAME_SALES = 1 max_sales = -1 for sublist in range(len(lst)): if float(lst[sublist][GAME_SALES]) > max_sales: max_sales = float(lst[sublist][GAME_SALES]) name = lst[sublist][GAME_TITLE] return name def sum_sold(filename): lst = open_file(filename) GAME_SALES = 1 total_sales = 0 for sublist in range(len(lst)): total_sales += float(lst[sublist][GAME_SALES]) return total_sales def get_selling_avg(filename): lst = open_file(filename) total_sum = sum_sold(filename) return total_sum / len(lst) def count_longest_title(filename): lst = open_file(filename) GAME_TITLE = 0 len_name = -1 for sublist in range(len(lst)): if len(lst[sublist][GAME_TITLE]) > len_name: len_name = len(lst[sublist][GAME_TITLE]) return len_name def get_date_avg(filename): lst = open_file(filename) GAME_YEAR = 2 sum_years = 0 for sublist in range(len(lst)): sum_years += int(lst[sublist][GAME_YEAR]) return mt.ceil(sum_years / len(lst)) def get_game(filename, title): lst = open_file(filename) GAME_TITLE = 0 GAME_SALES = 1 GAME_YEAR = 2 GAME_GENRE = 3 GAME_PUBLISHER = 4 for sublist in range(len(lst)): if lst[sublist][GAME_TITLE] == title: list_output = [lst[sublist][GAME_TITLE], float(lst[sublist][GAME_SALES]), int( lst[sublist][GAME_YEAR]), lst[sublist][GAME_GENRE], lst[sublist][GAME_PUBLISHER]] return list_output return "Game {} not found.".format(title) def count_grouped_by_genre(filename): lst = open_file(filename) dict_output = {} GAME_GENRE = 3 for sublist in range(len(lst)): if lst[sublist][GAME_GENRE] not in dict_output.keys(): dict_output[lst[sublist][GAME_GENRE]] = 1 else: dict_output[lst[sublist][GAME_GENRE]] += 1 return dict_output def get_date_ordered(filename): lst = open_file(filename) GAME_TITLE = 0 GAME_YEAR = 2 name_date = [] name_sorted = [] for sublist in range(len(lst)): name_date.append( {'name': lst[sublist][GAME_TITLE], 'year': int(lst[sublist][GAME_YEAR])}) name_date = sorted(name_date, key=itemgetter('name')) name_date = sorted(name_date, key=itemgetter('year'), reverse=True) for sublist in range(len(name_date)): name_sorted.append(name_date[sublist]['name']) return name_sorted
# Declaring a class class lotteryPlayers(): def __init__(self): # init method which has sone variables which is ## available to all the objects self.name = "Test" self.numbers = (10,23,1,234,2) def total(self): return sum (self.numbers) # Creating a player object player = lotteryPlayers() print (player.name) print (player.total()) ### Different class in which an argument other than default "self" is used class Student(): def __init__(self, name, school): #init method which requires arguments self.name = name self.school = school self.mark = [25,] def print_list(self): print ("Name: {}".format(self.name)) print ("List: {}".format(self.school)) print ("Mark: {}".format(self.mark)) def average(self): return (sum(self.mark)/len(self.mark)) anna = Student("Anna", "LMS") # passing argument and changing the value anna.mark.append(23) # appending the default empty list anna.print_list() print(anna.average()) ####
from flask import Flask, jsonify, request, render_template app = Flask (__name__) stores = [ { "name" : "My store", "items" :[ { "name" : 'book', "price": 10 } ] } ] @app.route("/") def home(): return render_template("index.html") # Create a shop using post @app.route("/shop", methods=["POST"]) def create_shop(): request_data = request.get_json() new_store = { "name" : request_data["name"], "item" : [] } stores.append(new_store) return jsonify(new_store) # Give details of a /shop/item_name with GET @app.route("/shop/<string:name>") #String : name is a varibale def get_shop(name): #Iterate over stores and if it finds the store return it for dic in stores: if ( dic["name"] == name ): return jsonify(dic) # dic is already a dictionary return jsonify({"message": 'store not found'} ) # outputing the message in dictionary format # Give details of a /shop/ with GET @app.route("/shop/") #String : name is a varibale def get_total_shop(): return jsonify({"stores": stores}) ### jsonify is used to change the stores variable to json format # Create a shop item using post @app.route("/shop/<string:name>/item", methods=["POST"]) def create_shop_item(name): request_item = request.get_json() for dic in stores: if (dic["name"] == name): new_item = { "name" : request_item["name"], "price" : request_item["price"] } dic["items"].append(new_item) return jsonify(new_item) return jsonify({"message": 'store not found'} ) # Give shop item using get @app.route("/shop/<string:name>/item") def get_shop_item(name): #Iterate over stores and if it finds the store return it for dic in stores: if ( dic["name"] == name ): return jsonify({"items": dic['items']}) # outputing items in dictionary format return jsonify({"message": 'store not found'} ) # outputing the message in dictionary format app.run(port=1000)
name = 'Oladimeji Oladepo' other_name = 'Akinlabi Ishola' print(name[2]) print(name[2:4]) print(name[2:]) print(name[0:7:2]) print(len(name)) print(name.index('j')) print(name.upper()) print(name.lower()) print(name.split()) print(name.split('O')) print(f"My name is {name} and my other name is {other_name}")
#you cant use index, rather use the keys or put the dictionary in a List salary = {'deji':400, 'enitan':500, 'bolu':350} salaries = {'ayo':[20,30,40], 'dele':[25,35,45]} print(salary) print(salary['enitan']) salary['kenny'] = 800 print(salary['kenny']) salary['enitan'] = salary['enitan'] + 100 print(salary) salary['deji'] = 1000 print(salary) print(salaries) print(salaries['ayo']) print(salaries['dele'][1]) student_attendance ={"deji": 90, 'tobi':55, 'nuru': 80} #To print the keys ie names for student in student_attendance: print(student) #to print the grades ie values for grade in student_attendance: print(student_attendance[grade]) #to grab key and values ie names and grades for student in student_attendance: print(f"{student} : {student_attendance[student]}") #Another way to print key and value using dictionary unpacking items(), tuple unpacking for student, grades in student_attendance.items(): print(student, " : " , grades) #Test, calculate average score of students values(), len and sum method total_attendance_values = student_attendance.values() average_score = sum(total_attendance_values) / len(student_attendance) print(average_score)
# age=input("请输入年龄") # age=int(age) # if(age<20): # print("小孩") # elif(age<40): # print("青年") # else: # print("old") for i in range(1,10,3): print(i) for i in "abc","def","jks": print(i) # 9*9乘法表 # i=1 # while i<10: # j=1 # while j<=i: # print("%d*%d=%d"%(j,i,j*i),end="\t") # if(j==i): # print() # j+=1 # i+=1 # # # for i in range(1,10): # for j in range(1,i+1): # print("%d*%d=%d"%(j,i,i*j),end="\t") # if(i==j): # print() str="abcdef" print(str[2]) print(str[::2]) print(str[4:2:-1]) for letter in "Python": print(letter,end="\t")
import sys order = int(input( """ Bem vindo a Loja de Vendas!!! 1.Guaraná Antarctica - $1.00 2.Coca-Cola - $ 1.50 3.Energético RedBull - $2.00 Escolha o numero do pedido (1, 2, 3...) """ )) if order == 1: disPrice = 1.00 print("Você escolheu Guaraná Antarctica.") elif order == 2: disPrice = 1.50 print("Você escolheu Coca-Cola.") elif order == 3: disPrice = 2.00 print("Você escolheu Energético RedBull.") else: sys.exit("Por favor tente novamente.") vinte_cinco_centavos = int(input("Coloque o tanto de moedas de 25c.")) dez_centavos = int(input("Coloque o tanto de moedas de 10c.")) cinco_centavos = int(input("Coloque o tanto de moedas de 5c.")) total = ((vinte_cinco_centavos * 0.25) + (dez_centavos * 0.10) + (cinco_centavos * 0.05)) print("O total que você colocou é $%.2f" %(total)) if total >= disPrice: print("Seu troco é $" + "%.2f" % (total - disPrice) + ". Tenha um bom dia.") else: print("Volte quando tiver dinheiro.")
#public => memberName #protected => _memberName #private => __memberName class Car: numberOfWheels = 4 #accesible anywhere within the program _color = 'Black' #can be accessed within the class and within its derived classes. also outside of the classes __yearOfManufacture = 2017 #cannot be accessed outside the class class BMW(Car): def __init__(self): print(" The color of the car is: ", self._color) car = Car() print("Public attribute: numberOfWheels: ", car.numberOfWheels) #print("Private attribute: yearOfManufacture:", car.__yearOfManufacture) #the proper way to aceess such private attribute is below print("Private attribute: yearOfManufacture:", car._Car__yearOfManufacture) bm = BMW()
import csv from datetime import datetime try: with open('testdata.csv') as csvfile: readCSV = csv.reader(csvfile, delimiter='-') voltages = [] time = [] for row in readCSV: print(row) #time.append(row) print("\n") print(voltages) print("\n") print(time) except IndexError: print("IndexError") except ValueError: print("ValueError") # consider the following path = "C:\\Users\\OluE\\Desktop\\Google Stock Market Data - google_stock_data.csv" file = open(path) for line in file: print(line) lines = [line for line in file] dataset = [line.strip().split() for line in file] # I can rewrite all of this using csv file = open(path, newline='') reader = csv.reader(file) # we know that the first line is the header # we can read it using the next funtion header = next(reader) # the reader is a lazy iterator.. with the header we have taken off the first line # data = [row for row in reader] # reads the remaining data # observe that the data is still read as strings .. now we make python read it appropriately data = [] for row in reader: # row = [Date, Open, High, Low, Close, Volume, Adj.Close] # below i will parse the date.. this allows the date to become a flexible tool for me to use as I like.. # what i have done in essence is to 'decompose' the date # or parse the data.. strptime= stringparsetime date = datetime.strptime(row[0], '%m/%d/%Y') # I can do more work on this date above and now rearrange as I like. I can scatter as i like since i already # parsed it in the statement above so its so flexible to use. strftime=stringformattime. eg # print(date.strftime('%Y__%b__:%d')) # this will basically print the date as 2017__Dec__:07 # note in the above that date is and must be a datetime object.. name doesnt matter. it could have been leg or cow open_price = float(row[1]) # this value is a float in high = float(row[2]) low = float(row[3]) close = float(row[4]) volume = float(row[5]) adj_close = float(row[6]) data.append([date, open_price, high, low, close, volume, adj_close]) print(data[1]) # to compute and store daily stock returns return_path = "C:\\Users\\OluE\\Desktop\\Google Stock Market Data returns.csv" # now I open this file in write mode file_O = open(return_path, 'w') # now a writer object writer = csv.writer(file_O) # I write the header first writer.writerow(["Date", "Return"]) for i in range(len(data)-1): todays_row = data[i] todays_date = todays_row[0] todays_price = todays_row[-1] yesterdays_row = data[i+1] yesterdays_price = yesterdays_row[-1] daily_return = (todays_price - yesterdays_price)/yesterdays_price # I write the date format I intend to use thus: date_format = todays_date.strftime('%m/%d/%Y') # now I write this using the writer object writer.writerow([date_format, daily_return])
# try: # for i in ['a','b','c']: # print(i**2) # pass # except: # pass # try: # x = 5 # y = 0 # z = x/y # print (z) # pass # except: # print ("Error") # pass # finally: # print ("All Done") def ask(): while True: try: val = int(input("Please enter an integer: ")) except: print("Looks like you did not enter an integer!") continue else: print("Yep that's an integer!") break finally: print("Finally, I executed!") print(val) ask()
class Solution: def findMedianSortedArrays(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: float """ median = None nums = nums1+nums2 nums = sorted(nums) median = nums[int((len(nums)-1)/2)] if len(nums)%2 == 1 else (nums[int(len(nums)/2-1)]+nums[int(len(nums)/2)])/2 return median nums1 = [1,3] nums2 = [2] print(Solution.findMedianSortedArrays(Solution.findMedianSortedArrays,nums1,nums2))
#!/usr/bin/python import sys for line in sys.stdin: # Input of the form "word docname count" word, docname_count = line.strip().split(" ") docname, count = docname_count.strip().split("\t") # Output of the form "docname word count" print"{0}\t{1} {2}".format(docname, word, count)
import pandas as pd import csv with open("height-weight.csv", newline = '') as f: reader = csv.reader(f) filedata = list(reader) filedata.pop(0) newdata = [] for i in range(len (filedata) ): num = filedata[i][2] newdata.append(float(num)) n = len(newdata) newdata.sort() if n % 2 == 0: median1 = float(newdata[n//2]) median2 = float(newdata[n//2-1]) median = (median1 + median2) / 2 else: median = newdata [n//2] print("the median is",median)
__author__ = "ResearchInMotion" # Write a Python program to sum all the items in a dictionary. dicto = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100, 11: 121, 12: 144, 13: 169, 14: 196, 15: 225} sum = 0 for values in dicto.values(): sum += values print(sum)
__author__ = "ResearchInMotion" arr = [2, 7, 11, 15, 6, 4] maxElement = max(arr) for i in range(len(arr)): for j in range(len(arr)): if arr[i] + arr[j] == maxElement: print(arr[i], arr[j])
__author__ = "ResearchInMotion" from collections import Counter nums = [2,2,1] def singleNumber(nums): result = Counter(nums) for key, value in result.items(): if value == 1: return key print(singleNumber(nums))
__author__ = "ResearchInMotion" def insertionSort(arr): indexing_len = range(1,len(arr)) for i in indexing_len: values_sort = arr[i] while arr[i-1] > values_sort and i > 0: arr[i-1] , arr[i] = arr[i] , arr[i-1] i = i-1 return arr print(insertionSort(arr=[244,34,12,6,56]))
__author__ = "ResearchInMotion" nums = [9,6,4,2,3,5,7,0,1] def missingNumber(nums): for value in range(0, len(nums) + 1): if value not in nums: return value print(missingNumber(nums))
__author__ = "ResearchInMotion" def searchInsert(nums, low, high, target): if (high >= low): mid = int(low + (high - low) / 2) if nums[mid] == target: return mid elif nums[mid] > target: return searchInsert(nums, low, mid - 1, target) else: return searchInsert(nums, mid + 1, high, target) else: return -1 # driver code nums = [1,3,5,6] target = 3 result = searchInsert(nums,0,len(nums)-1,target) if result != -1: print("The element is present at",result, "index") else: print("The element is not present")
__author__ = "ResearchInMotion" import math nums = [1, 2, 3, 4] newnums = [] maxval = max(nums) for values in nums: if values < maxval: newnums.append(values) for vals in newnums: if vals+vals > maxval: print("-1") else: print(maxval)
def txttolist(filename): """Takes a txt file and makes a list with each line being an element""" return [line.split("\n")[0] for line in open(filename, "r")] def isstrlessthan(string, length): """Checks if string is below length""" return len(string) < length def errormsg(e): """Generates an error message as a string""" return "ERROR: " + str(e)
print(range(5)) for i in range(5): print(i) p = list(range(0, 5)) print(p) q = list(range(5, 10)) print(q) r = list(range(0, 10, 2)) print(r) # range(5) --- 5 is the stop argument # range(5, 10) --- 5 is start, 10 is stop, although the values move from 5 to 10 as 5,6,7,8,9 # range(10, 20, 2) --- 10 is start, 20 is stop, and 2 is the step by which the range will increment at every loop # like, 10, 12, 14, 16, 18 t = [6, 23, 213, 1242, 12213] for x in enumerate(t): print(x) for i, v in enumerate(t): print("i={}, v={}".format(i, v))
# a method is different from a function in a sense that it can # only be called from within a class by the help of an object. # A Method is a function associated with a class. class Human: def __init__(self, name, gender): self.name = name self.gender = gender def speak_name(self): print("My name is ", self.name) def speak(self, text): print(text) def perform_math_task(self, math_operation, *args): print("{} performed a math operation, and the result was: {}".format(self.name, math_operation(*args))) will = Human("William", "Male") print(will.name) print(will.gender) will.speak_name() will.speak("I love programming.") # The above wouldn't work if you remove 'self' from the method "speak()". # Self is an implied (implicit) argument which has to be given to a method. # If you remove self as an argument from the method, and try running above code # you will get an error like below. # will.speak("I love programming.") # TypeError: speak() takes 1 positional argument but 2 were given def add(a, b, c, d): return a + b + c + d ryan = Human("Ryan Stevens", "Male") ryan.perform_math_task(add, 34, 6, 4, 10)
import math class Circle: def __init__(self, radius=1.0): self.__radius = radius def setRadius(self, r): self.__radius = r def getRadius(self): return self.__radius def calcArea(self): area = math.pi*self.__radius*self.__radius return area def calcCircum(self): circumference = 2.0*math.pi*self.__radius return circumference c1=Circle(10) print("원의 반지름=", c1.getRadius()) print("원의 넓이=", c1.calcArea()) print("원의 둘레=", c1.calcCircum())
class Student: def __init__(self, name=None, age=0): self.__name = name self.__age = age def getAge(self): return self.__age def getName(self): return self.__name def setAge(self, age): self.__age=age def setName(self, name): self.__name=name obj=Student("Hong", 20) obj.getName()
class Student: def __init__(self, name=None, age=0): self.__name = name self.__age = age obj=Student() print(obj.__age)
from tkinter import * from tkinter import messagebox from math import hypot from PIL import ImageTk, Image import os def circle_area(): name = radius_vvod.get() name = int(name) name = name*name*3.14 name = str(name) messagebox.showinfo('Circle Area', 'Area is: ' + name) def length_area(): leng = length_vvod.get() leng = int(leng) leng = leng*2*3.14 leng = str(leng) messagebox.showinfo('Length Circle', 'Length is: ' + leng) def vector_length(): x = vectorx_vvod.get() y = vectory_vvod.get() x = int(x) y = int(y) ans = hypot(x,y) ans = str(ans) messagebox.showinfo('Vector Length', 'Length is: ' + ans) name = 0 window = Tk() window.title('Geometrcic matching:') window.geometry('235x190') ############################################################ radius_title = Label(window, text="1) Circle's area") radius_title.grid(column=0, row=0) radius = Label(window, text="Radius:", padx = 0) radius.grid(column=0, row=1) radius_vvod = Entry(window,width=10) radius_vvod.grid(column=1, row=1) radius_count = Button(window, text="Count", command=circle_area) radius_count.grid(column=2, row=1) ############################################################ length_title = Label(window, text=" 2) Circle's length") length_title.grid(column=0, row=3, padx = 0) length = Label(window, text="Radius:") length.grid(column=0, row=4) length_vvod = Entry(window,width=10) length_vvod.grid(column=1, row=4) length_count = Button(window, text="Count", command=length_area) length_count.grid(column=2, row=4) ############################################################ vector_title = Label(window, text=" 3) Hypotenuse") vector_title.grid(column=0, row=5, padx = 0) vectorx = Label(window, text="Leg 1:") vectorx.grid(column=0, row=6) vectorx_vvod = Entry(window,width=10) vectorx_vvod.grid(column=1, row=6) vectory = Label(window, text="Leg 2:") vectory.grid(column=0, row=8) vectory_vvod = Entry(window,width=10) vectory_vvod.grid(column=1, row=8) vector_count = Button(window, text="Count", command=vector_length) vector_count.grid(column=2, row=6) ############################################################ window.mainloop()
countries_information={} countries_information["Polska"] = ("Warszawa" ,37.97) for country in countries_information.keys(): print(country) country=input("Info o jakim kraju chcesz zobaczyć ") country_informaction=countries_information.get(country) print("-") print("country") print('--') print('stolica'+country_informaction[0]) print('liczba mieszkancow mln ' + str(countries_information[1]))
# Uses python3 import sys def get_majority_element(a, left, right): if left == right: return -1 if left + 1 == right: return a[left] #write your code here return -1 def recursive_majority(A,len_,array,n): if len_ == 1: print(A) array[A[0]]+=1 if array[A[0]]>n/2: return 1,array,n else: return 0,array,n m = len_//2 out,array,n = recursive_majority(A[:m],m,array,n) out,array,n = recursive_majority(A[m:],len_ - m,array,n) return out,array,n def get_majority_advanced(a,n): counter={} for ii in a: if ii in counter.keys(): counter[ii]+=1 else: counter[ii] = 1 # print(counter) for key,item in counter.items(): if item>n//2: return 1 return 0 if __name__ == '__main__': # input = sys.stdin.read() # n, *a = list(map(int, input.split())) # if get_majority_element(a, 0, n) != -1: # print(1) # else: # print(0) n = int(sys.stdin.readline()) a = list(map(int,sys.stdin.readline().split())) out = get_majority_advanced(a,n) print(out)
# Uses python3 import sys def get_number_of_inversions(a, b, left, right): number_of_inversions = 0 if right - left <= 1: return number_of_inversions ave = (left + right) // 2 number_of_inversions += get_number_of_inversions(a, b, left, ave) number_of_inversions += get_number_of_inversions(a, b, ave, right) #write your code here return number_of_inversions # def MergeSort(A,len_,counter): # if len_ == 1: # counter+=1 # return A,counter # m = len_//2 # B,counter = MergeSort(A[:m],m,counter) # C,counter = MergeSort(A[m:],len_ - m,counter) # A_out,counter = Merge(B,C,counter) # return A_out,counter # def Merge(B,C,counter): # D = [] # len_b = len(B) # len_c = len(C) # flag_T = 0 # while len_b and len_c : # flag_T =1 # if B[0]>C[0]: # #print(B,C) # D.append(C[0]) # C = C[1:] # len_c-=1 # flag =1 # counter +=1 # else: # D.append(B[0]) # B = B[1:] # len_b-=1 # flag = 0 # if flag_T ==0: # return B+C,counter # elif flag == 0: # out = D+C # else: # out = D+B # return out,counter def MergeSort(A,len_,counter): if len_ == 1: return A,counter m = len_//2 B,counter = MergeSort(A[:m],m,counter) C,counter = MergeSort(A[m:],len_ - m,counter) A_out,counter = Merge(B,C,counter) return A_out,counter def Merge(B,C,counter): D = [] len_b = len(B) len_c = len(C) while len_b and len_c : if B[0]>C[0]: D.append(C[0]) C = C[1:] len_c-=1 flag =1 counter +=len(B) else: D.append(B[0]) B = B[1:] len_b-=1 flag = 0 # print(B,C,counter) if flag == 0: out = D+C else: out = D+B return out,counter if __name__ == '__main__': # input = sys.stdin.read() # n, *a = list(map(int, input.split())) # b = n * [0] # print(get_number_of_inversions(a, b, 0, len(a))) n = int(sys.stdin.readline()) array = list(map(int,sys.stdin.readline().split())) counter = 0 sorted_array,number_of_inversions = MergeSort(array,n,counter) print(number_of_inversions)
def binary_search_recursive(array,item,high,low): if low > high: return "ELEMENT NOT FOUND" mid = low + (high-low)//2 if array[mid]==item: print("array[{}] = {}".format(mid,array[mid])) return mid elif array[mid]<item: return binary_search_recursive(array,item,high,mid+1) else: return binary_search_recursive(array,item,mid-1,low) def binary_search_iterative(array,item,high,low): while True: if low>high: return "ELEMENT NOT FOUND" mid = low + (high-low)//2 if array[mid]==item: return mid elif array[mid] < item: low = mid+1 else: high = mid-1 if __name__=='__main__': out = binary_search_recursive([1,4,7,8,20,34,35,40],60,7,0) out_it = binary_search_iterative([1,4,7,8,20,34,35,40],1,7,0) print(out) print(out_it)
s = "aaAAwe Cc crwwwww wwBBbber WEr " k = 3 def chars_met_counter(s, k): refactored_string = s.lower().replace(' ', '') chars_cout_dict = { chr(character): refactored_string.count(chr(character)) for character in range(ord('a'), ord('z')+1)} final_string = ''.join('{}'.format(key) for key, val in sorted( chars_cout_dict.items(), key=lambda x: x[1], reverse=True) ) return(final_string[0:k]) print(chars_met_counter(s, k))
zin = input('vul een zin in: ') woorden = zin.split() acroniem='' for woord in woorden: acroniem = acroniem + woord[0].upper() print(acroniem)
from tkinter import * import json window = Tk() window.title("친구관리") address_book = {} # 공백 딕셔너리를 생성한다. def add() : name = e1.get() phone = e2.get() address = e3.get() print(name) info = [phone, address] print(address_book) print("추가") t.insert(END, "이름:" +name+ "을 추가 했습니다"+"\n") t.insert(END, "전화번호:" +info[0]+ "을 추가 했습니다"+"\n") t.insert(END, "주소:" +info[1]+ "을 추가 했습니다"+"\n") e1.focus_set() def delete() : key = e1.get() print(type(key)) print(type(address_book.get(key))) print(address_book) if address_book.get(key) is None: t.insert(END, "저장되지않은 이름입니다.") else: address_book.get(key) t.insert(END, key + "님이 삭제되었습니다.\n") e1.delete(0, END) e1.focus_set() def search() : key = e1.get() print(type(key)) print(type(address_book.get(key))) print(address_book) if address_book.get(key) is None: t.insert(END, "저장되지않은 이름입니다.") else: info = address_book.get(key) t.insert(END, key + "을 검색 했습니다\n") t.insert(END, info[0] + "을 검색 했습니다\n") t.insert(END, info[1] + "을 검색 했습니다\n") e1.delete(0, END) e1.focus_set() def output() : e1.focus_set() print("출력") t.insert(END, e1.get() + "을 출력 했습니다\n") e1.delete(0, END) def saveExit() : addressData = {'홍길동': '010-1234-1234', '이순신': '010-2222-2222'} # 파일저장 with open('./addressData.json', 'w', encoding='utf-8-sig') as f: json.dump(addressData.json, f, ensure_ascii=False, indent=4) f.close() print("저장 & 종료") t.insert(END, "저장 & 종료\n") exit() address_book = {} # 공백 딕셔너리를 생성한다. def fileLaod(): global address_book try: with open('./addressData.json', 'r', encoding='utf-8-sig') as f: lines = json.load(f) print(lines) address_book = lines print("final END", address_book) address_book = json.reader(f) # csv파일을 address에 저장 except FileNotFoundError as e: print('파일이 존재하지 않습니다..', e) # Label 객체 생성 및 배치 l1 = Label(window, text="이름", pady=5) l1.grid(row=0, column=0, sticky=W) l2 = Label(window, text="전화번호") l2.grid(row=1, column=0, sticky=W, pady=5) l3 = Label(window, text="주소") l3.grid(row=2, column=0, sticky=W, pady=5) # Entry 객체 생성 및 배치 e1 = Entry(window, bg="orange", width=26) e2 = Entry(window, bg="orange", width=26) e3 = Entry(window, bg="orange", width=26) e1.grid(row=0, column=1) e2.grid(row=1, column=1) e3.grid(row=2, column=1) # Button 들을 배치하기 위한 Frame 생성 및 배치, window가 부모임 bFrame = Frame(window, pady=5) bFrame.grid(row=3, column=0, columnspan=2) b1 = Button(bFrame, text='검색', width=6, command=search) b1.grid(row=0, column=0, padx=2) b2 = Button(bFrame, text='추가', width=6, command=add) b2.grid(row=0, column=1, padx=2) b3 = Button(bFrame, text='삭제', width=6, command=delete) b3.grid(row=0, column=2, padx=2) b4 = Button(bFrame, text='출력', width=6, command=output) b4.grid(row=0, column=3, padx=2) b5 = Button(bFrame, text='종료', width=6, command=saveExit) b5.grid(row=0, column=4, padx=2) # Text 객체 생성 및 배치 t = Listbox(window, bg="orange", height=12, width=33, border=0) t.grid(row=4, column=0, columnspan=2, pady=2) # Create scrollbar scrollbar = Scrollbar(window, orient='vertical') scrollbar.grid(row=4, column=2, sticky=N+S) # Set scroll to listbox t.configure(yscrollcommand=scrollbar.set) # scrollbar 실행 scrollbar.configure(command=t.yview) # Bind select # t.bind('<<ListboxSelect>>', select_item) window.mainloop()
class Calculadora: def calcular_soma(self, numero1, numero2): soma = numero1 + numero2 print("A soma é:", soma) def calcular_subtracao(self, numero1, numero2): subtracao = numero1 - numero2 print("A Subtracao é:", subtracao) def calcular_multiplicacao(self, numero1, numero2): multiplicacao = numero2 * numero1 print("A Multiplicacao é:", multiplicacao) def calcular_divisao(self, numero1, numero2): divisao = numero2 / numero1 print("A Divisao é:", divisao) calcular = Calculadora() print('Digite o número 1') numero1 = int(input()) print('Digite o número 2') numero2 = int(input()) calcular.calcular_soma(numero1, numero2) calcular.calcular_subtracao(numero1, numero2) calcular.calcular_multiplicacao(numero1, numero2) calcular.calcular_divisao(numero1, numero2)
for numero in range(1, 11): print('{0} x {1} = {2}'.format(8, numero, 8*numero))
num=int(input()) tree={'0':[1,0]} for i in range(num-1): parent,children=input().split() if parent in tree and tree[parent][1]<2: tree[children]=[tree[parent][0]+1,0] tree[parent][1]+=1 depth=[x[0] for x in tree.values()] print(max(depth))
import sqlite3 connection = sqlite3.connect("passwords.db") cursor = connection.cursor() masterPassword = "3141592" cursor.execute('CREATE TABLE IF NOT EXISTS passwords (accounts text, password text)') cursor.execute('SELECT * FROM passwords WHERE accounts = "masterPassword"') connection.commit() checker = cursor.fetchall() if len(checker) == 0: cursor.execute('INSERT INTO passwords VALUES(?, ?)', ("masterPassword", masterPassword)) connection.commit() elif checker[0][1] != masterPassword: cursor.execute("UPDATE passwords SET password=? WHERE accounts='masterPassword'", (masterPassword,)) cursor.execute("SELECT * FROM passwords WHERE accounts = 'masterPassword'") passChecker = cursor.fetchall() while True: userPassInput = str(input("Enter the master password: ")) if userPassInput == passChecker[0][1]: break else: print("Wrong Password") mainloop = True while mainloop: print('"A" to add \n"S" to see \n"Q" to quit program') userChoice = str(input()) if userChoice.lower() == "q": mainloop = False elif userChoice.lower() == 'a': accountName = str(input("Enter account name: ")) passwordName = str(input("Enter password: ")) cursor.execute("INSERT INTO passwords VALUES (?, ?)", (accountName.lower(), passwordName)) connection.commit() elif userChoice.lower() == "s": accountName = str(input("Enter account name: ")) cursor.execute("SELECT * FROM passwords WHERE accounts = ?", (accountName.lower(),)) info = cursor.fetchall() if len(info) > 0: print(f'The password is {info[0][1]}') else: print("Account doesn't exist within the database") else: print("Sorry, we dont understand that input")
# Run this code to play Nim :) import random as r print("Welcome to Nim.") player_type_input = raw_input("Please choose singleplayer (1) or multiplayer (2): ") try: value = int(player_type_input) except ValueError: print("Invalid input, please try again.") player_type_input = raw_input("Please choose singleplayer (1) or multiplayer (2): ") setting = [] print("The settings are on default, which allows for three randomly generated piles.") start_input = raw_input("Would you like to begin playing? [y/n] (choose n if you would like to change the settings): ") def print_pile_values(number_of_piles): for i in range(number_of_piles): print("pile 1: " + str(setting[i])) def play_game(piles): for i in range(piles): setting.append(r.randrange(2, 10, 1)) print_pile_values(len(setting)) if int(player_type_input) == 1: player_turn = "human" while sum(setting) > 1: if player_turn == "human": print("Player 1's turn:") multiplayer_move(1) player_turn = "computer" elif player_turn == "computer": computer_move() elif int(player_type_input) == 2: player_turn = "Player 1" while sum(setting) > 1: if player_turn == "Player 1": print("Player 1's turn:") multiplayer_move(1) player_turn = "Player 2" elif player_turn == "Player 2": print("Player 1's turn:") multiplayer_move(2) player_turn = "Player 1" def pick_number_of_piles(): piles_input = raw_input("Please indicate the number of piles you would like to play with: ") while int(piles_input) > 10: print("Sorry, invalid input. Nim Oasis will only allow a maximum of 10 piles.") piles_input = raw_input("Please pick again: ") user_agreement = raw_input("You have chosen to play with " + str(piles_input) + " piles. Continue? [y/n]: ") if user_agreement == "y": play_game(int(piles_input)) else: user_choice = raw_input("Would you like to quit the game (q) or choose a different number of piles (c)?: ") if user_choice == "c": pick_number_of_piles() else: "You have quit the game." return(int(piles_input)) def multiplayer_move(player): pile = input("Pile number: ") amount = input("Amount: ") # while amount is more than what's in the pile, run error and boundry checks while setting[(pile - 1)] < amount: print("Invalid turn, please try again.") pile = input("Pile number: ") amount = input("Amount: ") try: val_1 = int(pile) val_2 = int(amount) except ValueError: print("Invalid input, please try again.") setting[(pile - 1)] = setting[(pile - 1)] - amount if sum(setting) == 0: print("Player " + str(player) + " loses.") elif sum(setting) == 1: print("Player " + str(player) + " wins.") print_pile_values(len(setting)) def computer_move(): bin_setting = [] str_bin_setting = [] str_nim_sum = [] # converts integers in each pile into binary numbers for pile in setting: bin_setting.append(bin(pile)) # deconstructs binary numbers into an array of each digit for pile in bin_setting: str_pile = str(pile) str_pile = str_pile[2:] new_pile = [] for char in str_pile: new_pile.append(char) str_bin_setting.append(new_pile) digit_total = 0 # the sum of the one digit of each binary array digit_count = 1 # the digit being added together in each array # while loop allows it to stop after the maximum length of largest array while digit_count <= max(len(bin_array) for bin_array in str_bin_setting): # goes through each array to add to the digit_total for bin_array in str_bin_setting: # try and except allows us to skip over smaller arrays that don't have as many digits try: # if statement prevents a loop to last digit by index if (len(bin_array) - digit_count) > -1: digit_total += int(bin_array[len(bin_array) - digit_count]) except IndexError: print("ValueError") # computes the nim digit_total and creates the nim_sum if bin_array == str_bin_setting[-1]: digit_total = digit_total % 2 str_nim_sum.insert(0, digit_total) digit_total = 0 digit_count += 1 #TODO: winning strategy requires a 0 nim_sum if str_nim_sum.count(1) % 2 != 0: for bin_array in str_bin_setting: index_of_one = str_nim_sum.index(1) if bin_array[index_of_one] == 1: pile_index = str_bin_setting.index(bin_array) value_removed = 2**(len(bin_array) - 1 - index_of_one) setting[pile_index] -= value_removed print("Computer removed " + str(value_removed) + " from pile " + str(pile_index + 1)) else: random_pile_index = r.randrange(0, 3, 1) pile_value = setting[random_pile_index] random_value_removed = r.randrange(1, pile_value, 1) setting[random_pile_index] -= random_value_removed print("Computer removed " + str(random_value_removed) + " from pile " + str(random_pile_index + 1)) print_pile_values(len(setting)) if start_input == "y": play_game(3) elif start_input == "n": if int(player_type_input) == 1: print("Sorry, but the computer only plays with 3 piles. Please message the developer if you would like to open an inquiry.") continue_choice = raw_input("Would you like to continue? [y/n]: ") if continue_choice == "y": play_game(3) else: print("You have quit the game.") else: pick_number_of_piles()
class beautyConsole: """This class defines properties and methods to manipulate console output""" colors = { "black": '\33[30m', "red": '\33[31m', "green": '\33[32m', "yellow": '\33[33m', "blue": '\33[34m', "magenta": '\33[35m', "cyan": '\33[36m', "white": '\33[37m', "grey": '\33[90m', "lightblue": '\33[94m' } characters = { "endline": '\33[0m' } def __init__(self): return None @staticmethod def getColor(color_name): """returns color identified by color_name or white as default value""" if color_name in beautyConsole.colors: return beautyConsole.colors[color_name] return beautyConsole.colors["white"] @staticmethod def getSpecialChar(char_name): """returns special character identified by char_name""" if char_name in beautyConsole.characters: return beautyConsole.characters[char_name] return ""
from random import shuffle import time '''Write a Java program that uses a Monte Carlo algorithm to calculate the probability that next week's lottery draw won't have any consecutive pairs of numbers (eg 8 and 9 or 22 and 23). Six numbers are drawn from 1 to 45.''' a = time.clock() n = range(1,46) times =1000000 count = 0 for nums in range(0,times): shuffle(n) lotto = n[0:6] lotto.sort() for i in range(0,5): if lotto[i] == lotto[i+1]-1: count+=1 break print (times-count)/float(times) print time.clock()-a
# # problem_id_4.py # Problem: Largest palindrome product # Last Modified: 8/14/2017 # Modified By: Andrew Roberts # def largest_palindrome(): largest_product = 0 palin = None for i in range(100, 1000): for j in range(100, 1000): prod = i * j if str(prod) == str(prod)[::-1]: if prod > largest_product: largest_product=prod palin = prod return palin print("Largest palindrome: ", largest_palindrome())
class Address: def __init__(self, country, city, street): self.country = country self.city = city self.street = street def __str__(self): result = '' for k,v in self.__dict__.items(): result += f'{k} : {v}\n' return result class AddressParser: def getAddress(country, city, street): return Address(country, city, street) def main(): a = AddressParser.getAddress('Israel', 'Tel Aviv', 'HaShalom') print(type(a)) print(a) if __name__ == '__main__': main()
# Question 1 : # Consider one string as input. You have to check whether the strings obtained from the input string with single backward and single forward shift are the same or not. If they are the same, then print 1; otherwise, print 0. # Hint: # Backward Shift : A single circular rotation of the string in which the first character becomes the last character and all the other characters are shifted one index to the left. For example, "abcde" becomes "bcdea" after one backward shift. # Forward Shift: A single circular rotation of the string in which the last character becomes the first character and all the other characters are shifted to the right. For example, "abcde" becomes "eabcd" after one forward shift. # Instructions: # The system does not allow any kind of hard coded input value/values. # The written program code by the candidate will be verified against the inputs that are supplied from the system. # For more clarification, please read the following points carefully till the end. # Example 1: # Input : # sfdlmnop # Output: # 0 # Example 2: # Input: # mama # Output: # 1 # Explanation: # In the first example, the string is “sfdlmnop". # Forward Shift: fdlmnops # Backward Shift: psfdlmnop # Both the strings above are not equal, so the output is 0. # In the second example, the string is "mama" # Forward Shift: amam # Backward Shift: amam # Both the strings above are equal, so the output is 1. def shifting(string): bs = string[1:] + string[0] fs = string[-1] + string[:-1] print(f'Forward Shift: {fs}') print(f'Backward Shift: {bs}') return 1 if bs == fs else 0 string = input() result = shifting(string) print(result)
x=int(input("Give an integer:")) while x > 1000000: x=int(input("Give another number:")) #checks if the number given is already prime if x%2==1: print ("The number is already prime!") if x%2==0: i=0 j=0 k=0 z=0 tot=0 #does the modification with 2 while x%2==0 : x=x//2 i+=1 #does the modification with 3 while x%3==0 : x=x//3 j+=1 #does the modification with 5 while x%5==0 : x=x//5 k+=1 #does the modification with 7 while x%7==0 : x=x//7 z+=1 #prints the result-the analyzation of the number print("The number that you gave is analyzed as: (2**" + repr(i) + ")(3**" + repr(j) + ")(5**" + repr(k) + ")(7**"+ repr(z)+")(" + repr(x)+")")
# implementation of correlation of given two signals import numpy as np import matplotlib.pyplot as plt a=[5,2,3] b=[2,4,1] def convolution(a,b): m=np.size(a) n=np.size(b) c=np.zeros(m+n-1) for i in range(m): for j in range(n): c[i+j]=c[i+j]+a[i]*b[j] return c x=list() p=input("enter length of x=") for i in range(p): m=input("elements=") x.append(int(m)) print("array",x) y=[] for j in range(p): y.append(m-j) t=convolution(a,b) print("correlation of two signals is",t) plt.plot(t) plt.show()
from random import randint from gameComponents import gameVars def compare(status): # this will be the AI chiice -> random pick from the choices array computer = gameVars.choices[randint(0, 2)] #validate that the random choice worked for the AI print("AI chose: " + computer) # adding in separation print("________________") if (computer == gameVars.player): print("tie! no one loses a life\n") #alwats check for negative conditions first (the losing case) elif (computer == "rock"): if (gameVars.player == "scissors"): print("you lose! you lose a life :(\n") gameVars.player_lives -= 1 else: print("you win! computer loses a life\n") gameVars.Ai_lives -= 1 elif (computer == "paper"): if (gameVars.player == "rock"): print("you lose! you lose a life :(\n") gameVars.player_lives -= 1 else: print("you win! computer loses a life\n") gameVars.Ai_lives -= 1 elif (computer == "scissors"): if (gameVars.player == "paper"): print("you lose! you lose a life :(\n") gameVars.player_lives -= 1 else: print("you win! computer loses a life\n") gameVars.Ai_lives -= 1
# Got help from Jake Shams def knapsack(items, capacity): '''inputs: an array of tuples with weights and values maximum capacity of the bag output: the max value that can fit in the bag ''' if len(items) == 0 or capacity == 0: return 0 weight, val = items[0] if weight > capacity: # If weight is too much, disregard this one return knapsack(items[1:], capacity) value_without = knapsack(items[1:], capacity) value_with = knapsack(items[1:], capacity - weight) + val return max(value_with, value_without)
from util import file_to_graph from sys import argv if __name__ == '__main__': assert argv[1] is not None, "Data file path is required." assert argv[2] is not None, "'From' vertex is required." assert argv[3] is not None, "'To' vertex is required." graph = file_to_graph(argv[1]) start, stop = argv[2], argv[3] if start.isdigit(): start = int(start) if stop.isdigit(): stop = int(stop) path = graph.shortest_path_between(start, stop) print(f"Vertices in shortest path: {','.join(list(map(str, path)))}") print(f"Number of edges in shortest path: {len(path) - 1}")
name = input("Enter your name -> ") age = input("Enter your age -> ") age = int(age) if name == 'Kyle' and age == 29: print('You must be ' + name + ' because that info is correct.') elif name != 'Kyle' and age == 29: print('You must be someone else.') elif name != 'Kyle' and age != 29: print('So ' + name, ', you\'re ' + str(age))
# create a function named 'collatz' which accepts 1 argument - 'number' import sys def collatz(number): if number % 2 == 0: print(number // 2) return number // 2 elif number % 2 != 0: odd_result = 3 * number + 1 print(odd_result) return odd_result try: value = int(input('Enter a number -> ')) if value <= 1: print('The integer must be a non-negative number AND greater than 1.') sys.exit() while value > 1: value = collatz(value) except ValueError: print('You must enter an integer.')
def sqrt(n): if n == 0 or n == 1: return n if n < 0: return None start = 0 end = n return _find_root(n, start, end) def _find_root(n, start, end): mid = (start+end) // 2 mid_sq = mid*mid if mid_sq == n or abs(mid_sq-n) < 5: return mid elif mid_sq < n: return _find_root(n, mid+1, end) else: return _find_root(n, start, mid-1) if __name__ == "__main__": print("Pass" if (3 == sqrt(9)) else "Fail") print("Pass" if (0 == sqrt(0)) else "Fail") print("Pass" if (4 == sqrt(16)) else "Fail") print("Pass" if (1 == sqrt(1)) else "Fail") print("Pass" if (5 == sqrt(27)) else "Fail") print("Pass" if (7 == sqrt(53)) else "Fail")
from Trees import * class With_Stacks: def __init__(self, tree): self.tree = tree def pre_order(self, debug_mode = False): tree = self.tree node = tree.get_root() visit_order = [] state = State(node) stack = Stack() stack.push(state) count = 0 visit_order.append(node.get_value()) while (node): if debug_mode: print(""" loop count: {} current node: {} stack: {} """.format(count, node, stack)) count += 1 if node.has_left_child() and not state.get_visited_left(): state.set_visited_left() node = node.get_left_child() visit_order.append(node.get_value()) state = State(node) stack.push(state) elif node.has_right_child() and not state.get_visited_right(): state.set_visited_right() node = node.get_right_child() visit_order.append(node.get_value()) state = State(node) else: stack.pop() if not stack.is_empty(): state = stack.top() node = state.get_node() else: node = None if debug_mode: print(""" loop count: {} current node: {} stack: {} """.format(count, node, stack)) return visit_order def in_order(self, debug_mode = False): tree = self.tree node = tree.get_root() visit_order = [] state = State(node) stack = Stack() stack.push(state) count = 0 # visit_order.append(node.get_value()) while (node): if debug_mode: print(""" loop count: {} current node: {} stack: {} """.format(count, node, stack)) count += 1 if node.has_left_child() and not state.get_visited_left(): state.set_visited_left() node = node.get_left_child() state = State(node) stack.push(state) elif node.has_right_child() and not state.get_visited_right(): state.set_visited_right() node = node.get_right_child() # visit_order.append(node.get_value()) state = State(node) # elif stack: # state = stack.pop() # node = state.get_node() # # node = node.get_right_child() else: stack.pop() if not stack.is_empty(): state = stack.top() node = state.get_node() visit_order.append(node.get_value()) else: node = None # break if debug_mode: print(""" loop count: {} current node: {} stack: {} """.format(count, node, stack)) return visit_order class With_Recursion(object): def __init__(self, tree): self.tree = tree def pre_order(self): root = self.tree.get_root() visit_order = [] def traverse(node): if node: visit_order.append(node) traverse(node.get_left_child()) traverse(node.get_right_child()) traverse(root) return visit_order def in_order(self): root = self.tree.get_root() visit_order = [] def traverse(node): if node: traverse(node.get_left_child()) visit_order.append(node) traverse(node.get_right_child()) traverse(root) return visit_order def post_order(self): root = self.tree.get_root() visit_order = [] def traverse(node): if node: traverse(node.get_left_child()) traverse(node.get_right_child()) visit_order.append(node) traverse(root) return visit_order def create_tree(): tree = Tree("apple") tree.get_root().set_left_child(Node("banana")) tree.get_root().set_right_child(Node("cherry")) tree.get_root().get_left_child().set_left_child(Node("dates")) return tree if __name__ == "__main__": tree = create_tree() dfs = With_Stacks(tree) print(dfs.pre_order()) print(dfs.in_order(debug_mode=True))
class DoubleNode: def __init__(self, value): self.value = value self.next = None self.prev = None class DoubleLinkedList: def __init__(self, value=None): self.head = value self.tail = None def append(self, val): if self.head is None: self.head = DoubleNode(val) self.tail = self.head return node = self.tail node.next = DoubleNode(val) node.next.prev = node self.tail = self.tail.next return if __name__ == "__main__": linked_list = DoubleLinkedList() linked_list.append(1) linked_list.append(-2) linked_list.append(4) print("Going forward through the list, should print 1, -2, 4") node = linked_list.head while node: print(node.value) node = node.next print("\nGoing backward through the list, should print 4, -2, 1") node = linked_list.tail while node: print(node.value) node = node.prev
class Node: def __init__(self, value): self.value = value self.next = None def __repr__(self): return str(self.value) class LinkedList: def __init__(self): self.head = None def __str__(self): cur_head = self.head out_string = "" while cur_head: out_string += str(cur_head.value) + " -> " cur_head = cur_head.next return out_string def append(self, value): if self.head is None: self.head = Node(value) return node = self.head while node.next: node = node.next node.next = Node(value) def size(self): size = 0 node = self.head while node: size += 1 node = node.next return size def to_list(self): out = [] current = self.head while current: out.append(current.value) current = current.next return out def union(llist1, llist2): list1 = llist1.to_list() list2 = llist2.to_list() if len(list1) == 0 and len(list2) == 0: return None union_list = list(set(list1+list2)) ulist = LinkedList() for num in union_list: ulist.append(num) return ulist def intersection(llist1, llist2): set1 = set(llist1.to_list()) set2 = set(llist2.to_list()) intersect_list =[num for num in set1 if num in set2] if len(intersect_list) == 0: return None intersection_llist = LinkedList() for num in intersect_list: intersection_llist.append(num) return intersection_llist if __name__ == "__main__": ## test 1 linked_list_1 = LinkedList() linked_list_2 = LinkedList() element_1 = [3, 2, 4, 35, 6, 65, 6, 4, 3, 21] element_2 = [6, 32, 4, 9, 6, 1, 11, 21, 1] for i in element_1: linked_list_1.append(i) for i in element_2: linked_list_2.append(i) print(union(linked_list_1, linked_list_2)) #32 -> 65 -> 2 -> 35 -> 3 -> 4 -> 6 -> 1 -> 9 -> 11 -> 21 -> print(intersection(linked_list_1, linked_list_2)) #4 -> 6 -> 21 -> ## test 2 linked_list_3 = LinkedList() linked_list_4 = LinkedList() element_1 = [3, 2, 4, 35, 6, 65, 6, 4, 3, 23] element_2 = [1, 7, 8, 9, 11, 21, 1] for i in element_1: linked_list_3.append(i) for i in element_2: linked_list_4.append(i) print(union(linked_list_3, linked_list_4)) #65 -> 2 -> 35 -> 3 -> 4 -> 6 -> 1 -> 7 -> 8 -> 9 -> 11 -> 21 -> 23 -> print(intersection(linked_list_3, linked_list_4)) #None ## test 3 linked_list_5 = LinkedList() linked_list_6 = LinkedList() print(union(linked_list_5, linked_list_6)) # None print(intersection(linked_list_5, linked_list_6)) # None ## test 4 linked_list_7 = LinkedList() linked_list_8 = LinkedList() element_1 = [4, 6, 7, 8, 9 , 10, 2, 31] for num in element_1: linked_list_7.append(num) print(union(linked_list_7, linked_list_8)) # 2 -> 4 -> 6 -> 7 -> 8 -> 9 -> 10 -> 31 -> print(intersection(linked_list_7, linked_list_8)) # None
class Heap: def __init__(self, initial_size=10): self.cbt = [None for _ in range(initial_size)] # initialize arrays self.next_index = 0 # denotes next index where new element should go def insert(self, data): # insert element at the next index self.cbt[self.next_index] = data # heapify self._up_heapify() # increase index by 1 self.next_index += 1 # double the array and copy elements if next_index goes out of array bounds if self.next_index >= len(self.cbt): temp = self.cbt self.cbt = [None for _ in range(2 * len(self.cbt))] for index in range(self.next_index): self.cbt[index] = temp[index] def remove(self): if self.size() == 0: return None self.next_index -= 1 to_remove = self.cbt[0] last_element = self.cbt[self.next_index] # place last element of the cbt at the root self.cbt[0] = last_element # we do not remove the elementm, rather we allow next `insert` operation to overwrite it self.cbt[self.next_index] = to_remove self._down_heapify() return to_remove def size(self): return self.next_index def is_empty(self): return self.size() == 0 def _up_heapify(self): # print("inside heapify") child_index = self.next_index while child_index >= 1: parent_index = (child_index - 1) // 2 parent_element = self.cbt[parent_index] child_element = self.cbt[child_index] if parent_element > child_element: self.cbt[parent_index] = child_element self.cbt[child_index] = parent_element child_index = parent_index else: break def _down_heapify(self): parent_index = 0 while parent_index < self.next_index: left_child_index = 2 * parent_index + 1 right_child_index = 2 * parent_index + 2 parent = self.cbt[parent_index] left_child = None right_child = None min_element = parent # check if left child exists if left_child_index < self.next_index: left_child = self.cbt[left_child_index] # check if right child exists if right_child_index < self.next_index: right_child = self.cbt[right_child_index] # compare with left child if left_child is not None: min_element = min(parent, left_child) # compare with right child if right_child is not None: min_element = min(right_child, min_element) # check if parent is rightly placed if min_element == parent: return if min_element == left_child: self.cbt[left_child_index] = parent self.cbt[parent_index] = min_element parent = left_child_index elif min_element == right_child: self.cbt[right_child_index] = parent self.cbt[parent_index] = min_element parent = right_child_index def get_minimum(self): # Returns the minimum element present in the heap if self.size() == 0: return None return self.cbt[0] if __name__ == "__main__": heap_size = 5 heap = Heap(heap_size) elements = [1, 2, 3, 4, 1, 2] for element in elements: heap.insert(element) print('Inserted elements: {}'.format(elements)) print('size of heap: {}'.format(heap.size())) for _ in range(4): print('Call remove: {}'.format(heap.remove())) print('Call get_minimum: {}'.format(heap.get_minimum())) for _ in range(2): print('Call remove: {}'.format(heap.remove())) print('size of heap: {}'.format(heap.size())) print('Call remove: {}'.format(heap.remove())) print('Call is_empty: {}'.format(heap.is_empty()))
class GraphEdge(object): def __init__(self, destinationNode, distance): self.node = destinationNode self.distance = distance class GraphNode(object): def __init__(self, val): self.value = val self.edges = [] def add_child(self, node, distance): self.edges.append(GraphEdge(node, distance)) def remove_child(self, del_node): if del_node in self.edges: self.edges.remove(del_node) class Graph(object): def __init__(self, node_list): self.nodes = node_list # adds an edge between node1 and node2 in both directions def add_edge(self, node1, node2, distance): if node1 in self.nodes and node2 in self.nodes: node1.add_child(node2, distance) node2.add_child(node1, distance) def remove_edge(self, node1, node2): if node1 in self.nodes and node2 in self.nodes: node1.remove_child(node2) node2.remove_child(node1) import math def dijkstra(graph, start_node, end_node): queue = {} for node in graph.nodes: queue[node] = math.inf shortest_distance = {} queue[start_node] = 0 while queue: current_node, node_distance = sorted(queue.items(), key=lambda x: x[1])[0] shortest_distance[current_node] = queue.pop(current_node) for edge in current_node.edges: if edge.node in queue: distance_to_neighbour = node_distance + edge.distance if queue[edge.node] > distance_to_neighbour: queue[edge.node] = distance_to_neighbour return shortest_distance[end_node] node_u = GraphNode('U') node_d = GraphNode('D') node_a = GraphNode('A') node_c = GraphNode('C') node_i = GraphNode('I') node_t = GraphNode('T') node_y = GraphNode('Y') graph = Graph([node_u, node_d, node_a, node_c, node_i, node_t, node_y]) # add_edge() function will add an edge between node1 and node2 in both directions graph.add_edge(node_u, node_a, 4) graph.add_edge(node_u, node_c, 6) graph.add_edge(node_u, node_d, 3) graph.add_edge(node_d, node_c, 4) graph.add_edge(node_a, node_i, 7) graph.add_edge(node_c, node_i, 4) graph.add_edge(node_c, node_t, 5) graph.add_edge(node_i, node_y, 4) graph.add_edge(node_t, node_y, 5) # Shortest Distance from U to Y is 14 print('Shortest Distance from {} to {} is {}'.format(node_u.value, node_y.value, dijkstra(graph, node_u, node_y)))