text
stringlengths
37
1.41M
# 建立記帳程式專案(二維清單) # while true適合使用在使用者不知道要輸人幾次時使用,可以重複的執行的情況 # refactor 重構 import os # operating system作業系統模組 # 讀取檔案 def read_file(filename): products = [] # 建立清單,存放使用者輸入的商品名,要放在最外圈 with open(filename, 'r', encoding='utf-8') as f: for line in f: if '商品,價格' in line: continue # 迴圈內的continue為跳到下一回的意思,當if為true時,進到if的內,遇到continue時,不向下執行下面的程式,再跳回for loop迴圈開頭 name, price = line.strip().split(',') # line.strip().split(','):line的字串,先執行strip()把換行符號「\n」去除,再執行split()進行切割 products.append([name,price]) # 再把他存入products這個大清單 return products # 使用者輸入購買的商品與價格 def user_input(products): while True: name = input('請輸入商品名稱: ') if name == 'q': # 可以讓使用者跳出迴圈 break price = input('請輸入商品價格: ') price = int(price) products.append([name, price]) # 再把這個小清單p,存入products這個大清單 print(products) return products # 印出所有的商品與價格 def print_products(products): for p in products: # 用for loop把products清單內的內容,一個一個印出來 print(p[0], '的價格是', p[1]) # 寫入商品與價格到檔案內 def write_file(filename, products): with open(filename, 'w', encoding = 'utf-8') as f: # 'products.csv'為打開這個文件、'w'為寫入模式、encoding='utf-8'指字寫入時的文字編碼 f.write('商品,價格\n') # 讓第一個欄位顯示為商品、價格 for p in products: f.write(p[0] + ',' + str(p[1]) + '\n') # f.write(x)為把內容x寫入f內,str(p[1])把整數轉成字串 def main(): # 主要的程式進入點(真正的執行程式) filename = 'products.csv' if os.path.isfile(filename): # 檢查檔案在不在 print('yeah! 找到檔案了!') products = read_file(filename) else: print('找不到檔案....') products = user_input(products) print_products(products) write_file(filename, products) main()
# -*- coding: utf-8 -*- ''' @author: uidq1501 ''' import threading def sum(a): print(a+6) threads = [] for i in range(3): # print i t = threading.Thread(target=sum, args=(i,)) threads.append(t) for j in threads: j.start()
def maxProfit(self, prices: List[int]) -> int: ''' prices = [7, 1, 5, 3 ,6 ,4] check for edge cases: empty array, negaive numbers, specil characters, or something like [1, 1, 1, 1, 1, 1, 1], what to return for these cases? use for loop to iterate through the prices array how do we know which is the lowest and highest? => use two variables to hold those value => iterate through the entire list, and update those two values accorrdingly. Time: O(N) average: iterate through every single elements in the array once. Space: O(1) because no additional data structures ''' if len(prices) == 0 or len(prices) ==1: return 0 else: #what value should we hold initially for these two variables? #set lowest to prices[0], not 0 because let's say [1, 2, 3, 4], then lowest is 1, not 0 lowest = prices[0] highest = 0 for i in range( len(prices)): if prices[i] < lowest: lowest = prices[i] if (prices[i] - lowest) > highest: higest = prices[i] - lowest return highest def productExceptSelf(self, nums: List[int]) -> List[int]: """ check for edge cases: length of array is one. return 0 solve: multiple and store value in another array, multiply from left to right, another one from right to left, [1, 2, 3, 4 ] = [1, 1, 2, 6] [1, 2, 3, 4] = [24,12,4,1] Time: O(N), run the for loop once for every for loop run, therefore O(N) + O(N) = O(N) Space: O(N), because we are creating more array => more space in memory """ arrayleft = [1]* len(nums) arrayright = [1] * len(nums) templeft = 1 for i in range(len(nums)-1): templeft *= nums[i] arrayleft[i+1] = templeft nums.reverse() # build in fuction to reverse th list for the arrayright to multple and add in data templeft = 1 for i in range(len(nums)-1): templeft *= nums[i] arrayright[i+1] = templeft arrayright.reverse() for i in range(len(nums)): nums[i] = arrayleft[i] * arrayright[i] return nums def maxSubArray(self, nums: List[int]) -> int: """ thoguht process: check for edge cases: [-2, -4, -5, -20] => return -2, maybe don't need to search through the list [1, 3, 5, 7 ,10, 15] => search through the entire list [-2, 1, -3, 4, 30] remind me of kardane althorim. currenmax to keep largest sum so far finalmax to keep largest of currenmax and finalmax [-2,1,-3,4,-1,2,1,-5,4] -2 + 1 = -1 currmax = -1 -1 - 3 = -4 currmax = -1 -4 + 4 = 0 currmax = 0 0 -1 = -1 currmax = 0 -1 + 2 = 1 currmax = 1 1 + 1 = 2 => finalmax, and wrong, we can set currMax to zero whenever we see zero, but does not work too because [-2, 1] = finalmax = -1, not zero. we can do currmax = 2 2 -5 = -3 -3 + 4 = 1 currmax = -2+1 = 1 -3 = -2 +4 = 2 -1 = 1 + 2 = 3 + 1 = 4 -5 = -1 + 4 3 finalmax 4 """ if len(nums) <= 1: return nums[0] else: currmax = 0 finalmax = float('-inf') for i in range( len(nums)): currmax = max(nums[i], currmax + nums[i]) if currmax > finalmax: finalmax = currmax return finalmax def maxProduct(self, nums: List[int]) -> int: pre_max = nums[0] pre_min = nums[0] curr_max = nums[0] curr_min = nums[0] ans = nums[0] #run the for loop from value index 1 to the end for i in nums[1:]: #compare it with max(blablabla, i) => this is to satisfy the continigoue subarray requirement curr_max = max(max(pre_max*i, pre_min*i), i) curr_min = min(min(pre_max*i, pre_min*i), i) pre_max = curr_max pre_min = curr_min ans = max(ans, curr_max) return ans """ thought process => brainstorm the problem, don't jump straight into code, the more brainstorm, the more ideas will come across our mind. step 0 (edge cases): nums = [2,3,-2,4] 2 * 3 = 6 6 * -2 = -12 thinking of dynamic programming where we keep track of the current value and update it whenever nessescary. we need temp variable to hold the current mul: currmul: 2 * 3 = 6 6 * -2 = -12 -12 * 4 = - 48 another variable to keep highestpositive, and lowestnegative if currmul< 0: lowestnegative = currmul if currmul >= 0: highestpositive = currmul return highestpositive observation: currmul = 6 > -12, keep 6 => how do we do this? solve: [] => [one element] => [two elements] => [all positive] => return the whole array [-1 , -2, -2, -6] => check all elements [1, 2, 5, 0, -1, 4, -6] final_array = [] => has to be non empty => insert it with some temporary => which number should we choose => the first element in the array ofc final_array.append(nums[0]) use loop to iterate through the entire array => linear time O(N), can't have better time complexity than this because every elements needed to be access in this case for i in range(len(nums)): #at every itertion, what do we do? Time complexity: Space cpmplexity: """ def findMin(self, nums: List[int]) -> int: """ step 0: check for edge cases: [] or [one element] => return -1 given: sorted increasing order [-5, -3 , 0, 4, 7, 30] rotated between 1 and n time unique elements => does not matter negative, zero, or positive [5, 4, 6, 1, 2 ] => what to do with this case??? not gonna happends because given find pivot point maybe??? use BST to find pivot??? [3,4,5,1,2] search until we find the pivot index, the elemnt at that pivot index is the minimum, remember to check for outofounce array index too**** how to find the pivot=> we search => linear => search every element until we find nums[i-1] > nums[i] and nums[i] < nums[i+1] => return nums[i] as pivot point(make sure i+1 is not outofbounce of the array) time: O(N) for linear search use binary search for better time O(logN) space: O(1) no additional array needed because sorted array so we can use BST, otherwise can't!! recursively or iteratively => recursively steps for bst: find the middle index, check if middle index satisfy nums[i-1] > nums[i] and nums[i] < nums[i+1], if it is then return nums[middle], else go recursively call the function again, passing middle-1 as the most left element, and do the same thing with middle+1 as the most right element base case for recursive: while left < right if greater than target, 4,5,6,7,8, 9, 10, 11, 0,1,2 middle is 9, how do we know which way left or right to go? look at left most and right most, 4 < 9 => the left side is already in order and not rotated, right side suppose to be greater than 9 but we see 2 => check right side """ if len(nums) == 0: return None elif len(nums) == 1: return nums[0] elif len(nums) ==2: if nums[0] <nums[1]: return nums[0] return nums[1] else: #[1, 2, 3, 4, 5,] left, right = 0, len(nums)-1 while left < right: middle = int(left + ((right-left)/2)) if nums[middle] > nums[middle-1] and nums[middle+1] < nums[middle]: return nums[middle+1] if nums[middle] < nums[middle-1] and nums[middle] < nums[middle+1]: return nums[middle] else: if nums[0] < nums[middle]: left = middle+1 if nums[0] > nums[middle]: right = middle-1 return nums[0] # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next def reverseList(self, head: ListNode) -> ListNode: """ edge cases: empty linkedlist => return None one elemnt => return that element does not matter what the value in the linkedlist hold, duplicate are okay too. linkedlist has a node, which has val and next we use two pointers, one point at the curr, one point at next node. """ prev, curr = None, head while curr is not None: temp = curr.next curr.next = prev prev = curr curr = temp return prev # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None def hasCycle(self, head: ListNode) -> bool: dictionary = {} """ key/value hashmap store head value in the dictionary """ while head: if head in dictionary: return True dictionary[head] = True head = head.next return False # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: dummy = curr = ListNode(0) while l1 and l2: if l1.val < l2.val: curr.next = l1 l1 = l1.next else: curr.next = l2 l2 = l2.next curr = curr.next while l1: curr.next = l1 l1 = l1.next curr = curr.next while l2: curr.next = l2 l2 = l2.next curr = curr.next return dummy.next def isAnagram(self, s: str, t: str) -> bool: """ first loop if we first see the key, mark it with 1 second loop run the t string, if the char in t existed in counter, minutes 1 from their value finally check the status of the counter dictionary see if any value is still 1 => return false else return true counter key value a 1 """ """ a_string = "cba" sorted_characters = sorted(a_string) Sort string alphabetically and return list. a_string = "". join(sorted_characters) Combine list elements into one string. print(a_string) """ if len(s) != len(t): return False else: s_sorted_character = sorted(s) t_sorted_character = sorted(t) print(s_sorted_character) print(t_sorted_character) for i in range(len(s_sorted_character)): if s_sorted_character[i] != t_sorted_character[i]: return False return True def isAnagram(self, s: str, t: str) -> bool: """ first loop if we first see the key, mark it with 1 second loop run the t string, if the char in t existed in counter, minutes 1 from their value finally check the status of the counter dictionary see if any value is still 1 => return false else return true counter key value a 1 """ """ a_string = "cba" sorted_characters = sorted(a_string) Sort string alphabetically and return list. a_string = "". join(sorted_characters) Combine list elements into one string. print(a_string) """ if len(s) != len(t): return False else: counter =[0]* 26 print(counter)
import sys def open_file(file_name,mode): """Opens file in the given mode""" try: file = open(file_name, mode) return file except IOError as e: print("Unable to open the file", file_name, "Ending program.\n", e) input("\n\nPress the enter key to exit.") sys.exit() def next_line(the_file): """reads the next line in the file and formats it for our program""" line = the_file.readline() line = line.strip("\n") line = line.replace("/","\n") return line def question_block(the_file): """ reade the question block from the file and returns category, question, answers list, correct answer, and explanation""" category = next_line(the_file) question = next_line(the_file) answers = [] for i in range(4): answers.append(next_line(the_file)) correct = next_line(the_file) if correct: correct = correct[0] explanation = next_line(the_file) return category,question,answers,correct,explanation def welcome(title): """Welcome the player and get his/her name.""" print("\t\tWelcome to my python Trivia Challenge!\n") print("\t\t this test was created by", title, "\n") def main(): file_name = get_file_name() file = open_file(file_name,"r") title = next_line(file) name = input("Enter in your full name") questions = 0 score = 0 category,question,answers,correct,explanation = question_block(file) welcome(title) while category: print(category) print() print(question) print() for i in range(len(answers)): print("\t", i + 1, "-", answers[i]) userAnswer = input("What's your answer?: ") if userAnswer == correct: score += 1 questions += 1 print("correct") else: questions += 1 print("Wrong") print() print(explanation) category,question,answers,correct,explanation = question_block(file) file.close() print("That was the last question!") report_card(name,questions,score) def get_file_name(): while True: file = input("enter in the name of the test file") if ".txt" in file and " " not in file: return file else: print("not a good file name") def report_card(name,questions,score): A = """ # # # # # # # ####### # # # # """ B = """ ###### # # # # ###### # # # # ###### """ C = """ ##### # # # # # # # ##### """ D = """ ###### # # # # # # # # # # ###### """ F = """ ####### # # ##### # # # """ title = """ ###### ##### # # ###### ##### #### ##### ##### # # ## ##### ##### # # # # # # # # # # # # # # # # # ###### ##### # # # # # # # # # # # # # # # # # ##### # # ##### # # ###### ##### # # # # # # # # # # # # # # # # # # # # # ###### # #### # # # ##### # # # # ##### """ print("**************************************************************************") print(title) print("**************************************************************************") print() print() print("\tstudent: "+ name) print("\tyou answered "+str(score)+"/"+str(questions) +" Correct") percent = score / questions * 100 percent_str = str(percent) + "%" point_per_question = (100/questions) totalpoints = point_per_question*questions totalscore = point_per_question*score print("\teach question was worth "+str(point_per_question)+ " points") print("\tyou received "+str(totalscore) +"/"+str(totalpoints) +" points") print("\tyou got a " + percent_str) if percent >= 90: print(A) print() print("\tGreat job") elif percent < 90 and percent >= 80: print(B) print() print("\tnot to bad") elif percent < 80 and percent >= 70: print(C) print() print("\tOK") elif percent < 70 and percent >= 60: print(D) print() print("\ttry harder") elif percent < 60: print(F) print() print("\tRealy try harder") print() print("**************************************************************************") main()
import random import sys print("Welcome the computer is going to guess your number") minrange =int(input("what number do you want to start with?")) mxrange = int(input("what do number do you want to go to?")) num = int(input("now pick a number between your previous numbers")) randnum = random.randint(minrange,mxrange) trys = 0 maxTrys = 3 trys += 1 while num != randnum and trys != maxTrys: if num > randnum: else: num = testing_guess(rmin,rmax) trys += 1
# # bool = True # num = 200 # # # # list = [] # list.append(7) # list.append(93) # list.append(3) # list.append(45) # print (list) # print(list[2]) # if num < 100: # print('hi') # elif num == 120: # num = 10/2 # print('hello again') # else: # print('goodbye') # # print(num) # # while bool == True and num > 30: # bool = num != 30 # print('cool') # num = num - 20 # print('loop done') # # tuple = (1,7) # print(tuple) # print(tuple[0]) # # for count in range (0, 10): # print(list[count]) # for value in list: # print(value) x_list = [] x_list.append('secret') x_list.append('life') print (len(x_list)) # # for name in x_list: # print(name) # print(x_list[1]) age = 32 age += 4
#!/usr/bin/env python # encoding: utf-8 import operator class Solution(object): def findTheDifference(self, s, t): """ :type s: str :type t: str :rtype: str """ for i, letter in enumerate(t): if i < len(s) and letter == s[i]: continue else: return letter def findTheDifference2(self, s, t): """ 1. chr(i): 将数值(0 <= i < 256)转换为字符并返回 2. reduce(function, sequence): 先把sequence中的第一个值和第二个值当参数传给function, 再把function的返回值和第三个值当参数传给function, 然后只返回一个结果 3. map(function, iterable, ...): 将function作用于iterable中的每个item, 返回结果列表 """ return chr(reduce(operator.xor, map(ord, s + t))) if __name__ == "__main__": solution = Solution() print solution.findTheDifference2("abcd", "abcde")
""" Python does not generally support the concept of private variable like in Java i.e. they will still be accessible from the object. They are not hidden. But in general practice, if a attribute or a method is made private, then it means they should be accessed outside the class i.e. the developer needs to take care that they are not accessed outside although Python doesn't throw an error. """ class Employee: def __init__(self, first_name, last_name, salary) -> None: self.first_name = first_name self.last_name = last_name self._salary = salary # Here salary is made private by appending '_' (underscore) def full_name(self): return f'{self.first_name} {self.last_name}' def _get_salary_band(self): return self._salary / 10 # Accessing private variable inside a class is allowed. mohan = Employee('mohan', 'peddapuli', 32000) print(mohan._salary) # Even though this works, we should not do this. print(mohan._get_salary_band()) # Same as above. """ To really hide variable from getting accessed accidentally by users, we can do that by appending two underscores(__) to the attribute. """ class Employee: def __init__(self, first_name, last_name, salary) -> None: self.first_name = first_name self.last_name = last_name self.__salary = salary def full_name(self): return f'{self.first_name} {self.last_name}' def get_salary_band(self): # Made a normal method return self.__salary / 10 # Inside the class, we can access this. mohan = Employee('mohan', 'peddapuli', 32000) # print(mohan.__salary) This wont work print(mohan.get_salary_band())
#!/usr/bin/python def print_stars(): num_of_lines = int(input("Please enter the number of lines: ")) for j in range(num_of_lines, 0, -1): print("* "*j, end='\n') print("Finished printing") print_stars()
class Decorate: def __init__(self, function): self.f = function def __call__(self, *args, **kwargs): print("Executing the decorated function") self.f(*args, **kwargs) @Decorate def decorated_greet(name): print(f"Hello, {name}") def undecorated_greet(name): print(f"Hello, {name}") print('-'*30, ' Executing decorated function ', '-'*30) decorated_greet('Mohan') print('-'*30, ' Executing undecorated function ', '-'*30) undecorated_greet('Mohan')
#!/usr/bin/env python3 """Reads mathematical expressions from stdin and evaluates them.""" from lark import Lark, Transformer class CalcTransformer(Transformer): # pylint: disable=too-few-public-methods """Transformer for the parser.""" @staticmethod def _num(args): return float(args[0]) @staticmethod def _add(args): return float(args[0]) + float(args[1]) @staticmethod def _sub(args): return float(args[0]) - float(args[1]) @staticmethod def _mul(args): return float(args[0]) * float(args[1]) @staticmethod def _div(args): return float(args[0]) / float(args[1]) @staticmethod def _negate(args): return -args[0] def main(): """Creates a parser and uses it to evaluate stdin.""" parser = Lark.open("grammar.lark", parser='lalr', transformer=CalcTransformer()) try: result = parser.parse(input('> ')) if result == int(result): result = int(result) print(result) except ZeroDivisionError: print('Tried to divide by zero!') except: print('Syntax error!') if __name__ == "__main__": main()
""" solve_netlist.py Evan Greene and Anthony Lowery 2017/03/18 """ import numpy as np from parse_netlist import parse_netlist from gaussian_elimination import gaussian_elimination def solve_netlist(V, I, R, N): """ transforms the output of parse_netlist into a solved linear system using modified nodal analysis. Creates a matrix equation, then solves it using Gaussian elimination. """ """ V represents a list of voltage sources. Each voltage source has a list of four elements, name, source, destination, and value (in Volts). I represents a list of current sources. The current sources likewise have name, source, destination, and value (in Amps). R represents a list of resistors, with name, source, destination, and value, (in Ohms). N is the number of nodes, not including ground """ # create these variables so that we can call Resistor[src] instead of # having to remember the order of the information. name = 0 src = 1 dst = 2 val = 3 # set up the values of m and n. m = len(V) n = N """ The idea here is to create a linear equation given by Ax = z. A consists of four submatrices, A = [[G, B], [ C, D]]. Create the G matrix. the G matrix is an n x n matrix where the diagonal elements are the sum of the conductances connected to node n, and the off-diagonal elements are the negative conductances of the connection between the two nodes. """ G = np.zeros([n, n]) for resistor in R: # print 'G = ', G if resistor[src] != 0: G[resistor[src] - 1, resistor[src] - 1] += 1.0 / resistor[val] if resistor[dst] != 0: G[resistor[dst] - 1, resistor[dst] - 1] += 1.0 / resistor[val] if resistor[dst] != 0 and resistor[src] != 0: G[resistor[src] - 1, resistor[dst] - 1] -= 1.0 / resistor[val] G[resistor[dst] - 1, resistor[src] - 1] -= 1.0 / resistor[val] """ Create the B matrix. The b matrix is an n x m matrix with only 1, 0 and -1 as elements. If the positive terminal of voltage source i is connected to node k, then element (k, i) has value 1. If the negative element of the voltage source i is connected to node k, then element (k, i) has value -1. Otherwise, all elements are zero. """ # create an n x n matrix filled with zeros. B = np.zeros([n, m]) for i in range(len(V)): # loop through each voltage source if V[i][src] != 0: B[V[i][src] - 1, i] = 1.0 # assign the positive terminal to be 1 if V[i][dst] != 0: B[V[i][dst] - 1, i] = -1.0 #assign the negative terminal to be -1 """ create the C matrix The C matrix is a m x n matrix with only 0, 1 and -1 elements. For each independent voltage source, if the positive terminal of the ith voltage source is connected to node k, the element, (i, k) is 1. If the negative terminal of the ith voltage source is connected to node k, then element (i, k) is -1. For each op-amp let the positive terminal be at node k and the negative terminal be at node j. The corresponding ith row of the C matrix has a 1 at the positive terminal --location (i, k), and a -1 at the negative terminal -- location (j, k) Otherwise, the elements of C are zero. """ # if there are no op amps, then C = B^T. C = np.zeros([m, n]) for i in range(len(V)): if V[i][src] != 0: C[i-1, V[i][src]- 1] = 1.0 # assign the positive terminal to be 1 if V[i][dst] != 0: C[i-1, V[i][dst] - 1] = -1.0 # assign the negative terminal to be -1 # we're not looking at Op Amp circuits here, so we're done. """ create the D matrix. The D matrix is an m x m matrix composed entirely of zeros. """ D = np.zeros([m, m]) # print 'G has shape {} \nB has shape {} \nC has shape {} \nD has shape {}'.format(\ # G.shape, B.shape, C.shape, D.shape) # part1 = np.concatenate((G, B), axis = 1) # print 'part1 has shape {}'.format(part1.shape) # part2 = np.concatenate((C, D), axis = 1) # print 'part2 has shape {}'.format(part2.shape) # A = np.concatenate((part1, part2), axis = 0) A = np.concatenate((np.concatenate((G, B), axis = 1), \ np.concatenate((C, D), axis = 1)), axis = 0) """ Now we need to develop the Z matrix. The Z matrix is developed as the combination of two smaller matrices i and e The i matrix is a 1 x n """ eye = np.zeros(n) # can't very well use i (reserved for loops) or I (already used for current) for index in range(len(I)): # using i might get confusing. if I[index][dst] != 0: eye[I[index][dst] - 1] += I[index][val] if I[index][src] != 0: eye[I[index][src] - 1] -= I[index][val] """ The e matrix is a 1 x m matrix with each element corresponding to a voltage source. If the element in the e matrix corresponds to an independent voltage source, it is set equal to the value of that voltage source. If the element corresponds to an op-amp, it is set to zero. """ e = np.zeros(m) for index in range(len(V)): if V[index][src] != 0: e[index - 1] = V[index][val] # print 'i has shape {} \ne has shape {} \n'.format(eye.shape, e.shape) Z = np.concatenate((eye, e), axis = 0 ) """ The x matrix (found from Ax = Z) consists of two submatrices v and j. The v matrix is an n x 1 matrix of node voltages. Each element in v[i] corresponds to the equivalent node i+1 (there is no entry for ground, i = 0) The j matrix is an m x 1 matrix of currents, with one entry for the current through each voltage source. """ return A, Z, gaussian_elimination(A, Z) def main(): V, I, R, n = parse_netlist('example2.txt') A, z, x = solve_netlist(V, I, R, n) for index in range(n): print 'The voltage at node {} is {} V'.format(index + 1, x[index]) for index in range(len(V)): print 'The current through voltage source {} is {} A'.format(V[index][0], x[index + n]) if __name__ == '__main__': main()
# -*- coding: utf-8 -*- """ Created on Sun Jun 27 17:09:53 2021 @author: Jose Alcivar Garcia """ sueldo= float(input("ingresa el sueldo: ")) a= float(input("ingresa la venta 1 ")) b= float(input("ingresa la venta 2 ")) c= float(input("ingresa la venta 3 ")) comision= (a+b+c)*.10 print("el sueldo del trabajador es: $", sueldo) print("la comision del mes por las 3 ventas es: ", comision) print("el sueldo total ya con la comision es: $", sueldo + comision)
# Samuel Ng 112330868 # CSE 352 Assignment 1 from TileProblem import TileProblem from Heuristics import Heuristics # Python standard library import sys from queue import PriorityQueue import math import tracemalloc import time # takes in an input file and returns a matrix of ints representing the state of the board def convert_txt_to_board(input_txt): inputLines = input_txt.read().splitlines() board = [] for row in inputLines: lst = [] nums = row.split(',') for num in nums: if num == '': lst.append(0) else: lst.append(int(num)) board.append(lst) return board # takes in a board and returns the position of the blank space (x, y) def get_blank_pos(board): for i in range(len(board)): for j in range(len(board[i])): if board[i][j] == 0: return (i, j) return (-1, -1) # takes in the size of the puzzle and the position of the blank space and returns a list of the possible actions def get_valid_actions(N, blank_pos): valid_actions = [] if blank_pos[0] > 0: valid_actions.append('U') if blank_pos[1] < N-1: valid_actions.append('R') if blank_pos[0] < N-1: valid_actions.append('D') if blank_pos[1] > 0: valid_actions.append('L') return valid_actions # performs A* graph search on a given problem and heuristic function, returns (# states explored, path to goal state) on success and False on failure # modeled after class pseudocode def A_star_graph_search(problem, N, H): frontier = PriorityQueue() explored = [] g_cost = 0 h_instance = Heuristics(H) h_instance.heuristic_cost(problem.state, problem.goal) h_cost = h_instance.h_cost f = g_cost + h_cost problem.f = f frontier.put((f, problem, g_cost, None, '')) # node consists of f value, tile problem, g value, parent node, and action from parent node while frontier: current_node = frontier.get() current = current_node[1] # current is a tile problem instance if current.is_solution(): actions = [] parent_node = current_node while parent_node is not None: action = parent_node[4] if action != '': actions.append(action) parent_node = parent_node[3] return (len(explored), actions) if current.state not in explored: explored.append(current.state) for action in current.actions: new_state = current.transition(action) blank_pos = get_blank_pos(new_state) actions = get_valid_actions(N, blank_pos) new = TileProblem(N, new_state, blank_pos, actions) g_cost = current_node[2] + 1 h_instance.heuristic_cost(current.state, current.goal) h_cost = h_instance.h_cost f = g_cost + h_cost new.f = f frontier.put((f, new, g_cost, current_node, action)) return False # performs RBFS on a given problem and heuristic function, returns True on success and False on failure rbfs_states = 0 # counter for keeping track of explored states for rbfs def recursive_best_first_search(problem, N, H): # pseudocode from mtu.edu referenced g_cost = 0 h_instance = Heuristics(H) h_instance.heuristic_cost(problem.state, problem.goal) h_cost = h_instance.h_cost f = g_cost + h_cost problem.f = f return RBFS([f, problem, g_cost, None, ''], math.inf, N, h_instance) # node consists of f value, tile problem, g value, parent node, and action from parent node # recursive helper for RBFS def RBFS(node, f_limit, N, h_instance): current = node[1] global rbfs_states rbfs_states += 1 if current.is_solution(): actions = [] parent_node = node while parent_node is not None: action = parent_node[4] if action != '': actions.append(action) parent_node = parent_node[3] return (True, f_limit, actions) # returning (True for success, f_limit, solution path) successors = [] for action in current.actions: new_state = current.transition(action) blank_pos = get_blank_pos(new_state) actions = get_valid_actions(N, blank_pos) new = TileProblem(N, new_state, blank_pos, actions) g_cost = node[2] + 1 h_instance.heuristic_cost(current.state, current.goal) h_cost = h_instance.h_cost f = g_cost + h_cost new.f = f successors.append([f, new, g_cost, node, action]) if not successors: return (False, math.inf, []) # if deadend, propagate infinity f value up path for successor in successors: successor[0] = max(successor[0], node[0]) # updating f with value from previous search if any successor[1].f = max(successor[0], node[0]) while True: sorted_successors = sorted(successors, key=lambda successor: successor[0]) best = sorted_successors[0] # successor with min f value if best[0] > f_limit: # none of the successors' f values are less than the f_limit return (False, best[0], []) # return (False, best f value, empty solution path) alternative = sorted_successors[1] result, best[0], actions = RBFS(best, min(f_limit, alternative[0]), N, h_instance) # the new f-limit is the minimum of the current f-limit and the f-value of the alternative path if result: return (result, best[0], actions) # function for outputting solution to output text file, solution is a string in output format def output(solution, outputPath): outF = open(outputPath, 'w') outF.write(solution) outF.close() # main function for running the script def main(): A = int(sys.argv[1]) # algorithm N = int(sys.argv[2]) # N=3 for 8-puzzle, N=4 for 15-puzzle H = int(sys.argv[3]) # H=1 for h1, H=2 for h2 inputPath = sys.argv[4] outputPath = sys.argv[5] inF = open(inputPath, 'r') board = convert_txt_to_board(inF) blank_pos = get_blank_pos(board) actions = get_valid_actions(N, blank_pos) problem = TileProblem(N, board, blank_pos, actions) time_start = time.time() tracemalloc.start() if A == 1: searchReturn = A_star_graph_search(problem, N, H) # returns a tuple with the number of states and path to goal in reverse elif A == 2: searchReturn = recursive_best_first_search(problem, N, H) else: print('Invalid A.') current, peak = tracemalloc.get_traced_memory() time_end = time.time() tracemalloc.stop() if searchReturn: # solution was found print('Success') print(f"Current memory usage is {current / 10**6} MB; Peak was {peak / 10**6} MB") print(f"Time: {(time_end - time_start) * 1000} ms") if A == 1: states = searchReturn[0] path = searchReturn[1] elif A == 2: path = searchReturn[2] path.reverse() path_str = ','.join(path) if A == 1: print(f'States explored: {states}') elif A == 2: print(f'States explored: {rbfs_states}') print(f'Path: {path_str}') print(f'Depth: {len(path_str) - path_str.count(",")}') output(path_str, outputPath) else: print('Failure') inF.close() if __name__ == '__main__': main()
def read_numbers(): numbers = [ int(i) for i in input().split(' ') ] return numbers def num_sum(x): sum = 0 while x > 0: sum += x % 10 x //= 10 return sum def good_time(hh, mm): hh_sum = num_sum(hh) mm_sum = num_sum(mm) return hh_sum != mm_sum def solution(hour, minutes): hour.sort() minutes.sort() retval = [] for hh in hour: for mm in minutes: if good_time(hh, mm): retval.append('{:02d}:{:02d}'.format(hh, mm)) return retval def main(): hour = read_numbers() minutes = read_numbers() result = solution(hour, minutes) print('\n'.join(result)) main()
''' Write a program to evaluate poker hands and determine the winner Read about poker hands here. https://en.wikipedia.org/wiki/List_of_poker_hands ''' def sort(hand): ''' appending face values into a list ''' newlist = [] for character in hand: if character[0] == 'A': newlist.append(14) elif character[0] == 'K': newlist.append(13) elif character[0] == 'Q': newlist.append(12) elif character[0] == 'J': newlist.append(11) elif character[0] == 'T': newlist.append(10) else: newlist.append(int(character[0])) return newlist def is_straight(hand): ''' How do we find out if the given hand is a straight? The hand has a list of cards represented as strings. There are multiple ways of checking if the hand is a straight. Do we need both the characters in the string? No. The first character is good enough to determine a straight Think of an algorithm: given the card face value how to check if it a straight Write the code for it and return True if it is a straight else return False ''' count = 0 sor_lis = sorted(sort(hand)) for i in range(len(sor_lis)-1): if int(sor_lis[i+1]) - int(sor_lis[i]) == 1: count += 1 if count+1 == len(sor_lis): return True return False def is_flush(hand): ''' How do we find out if the given hand is a flush? The hand has a list of cards represented as strings. Do we need both the characters in the string? No. The second character is good enough to determine a flush Think of an algorithm: given the card suite how to check if it is a flush Write the code for it and return True if it is a flush else return False set_ = set() for face, suite in hand: set_.add(suite) return ''' char = hand[0][1] count = 0 for character in hand: if character[1] == char: count += 1 if count == len(hand): return True return False # for x, y in range(5): # if lis[][y] == lis[][y+1]: # return True # else: # return False def is_fourofakind(hand): ''' if the four face values in a hand are same then the hand will be four of a kind ''' count = 0 sor_lis = sorted(sort(hand)) for i in range(len(sor_lis)-3): if sor_lis[i] == sor_lis[i+1] == sor_lis[i+2] == sor_lis[i+3]: count += 1 if count == 1: return True return False def is_threeofakind(hand): ''' if the three face values in a hand are same then the hand will be three of a kind ''' count = 0 sor_lis = sorted(sort(hand)) for i in range(len(sor_lis)-2): if sor_lis[i] == sor_lis[i+1] == sor_lis[i+2]: count += 1 if count == 1: return True return False def is_onepair(hand): ''' if face values of one pair of cards in a hand is equal then hand is daid to be one pair ''' new_lis = [] for character in hand: if character[0] == 'A': new_lis.append(float(0.14)) elif character[0] == 'K': new_lis.append(float(0.13)) elif character[0] == 'Q': new_lis.append(float(0.12)) elif character[0] == 'J': new_lis.append(float(0.11)) elif character[0] == 'T': new_lis.append(float(0.10)) else: new_lis.append(float(character[0])/float(100)) sor_lis = sorted(new_lis) # print(sor_lis) new = [] for i in sor_lis: if sor_lis.count(i) == 2: new.append(i) # print(new) if len(new) == 0: return False maximum = max(new) # print(maximum) return (maximum + 1) def is_twopair(hand): ''' if face values of two pair of cards in a hand is equal then hand is daid to be one pair ''' sor_lis = sorted(sort(hand)) set_list = set(sor_lis) if len(sor_lis) - len(set_list) == 2: return True return False def is_fullhouse(hand): ''' three face values and two face values must be equal in a hand ''' # count = 0 i = 0 sor_lis = sorted(sort(hand)) # for i in range(len(sor_lis)): new = [] if sor_lis[i] == sor_lis[i+1] == sor_lis[i+2] and sor_lis[i+3] == sor_lis[i+4]: # count += 1 new.append(sor_lis[i]) elif sor_lis[i] == sor_lis[i+1] and sor_lis[i+2] == sor_lis[i+3] == sor_lis[i+4]: # count += 1 new.append(sor_lis[i+2]) if len(new) == 0: return False maximum = max(new)/100 return maximum+7 def is_highcard(hand): new_lis = [] for character in hand: if character[0] == 'A': new_lis.append(float(0.14)) elif character[0] == 'K': new_lis.append(float(0.13)) elif character[0] == 'Q': new_lis.append(float(0.12)) elif character[0] == 'J': new_lis.append(float(0.11)) elif character[0] == 'T': new_lis.append(float(0.10)) else: new_lis.append(float(character[0])/float(100)) return max(new_lis) def hand_rank(hand): ''' You will code this function. The goal of the function is to return a value that max can use to identify the best hand. As this function is complex we will progressively develop it. The first version should identify if the given hand is a straight or a flush or a straight flush. ''' if is_flush(hand) and is_straight(hand): return 8 if is_fullhouse(hand): return is_fullhouse(hand) if is_flush(hand): return 6 if is_straight(hand): return 5 if is_fourofakind(hand): return 4 if is_threeofakind(hand): return 3 if is_twopair(hand): return 2 if is_onepair(hand): return is_onepair(hand) return is_highcard(hand) # By now you should have seen the way a card is represented. # If you haven't then go the main or poker function and print the hands # Each card is coded as a 2 character string. Example Kind of Hearts is KH # First character for face value 2,3,4,5,6,7,8,9,T,J,Q,K,A # Second character for the suit S (Spade), H (Heart), D (Diamond), C (Clubs) # What would be the logic to determine if a hand is a straight or flush? # Let's not think about the logic in the hand_rank function # Instead break it down into two sub functions is_straight and is_flush # check for straight, flush and straight flush # best hand of these 3 would be a straight flush with the return value 3 # the second best would be a flush with the return value 2 # third would be a straight with the return value 1 # any other hand would be the fourth best with the return value 0 # max in poker function uses these return values to select the best hand def poker(hands): ''' This function is completed for you. Read it to learn the code. Input: List of 2 or more poker hands Each poker hand is represented as a list Print the hands to see the hand representation Output: Return the winning poker hand ''' # the line below may be new to you # max function is provided by python library # learn how it works, in particular the key argument, from the link # https://www.programiz.com/python-programming/methods/built-in/max # hand_rank is a function passed to max # hand_rank takes a hand and returns its rank # max uses the rank returned by hand_rank and returns the best hand return max(hands, key=hand_rank) if __name__ == "__main__": # read the number of test cases COUNT = int(input()) # iterate through the test cases to set up hands list HANDS = [] for x in range(COUNT): line = input() ha = line.split(" ") HANDS.append(ha) # test the poker function to see how it works print(' '.join(poker(HANDS)))
''' Document Distance - A detailed description is given in the PDF ''' import re import math FILE_NAME = "stopwords.txt" def similarity(dict1, dict2): ''' Compute the document distance as given in the PDF ''' lis = dict1.lower().split() lis1 = [] for word in lis: lis1.append(re.sub('[^a-zA-Z]', '', word.strip())) temp1 = lis1[:] for word in temp1: if word in load_stopwords(FILE_NAME): lis1.remove(word) for word in lis1: if not word: lis1.remove(word) dic_t1 = {} for word in lis1: count = 0 for char in lis1: if word == char: count += 1 dic_t1[word] = count pis = dict2.lower().split() lis2 = [] for word in pis: lis2.append(re.sub('[^a-zA-Z]', '', word.strip())) temp2 = lis2[:] for word in temp2: if word in load_stopwords(FILE_NAME): lis2.remove(word) for word in lis2: if not word: lis2.remove(word) dic_t2 = {} for word in lis2: count = 0 for char in lis2: if word == char: count += 1 dic_t2[word] = count key = set(list(dic_t2.keys()) + list(dic_t1.keys())) dic_t3 = {} for keys in key: dic_t3[keys] = [0, 0] for key in dic_t1: dic_t3[key][0] = dic_t1[key] for key in dic_t2: dic_t3[key][1] = dic_t2[key] numerator = 0 for key in dic_t3: numerator += dic_t3[key][0]*dic_t3[key][1] dem1 = 0 dem2 = 0 for key in dic_t3: dem1 += dic_t3[key][0]**2 dem2 += dic_t3[key][1]**2 denominator = math.sqrt(dem1)*math.sqrt(dem2) similar = numerator/denominator return similar def load_stopwords(file_name): ''' loads stop words from a file and returns a dictionary ''' stopwords = {} with open(FILE_NAME, 'r') as file_name: for line in file_name: stopwords[line.strip()] = 0 return stopwords def main(): ''' take two inputs and call the similarity function ''' input1 = input() input2 = input() print(similarity(input1, input2)) if __name__ == '__main__': main()
# Write a python program to find the square root of the given number # using approximation method # testcase 1 ''' # input: 25 # output: 4.999999999999998 # testcase 2 # input: 49 # output: 6.999999999999991 ''' def main(): ''' to find out square root of a number using approximation ''' s_i = int(input()) epsilon_i = 0.01 guess_i = 0.0 i_i = 0.1 while abs(guess_i**2-s_i) >= epsilon_i and guess_i <= s_i: guess_i += i_i if abs(guess_i**2-s_i) >= epsilon_i: print("failed") else: print(str(guess_i)) if __name__ == "__main__": main()
''' #Exercise : Function and Objects Exercise-3 #Implement a function that converts the given testList = [1, -4, 8, -9] into [1, 16, 64, 81] ''' def applyto_each(l_i, f_i): ''' input: int or float returns int or float ''' for i_i in range(len(l_i)): l_i[i_i] = square(l_i[i_i]) return l_i def square(a_i): ''' calculating square ''' return a_i*a_i def main(): ''' giving input as list ''' data = input() data = data.split() list1 = [] for j in data: list1.append(int(j)) print(applyto_each(list1, square)) if __name__ == "__main__": main()
# Work with Pandas and data munging import pandas as pd df = pd.read_csv('https://raw.githubusercontent.com/fantasydatapros/data/master/fantasypros/fp_projections.csv') #iloc shows us which [columns, rows] to look at. In this case, all columns, and all but the first row df = df.iloc[:, 1:] #defining columns we care to see base_columns = ['Player', 'Team', 'Pos'] QB_columns = ['PassingAtt', 'PassingCmp', 'PassingTD', 'FantasyPoints'] RB_columns = ['RushingAtt', 'RushingYds', 'RushingTD', 'Receptions', 'ReceivingYds', 'ReceivingTD'] WR_columns = ['Receptions', 'ReceivingYds', 'ReceivingTD'] # 'Pos' could be changed, would have to add that positions relative columns # New dataframe is made of just QB's qb_df = df.loc[(df['Pos'] == 'QB'), base_columns + QB_columns] wr_df = df.loc[(df['Pos'] == 'WR'), base_columns + WR_columns] rb_df = df.loc[(df['Pos'] == 'RB'), base_columns + RB_columns] te_df = df.loc[(df['Pos'] == 'TE'), base_columns + WR_columns] #Can change the 'by' to sort by preferred category #print(qb_df.sort_values(by = 'PassingAtt', ascending = False).head(10)) #print(wr_df.sort_values(by = 'ReceivingTD', ascending = False).head(25)) #print(rb_df.sort_values(by = 'Receptions', ascending = False).head(15)) print(te_df.sort_values(by = 'Receptions', ascending = False).head(10)) ## or take them away
# -*- coding: utf-8 -*- import numpy def printGraph(graph): k=0 for k in range(0,len(graph)): print graph[k] t,b,f,c = raw_input("Enter t b f c: ").strip().split(' ') #Input the tree, backward, forward and cross edges t,b,f,c = [int(t),int(b),int(f),int(c)] #Convert the strings to ints. n = t+1 graph = numpy.zeros(shape=(n,n)) #Rows are existing Nodes. Columns are its connections with other nodes. #Create tree edges r = 0 while t>0: if(t >= 1 and r==0): graph[0][1] = 1 t -= 1 if(t >= 1 and r==0): graph[0][2] = 1 t -= 1 r == 2 for i in range(2,n - 1): graph[i][i+1] = 1 t -= 1 #Create backward edges j = n - 1 i = 1 while b>0: if (j-i != 1): graph[j][j-i] = 1 i += 1 b -= 1 elif (j-i == 1): graph[j][0] = 1 i += 1 b -= 1 else: i += 1 if (i==j): i = 1 j -= 1 #Create forward edges u = n - 1 d = 0 while f>0: if (u!= (2 or d+1)): graph[d][u] = 1 u -= 1 f -= 1 else: if(d==0): d += 2 else: d += 1 u = n - 1 #Create cross edges j = n-1 while c>0: if j == 1: j -= 1 continue graph[1][j] = 1 j -= 1 c -= 1 printGraph(graph) print n k = 0 h = 0 edge = 0 for k in range(0, n): l =" " for h in range(0, n): if graph[k][h] == 1 : l += str(h+1) + " " edge +=1 l = str(edge) + l print l edge = 0
from random import uniform from math import pi, sqrt #Using 2 random numbers from the range of 0-1 calculate/estimate pi def pi_estimate(n): x = uniform(0,1) y = uniform(0,1) distance = x**2 + y**2 total_square = 0 total_circle = 0 #Formula of square area = 4r #Formula of circle = PI r^2 #The ratio of the total square area/total circle area will be pi for i in range (n): if distance <= 1: total_circle += 1 total_square += 1 pie = total_square/total_circle print(pie) pi_estimate(10000)
#MID-SESSION TAKE HOME QUIZ - DICTIONARY & FILE I/0 EXERCISES #Miranda Remmer #2.17 import string MIDSESSION_file = open ("midreviewfile2.txt") words = MIDSESSION_file.read() MIDSESSION_file.close() punctuation = string.punctuation digits = string.digits def clean_text(file): return [word.strip(punctuation) for line in file for word in line.split()] def word_count (file): word_count_dictionary = {} file = file.lower() file_split = clean_text(file.split()) for word in file_split: if (word not in punctuation) and (word not in digits): if (word not in word_count_dictionary): word_count_dictionary[word] = 1 else: word_count_dictionary[word] += 1 return word_count_dictionary with open("midreviewfile.txt") as MIDSESSION_file: midsession_dictionary = word_count(words) for key, value in sorted(midsession_dictionary.items()): print key, ":", value #maybe add a function to remove certain instances where punctuation within a word exists (e.g. miranda's document - remove ''s')?
#!/usr/bin/env python # digits_overlay.py # # Copyright(c) Exequiel Ceasar Navarrete <esnavarrete1@up.edu.ph> # Licensed under MIT # Version 1.0.1 import os import cv2 from app import recognize_characters # function to filter out contours on an image def filter_contours(contour): # get rectangle bounding contour [_, _, w, h] = cv2.boundingRect(contour) # remove any small contours present if h < 40 or w < 40: return False return True # read the image image = os.path.join(os.getcwd(), "assets/img/digits-overlay.jpg") cv_image = cv2.imread(image) # convert to grayscale gray_image = cv2.cvtColor(cv_image, cv2.COLOR_BGR2GRAY) # apply some thresholding to convert to binary image (inverted) _, thresh = cv2.threshold(gray_image, 150, 255, cv2.THRESH_BINARY_INV) # apply some morphological operation (dilation) kernel = cv2.getStructuringElement(cv2.MORPH_CROSS, (3, 3)) dilated = cv2.dilate(thresh, kernel, iterations=5) # box out all possible characters present in the image num_characters = recognize_characters(dilated, cv_image, random_shape_color=True, filter_fn=filter_contours) print(f"Number of Boxes/Connected Components: {num_characters}") cv2.imshow('Output', cv_image) cv2.waitKey(0) cv2.destroyAllWindows()
# collections are of 3 types # 1. List # 2. Set - same as list, but no dupplicates # 3. Dictionary - contains list with key, value pair str1 = " this is first string " print(str1) str2 = "this is second string" print(len(str1)) # indexing print(str1[10]) # repetition print(str1*3) # slicing print(str2[0:10]) print(str1[0:]) print(str2[:9]) print(str1[-3:-10]) # step in slicing print(str1[0:19:3]) print(str1[20::-2]) # stripping spaces, string, lstrip, rstrip print(str1.strip()) # find string print(str1.find("first")) print(str1.find("first", 0, 8)) # count occurrences print(str1.count("is")) # replace string print(str1.replace("is", "XX", 1))
#import this """This is the data definition class for regex_list. regex_list takes a list of strings and makes it searchable. Searchable meaning you can find which elements in the list have a pattern. you could add the '+' to the add word. Remember seq is a subset of word """ import itertools import timeit def timer(val): """times""" start=timeit.default_timer() ff.find_matches(val) stop=timeit.default_timer() return stop-start class Regex_list(object): """this will make your word list searchable. Note, It will also loose the original order of the list.""" def __init__(self, lis): assert hasattr(lis,"__iter__") self.all_words = set() self.search_dict = dict() for word in set(lis):self.add_word(word) #self.calculateFreqs() def add_word(self,word): """this will add a word to the search_dict search dict is of the form: {letter:{nextletter:{(index,word)}}} """ assert type(word) is str#or isinstance(word,str) assert word not in self.all_words#already have it! assert "+" not in word if "." in word: print("you shouldn't have a '.' but suit yourself") self.all_words.add(word) word="+"+word+"+"#helps find words that start/end with the pattern #doesn't interfere with patterns that dont have "+" at start/end for index,val in enumerate(word[:-1]): next_letter = self.search_dict.setdefault(val,dict()) words_list = next_letter.setdefault(word[index+1],set())#object modification words_list.add((index,word))#object modifification def find_matches(self,seq): """finds all the words in the list with this sequence. Uses '.' as wildcard. (remember it only finds exact matches)""" assert len(seq)>=2 s_d = self.search_dict finalSetPairs=list() while seq[-1]=='.' and len(seq)>2:#problem """not solved by if index+1=='.' because there's no [letter][''] for word endings in self.search_dict. #without this, ".f." wouldn't find (0,"of"), because the L_m in the seq[index+1]=="." if wouldn't include it. #the len>2 is needed to find sequences matches that are like "f." despite these improvements, 1 letter sequences still won't be found. but they're obvious... worst case, just search self.all_words for them Note, "of" isnt an exact match with ".f." but I thought it'd be good to include. """ seq = seq[:-1] for index,letter in enumerate(seq[:-1]): if not(letter=="." and seq[index+1]=="."):#no point if they all match... if letter==".": L_m = set.union(*(i.get(seq[index+1],set()) for i in s_d.values())) #.get is important here. not all i's have i[seq[index+1]] elif seq[index+1]==".": L_m = set.union(*s_d[letter].values()) else: L_m = s_d[letter].get(seq[index+1],{})#this is a set. #not using s_d.get could cause errors here... #L_m==letter_matches finalSetPairs.append([index,L_m]) s2=self.fast_intersection(finalSetPairs) return s2 def fast_intersection(self,finalSetPairs): """needs work ff.find_matches("g..rs") really not sure what the problem is... theres a string of enumerates here that are complicated but provid speed """ sorted_pairs=sorted(finalSetPairs,key=lambda x: len(x[1])) thisSet=sorted_pairs[0][1] for index,pair in enumerate(sorted_pairs[1:]): offset=(pair[0]-sorted_pairs[index][0]) #note: sorted_pairs[1:][index-1][0]== sorted_pairs[index][0] thisSet={(i+offset,word) for i,word in thisSet} thisSet.intersection_update(pair[1]) return thisSet def find_scrabble_strings(self,seq): """you need to test this. Finds all combinations of seq that you could play on in scrabble delimited with '.' (meaning the spaces on the board are '.' """ listSeqs=seq.split(".") seqSets=set() for comb in itertools.combinations(range(len(listSeqs)),2): MIN=min(comb) MAX=max(comb) seqSets.add((MIN>0)*"+"+".".join(listSeqs[MIN:MAX+1])+(MAX<(len(listSeqs)-1))*"+") seqSets=filter(lambda x:len(x.replace("+",""))>1,seqSets) #at least 2 searchable characters seqSets=filter(lambda x:len(x.replace(".","").replace("+",""))>=1,seqSets) #at least 1 actual letter return set(seqSets) def new_scrabble(self,seq): """finds the scrabble matches for example in scrabble, "of" would fit +.f..g.k+ """ assert "+" not in seq[1:-1] setsList=list() seqs=self.find_scrabble_strings(seq) for seq in seqs: setsList.append(self.find_matches(seq)) return set.union(*setsList) if __name__=="__main__": from scrabble import make_words_list d = make_words_list() ff = Regex_list(d) L = ff.new_scrabble(".f") #with "..f" (-1,'of')
import numpy as np from .fastmath import inv3, matvec __all__ = [ 'normalized', 'veclen', 'sq_veclen', 'scaled', 'dot', 'project', 'homogenize', 'dehomogenize', 'hom', 'dehom', 'ensure_dim', 'hom3', 'hom4', 'transform', 'convert_3x4_to_4x4', 'to_4x4', 'assemble_4x4', 'assemble_3x4', 'inv_3x4', ] ARR = np.asanyarray def normalized(vectors): """ normalize vector(s) such that ||vectors|| == 1 """ vectors = ARR(vectors) lengths = veclen(vectors) return vectors / lengths[..., np.newaxis] def veclen(vectors): """ calculate euclidean norm of a vector or an array of vectors when an nd-array is given, then the norm is computed about the last dimension """ return np.sqrt(np.sum(ARR(vectors)**2, axis=-1)) def sq_veclen(vectors): """ calculate squared euclidean norm of a vector or an array of vectors when an nd-array is given, then the norm is computed about the last dimension """ vectors = ARR(vectors) return np.sum(vectors**2, axis=vectors.ndim-1) def scaled(vectors, scale): """ scales vectors such that ||vectors|| == scale """ return normalized(vectors) * ARR(scale)[..., np.newaxis] def dot(v, u): """ pairwise dot product of 2 vector arrays, essentially the same as [sum(vv*uu) for vv,uu in zip(v,u)], that is, pairwise application of the inner product >>> dot([1, 0], [0, 1]) 0 >>> dot([1, 1], [2, 3]) 5 >>> dot([[1, 0], [1, 1]], [[0, 1], [2, 3]]).tolist() [0, 5] """ return np.sum(ARR(u)*ARR(v), axis=-1) def project(v, u): """ project v onto u """ u_norm = normalized(u) return (dot(v, u_norm)[..., np.newaxis] * u_norm) def homogenize(v, value=1): """ returns v as homogeneous vectors by inserting one more element into the last axis the parameter value defines which value to insert (meaningful values would be 0 and 1) >>> homogenize([1, 2, 3]).tolist() [1, 2, 3, 1] >>> homogenize([1, 2, 3], 9).tolist() [1, 2, 3, 9] >>> homogenize([[1, 2], [3, 4]]).tolist() [[1, 2, 1], [3, 4, 1]] >>> homogenize([[1, 2], [3, 4]], 99).tolist() [[1, 2, 99], [3, 4, 99]] >>> homogenize([[1, 2], [3, 4]], [33, 99]).tolist() [[1, 2, 33], [3, 4, 99]] """ v = ARR(v) if hasattr(value, '__len__'): return np.append(v, ARR(value).reshape(v.shape[:-1] + (1,)), axis=-1) else: return np.insert(v, v.shape[-1], np.array(value, v.dtype), axis=-1) # just some handy aliases hom = homogenize def dehomogenize(a): """ makes homogeneous vectors inhomogenious by dividing by the last element in the last axis >>> dehomogenize([1, 2, 4, 2]).tolist() [0.5, 1.0, 2.0] >>> dehomogenize([[1, 2], [4, 4]]).tolist() [[0.5], [1.0]] """ a = np.asfarray(a) return a[...,:-1] / a[...,np.newaxis,-1] # just some handy aliases dehom = dehomogenize def ensure_dim(a, dim, value=1): """ checks if an array of vectors has dimension dim, and if not, adds one dimension with values set to value (default 1) """ cdim = a.shape[-1] if cdim == dim - 1: return homogenize(a, value=value) elif cdim == dim: return a else: raise ValueError('vectors had %d dimensions, but expected %d or %d' % (cdim, dim-1, dim)) def hom4(a, value=1): return ensure_dim(a, 4, value) def hom3(a, value=1): return ensure_dim(a, 3, value) def transform(v, M, w=1): """ transforms vectors in v with the matrix M if matrix M has one more dimension then the vectors this will be done by homogenizing the vectors (with the last dimension filled with w) and then applying the transformation """ if M.shape[-1] == v.shape[-1] + 1: v1 = matvec(M, hom(v)) if v1.shape[-1] == v.shape[-1] + 1: v1 = dehom(v1) return v1 else: return matvec(M, v) def toskewsym(v): assert v.shape == (3,) return np.array([[0, -v[2], v[1]], [v[2], 0, -v[0]], [-v[1], v[0], 0]]) def convert_3x4_to_4x4(matrices, new_row=[0, 0, 0, 1]): """ Turn a 3x4 matrix or an array of 3x4 matrices into 4x4 matrices by appending the <new_row>. >>> A = np.zeros((3, 4)) >>> convert_3x4_to_4x4(A).shape (4, 4) >>> convert_3x4_to_4x4(A)[3].tolist() [0.0, 0.0, 0.0, 1.0] >>> many_A = np.random.random((10, 20, 3, 4)) >>> many_A_4x4 = convert_3x4_to_4x4(many_A) >>> many_A_4x4.shape (10, 20, 4, 4) >>> many_A_4x4[2, 1, 3].tolist() [0.0, 0.0, 0.0, 1.0] >>> np.all(many_A_4x4[:, :, :3, :] == many_A) True """ assert matrices.shape[-1] == 4 and matrices.shape[-2] == 3 return np.insert(matrices, 3, new_row, axis=-2) to_4x4 = convert_3x4_to_4x4 def assemble_3x4(rotations, translations): """ Given one (or more) 3x3 matrices and one (or more) 3d vectors, create an array of 3x4 matrices >>> rots = np.arange(9).reshape(3, 3) >>> ts = np.array([99, 88, 77]) >>> assemble_3x4(rots, ts) array([[ 0, 1, 2, 99], [ 3, 4, 5, 88], [ 6, 7, 8, 77]]) >>> rots = np.random.random((100, 3, 3)) >>> ts = np.random.random((100, 3)) >>> Ms = assemble_3x4(rots, ts) >>> Ms.shape (100, 3, 4) >>> np.all(Ms[:, :, :3] == rots) True >>> np.all(Ms[:, :, 3] == ts) True """ translations = np.asarray(translations) rotations = np.asarray(rotations) if rotations.ndim not in [2, 3] or rotations.shape[-2:] != (3, 3): raise ValueError("requires rotations argument to be one or more 3x3 matrices, so the shape should be either (3, 3) or (n, 3, 3)") if translations.ndim not in [1, 2] or translations.shape[-1] != 3: raise ValueError("requires translations argument to be one or more 3d vectors, so the shape should be either (3,) or (n, 3)") if rotations.ndim == 2 and translations.ndim == 1: # single translation, single rotation -> output single matrix return np.column_stack((rotations, translations)) else: if rotations.ndim == 2: rotations = rotations[np.newaxis] if translations.ndim == 1: translations = translations[np.newaxis] translations = translations[:, :, np.newaxis] return np.concatenate((rotations, translations), axis=-1) def assemble_4x4(rotations, translations, new_row=[0, 0, 0, 1]): """ Given one (or more) 3x3 matrices and one (or more) 3d vectors, create an array of 4x4 matrices >>> rots = np.arange(9).reshape(3, 3) >>> ts = np.array([99, 88, 77]) >>> assemble_4x4(rots, ts) array([[ 0, 1, 2, 99], [ 3, 4, 5, 88], [ 6, 7, 8, 77], [ 0, 0, 0, 1]]) >>> rots = np.random.random((100, 3, 3)) >>> ts = np.random.random((100, 3)) >>> Ms = assemble_4x4(rots, ts) >>> Ms.shape (100, 4, 4) >>> np.all(Ms[:, :3, :3] == rots) True >>> np.all(Ms[:, :3, 3] == ts) True >>> np.all(Ms[:, 3, :] == np.array([0, 0, 0, 1])) True """ return to_4x4(assemble_3x4(rotations, translations), new_row=new_row) def inv_3x4(matrices): """Given one (or more) 3x4 matrices, converts matrices into common transformation matrices by appending a row (0, 0, 0, 1), then inverts those matrices. Since the inverse will also have the same last row, the returned matrices are also 3x4 >>> X = np.random.random((3, 4)) >>> X_4x4 = to_4x4(X) >>> np.allclose(inv_3x4(X), np.linalg.inv(X_4x4)[:3, :]) True """ if matrices.ndim not in [2, 3] or matrices.shape[-2:] != (3, 4): raise ValueError("requires matrices argument to be one or more 3x4 matrices, so the shape should be either (3, 4) or (n, 3, 4)") R_inv = inv3(matrices[..., :3, :3]) # "rotation" part (upper left 3x3 block) t_inv = matvec(R_inv, -matrices[..., :3, 3]) # "translation" part return assemble_3x4(R_inv, t_inv)
import pygame, sys, math from pygame.locals import * def tree(x, y, length, angle): if(length < 3): return x_top = int(x + math.cos(math.radians(angle)) * length) y_top = int( y - math.sin(math.radians(angle)) * length) pygame.draw.line(DISPLAYSURF, THE_COLOR, (x, y), (x_top, y_top), int(length / 10) + 1) tree(x_top, y_top, int(length/2), angle+30) tree(x_top, y_top, int(length/3), angle+80) tree(x_top, y_top, int(length/1.3), angle+5) tree(x_top, y_top, int(length/1.6), angle-45) pygame.init() # set up the window DISPLAYSURF = pygame.display.set_mode((1800, 1000), 0, 32) pygame.display.set_caption('Little Fractal') BACKGROUND = (50, 100, 50) THE_COLOR = (100, 200, 100) # draw on the surface object DISPLAYSURF.fill(BACKGROUND) tree(500, 1050, 250,90) # rund the game loop while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() pygame.display.update()
# Quiz Quest Component 9 Introduction # To Do # - Ask user if they would like to read the instructions # - if not print introduction # - if yes then go straight to the bulk of the code def string_check(question, to_check): # Loops until a valid answer is given valid = False while not valid: # Asks question response = input(question).lower() for item in to_check: # If the users response is in the list given(to_check) if response == item: # return the response to the main code return response # If the users response is the first letter of one of the items in to_check elif response == item[0]: # return the whole word to the main code return item print("Please enter Yes/No") yes_no_for_string_check = ["yes","no"] # List for string checker print("********* Welcome to the times tables practice program ********* ") # Nice title/welcome displayed # Ask the user if they want to read instructions introduction = string_check("Would you like to read the instructions(Recommended for first time users)", yes_no_for_string_check) # If answer is yes then display introduction if not then continue on with the main code if introduction == "yes": print() print("Instructions \n" "- You can chose the range of numbers of each side of the question \n" "- If you want to do one times tables put the lowest and highest of one side of the equation as the same number\n" "- You can chose to answer questions continuously or set a certain amount of questions you want to answer \n" "- You then have to answer questions until you answer all the questions given or if you enter the exit code(1111)") print() # Stops the rest of the code appearing so that the user can read the instructions input("Press <enter> to continue")
# Quiz Quest Component 8 ask user if they want to play again # To Do # - Ask user if they want to play again # - if yes code loops again # - if no then code ends def string_check(question, to_check): # Loops until a valid answer is given valid = False while valid == False: # Asks question response = input(question).lower() for item in to_check: # If the users response is in the list given(to_check) if response == item: # return the response to the main code return response # If the users response is the first letter of one of the words in to_check elif response == item[0]: # return the whole word to the main code return item print("Please enter Yes/No") yes_no_for_string_check = ["yes", "no"] keepgoing = "yes" while keepgoing == "yes": keepgoing = string_check("Would you like to play again(Yes or No)",yes_no_for_string_check)
import unittest from homework5.homework5_functions_to_test import check_isIntercalary, check_is_triangle, check_type_triangle class TestIsYearLeap(unittest.TestCase): def test_leap_year(self): year = 2000 res = check_isIntercalary(year) self.assertTrue(res, "True") class TestIsTriangle(unittest.TestCase): def test_is_triangle(self): a = 3 b = 4 c = 5 res = check_is_triangle(a, b, c) self.assertTrue(res, "True") class TestTypeOfTriangle(unittest.TestCase): def test_type(self): a = 4 b = 4 c = 5 res = check_type_triangle(a, b, c) self.assertTrue(res, "Equilateral triangle.") if __name__ == "__main__": unittest.main()
from homework4.homework4 import only_alphabet #5.1 Создайте список 2 в степени N, где N от 0 до 20. rez = [2**n for n in range(0, 20)] print(rez) #5.2 У вас есть список целых чисел. Создайте новый список остатков от деления на 3 чисел из исходного списка. rez = [0, 1, 3, 5, 6, 8, 9, 10, 11] new_rez = [n % 3 for n in rez] print(new_rez) #5.3 У вас есть список, в котором могут быть разные типы данных. Создайте новый список только чисел из этого списка. l =[1, "2", "string some", True, "asaa", "123some text!!! 12", "Hello! what???", 4.67, ["fff", 56]] l = [x for x in l if (type(x) == int or type(x) == float)] print(l) # 5.4 У вас есть список, в котором могут быть разные типы данных. Создайте новый список только строк, при этом удалите # усе небуквенные символы из них. Воспользуйтесь функцией из предыдущего задания # (импортируйте её из другого своего файла) l_in = [1, "2", "string some", True, "asaa", "123some text!!! 12", "Hello! what???"] l_out = [''.join(x for x in string if x.isalpha()) for string in l_in if type(string) == str] print(l_out) #second variant l_in = [1, "2", "string some", True, "asaa", "123some text!!! 12", "Hello! what???"] l_out1 = [x for x in [only_alphabet(string) for string in l_in if type(string) == str] if x != ''] print(l_out1) #У вас есть словарь – характеристик человека. Ключи например: “name”, “surname”, “age”, “position”, “address”, “skills”. #Сгенерируйте новый словарь с такими же ключами, а в значениях типы значений. d = {"name": "Natasha", "surname": "Tiutiunnyk", "age": 65, "position": "QA engineer", "address": "Kyiv some str.566", "skills": ["smart", "sadsad", "dfsd"]} d1 = {k: type(v) for k, v in d.items()} print(d1) # Сгенерируйте новый словарь с только парами ключ-значение, если значение исходного словаря было строкой. # Значения нового словаря должны быть переведены в нижний регистр и удалены всё небуквенные символы из них. d = {k: only_alphabet(d[k].lower()) for k in d if type(d[k]) == str} print(d)
def starts_with_a_vowel(word): return word[0] in "AEIOU" x = starts_with_a_vowel("Iggi") print x names = ["Alice", "Bob", "Cara", "Editch"] namesArr = [name.lower() for name in names] print "HEY this is name ARR: " + str(namesArr) def filter_to_vowel_words(word_list): vowel_words = [] for word in word_list: if starts_with_a_vowel(word): vowel_words.append(word) return vowel_words print filter_to_vowel_words(names)
# A palindromic number reads the same both ways. # The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 99. # Find the largest palindrome made from the product of two 3-digit numbers. # Brute force solution s = 0 for i in range(100, 1000): for j in range(100, 1000): x = i * j if str(x) == str(x)[::-1] and x > s: s = x c = [i, j] print s, c # faster solution?
import random as r import matplotlib.pyplot as plt class SpellingBeeContestant: _knowledge = 0 def __init__(self, percentage_knowledge): self._knowledge = percentage_knowledge def get_knowledge(self): return self._knowledge def __str__(self): return str(self._knowledge) def setup_spelling_bee(incrementation_bool : bool): players = [] for i in range(0, 10): if incrementation_bool: players.append(SpellingBeeContestant(90 + i)) else : players.append(SpellingBeeContestant(99 - i)) return players def test_player(player : SpellingBeeContestant): return player.get_knowledge() >= r.randint(1, 100) def run_spelling_bee(increment_bool): players = setup_spelling_bee(increment_bool) while True: for player in players: if not test_player(player): players.remove(player) if len(players) == 1: return players[0] def simulate_several_bees(amount, incrementation_bool): wincount = [0 for i in range(10)] for i in range(amount): wincount[run_spelling_bee(incrementation_bool).get_knowledge() - 90] += 1 return [x / amount for x in wincount] def graph_wins(win_count_list : list): labels = [str(i) for i in range(90, 100)] winpct = win_count_list plt.bar(labels, winpct) plt.ylabel('Win Share') plt.title('Win Share by incrementing order') plt.show() graph_wins(simulate_several_bees(10000, False))
import random def sel(arr): for i in range(0,len(arr)-1): min_index=i for j in range(i+1,len(arr)): if arr[j] < arr[min_index]: min_index=j arr[i], arr[min_index] = arr[min_index],arr[i] print("정렬중",arr) arr = list() for i in range(10): arr.append(random.randint(1,100)) print("처음 리스트 : ",arr) sel(arr) print("선택 정렬 후 리스트 : ",arr)
# -*- coding: utf-8 -*- """列隊""" class Queue(object): """ 列隊類別 為先進先出的資料結構 """ def __init__(self): self.items = [] def enqueue(self, item): """ 新增資料 從尾部入列資料 """ self.items.append(item) def dequeue(self): """ 移除資料 從頭部出列資料 """ if not self.is_empty(): return self.items.pop(0) return False def front(self): """ 返回最先入隊的資料 """ if self.is_empty(): return self.items[0] return False def clear(self): """ 清空該列隊實例 """ self.items = [] def size(self): """ 返回列隊大小 """ return len(self.items) def is_empty(self): """ 判斷列隊長度是否等於小於0 """ return self.size() <= 0 def preview(self): """ 列舉出列隊資料 """ for item in self.items: print(item) # practice class PriorityItem(object): """ 優先列隊項目類別 額外存放了優先等級 """ def __init__(self, item, priority): self.item = item self.priority = priority def get_item(self): """ 返回該項目 """ return self.item def get_priority(self): """ 返回該項目的優先等級 """ return self.priority class PriorityQueue(Queue): """ 優先列隊類別 繼承自普通列隊類別 """ def __init__(self): Queue.__init__(self) def enqueue(self, item, priority=0): """ 推入資料至列隊 優先等級的排序為,數字越大越前面 """ if self.is_empty(): return self.items.append(PriorityItem(item, priority)) for i in range(0, self.size()): if priority > self.items[i].get_priority(): self.items[i:i] = [PriorityItem(item, priority)] break else: self.items.append(PriorityItem(item, priority)) def preview(self): """ 覆蓋print方法 """ for item in self.items: print('Item: {}, Priority: {}'.format( item.get_item(), item.get_priority() )) def hot_potato(members, number): """ 傳遞練習 每次遍歷項目時,數字都減一 當數字為0時,將該位置的項目出列 直到剩下一個玩家為止 """ queue = Queue() for member in members: queue.enqueue(member) while queue.size() is not 1: counter = number while counter > 0: counter -= 1 queue.enqueue(queue.dequeue()) print("{} get out.".format(queue.dequeue())) print("{} is winner!".format(queue.dequeue())) if __name__ == '__main__': print('Normal Queue') print('-------------') normal_queue = Queue() normal_queue.enqueue("Han") normal_queue.enqueue("Jackie") normal_queue.enqueue("Oda") normal_queue.enqueue("Sabra") normal_queue.preview() print('') print('Priority Queue') print('-------------') prio_queue = PriorityQueue() prio_queue.enqueue("Jay", 3) prio_queue.enqueue("Abbey") prio_queue.enqueue("Kevin", 3) prio_queue.enqueue("Ben", 1) prio_queue.enqueue("Sam", 4) prio_queue.enqueue("Hai", 3) prio_queue.enqueue("Ken", 2) prio_queue.preview() print('') print('Hot Potato') print('-------------') hot_potato(['Jay', 'Abbey', 'Kevin', 'Ben', 'Sam', 'Hai', 'Ken'], 7)
# -*- coding: utf-8 -*- """插入排序法""" def insertion_sort(original_list): """ 透過遍歷陣列中元素 並將當前元素的位置和值暫存起來 當遍歷進行時,依序比較前面的元素 如前一個元素大於當前元素,則將前一個元素放入當前的位置(當前元素依然存放在暫存中) 在遍歷結束後,將放在暫存中的當前元素放在最小的位置上(最小的位置為結束迴圈時的索引) 效率尚可 """ new_list = original_list[:] for i, val in enumerate(new_list): curr_index = i while curr_index > 0 and new_list[curr_index - 1] > val: new_list[curr_index] = new_list[curr_index - 1] curr_index -= 1 new_list[curr_index] = val return new_list EXAMPLE = [12, 22, 5, 3, 25, 33, 45, 10, 16, 20] print(insertion_sort(EXAMPLE))
# -*- coding: utf-8 -*- """合併排序法""" def merge_sort(original_list): """ 為分治演算法的一種 需以遞迴排列 算是常用的排序演算法 """ return merge_recursive(original_list) def merge_recursive(sub_list): """ 將陣列進行對切 直至長度為1為止,才對分割後的左右兩邊進行合併 """ list_len = len(sub_list) if list_len <= 1: return sub_list mid = list_len // 2 left = sub_list[:mid] right = sub_list[mid:] return merge_list(merge_recursive(left), merge_recursive(right)) def merge_list(left, right): """ 在合併的同時進行排序 合併前判斷較小一方,並將其推入結果陣列 之後將該方索引變數加一 當有某一方的索引變數不再小於長度時 代表該方的陣列已被推入結果陣列 這時將另一方的陣列依序推入結果陣列(雙方都已經排序過) 最後返回結果陣列 """ result = [] l_c = 0 r_c = 0 while l_c < len(left) and r_c < len(right): if left[l_c] < right[r_c]: result.append(left[l_c]) l_c += 1 else: result.append(right[r_c]) r_c += 1 while l_c < len(left): result.append(left[l_c]) l_c += 1 while r_c < len(right): result.append(right[r_c]) r_c += 1 return result EXAMPLE = [12, 22, 5, 3, 25, 33, 45, 10, 16, 20] print(merge_sort(EXAMPLE))
import sys import csv from cs50 import SQL def main(): db = SQL("sqlite:///students.db") house = sys.argv[1] if (len(sys.argv) != 2): print("enter 1 command line argument") return 1 list = db.execute("select first, middle, last, house, birth from students where house = ? order by last", house) for item in list: print(item['first'], item['last'], 'born', item['birth']) main()
def future_ages(): # Name name = input("What's your name? ") # Age while True: year_born = input("What year were you born? ") try: year_born = int(year_born) except ValueError: continue else: break # The Facts current_year = 2018 now_age = current_year - int(year_born) ages = [25, 50, 75, 100] # Holy crap! Now way! Am I really that old! for age in ages: if now_age < age: future_age_year = (age - now_age) + current_year response = "{}, you'll be {} in {}.".format(name, age, future_age_year) print(response) else: continue
''' Objective: Return an array consisting of the largest number from each provided sub-array. >>> largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]) [5, 27, 39, 1001] >>> largestOfFour([[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]]) [27, 5, 39, 1001] >>> largestOfFour([[4, 9, 1, 3], [13, 35, 18, 26], [32, 35, 97, 39], [1000000, 1001, 857, 1]]) [9, 35, 97, 1000000] >>> largestOfFour([[-4, -9, -10, -3], [-13, -35, -18, -26], [-32, -35, -97, -39], [-1000000, -1001, -857, -1]]) [-3, -13, -32, -1] ''' def largestOfFour(list_of_lists: list) -> list: largest = [max(num) for num in list_of_lists] return largest
class Cloud: # __setattr__: same as cloud.color='pink' def __setattr__(self, name, value): self.__dict__[name] = value.upper() cloud = Cloud() cloud.color = 'pink' print ('cloud.color:', cloud.color)
import unittest def FuncAddNumber(first, second): result = first + second return result class addTestCase(unittest.TestCase): def test_add_func1(self): result = FuncAddNumber(3,5) self.assertEqual(result, 8) def test_add_func1(self): result = FuncAddNumber(6,7) self.assertEqual(result, 13) unittest.main()
# Importing essential packages from tkinter import * import tkinter.messagebox import sqlite3 class Add: def __init__(self, parent): # Window Initialization self.register_window = Toplevel(parent) self.register_window.title("Redline | Add Blood") self.register_window.geometry("500x550") self.name = StringVar() self.age = IntVar() self.add = StringVar() self.quantity = IntVar() self.var = StringVar() self.mob = IntVar() # Database Info self.connection = sqlite3.connect("Blood.db") self.tablename = "blood_bank" # Heading lbl_0 = Label(self.register_window, text="Add Blood", bg="grey", width="300", height="2", font=("Calibri", 18), fg="white" ).pack() Label(self.register_window, text="").pack() # Name lbl_1 = Label(self.register_window, text="Enter the Name", font=("bold", 8)).pack() entry_1 = Entry(self.register_window, textvar=self.name).pack(pady=(0, 20)) # Age lbl_2 = Label(self.register_window, text="Enter the Age", font=("bold", 8)).pack() entry_2 = Entry(self.register_window, textvar=self.age).pack(pady=(0, 20)) # Quantity lbl_21 = Label(self.register_window, text="Enter the Quantity", font=("bold", 8)).pack() entry_21 = Entry(self.register_window, textvar=self.quantity).pack(pady=(0, 20)) # Address lbl_3 = Label(self.register_window, text="Enter the Address", font=("bold", 8)).pack() entry_3 = Entry(self.register_window, textvar=self.add).pack(pady=(0, 20)) # Blood group - Radio buttons lbl_4 = Label(self.register_window, text="Chose the Blood Group", font=("bold", 8)).pack() r1 = Radiobutton(self.register_window, text="A Positive", padx=5, variable=self.var, value="A+").pack() r2 = Radiobutton(self.register_window, text="B Positive", padx=15, variable=self.var, value="B+").pack() r3 = Radiobutton(self.register_window, text="O Positive", padx=30, variable=self.var, value="O+").pack() r4 = Radiobutton(self.register_window, text="A Negative", padx=30, variable=self.var, value="A-").pack() r5 = Radiobutton(self.register_window, text="B Negative", padx=30, variable=self.var, value="B-").pack() r6 = Radiobutton(self.register_window, text="O Negative", padx=30, variable=self.var, value="O-").pack() r7 = Radiobutton(self.register_window, text="AB Positive", padx=30, variable=self.var, value="AB+").pack() r8 = Radiobutton(self.register_window, text="AB Negative", padx=30, variable=self.var, value="AB-").pack(pady=(0, 20)) # Mobile number lbl_5 = Label(self.register_window, text="Enter the Mobile Number", font=("bold", 8)).pack() entry_5 = Entry(self.register_window, textvar=self.mob).pack(pady=(0, 20)) # Submit Button Button(self.register_window, text="Submit", width=20, bg="brown", fg="white", command=self.add_data).pack() def add_data(self): print("Accessing the database . . ") # Get values for adding name = self.name.get() age = self.age.get() address = self.add.get() b_group = self.var.get() quantity = self.quantity.get() mobile_number = self.mob.get() print(quantity) # Accessing the database (blood.db) try: self.connection.execute( "CREATE TABLE IF NOT EXISTS %s(name,age,address,quantity,bgroup,mobile)" % (self.tablename)) self.connection.execute("INSERT INTO %s VALUES(?,?,?,?,?,?)" % (self.tablename), (name, age, address, quantity, b_group, mobile_number)) self.connection.commit() tkinter.messagebox.showinfo("Message", "Registration Successfull") self.connection.close() except Exception as e: tkinter.messagebox.showinfo( "Error", "Insertion Failed : " + str(e))
###Given a tuple of numbers, iterate through it and print only those numbers which are divisible by 5### num_tuple = (3, 5, 33, 46, 4) print("Given list is ", num_tuple) # Print elements that are divisible by 5 print("Elements that are divisible by 5:") for num in num_tuple: if (num % 5 == 0): print(num)
from tkinter import * import pandas as pd data = pd.read_excel("C:/Users/user/Desktop/store-dataset.xlsx") global y global m global product_list product_list = [] global mon y,m = 2014,'Jan' SalesReport = Tk() SalesReport.title("Sales Report") SalesReport.geometry("800x600") def option_changed_year(*args): print("the user chose the value {}".format(year.get())) y = year.get() print(y) return y year = StringVar() #year.set('Select the Year') year.set(2014) year.trace("w", option_changed_year) year_widget = OptionMenu(SalesReport, year, '2014', '2015', '2016', '2017') year_widget.place(relx = 0.35,rely = 0.15) def option_changed_month(*args): print("the user chose the value {}".format(month.get())) y = year.get() m = month.get() mon = 1 if(True): if(m=='Jan'): mon = 1 elif(m=='Feb'): mon = 2 elif(m=='Mar'): mon = 3 elif(m=='Apr'): mon = 4 elif(m=='May'): mon = 5 elif(m=='Jun'): mon = 6 elif(m=='Jul'): mon = 7 elif(m=='Aug'): mon = 8 elif(m=='Sep'): mon = 9 elif(m=='Oct'): mon = 10 elif(m=='Nov'): mon = 11 elif(m=='Dec'): mon = 12 y,m = y,mon print(y,m) product_list = list(data[(data['Order Date'].dt.year==y) & (data['Order Date'].dt.month==m)]['Product Name']) print(len(product_list)) return m month = StringVar(SalesReport) #month.set('Select the Month') month.set('Jan') month.trace("w", option_changed_month) month_widget = OptionMenu(SalesReport,month,'Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec',command=option_changed_month(month)) month_widget.place(relx = 0.1,rely = 0.15) '''y,m = int(y),int(m) print(y,m) product_list = list(data[(data['Order Date'].dt.year==y) & (data['Order Date'].dt.month==m)]['Product Name']) print(product_list) product = StringVar(SalesReport) product.set('Select the Product') product_widget = OptionMenu(SalesReport, product, *product_list) product_widget.pack() ''' mainloop()
# print "Hello World" # print 1234 * 1234 # a = 5 # print a # a = 6 # print a # print type(5.4) print "Welcome to the wild world of random questions!" print "Let us begin" name = raw_input ("What is your name? ") age = input ("How old are you?: ") hair = raw_input ("What color is your hair? ") age_add = input ("How many years would you like me to add to your life?") print "Your name is " + name + "." print "Your name is %s. You are %s years old. And your hair is %s" % (name, age, hair) print "In %s years you will be %s." % (age_add, (age + age_add)) if hair == "brown": print "Because your hair is Brown, you'll lose it soon." elif hair == "red" print "Your hair is red!" else: print "Because your hair is not Brown but %s you'll have it forever." % (hair)
__author__ = 'Beni' name_list = [] times_greeted = 0 def greeting(): name = raw_input("What is your name? ") name_list.append(name) print("Hello, {}".format(name)) print("{}, I noticed that your working hard today.".format(name)) print("Work a little less tomorrow {}".format(name)) print("There are {} people in your list, they are:".format(len(name_list))) for i in name_list: print i while True: if times_greeted <= 2: greeting() times_greeted = times_greeted + 1 else: break
from PIL import Image print("\nThis program will insert a background image of your choice in a image of your choice!\n") front_number = input("What image would you like to insert in the front?\n1- A Boat\n2- A Cactus\nEnter the option number: ") while front_number < "1" or front_number > "2": front_number = input("\nWhat image would you like to insert in the front?\n1- A Boat\n2- A Cactus\nEnter the option number: ") front_image = "" if front_number == "1": front_image = "boat.jpg" elif front_number == "2": front_image = "cactus.jpg" image_front = Image.open(front_image) width, height = image_front.size pixels_front = image_front.load() back_number = input("\nWhat image would you like to insert in the background?\n1- A Beach\n2- A Desert\n3- The Earth\n4- A Forest\n5- A Sunset\nEnter the option number: ") while back_number < "1" or back_number > "5": back_number = input("\nWhat image would you like to insert in the background?\n1- A Beach\n2- A Desert\n3- The Earth\n4- A Forest\n5- A Sunset\nEnter the option number: ") back_image = "" if back_number == "1": back_image = "beach.jpg" elif back_number == "2": back_image = "desert.jpg" elif back_number == "3": back_image = "earth.jpg" elif back_number == "4": back_image = "forest.jpg" elif back_number == "5": back_image = "sunset.jpg" image_back = Image.open(back_image) pixels_original = image_back.load() if front_number == "1": for x in range(0, width): for y in range(0, height): (r, g, b) = pixels_original[x, y] if (51, 102, 51) <= pixels_front[x, y]: pixels_front[x, y] = (r, g, b) elif front_number == "2": for x in range(0, width): for y in range(0, height): (r, g, b) = pixels_original[x, y] if (62, 62, 0) < pixels_front[x, y] and (200, 200, 200) > pixels_front[x, y]: pixels_front[x, y] = (r, g, b) image_front.show() # Saving the new image save = input("\ndo you want to save the new image?(yes/no) ") if save.lower() == "yes": name = input("What do you want to name this image file? ") image_front.save(f'{name}.jpg') print("Image Sucessfully saved!\n") else: print("\nSee You!\n")
import unittest from Order_Statistics import * class RandomisedSelectTestCase(unittest.TestCase): def setUp(self): self.listA = [3, 8, 1, 7, 4, 6, 2, 5, 9] # example by MM self.listB = [i + 1 for i in range(10)] self.listC = [5, 2, 9, 1, 10, 3, 4, 6, 8, 7] def test6thInA(self): self.assertEqual(randomisedSelect(self.listA, 0, len(self.listA) - 1, 6), 6, "found order statistic incorrectly") def test8thInB(self): self.assertEqual(randomisedSelect(self.listB, 0, len(self.listB) - 1, 8), 8, "found order statistic incorrectly") def test2ndInC(self): self.assertEqual(randomisedSelect(self.listC, 0, len(self.listC) - 1, 2), 2, "found order statistic incorrectly") if __name__ == "__main__": unittest.main()
""" This program has been written to solve problem 2 on projecteuler.net author: Jeremiah Lantzer """ max_num = 4000000 # even fibonacci numbers under this value result = [] # stores the fibonacci sequence past, current = 0, 1 # initializes the first 2 numbers in the sequence even_sum = 0 # sums the even numbers in the sequence while past < max_num: if past % 2 == 0: even_sum += past result.append(past) past, current = current, past+current print(result) print(even_sum)
questions = ['Are you over 14?\n', 'Want to use sauna?\n', 'Are you a student?\n', 'Are you Male?\n'] while True: q1 = input(questions[0]) if q1 == 'no': print('You are underage!') break elif q1 == 'yes': q2 = input(questions[1]) if q2 == 'yes': print('Price: 1500HUF') break elif q2 == 'no': q3 = input(questions[2]) if q3 == 'yes': print('Price: 300HUF') break elif q3 == 'no': q4 = input(questions[3]) if q4 == 'yes': print('Price: 750HUF') break elif q4 == 'no': print('Price: 500HUF') break
while True: a = (input('Enter a number (or letter to exit): ')) if str.isalpha(a): break operation = input('Enter an operation: ') b = (input('Enter another number: ')) if operation == '+': print('Result: ', int(a) + int(b), '\n') if operation == '-': print('Result: ', int(a) - int(b), '\n') if operation == '*': print('Result: ', int(a) * int(b), '\n') if operation == '/': print('Result:', int(a) / int(b), '\n')
total = 0 for number in range(1, 10 + 1): total += number print(total) # ############## print(sum(range(1, 10 + 1))) ############ factorial = 1 num = int(input("Type in a number:\n")) for i in range(1, num + 1): factorial *= i print(factorial) ############## sum = 0 prd = 1 for i in range(1, 10 + 1): x = float(input("Type in the %d. number: " % i)) sum += x prd *= x avg = sum/10 print("Sum = %g\nAverage = %g\nProduct = %g" % (sum, avg, prd)) ######################## sum = 0 prd = 1 lst = [] for i in range(10): x = float(input("Type in the %d. number: " % (i + 1))) lst.append(x) for j in lst: sum += j prd *= j avg = sum/10 print("Sum = %g\nAverage = %g\nProduct = %g" % (sum, avg, prd)) # itt is rossz volt a példa megoldás
import copy def shooting(grid, row, column): hit = 0 if grid[row][column] == 0: grid[row][column] = "#" elif grid[row][column] == "X": grid[row][column] = "H" hit = 1 return hit def ship_placement(grid, row, column, direction, length): k = 0 if direction == 1: while k < length: grid[row + k][column] = "X" k += 1 elif direction == 0: while k < length: grid[row][column + k] = "X" k += 1 return length def fogofwar(grid): for i in range(len(grid)): for j in range(len(grid[i])): if grid[i][j] == "#" or grid[i][j] == "H": print(grid[i][j], end=" ") else: print(0, end=" ") print() def cheatsheet(grid): for i in range(len(grid)): for j in range(len(grid[i])): if grid[i][j] == "#" or grid[i][j] == "H" or grid[i][j] == "X": print(grid[i][j], end=" ") else: print(0, end=" ") print() def print_grid_preview(grid): for i in range(len(grid)): for j in range(len(grid[i])): print(grid[i][j], end=" ") print() def outofgrid(grid, row, column, direction, length): if direction == 1: if row < 0 or row > len( grid) or row + length > len(grid) or column < 0 or column > len(grid[0]): allgood = 0 else: allgood = 1 elif direction == 0: if row < 0 or row > len(grid) or column < 0 or column > len( grid[0]) or column + length > len(grid[0]): allgood = 0 else: allgood = 1 else: allgood = 0 print("Direction error! 1 is vertical, 0 is horizontal.") return allgood # ITT KEZDODIK-************-----------------------**************x*#*#x---x#*#* # try: # sor = int(input('Hány soros táblát szertnél? \n')) # oszlop = int(input('Hány oszlopos táblát szeretnél? \n')) # turn = int(input("Hány körös legyen? \n")) # except ValueError: # print("Please enter a valid parameter!\n") sor = 5 oszlop = 5 turn = 5 # palyak grid1 = [0] * sor i = 0 for i in range(sor): grid1[i] = [0] * oszlop grid2 = copy.deepcopy(grid1) ########################################## # hajo elhelyezes allgood = 0 while allgood == 0: # P1 print("First player:") try: rowboat = int(input("Row of ship? \n")) columnboat = int(input("Column of ship? \n")) direction = int(input("Direction of ship? \n")) length = int(input("Length of ship? \n")) except ValueError: print("Please enter a valid parameter!\n") continue life1 = ship_placement(grid1, rowboat, columnboat, direction, length) allgood = outofgrid(grid1, rowboat, columnboat, direction, length) if allgood == 0: continue # P2 print("Second player:") try: rowboat = int(input("Row of ship? \n")) columnboat = int(input("Column of ship? \n")) direction = int(input("Dircetion of ship? \n")) length = int(input("Length of ship? \n")) except ValueError: print("Please enter a valid parameter!\n") continue life2 = ship_placement(grid2, rowboat, columnboat, direction, length) allgood = outofgrid(grid2, rowboat, columnboat, direction, length) print() # boat printeles # P1 print_grid_preview(grid1) # P2 print() print_grid_preview(grid2) print("##########################################################") while life1 > 0 and life2 > 0 and turn > 0: print() # function shooting allgood = 0 while allgood == 0: # P1 print("First player shoots:\n") try: rowboat = int(input("Row of target?\n")) columnboat = int(input("Column of target?\n")) except ValueError: print("Please enter a valid parameter!\n") continue life2 = life2 - shooting(grid1, rowboat, columnboat) allgood = outofgrid(grid1, rowboat, columnboat, 1, 0) if allgood == 0: continue # P2 print("Second player shoots:\n") try: rowboat = int(input("Row of target?\n")) columnboat = int(input("Column of target?\n")) except ValueError: print("Please enter a valid parameter!\n") continue life1 = life1 - shooting(grid2, rowboat, columnboat) allgood = outofgrid(grid2, rowboat, columnboat, 1, 0) # állás print() print("First players life:", life1) print("Second players life:", life2) print("Turns left:", turn) # fogofwar akcio utan print() print("First player:") fogofwar(grid1) print() print("Second player:") fogofwar(grid2) print() cheatsheet(grid1) print() cheatsheet(grid2) print() turn -= 1 if life2 == 0: print("First player wins!") elif life1 == 0: print("Second player wins!") elif turn == 0: print("Game fucking over, mate!")
# -*- coding: utf-8 -*- """ Created on Sun Feb 2 12:27:05 2020 @author: Chenyang """ class Node(object): def __init__(self, data, next = None): '''data为数据项 next为下一节点的链接 初始化节点默认链接为None''' self.data = data self.next = next node1 = None node2 = Node(1, None) node3 = Node('hello', node2) print(node1, node2.next, node2, node3.next)
# -*- coding: utf-8 -*- """ Created on Fri Jun 26 10:21:39 2020 @author: Chenyang 该模块包含以下内容 my_book: 字符串变量 say_hi: 简单的函数 User: 代表用户的类 """ print("this is module 1") my_book = "讲义" def say_hi(user): print("%s,欢迎学习python"%user) #模块的测试函数 def test_my_book(): print(my_book) def test_say_hi(): say_hi("孙悟空") say_hi(User("charlie")) def test_User(): u = User("白骨精") u.walk() print(u) class User: def __init__(self,name): self.name = name def walk(self): print("%s is walking slowly"%self.name) def __repr__(self): return "User[username=%s]"%self.name """ 如果直接使用python命令来来运行一个模块,__name__变量的值为__main__ 如果该模块被导入其他程序中,__name__变量的值就是模块名 """ if __name__ == "__main__": test_my_book() test_say_hi() test_User()
import csv count = 0 dates = [] Rev = [] avg = [] goldchange = 5 loldchange = 1000000000 print("") print("Financial Analysis") print("-----------------------------") #put what ever file you want with open('budget_data_1.csv', 'r') as csvfile: csv_reader = csv.reader(csvfile, delimiter = ',') next(csv_reader) for row in csv_reader: dates.append(row[0]) Rev.append(row[1]) for r in Rev: count = int(r) + count num_date = len(dates) #if row #print(row[0]) print("total months: " + str(num_date)) print("total revenue: $" + str(count)) for i in range(num_date-1): change = int(((int(Rev[i])-int(Rev[i+1])))) if change > goldchange: goldchange = change if change < loldchange: loldchange = change avg.insert(i, int(abs(change))) avg_change = sum(avg)/len(avg) print("average revenue change: $" +str(avg_change)) print("Greatest Increase in Revenue: ($" +str(goldchange)+")") print("Greatest Decrease in Revenue: ($" +str(loldchange) +")") print("")
""" CSE-1310 Final Exam Practice problem #24 """ """ fp = open("movies.csv", "r") MovL = fp.readlines() fp.close() MovD = {} for line in MovL: tokens = line.split(",") inList = [] inList.append(tokens[1]) inList.append(tokens[2]) MovD[tokens[0]] = inList #MovD complete find = raw_input("Please enter a search topic: ") for title in MovD: if find in MovD[title][0] and int(MovD[title][1]) % 2 == 0: print title """ """ CSE-1310 Final Exam Practice problem #1 """ def clean( line ) : newline = [ ] t = line.strip().split(',') for x in t : newline.append( int(x) ) return newline def fx( d ) : rows = len( d ) cols = len( d[0] ) c = 0 while c < cols : sum = 0 r = 0 while r < rows : sum += d[r][c] d[r][c] = sum r += 1 c += 1 ##### main ##### data = [ ] fp = open("file3-5.csv", "r") for line in fp : data.append( clean(line) ) fp.close() fx( data ) for line in data : print line
""" this program will prompt the user 6 times for a number and then tell if the number is odd or even """ count = 0 #remember count started at zero and zero counts too[0,1,2,3,4,5] is six numbers while count <=5: num = input("Enter a number: ") if num%2 == 0: print print "the number is even" print count = count +1 else: print print "the number is odd" count = count +1 print
""" James Hawley 10-03-2013 Howmwork#5a """ def countTokens(n): count = 0 tokens = List[n].split(",") for t in tokens: count = count + 1 return count def countChar(n): tokens = List[n].split(",") count = 0 for t in tokens: for c in t: count = count + 1 return count def TokMaxChar(n): tokens = List[n].split(",") L3 = len(tokens) - 1 a = 0 count = 0 themax = 0 while 0 <= a and a <= L3: count = 0 for c in tokens[a]: count = count + 1 if count > themax: themax = count Srtmax = tokens[a] a = a + 1 return Srtmax List = ["cat,elephant,horse,anteater,giraffe", "Impala,Mustang,Thunderbird,Viper", "123.4567,987654,99.99%"] L1 = len(List)-1 t = 0 while 0 <= t and t <= L1: print "token count = %d," % countTokens(t) , print "character count = %d," % countChar(t) , print "%s has the most characters" % TokMaxChar(t) t = t + 1
""" This is me using a Mac """ a = input("Enter a number: ") while a != 10000: if a: print "this evaliates to true" else: print "this is always false" a = input("Enter a number: ") print print "Remember, when dealing with logic operators, a nonzero number will always be true. A zero value will be false"
""" James Hawley 09/04/2013 Homework#2 """ num = input("Please type an integer: ") if num == 0: print "zero" elif num > 0: print "The number is positive" if num%5 ==0: print "The number is divisible by 5" else: print "The number is not divisible by 5" elif num < 0: print "The number is negative" if num%5 ==0: print "The number is divisible by 5" else: print "The number is not divisible by 5"
""" This is a number guessing game that will let the player guess 7 times to find the right number """ import random snum = random.randint(1,100) print snum count = 0 guess = -1 while count != 7: count = count + 1 print count count = 1 while count != 7: while guess != snum: guess = input("Enter your guess: ") if guess == snum: print "You got it!" elif guess < snum: print "Too low" else: print "Too high" count = count + 1 print " The count is ", count """ while guess != snum: guess = input("Enter your guess: ") if guess == snum: print "You got it!" #count = count + 1 elif guess < snum: print "Too low" #count = count+ 1 else: print "Too high" """
class calculator: def __init__(self,a ,b, typeOfOperation): self.a = a self.b = b self.typeOfOperation = typeOfOperation if typeOfOperation == '+': print("Result obtained after adding the numbers : ", self.addition()) elif typeOfOperation == '-': print("Result obtained after adding the numbers : ", self.subtraction()) elif typeOfOperation == '*': print("Result obtained after adding the numbers : ", self.multiplication()) elif typeOfOperation == '/': print("Result obtained after adding the numbers : ", self.division()) else: print("Enter a valid type of operation") def addition(self): return self.a + self.b def subtraction(self): return self.a - self.b def multiplication(self): return self.a * self.b def division(self): return self.a / self.b a = float(input("Enter the first number\n")) b = float(input("Enter the second number\n")) typeOfOperation = input("Enter the type of operation\n") cal = calculator(a, b, typeOfOperation) cal
''' This part contains the encrypt and decrypt function of Beale Cipher. The encryption and decryption rule is that the if the book does not contain certain letter in plaintext, it will raise an error. Since the same number should not be used for the same letter throughout encryption, if the book has used out all numbers for a letter, it will raise an error. If numbers presented in plaintext, they will be removed. Only the letters will be encrypted. If a number in ciphertext exceeds the length of the book, it will raise an error. ''' import utils import random def encrypt(plaintext, file_name, seed): ''' Function -- encrypt encrypt the plaintext using Beale Cipher. Parameters: plaintext -- some unencrypted data file_name -- the book used to encode message seed -- an integer to make the generator pseudorandom Returns a string of encrypted message Raises a TypeError or ValueError if any errors occur while reading the parameters ''' if not isinstance(plaintext, str): raise TypeError('encrypt is expecting a string as' ' the first parameter') if plaintext == '': raise ValueError('plaintext cannot be empty') plaintext = utils.strip(plaintext) plaintext = plaintext.lower() plaintext = utils.remove_numbers(plaintext) if not isinstance(seed, int): raise TypeError('encrypt is expecting an integer as' ' the third parameter') content = read_data(file_name) dict = to_dict(content) random.seed(seed) res = '' for i in range(len(plaintext)): if plaintext[i] in dict: list = dict[plaintext[i]] if len(list) != 0: random_int = random.randint(0, len(list) - 1) res += str(list[random_int]) + ' ' del dict[plaintext[i]][random_int] else: raise ValueError('The book has used out all words ' 'start with ' + '\'' + plaintext[i] + '\'') else: raise ValueError('The book does not have a word starts with ' + '\'' + plaintext[i] + '\'') res = res.rstrip() return res def decrypt(ciphertext, file_name): ''' Function -- decrypt decrypt the ciphertext using Beale Cipher. Parameters: ciphertext -- some unencrypted data file_name -- the book used to encode message Returns a string of encrypted message Raises a TypeError or ValueError if any errors occur while reading the parameters ''' content = read_data(file_name) len_content = 0 for i in range(len(content)): for j in range(len(content[i])): len_content += 1 if not isinstance(ciphertext, str): raise TypeError('decrypt is expecting a string as' ' the first parameter') if ciphertext == '': raise ValueError('ciphertext cannot be empty') ciphertext = ciphertext.split() for i in range(len(ciphertext)): if not ciphertext[i].isdigit(): raise ValueError('ciphertext can only contain numbers') if int(ciphertext[i]) > len_content: raise ValueError('wrong number ' + ciphertext[i] + ' in ciphertext, which exceeds the length ' 'of this book') res = '' start = 0 while start < len(ciphertext): length = 0 flag = False for i in range(len(content)): for j in range(len(content[i])): if length + j + 1 == int(ciphertext[start]): res += content[i][j][0].upper() start += 1 flag = True break if j == len(content[i]) - 1: length += len(content[i]) if flag: break return res def read_data(file_name): ''' Function -- read_data reads all of the words in that file into a list and return Parameters: file_name -- accepts the name of a text file as a parameter Returns a list with all the words in the file Raises a ValueError if any errors occur while reading the file ''' try: input_file = open(file_name, 'r') file_data = input_file.readlines() input_file.close() list1 = [] for i in range(len(file_data)): list1.append(file_data[i].split()) list1 = list(filter(None, list1)) return list1 except FileNotFoundError: raise except PermissionError: raise except OSError: raise def to_dict(content): ''' Function -- to_dict reads all of the words in the list and allocate their positions by their first letters Parameters: content -- a list contains all words Returns a dictionary with the first letters as key and positions as values ''' dict = {} position = 1 for j in range((len(content))): k = 0 while k < len(content[j]): content[j][k] = content[j][k].lower() if content[j][k].endswith('-'): content[j][k] = content[j][k][0: -1] + content[j][k + 1] del content[j][k + 1] if content[j][k][0] in dict: dict[content[j][k][0]].append(position) else: dict[content[j][k][0]] = [position] k += 1 position += 1 return dict
# How to Think Like a Computer Scientist # Chapter 4 and Chapter 5 Exercises and Lab ################################################################ ''' 4.11.6 -- (draw shape filled in with color) Write a program that asks the user for the number of sides, the length of the side, the color, and the fill color of a regular polygon. The program should draw the polygon and then fill it in. ''' import turtle sides = int(input("sides? ")) length = int(input("length? ")) color = input('color? ') fill = input('fill color? ') wn = turtle.Screen() alex = turtle.Turtle() alex.color(color, fill) alex.hideturtle() # borrowed this function from exercises I'd done previously in chapters to come def drawPolygon(tur, sideLen, numSides): angle = 360/numSides for i in range(numSides): tur.forward(sideLen) tur.left(angle) # fill shape with color as follows: # begin fill # draw the shape # end fill #SEE: http://www.eg.bucknell.edu/~hyde/Python3/TurtleDirections.html#beginfill alex.begin_fill() drawPolygon(alex, length, sides) alex.end_fill() wn.exitonclick() ################################################################ ''' 4.11.9 Draw a Star ''' import turtle wn = turtle.Screen() t = turtle.Turtle() side = 50 # To draw a star -- Observations # (I did some sketches by hand to figure out the angles) # # angle: 360/number_sides_interior_shape <pentagon> # 360/5 = 72 degrees # star is 5 long lines, interior shape (pentagon) has 5 lines too # Pattern is: # turn the angle # draw the length of a side # turn the angle for _ in range(5): t.right(72) # 360/5 t.forward(side) t.right(72) wn.exitonclick() # HTLACS draw-star code: def drawFivePointStar(t, side): for i in range(5): t.forward(side) t.left(216) ################################################################ ''' 4.11.10 Write a program to draw a face of a clock [with turtles.] ''' # go forward (diameter) # pendown # go forward (making a line mark) # penup # go forward (whitespace twice len of mark) # stamp # move back (diameter + length of marks) # change angle import turtle wn = turtle.Screen() wn.bgcolor("green") t = turtle.Turtle() t.shape('turtle') t.color('blue') t.penup() diam = 100 mark = 10 clockface = 12 for _ in range(12): t.left(360//clockface) # 360/12 t.forward(diam) t.pendown() t.forward(mark) t.penup() t.forward(2*mark) t.stamp() t.forward(-1 * (diam + 3*mark)) wn.exitonclick() ################################################################ # Lab 4.4, "sinlab2" # Plotting a sine Wave # http://interactivepython.org/runestone/static/thinkcspy/Labs/sinlab.html ''' Plot a single sine wave We need to set our screen's coordinate system to give us appropriate room to plot the values of a sine function. To do this, we will use a method of the Screen class called ```setworldcoordinates```. This method allows us to change the range of values on the x and y coordinate system for our turtle. REF - https://docs.python.org/3/library/turtle.html#turtle.setworldcoordinates ''' import math import turtle wn = turtle.Screen() wn.bgcolor('lightblue') # coord args: (lower-left-x, lower-left-y, upper-right-x, upper-right-y) wn.setworldcoordinates(0, -1.25, 360, 1.25) fred = turtle.Turtle() for x in range(360): y = math.sin(math.radians(x)) fred.goto(x,y) wn.exitonclick()
def count_letters_digits(sentence): letter = digit = 0 for value in sentence: if value.isalpha(): letter += 1 elif value.isdigit(): digit += 1 else: pass print("Letters : ",letter) print("Digits : ",digit) sentence = input("Enter sentence :: ") count_letters_digits(sentence)
def pick_odd(numbers): str1 = "" num_list = numbers.split(',') for value in num_list: if int(value)%2 != 0: str1 += value + ',' else: pass print("Odd numbers of list :: ",str1) numbers = input("Enter list of numbers : ") pick_odd(numbers)
from nltk.util import ngrams from collections import OrderedDict import re n = 0 i = 0 l = 0 data = {} gram = [] frequence = [] file = open("Apple.txt","r",encoding='UTF-8') n = input("ngram n=") def ngram(n): global i while True: line = file.readline() if line == '': break else: i +=1 lis = re.findall("[a-z]+",line.lower()) ingrams = ngrams(lis,int(n)) for grams in ingrams: #print (grams) if grams in data: data[grams][0] +=1 data[grams].append(i) else: data[grams]=[1, i] file.close() revise = OrderedDict(sorted(data.items(), key=lambda t: t[1],reverse=True)) print("切割結果\n") print(revise) test = revise.items() for d in test: gram.append(d[0]) frequence.append(d[1]) print("\nTop 5 Sequence") for i in range(6): print(str(gram[i])+" [次數,出現行數]為"+str(frequence[i])) #print(revise[0]) ngram(n)
import numpy as np #Take specific number of array my_array = np.array([1,2,3,4,5,6]) print(my_array[2:]) #Selecting values by conditions x = np.array([[1,2,3],[4,5,6],[7,8,9]]) print(x[x > 5]) print(x[x%2 == 0]) print(x[(x > 2) & (x < 11)]) print(x[(x > 5) | (x == 5)])
import os import sqlite3 import matplotlib import matplotlib.pyplot as plt def scatterplot(cur, conn): cur.execute("SELECT * FROM 'GDP Info'") country_list = cur.fetchall() gdp_day_list = [] for country in country_list: try: cur.execute("SELECT 'GDP Info'.'GDP', Day1.day FROM 'GDP Info' JOIN Day1 ON 'GDP Info'.'Country ID' = Day1.id WHERE Day1.id = ?", (country[0],)) gdp_day = cur.fetchone() gdp_day_list.append(gdp_day) except: continue x_vals = [] y_vals = [] for item in gdp_day_list: if item != None: x_vals.append(item[1]) y_vals.append(item[0]) print(len(x_vals)) plt.plot(x_vals,y_vals,'b.') plt.xlabel('Days From 1 Case to 100') plt.ylabel('GDP') plt.title('Correlation Between Days to 100 Cases and GDP') plt.yscale('log') plt.show() # Inputs: cursor and connection # Output: A scatterplot of days to 100 cases vs. country GDP # The purpose of scatterplot() is to create a visualization that displays the correlation between the number of days to get to 100 cases of COVID-19 and country GDP def main(): path = os.path.dirname(os.path.abspath(__file__)) conn = sqlite3.connect(path+'/'+'coronacation.db') cur = conn.cursor() scatterplot(cur, conn) # Input: None # Output: None # The purpose of the main() function is to run the other functions in the file in a specified order. Additionally, this function specifies the database to pull information from and establishes a connection and cursor. if __name__ == "__main__": main()
# CONSOLE_GUESSING_GAME import random def test_number(): # Computer 3_digit random number sample_space = list(range(0, 10)) random.shuffle(sample_space) # shuffle the list of numbers to avoid repitition target = sample_space[:3] ''' Checks whether user- input 3-digit number is exactly the same as the chosen random 3-digit number(case 1), or if at least one of the digits are equal(case 2' or none of the are equal(case 3). :return: match for case 1, close for case 2, nope for case 3 ''' while True: # User prompted 3_digit number guessed_number = input("Enter 3 numbers and separate each with a comma:\n") guessed_list = guessed_number.split(",") if len(guessed_list) != 3: print("ENTER ONLY 3 DIGITS") continue # for i in range(0, 3): # if guessed_list[i] == target[i]: # print("Match") # elif guessed_list != target[i]: # print("Nope") # else: # print("Close") if (guessed_list[0] == target[0]) and (guessed_list[1] == target[1]) and (guessed_list[2] == target[2]): print("Match") elif (guessed_list[0] != target[0]) and (guessed_list[1] != target[1]) and (guessed_list[2] != target[2]): print("Nope") else: print("Close") print("You almost guessed the number") pass a = input("Would you love to play again?? type 'y' to continue and 'n to stop'.\n") if a is "y": test_number() else: print(target) print("Thank You!! for playing the game.") break test_number()
#!/usr/bin/python class Person: def __init__(self,name,age): self.name,self.age = name,age def __str__(self): return 'This guy is {self.name},is {self.age} old'.format(self=self) a=Person("lei.yang","1") print str(a)
# fifth Program/Homework 5 # Programmer Lauren Cox # Date of last revision 20-01-2016 data=input('type in the data:') first_change=data.replace('a','*') print(first_change.replace('A','*'))
#thrid Program/Homework 3 # Programmer Lauren Cox # Date of last revision 20-01-2016 a=float(input("Input a floating point number :")) b=float(input("Input a floating point number :")) c=float(input("Input a floating point number :")) d=float(input("Input a floating point number :")) print('%10.2f'%a) print('%10.2f'%b) print('%10.2f'%c) print('+''%9.2f'%d) print('__________') e=int(a + b + c + d) print ('%10.2f'%e)
#Homework 27 #Programmer Lauren Cox #Date of Last Revision 28-4-2016 import turtle s=0 a=turtle.Screen() b=turtle.Turtle() b.penup() b.goto(-75,-160) b.pencolor("black") b.pensize(250) b.pendown() b.forward(150) b.left(90) b.forward(325) b.left(90) b.forward(150) b.left(90) b.forward(325) def key_color_x1(): s=b.position() x b.penup() b.shapesize(8) b.shape("circle") b.pensize(330) if s[1]==0: b.hideturtle() b.goto(0,125) b.color("red") b.showturtle() elif s[1]==125: b.hideturtle() b.goto(0,-125) b.color("green") b.showturtle() else: b.hideturtle() b.goto(0,0) b.color("yellow") b.showturtle() return a.onkey(key_color_x1,"x") a.listen() a.mainloop()
# eighth Program/Homework 8 # Programmer Lauren Cox # Date of last revision 28-01-2016 a=int(input('Type in a integer:')) b=int(input('Type in a integer:')) c=int(input('Type in a integer:')) if (a>0) and (b>0) and (c>0): print('yes') # I put zero because, zero is not a positive or negative intereger else: print('no')
# - 每行代码,或每个方法要求添加注释(基础不好的同学) # # 题目内容: # # 1. ⼀个回合制游戏,有两个英雄,分别以两个类进⾏定义。分别是Timo和Jinx。每个英雄都有 hp 属性和 power属性,hp 代表⾎量,power 代表攻击⼒ # 2. 每个英雄都有⼀个 fight ⽅法, fight ⽅法需要传⼊“enemy_hp”(敌⼈的⾎量),“enemy_power”(敌⼈的攻击⼒)两个参数。需要计算对打一轮过后双方的最终血量, # 英雄最终的⾎量 = 英雄hp属性-敌⼈的攻击⼒enemy_power # 敌⼈最终的⾎量 = 敌⼈的⾎量enemy_hp-英雄的power属性 # 量和敌⼈最终的⾎量,⾎量剩余多的⼈获胜。如果英雄赢了打印 “英雄获胜”,如果敌⼈赢了,打印“敌⼈获胜” # # 4. 使用继承、简单工厂方法等各种方式优化你的代码 # 继承方式 import random #创建一个英雄类 class Hero: Hero_name="Hero" Hero_hp = 0 Hero_power = 0 def fight(self, name,enemy_hp, enemy_power): ''' :param name: 英雄名 :param enemy_hp: 敌人血量 :param enemy_power: 敌人攻击力 :return: ''' #敌人战斗后血量 enemy_end_hp = enemy_hp - self.Hero_power #英雄战斗后血量 hero_end_hp = self.Hero_hp - enemy_power #当英雄血量大于敌人血量时 if hero_end_hp > enemy_end_hp: print(f"{name}胜利") #当血量相等时 elif hero_end_hp == enemy_end_hp: print("平局") #当血量低于敌人血量 else: print(f"{name}败北") #创建一个英雄提莫,继承主类 class timo(Hero): Hero_name = "提莫" Hero_hp = random.randint(1000, 1300) Hero_power = random.randint(100, 150) pass #创建一个英雄金克斯 class Jinx(Hero): Hero_name = "金克斯" Hero_hp = random.randint(1000, 1300) Hero_power = random.randint(100, 150) pass
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Apr 20 20:12:57 2020 @author: redhwanzaman1989 """ def calculate_mean(number): s = sum(number) l = len(number) mean = s/l print('mean is {0}'.format(mean)) return mean def calculate_median(number): number = money number1 = sorted(number) n = len(number1) print(n) if (n%2) == 1: print('odd') m = (n+1) / 2 median = number[m] elif (n%2) == 0: print('even') n = len(number) m1 = int(n/2) m2 = int(n/2 + 1) median = (float(number[m1]) + float(number[m2]))/2 print('median is {0}'.format(median)) return median print('median is {0}'.format(median)) money = [ 806.75, 801.92, 774.01, 587.03, 797.51, 908.04, 859.05, 528.03, 978.42, 911.05 ] calculate_mean(money) calculate_median(money) #find mode simplelist = [4,2,1,3,4] from collections import Counter c = Counter(simplelist) c # Online Python compiler (interpreter) to run Python online. # Write Python 3 code in this online editor and run it. # Get started with interactive Python! # Supports Python Modules: builtins, math,pandas, scipy # matplotlib.pyplot, numpy, operator, processing, pygal, random, # re, string, time, turtle, urllib.request import matplotlib.pyplot as plt import pandas as pd import numpy as np import scipy as sp from collections import Counter # from collections import Counter # SimpleList = [4,2,1,3,4] # c = Counter(SimpleList) # c.most_common() # print('Counter = ',c) # print('list of most common: ',c.most_common()) # a = c.most_common() # print('first element of most common (method 1): ',a[0]) # print('first element of most common using a different method (method 2): ', #c.most_common(1)) # print('as can be seen, the difference between method 1 and method 2 is that #method 2 results in a list with a tuple as the first element, #whilst method 1 results in just a tuple') # print('method 1: ', c.most_common()[0], ', and method 2: ', c.most_common(1)) # going to create a function that identifies the mode # from collections import Counter # def mode(number): # count_list = Counter(number) # mode_list = count_list.most_common() # print('count_list = ', count_list) # print('mode_list = ', mode_list) # print('mode is :', mode_list[0][0],', and it appears ', #mode_list[0][1], ' times') # return # mode(number) # def mode_updated(number): # count_list = Counter(number) # mode_list = count_list.most_common() # max_number = mode_list[0][1] # final_modes = [] # for i in range(0, len(mode_list)): # if mode_list[i][1] == max_number: # final_modes.append(mode_list[i][0]) # print(count_list) # print(mode_list) # print(max_number) # print('modes are: ', final_modes, 'and it appears: ', max_number, #' times') # print('number\tfrequency') # m = 0 # for j in mode_list: # print('{0}\t{1}'.format(j[0], j[1])) # number = [1,3,4,5,5,5,5,5,4,4,4,4] # number = [7, 8, 9, 2, 10, 9, 9, 9, 9, 4, 5, 6, 1, 5, 6, 7, 8, 6, 1, 10] # mode_updated(number) # def find_range(number): # lowest = min(number) # highest = max(number) # r = highest - lowest # return lowest, highest, r # lowest, highest, r = find_range(number) # print('lowest = {0}, highest = {1}, range = {2}'.format(lowest, highest, r)) #variance is defined as sigma((x - mean(x))^2)/n def DescriptiveStatistics(number): n = len(number) total = sum(number) mean = total/n minimum = min(number) maximum = max(number) range_number = maximum - minimum mode1 = Counter(number) mode2 = mode1.most_common() mode_number = [] mode_frequency = [] max_number = mode2[0][1] for j in mode2: if j[1] == max_number: mode_number.append(j[0]) mode_frequency.append(j[1]) var1 = [] for k in range(0,n): var1.append((number[k] - mean)**2) variance = sum(var1)/n standard_deviation = variance**(0.5) print('n = {0}'.format(n)) print('total = {0}'.format(total)) print('mean = {0}'.format(mean)) print('mode1 = {0}'.format(mode1)) print('mode2 = {0}'.format(mode2)) print('max_number = {0}'.format(max_number)) print('mode_number = {0}'.format(mode_number)) print('mode_frequency = {0}'.format(mode_frequency)) print('variance = {0}'.format(variance)) print('standard_deviation = {0}'.format(standard_deviation)) # number = [53, 60, 69, 58, 82, 73, 9, 23, 24, 13, # 67,67,67,67,67,67,67,10,10,10,10,10,10,10] donations1 = [100, 60, 70, 900, 100, 200, 500, 500, 503, 600, 1000, 1200] donations2 = [382, 389, 377, 397, 396, 368, 369, 392, 398, 367, 393, 396] # DescriptiveStatistics(number) print('end') DescriptiveStatistics(donations1) print('end') DescriptiveStatistics(donations2) plt.plot(range(1,len(donations1)+1),sorted(donations1)) plt.plot(range(1,len(donations2)+1),sorted(donations2)) plt.show() number1 = [1,2,3] number2 = [4,5,6] def correl(number1, number2): cov1 = [] varx = [] vary = [] n1 = len(number1) n2 = len(number2) if n1==n2: mean1 = sum(number1)/n1 mean2 = sum(number2)/n2 for i in range(0,n1): cov1.append((number1[i] - mean1)*(number2[i] - mean2)) varx.append((number1[i] - mean1)**2) vary.append((number2[i] - mean2)**2) cov = sum(cov1)/n1 varx = sum(varx)/n1 vary = sum(vary)/n2 sdx = varx**0.5 sdy = vary**0.5 correlation = cov/(sdx*sdy) print('cov = {0}'.format(cov)) print('varx = {0}'.format(varx)) print('vary = {0}'.format(vary)) print('sdx = {0}'.format(sdx)) print('sdy = {0}'.format(sdy)) print('correlation = {0}'.format(correlation)) else: print('different_lengths') correl(number1, number2) import matplotlib.pyplot as plt high_school = [90 ,92 ,95 ,96 ,87 ,87 ,90 ,95 ,98 ,96] college = [85, 87, 86, 97, 96, 88, 89, 98, 98, 87] plt.plot(high_school, college, 'o') plt.show() ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' import os curDir = os.getcwd() os.chdir('/home/redhwanzaman1989/DoingMathWithPython') def sum_data(filename): s = 0 with open(filename) as f: for line in f: s = s + float(line) # print(line) print('Sum of of the numbers: {0}'.format(s)) sum_data('myfile.txt') def read_files(filename): numbers = [] with open(filename) as f: for line in f: numbers.append(float(line)) return numbers a = read_files('myfile.txt') def calculate_mean(numbers): s = sum(numbers) N = len(numbers) mean = s/N return mean if __name__ == '__main__': data = read_files('myfile.txt') mean = calculate_mean(data) print('Mean: {0}'.format(mean)) import csv import matplotlib.pyplot as plt def read_csv(filename): numbers = [] squared = [] with open(filename) as f: reader = csv.reader(f) next (reader) for row in reader : print(row) numbers.append(row[0]) squared.append(row[1]) return numbers, squared numbers, squared = read_csv('Number Squared.csv') plt.scatter(numbers, squared) plt.plot([9,10,22], [81,100,484])
import re from dateutil import parser months = {'января': 'january', 'февраля': 'february', 'марта': 'march', 'апреля': 'april', 'мая': 'may', 'июня': 'june', 'июля': 'july', 'августа': 'august', 'сентября': 'september', 'октября': 'october', 'ноября': 'november', 'декабря': 'december'} def str2date(str_date): try: date = parser.parse(str_date) except: m = re.findall(r'[А-Яа-я]+', str_date) if m: date = parser.parse(re.sub(m[0], months[m[0]], str_date)) else: date = None return date
import numpy as np from random import shuffle from past.builtins import xrange def softmax_loss_naive(W, X, y, reg): """ Softmax loss function, naive implementation (with loops) Inputs have dimension D, there are C classes, and we operate on minibatches of N examples. Inputs: - W: A numpy array of shape (D, C) containing weights. - X: A numpy array of shape (N, D) containing a minibatch of data. - y: A numpy array of shape (N,) containing training labels; y[i] = c means that X[i] has label c, where 0 <= c < C. - reg: (float) regularization strength Returns a tuple of: - loss as single float - gradient with respect to weights W; an array of same shape as W """ # Initialize the loss and gradient to zero. loss = 0.0 dW = np.zeros_like(W) # D x C ############################################################################# # TODO: Compute the softmax loss and its gradient using explicit loops. # # Store the loss in loss and the gradient in dW. If you are not careful # # here, it is easy to run into numeric instability. Don't forget the # # regularization! # ############################################################################# num_train = X.shape[0] loss = 0.0 for i in xrange(num_train): scores = X[i].dot(W) # C, sc_exp = np.exp(scores) sc_exp_sum = np.sum(sc_exp) sc_exp_correct = sc_exp[y[i]] f_i = sc_exp_correct / sc_exp_sum loss += -np.log(f_i) temp = sc_exp # C, temp[y[i]] -= sc_exp_sum temp /= sc_exp_sum dW += np.dot(np.reshape(X[i], (-1, 1)), np.reshape(temp, (1, -1))) loss /= num_train loss += reg*np.sum(W*W) dW /= num_train dW += 2*reg*W ############################################################################# # END OF YOUR CODE # ############################################################################# return loss, dW def softmax_loss_vectorized(W, X, y, reg): """ Softmax loss function, vectorized version. Inputs and outputs are the same as softmax_loss_naive. """ # Initialize the loss and gradient to zero. loss = 0.0 dW = np.zeros_like(W) # D x C ############################################################################# # TODO: Compute the softmax loss and its gradient using no explicit loops. # # Store the loss in loss and the gradient in dW. If you are not careful # # here, it is easy to run into numeric instability. Don't forget the # # regularization! # ############################################################################# num_train = X.shape[0] scores = np.dot(X, W) # N x C sc_exp = np.exp(scores) # N x C sc_exp_sum = np.sum(sc_exp, axis=1) # N? f = sc_exp[range(num_train), y] / sc_exp_sum # N? loss = -np.sum(np.log(f)) loss /= num_train loss += reg*np.sum(W*W) sc_exp[range(num_train), y] -= sc_exp_sum sc_exp = sc_exp.T # C X N sc_exp /= sc_exp_sum dW = np.dot(sc_exp, X).T # D x C dW /= num_train dW += 2*reg*W ############################################################################# # END OF YOUR CODE # ############################################################################# return loss, dW
def extrai_naipe (carta): divide_str = [list(letra) for letra in carta] if len(divide_str) == 3: return divide_str [2] [0] if len(divide_str) == 2: return divide_str [1] [0] def extrai_valor (carta): divide_str = [list(letra) for letra in carta] if len(divide_str) == 3: return divide_str [0] [0] + divide_str [1] [0] if len(divide_str) == 2: return divide_str [0] [0] def lista_movimentos_possiveis (baralho, posicao): lugar = [] if posicao == 0: return [] for cartas in range(len(baralho)): if extrai_naipe(baralho[cartas]) == extrai_naipe (baralho [posicao]) and cartas == posicao - 1: lugar.append (1) if extrai_naipe(baralho[cartas]) == extrai_naipe (baralho [posicao]) and cartas == posicao - 3: lugar.append (3) if extrai_valor(baralho[cartas]) == extrai_valor (baralho [posicao]) and cartas == posicao - 1: lugar.append (1) if extrai_valor(baralho[cartas]) == extrai_valor (baralho [posicao]) and cartas == posicao - 3: lugar.append (3) if lugar == []: return [] return sorted(lugar) print (lista_movimentos_possiveis (['6♥', 'J♥', '9♣', '9♥'], 3))
#!/usr/bin/env python # -*- coding: utf-8 -*- class Graph: def __init__(self): self.noeuds=[] self.arretes=[] class Noeud: def __init__(self, intitule): self.intitule=intitule self.voisins=[] def __eq__(self, other): return self.intitule == other.intitule class Arrete: def __init__(self,noeud_a,noeud_b,cout): self.premier_noeud=noeud_a self.second_noeud=noeud_b self.cout=cout def __eq__(self, other): if(self.premier_noeud == other.premier_noeud and self.second_noeud == other.second_noeud and self.cout == other.cout): return True elif(self.premier_noeud == other.second_noeud and self.second_noeud == other.premier_noeud and self.cout == other.cout): return True else: return False if __name__ == '__main__': A = Noeud("A") B = Noeud("B") AB5 = Arrete(A,B,5) BA5 = Arrete(B,A,5) AB4 = Arrete(A,B,4) print "Noeuds :" print "A == A ? "+ str(A==A) print "A == B ? "+ str(A==B) print "Arrêtes : " print "AB5 == AB5 ? "+str(AB5 == AB5) print "AB5 == BA5 ? "+str(AB5 == BA5) print "AB5 == AB4 ? "+str(AB5 == AB4)
people = [ {"name": "Harry", "house": "Gryffindor"}, {"name": "Cho", "house": "Raveclaw"}, {"name": "Draco", "house": "Slytherin"} ] # def a function that tells the sort function how to do the sorting def f(person): # need to tell sort function how to sort these people return person["house"] # sort by persons name/house people.sort(key = f) # sort the people by running this function print(people)
from itertools import chain def maximal_spanning_non_intersecting_subsets(sets): """ Finds the maximal spanning non intersecting subsets of a group of sets This is usefull for parsing out the sandboxes and figuring out how to group and calculate these for thermo documents sets (set(frozenset)): sets of keys to subsect, expected as a set of frozensets """ to_return_subsets = [] # Find the overlapping portions and independent portions for subset in sets: for other_set in sets: subset = frozenset(subset.intersection(other_set)) or subset if subset: to_return_subsets.append(subset) # Remove accounted for elements and recurse on remaining sets accounted_elements = set(chain.from_iterable(to_return_subsets)) sets = {frozenset(subset - accounted_elements) for subset in sets} sets = {subset for subset in sets if subset} if sets: to_return_subsets.extend(maximal_spanning_non_intersecting_subsets(sets)) return set(to_return_subsets)
#!/usr/bin/env python class Sort: def __init__(self, my_list): self.my_list = my_list def bubble_sort(self): if len(self.my_list) > 1: for i in range(len(self.my_list)-1): for j in range(len(self.my_list)-1-i): if self.my_list[j] > self.my_list[j+1]: self.my_list[j], self.my_list[j+1] = self.my_list[j+1], self.my_list[j] return self.my_list def select_sort(self): if len(self.my_list) > 1: for index in range(len(self.my_list)): for i in range(index, len(self.my_list)): if self.my_list[index] > self.my_list[i]: self.my_list[index], self.my_list[i] = self.my_list[i], self.my_list[index] return self.my_list def insert_sort1(self): if len(self.my_list) > 1: for index in range(len(self.my_list)): for i in range(index, 0, -1): if self.my_list[i] < self.my_list[i-1]: self.my_list[i-1], self.my_list[i] = self.my_list[i], self.my_list[i-1] return self.my_list def shell_sort(self): if len(self.my_list) > 1: distance = len(self.my_list)//2 while distance > 0: for index in range(0, len(self.my_list), distance): for i in range(index, 0, -distance): if self.my_list[i] < self.my_list[i - distance]: self.my_list[i - distance], self.my_list[i] = self.my_list[i], self.my_list[i - distance] distance //= 2 return self.my_list def heap_sort(self): """get the index of left and right data""" for i in range(0, len(self.my_list)): index = (len(self.my_list) - i - 2) // 2 for root in range(index, -1, -1): if (2*root+2) < (len(self.my_list)-i) and self.my_list[2*root+2] > self.my_list[2*root+1]: mark = 2 * root + 2 else: mark = 2 * root + 1 if self.my_list[root] > self.my_list[mark]: mark = root if mark != root: self.my_list[root], self.my_list[mark] = self.my_list[mark], self.my_list[root] else: continue self.my_list[0], self.my_list[len(self.my_list)-1-i] = self.my_list[len(self.my_list)-1-i], self.my_list[0] return self.my_list def quick_sort(self): def quicksort(left, right, mylist): print(left, right) if left >= right: return else: benchmark = mylist[left] low = left high = right while left < right: while left < right and mylist[right] >= benchmark: right -= 1 mylist[left] = mylist[right] while left < right and mylist[left] <= benchmark: left += 1 mylist[right] = mylist[left] mylist[right] = benchmark quicksort(low, left-1, mylist) quicksort(left+1, high, mylist) quicksort(0, len(self.my_list) - 1, self.my_list) return self.my_list
# ** MULTIPLES ** # Part I for x in range(1, 1000, 2): print x # Part II for x in range(5, 1000000, 5): print x # ** SUM LIST ** a = [1, 2, 5, 10, 255, 3] sum = 0 for x in a: sum += x print sum # ** AVERAGE LIST ** a = [1, 2, 5, 10, 255, 3] sum = 0 for x in a: sum += x avg = sum / len(a) print avg
class product(object): def __init__(self, price, name, weight, brand, cost): self.price = price self.name = name self.weight = weight self.brand = brand self.cost = cost self.status = 'for sale' self.discount = 'none' #self.show() # optional displays all information about all products # chainable method displays all information for an object/instance def show(self): print 'Brand:', self.brand print 'Item Name:', self.name print 'Price:', '$'+str(self.price) print 'Weight:', self.weight print 'Cost:', '$'+str(self.cost) print 'Status:', self.status print 'Discount:', self.discount, '\n' return self # chainable method sets status value to sold def sell(self): self.status = 'sold' return self # method calculates and returns price including tax # must pass in an argument when calling this method def tax(self, salesTax): return '$'+str(self.price + (self.price * salesTax))+'\n' # chainable method takes argument when called # based on argument will set status, price, and discount def Return(self, reason): if reason == 'defective': self.status = 'defective' self.price = 0 elif reason == 'open box': self.status = 'used' self.price *= 0.8 self.discount = 'Discounted 20%' else: reason == 'like new' return self # instances/objects of product class product1 = product(189, 'Air Max', '13 oz', 'Nike', 76) product2 = product(2399, 'MacBook Pro', '4 lbs', 'Apple', 1100) product3 = product(190700, '911 Turbo S', 'TBD', 'Porsche', 125000) product4 = product(5, "Peppered Bacon", '1 lb', 'Pigler Farms', 1) print 'Total price including tax for your Air Max is', product1.tax(0.1) print product2.Return('open box').show() print product3.sell().show()
class bike(object): def __init__(self, price, maxSpeed): self.price = price self.maxSpeed = maxSpeed self.miles = 0 def displayInfo(self): print 'Price is', self.price, 'Top speed is', self.maxSpeed, 'Miles ridden', self.miles def ride(self): print 'Riding' self.miles += 10 return self def reverse(self): print 'Reversing' if self.miles >= 5: self.miles -= 5 return self unoBike = bike(100, '15 mph') dosBike = bike(500, '25 mph') tresBike = bike(950, '35 mph') print unoBike.ride().ride().ride().reverse().displayInfo() print dosBike.ride().ride().reverse().reverse().displayInfo() print tresBike.reverse().reverse().reverse().displayInfo()
## 1290. Convert Binary Number in a Linked List to Integer ''' Given head which is a reference node to a singly-linked list. The value of each node in the linked list is either 0 or 1. The linked list holds the binary representation of a number. Return the decimal value of the number in the linked list. Example 1: Input: head = [1,0,1] Output: 5 Explanation: (101) in base 2 = (5) in base 10 Example 2: Input: head = [0] Output: 0 Example 3: Input: head = [1] Output: 1 Example 4: Input: head = [1,0,0,1,0,0,1,1,1,0,0,0,0,0,0] Output: 18880 Example 5: Input: head = [0,0] Output: 0 Constraints: The Linked List is not empty. Number of nodes will not exceed 30. Each node's value is either 0 or 1. ''' # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def getDecimalValue(self, head: ListNode) -> int: num=head.val '''takes values from linked list and puts in num''' while head.next: num=num*2 + head.next.val '''converting binary to integer''' head=head.next return num
import pygame import random pygame.init() # grid settings grid = 25 # px screen_width = 30 * grid screen_height = 20 * grid refresh_rate = 1 # ms # character width = grid height = grid win = pygame.display.set_mode((screen_width, screen_height)) alive = True def decide(x, y): # decide direction global length global move if (length == 1 or move != 'RIGHT') and x >= 0: move = random.choice(['LEFT', 'UP', 'DOWN']) elif (length == 1 or move != 'LEFT') and x <= screen_width - width: move = random.choice(['RIGHT', 'UP', 'DOWN']) elif (length == 1 or move != 'UP') and y >= 0: move = random.choice(['LEFT', 'RIGHT', 'DOWN']) elif (length == 1 or move != 'DOWN') and y <= screen_height - height: move = random.choice(['LEFT', 'RIGHT', 'UP']) # if keys[pygame.K_LEFT] and x >= 0: # if length == 1 or move != 'RIGHT': # prevent moving into self # move = 'LEFT' # if keys[pygame.K_RIGHT] and x <= screen_width - width: # if length == 1 or move != 'LEFT': # move = 'RIGHT' # if keys[pygame.K_UP] and y >= 0: # if length == 1 or move != 'DOWN': # move = 'UP' # if keys[pygame.K_DOWN] and y <= screen_height - height: # if length == 1 or move != 'UP': # move = 'DOWN' # main loop while True: x = random.randrange(grid, screen_width - 2*grid, grid) # snake starting coordinates y = random.randrange(grid, screen_height - 2*grid, grid) x_hist = [0, x] y_hist = [0, y] move = 'STOP' apple_x = random.randrange(grid, screen_width - 2*grid, grid) # apple starting coordinates apple_y = random.randrange(grid, screen_height - 2*grid, grid) eaten = False length = 1 while alive: # determine direction decide(x, y) if x < 0 or x > screen_width - width or y < 0 or y > screen_height - height: # hit walls move = 'STOP' alive = False if x == apple_x and y == apple_y: # eat apple apple_x = random.randrange(grid, screen_width - 2*grid, grid) apple_y = random.randrange(grid, screen_height - 2*grid, grid) length += 1 eaten = False # new apple only generated once per collision for i in range(0, length): if x == x_hist[::-1][1+i] and y == y_hist[::-1][1+i]: # collide with self move = 'STOP' alive = False if move == 'LEFT': x -= grid x_hist.append(x) y_hist.append(y) elif move == 'RIGHT': x += grid x_hist.append(x) y_hist.append(y) elif move == 'UP': y -= grid y_hist.append(y) x_hist.append(x) elif move == 'DOWN': y += grid y_hist.append(y) x_hist.append(x) else: break win.fill((0,0,0)) for i in range(0, length): pygame.draw.rect(win, (0,255,0), (x_hist[::-1][0+i], y_hist[::-1][0+i], grid, grid)) # draw character if eaten is False: # draw apple pygame.draw.rect(win, (255,0,0), (apple_x, apple_y, grid, grid)) pygame.display.update() pygame.time.delay(refresh_rate) while alive == False: print(length) alive = True pygame.quit()
#!/usr/bin/python # Rocks, Paper, Scissors ! # Written and Designed by CJ Clark & Chris Clark # No Licence or warranty expressed or implied, use however you wish! import sys, random, argparse, time def findweapon(weapon): if weapon == "s" or weapon == "scissors": print "\n[+] You Picked Scissors! ... sneaky!\n" return "Scissors" if weapon == "r" or weapon == "rock": print "\n[+] You Picked Rock! .. Hulk Smash!!\n" return "Rock" if weapon == "p" or weapon == "paper": print "\n[+] You Picked Paper! .. eeww gross!\n" return "Paper" else: print "\n[-] Woah " + weapon + " is cheating!" print "[-] You need to pick: [R]ocks, [P]aper, or [S]cissor\n" sys.exit(1) def computerweapon(): weapons = ['Rock','Paper','Scissors'] return random.choice(weapons) def battle(p_weapon, c_weapon): if p_weapon == "Rock": if c_weapon == "Rock": winner = "Tie" if c_weapon == "Paper": winner = "Computer" if c_weapon == "Scissors": winner = "Player" if p_weapon == "Paper": if c_weapon == "Rock": winner = "Player" if c_weapon == "Paper": winner = "Tie" if c_weapon == "Scissors": winner = "Computer" if p_weapon == "Scissors": if c_weapon == "Rock": winner = "Computer" if c_weapon == "Paper": winner = "Player" if c_weapon == "Scissors": winner = "Tie" return winner def main(): weapon = raw_input("[+] Chose your Weapon Warrior!! [R]ocks, [P]aper, or [S]cissors \n[+] Pick now: ").lower() # opt=argparse.ArgumentParser(description="RPS! Try to beat the computer at Rocks Paper Scissors!") # opt.add_argument("RPS", help="Pick your weapon! [R]ocks, [P]aper, or [S]cissors") # options= opt.parse_args() # weapon = options.RPS.lower() player_weapon = findweapon(weapon) computer_weapon = computerweapon() time.sleep(2) print "[+] PREPARE FOR BATTLE!!!!\n" time.sleep(2) print "\n[+] The Terminator has chosen " + computer_weapon +"!" winner = battle(player_weapon, computer_weapon) time.sleep(2) if winner == "Tie": print "\n[+] You've TIED!! Weak! Play again!\n" else: print "\n[+] All Hail!! The great " + winner + " is Victorious!!!\n" if __name__ == '__main__': main()
""" 127.单词接龙 给定两个单词(beginWord 和 endWord)和一个字典,找到从 beginWord 到 endWord 的最短转换序列的长度。转换需遵循如下规则: 每次转换只能改变一个字母。 转换过程中的中间单词必须是字典中的单词。 说明: 如果不存在这样的转换序列,返回 0。 所有单词具有相同的长度。 所有单词只由小写字母组成。 字典中不存在重复的单词。 你可以假设 beginWord 和 endWord 是非空的,且二者不相同。 """ from collections import defaultdict def ladderLength(beginWord, endword, wordList): if endword not in wordList or not wordList: return 0 dic = defaultdict(list) for word in wordList: for i in range(len(word)): dic[word[:i]+'*'+word[i+1:]].append(word) que = [(beginWord,1)] have={beginWord:True} while que: current_word, depth = que.pop(0) if current_word == endword: return depth for i in range(len(current_word)): k = current_word[:i]+'*' + current_word[i+1:] if dic.get(k): for w in dic[k]: if not have.get(beginWord): que.append((w, depth+1)) have[w] =True return 0 beginWord = "hit" endWord = "cog" wordList = ["hot","dot","dog","lot","log","cog"] print(ladderLength(beginWord, endWord, wordList))
""" 2019.06.29 判断二叉树 是否是对称的 """ # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None ## 递归 class Solution(object): def isSymmetric(self, root): """ :type root: TreeNode :rtype: bool """ if not root: return True return self.ismirror(root,root) def ismirror(self,root1,root2): if not root1 and not root2: return True if not root2 or not root1: return False if root1.val == root2.val: return True and self.ismirror(root1.left,root2.right) and self.ismirror(root1.right,root2.left) ### 非递归 class Solution_(object): def isSymmetric(self, root): """ :type root: TreeNode :rtype: bool """ if not root: return True stack=[root,root] while stack: node1 = stack.pop(0) node2 = stack.pop(0) if not node1 and not node2: continue if not node1 or not node2: return False if node1.val != node2.val: return False stack.append(node1.left) stack.append(node2.right) stack.append(node1.right) stack.append(node2.left) return True # 非递归 class Solution__: def isSymmetrical(self, root): # write code here if not root: return True q =[root,root] while q: node1,node2 = q.pop(0),q.pop(0) if node1 and node2: if node1.val == node2.val: q.append(node1.left) q.append(node2.right) q.append(node1.right) q.append(node2.left) else: return False if (not node1 and node2 ) or (not node2 and node1): return False return True
""" 131.分割回文串 给定一个字符串 s,将 s 分割成一些子串,使每个子串都是回文串。 返回 s 所有可能的分割方案。 """ def partition(s): if not s: return [] res=[] cur =[] def helper(s, start, cur): if start == len(s): res.append(cur[:]) return else: j = 1 while start+ j <= len(s): ss =s[start:start+j] if ss[::-1] == ss[:]: cur.append(ss[:]) helper(s, start+j,cur) cur.pop() j += 1 helper(s, 0, cur) return res s = 'efe' print(partition(s))
""" 31.下一个排列 实现获取下一个排列的函数,算法需要将给定数字序列重新排列成字典序中下一个更大的排列。 如果不存在下一个更大的排列,则将数字重新排列成最小的排列(即升序排列)。 必须原地修改,只允许使用额外常数空间。 以下是一些例子,输入位于左侧列,其相应输出位于右侧列。 1,2,3 → 1,3,2 3,2,1 → 1,2,3 1,1,5 → 1,5,1 """ def nextPermutation(nums): """ :type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead. """ if not nums: return n = len(nums) flag = 0 for k in range(1, n): if nums[k - 1] >= nums[k]: flag = 0 else: flag = 1 break if flag == 0: print( nums[::-1]) n = len(nums) for i in range(n-1,-1,-1): if nums[i-1] < nums[i]: for j in range(n-1,i-1,-1): if nums[j] > nums[i-1]: tmp = nums[j] nums[j] = nums[i-1] nums[i-1] = tmp break else: continue break else: continue res = inverse(nums,i,len(nums)-1)# 对排序再改进一下 return res def inverse(nums,start,end): if start < end: m = (end-start+1)//2 for i in range(start,start+m,1): tmp = nums[i] nums[i] = nums[end-(i-start)] nums[end-(i-start)] = tmp return nums nums =[1,3,2] print(nextPermutation(nums))
""" 80.删除排序数组中的重复项II 给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素最多出现两次,返回移除后数组的新长度。 不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。 """ def removeDuplicates(nums): flag = 1 i = 0 while i < len(nums): if i > 0 and nums[i] == nums[i-1]: flag += 1 if i>0 and nums[i] != nums[i-1]: flag = 1 if flag > 2: nums.pop(i) flag -=1 else: i+=1 return nums nums=[1,1,1,1] print(removeDuplicates(nums)) # 因为题目要求返回 修改后的数组的长度 def removeDuplicates2(nums): """ :type nums: List[int] :rtype: int """ i = 0 for e in nums: if i < 2 or e != nums[i - 2]: nums[i] = e i += 1 return i nums=[1,1,1,2,2,3] print(removeDuplicates2(nums))
""" 148.在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。 对链表进行归并排序 先递归地分割 再merge """ class ListNode(object): def __init__(self,val): self.val = val self.next = None class Solution(object): def sortList(self, head): """ :type head: ListNode :rtype: ListNode """ if not head or not head.next: return head slow = head fast = head.next while fast and fast.next: fast = fast.next.next slow = slow.next tmp = slow.next mid = tmp slow.next = None # save and cut # recursive for cutting left = self.sortList(head) right = self.sortList(mid) return self.merge(left, right) def merge(self, left, right): res = ListNode(0) h = res # merge while left and right: if left.val < right.val: h.next = left left = left.next h = h.next else: h.next = right right = right.next h = h.next if left: h.next = left else: h.next = right return res.next