text
stringlengths
37
1.41M
#!/usr/bin/python alist=['a','b','c','d','e','f'] orb_pairs=[(i,j) for i in range(len(alist)) for j in range(len(alist)) if i<=j] print orb_pairs count=0 for pindex1 in range(len(orb_pairs)): for pindex2 in range(0,pindex1+1): print "Left side of intrgral = ", orb_pairs[pindex1] print "Right side of intrgral = ", orb_pairs[pindex2] print "----" count+=1 print "total = ",count
#ask for age age = int(input('How old are you? : ')) if age != '': if age<=6: #is a child <=6 print('Child discount') elif age >6 and age<11: #is a family >6 or <=11 print('Family discount') elif age >11 and age<=13: #is a teen >11 or <=13 print('Teen discount') elif age >13 and age<=18: #is a mature >13 or <=18 print('Mature discount') elif age >18 and age<=60: #is an adult >18 or >=60 print('Mature discount') elif age >60: #is a senior < 60 print('Senior discount') else: print('a number is needed...')
# task2.1.py implements a hill climbing algorithm to find a solution for the n-queens problem from a random given pos import random import sys def main(): # input n = int(sys.argv[1]) # board dimension given by user queens = [] # 100 iterations each time itr = 0 while itr < 100: itr += 1 # generate random position for all queens for i in range(n): queens.append(random.randrange(0, n)) # initial display: iterations, queen board, and num initial attacks print("-----Iteration", itr, "-----") print('Initial State') printQueens(queens, n) print("Initial Attacks:", numAttacks(queens, n)) # hill climb with given queen positions hillClimbing(queens, n) queens.clear() # number of attacks per board (counts one attack per pair) # q = list of queen positions, n = board dimension (nxn) def numAttacks(q, n): attacks = 0 for i in range(0, n): for j in range(i+1, n): if q[i] == q[j]: # checks across attacks += 1 elif q[i] - i == q[j] - j or q[i] + i == q[j] + j: # checks diagonals attacks += 1 return attacks # show the board of queens # q = list of queen positions, n = dimension of board (nxn) def printQueens(q, n): board = [['-' for i in range(n)] for i in range(n)] for j in range(n): board[q[j]][j] = 'Q' print('\n'.join([''.join(['{:2}'.format(item) for item in row]) for row in board])) def hillClimbing(q, n): # declare variables qBest = q[:] qTemp = q[:] steps = 0 initial = numAttacks(q, n) best = initial attacks = [] # while still finding a lower value within the last 100 consecutive steps while steps < 100: for i in range(0, n): for j in range(0, n): qTemp[j] = i temp = numAttacks(qTemp, n) # determine number of attacks in each position attacks.append(numAttacks(qTemp, n)) # find the best (lowest) value if temp < best: qBest = qTemp[:] best = temp steps = 0 else: steps += 1 qTemp = qBest[:] print("Final State") printQueens(qBest, n) print("Final Num Attacks:", best) if __name__ == "__main__": main()
# original code """Generate sales report showing total melons each salesperson sold.""" salespeople = [] melons_sold = [] # make a file object "f" from the sales report file f = open('sales-report.txt') # iterate over each line in the file (each order) for line in f: # get rid of extra whitespace/new lines, etc. line = line.rstrip() # split up the line by '|' character and put each element in a list called entries entries = line.split('|') # grab the first of the entries, this is the salesperson salesperson = entries[0] # grab the last of the entries, this is the number of melons sold. cast as int melons = int(entries[2]) # if this salesperson is already in our list if salesperson in salespeople: position = salespeople.index(salesperson) #add the melons in this order to the total number of melons sold for that sales person # the lists are linked by having the same index melons_sold[position] += melons # otherwise add the salesperson to the list else: salespeople.append(salesperson) melons_sold.append(melons) # print the number of melons sold by each sales person for i in range(len(salespeople)): print(f'{salespeople[i]} sold {melons_sold[i]} melons') print('--------------------------------------------') # improved code: use a dictionary instead of two lists. use .get() to replace need for conditional """Generate sales report showing total melons each salesperson sold.""" def get_sales_info(filename): """ Takes in a filename and returns a dictionary with salespeople as keys and melons sold as values File is a text file with each line being a order with salesperson, amount paid, and melons sold separated by | """ # dictionary where salesperson will be key, melons sold will be value melon_sales = {} # make a file object "f" from the sales report file with open(filename) as f: # iterate over each line in the file (each order) for line in f: # get rid of extra whitespace/new lines, etc. line = line.rstrip() # split up the line by '|' character salesperson, payment, melons = line.split('|') melon_sales[salesperson] = melon_sales.get(salesperson, 0) + int(melons) return melon_sales def print_sales_report(melon_sales): """ Takes in a dictionary with {salesperson:total melons sold} and prints out sales report. """ # print the number of melons sold by each sales person for salesperson, melons in melon_sales.items(): print(f'{salesperson} sold {melons} melons') melon_sales = get_sales_info('sales-report.txt') print_sales_report(melon_sales)
# # In this version, the program generates a random number with number of digits equal to length. # # If the command line argument length is not provided, the default value is 1. Then, the program prompts the user to type in a guess, # informing the user of the number of digits expected. The program will then read the user input, and provide basic feedback to the user. # If the guess is correct, the program will print a congratulatory message with the number of guesses made and terminate the game. # Otherwise, # # the program will print a message asking the user to guess a higher or lower number, and prompt the user to type in the next guess. import random,sys def mims_mind(): try: if len(sys.argv)>1: num_of_digits=int(sys.argv[1]) else: print("No command line argument entered,setting it to default number of digits") num_of_digits=1 except: print("Invalid command line argument entered,setting it to default number of digits") num_of_digits=1 start_range=10**(num_of_digits-1) end_range=(10**num_of_digits)-1 num=random.randint(start_range,end_range) guess_count=0 while True: user_num=int(input("Enter your guess")) guess_count+=1 if user_num<num: print("Enter a higher number") print("The correct number is a {} digit number".format(num_of_digits)) elif user_num>num: print("Enter a lower number") print("The correct number is a {} digit number".format(num_of_digits)) else: print("Congratulations, your guess is right!") print("No. of guesses:"+str(guess_count)) break def main(): mims_mind() if __name__=="__main__": main()
# User Input and Type Converting # Accepting User Input # accepting and outputting user input print(input("What is your name?")) # Storing User Input # saving what the user inputs ans = input("What is your name?") print("Hello {}!".format(ans)) # Python defines type conversion functions to directly convert one data type to another. # Checking the Type # how to check the data type of a variable num = 5 print(type(num)) # Converting Data Types # converting a variable from one data type to another num = "9" num = int(num) # re-declaring num to store an integer print(type(num)) # checking type to make sure conversion worked str(9) float(5) int(5.6) int('9') bool('True') int(True) """ Note: Not all data types can be converted properly. There are limits. """ # Converting User Input # working with user input to perform calculations ans = input("Type a number to add:") print(type(ans)) # default type is string, must convert result = 100 + int(ans) print("100 + {} = {}".format(ans, result)) # Handling Errors # using the try and except blocks, use tab to indent where necesary try: ans = float(input("Type a number to add: ")) print("100 + {} = {}".format(ans, 100 + ans)) except: print("You did not put in a valid number!") # without try/except print statement would not get hit if error occurs print("The program did not break!") # Code Blocks and Indentation """ In Python, indentation is required for indicating a block of code. """ """ Note: The indents must be consistent. It does not always need to be four spaces; however, a tab is four spaces, so it's usually easier to indent with tabs. """ # Exercises """ Converting: Try converting a string of “True” to a boolean, and then output its type to make sure it converted properly. """ # Solution myString = bool("True") print(type(myString)) """ Sum of Inputs: Create two input statements, and ask the user to enter two numbers. Print the sum of these numbers out. """ # Solution number1 = int(input("Enter the first number: ")) number2 = int(input("Enter the second number: ")) ans = number1 + number2 print("The sum of the number is {}".format(ans)) """ 3. Car Information: Ask the user to input the year, make, model, and color of their car, and print a nicely formatted statement like “2018 Blue Chevrolet Silverado.” """ yearInput = input("Enter the year: ") makeInput = input("Enter the make: ") modelInput = input("Enter the model: ") colorInput = input("Enter the color: ") print("{} {} {} {}".format(yearInput, colorInput, makeInput, modelInput)) # If Statements # using an if statement to only run code if the condition is met x, y = 5, 10 if x < y: print("x is less than y") # Comparison Operators # == Equality if x == y: # != Inequality if x!= y: # > Greater than if x > y: # < Less than if x < y: # >= Greater or equal if x >= y: # <= Less or equal if <= y: # Checking User Input ans = int(input("What is 5+5? ")) if ans == 10: print("You got it right!") # Logical Operators - used to combine conditional statements # Logical Operator - "and" """ Logical Operator "and" - ensures that when you check multiple conditions, both sides of the condition are True. This means that if either the condition to the left or right of the "and" is False, then the code block will not run. """ # using the keyword 'and' in an 'if statement' x, y, z = 5, 10, 5 if x < y and x == z: print("Both statements were true") # Logical Operator - "or" """ Logical Operator "or" checks for one or both conditions to be true. Such that if the condition to the left is False and the condition to the right is True, the block of code will still run because at least one condition was true. An "if block" will not run if both conditions are False. """ # using keyword 'or' in an 'if statement' x, y, z = 5, 10, 5 if x < y or x != z: print("Both statements were true") # Logical Operator - "not" """ Logical Operator "not" checks for the opposite of a value. """ # using the keyword 'not' within and 'if statement' flag = False if not flag: # same as saying if not true print("Flag is False") """ Note: We get the same result if we write "if flag == False". """ # Membership Operators """ Membership Operators - Used to test if a sequence appears in an object. Keywords used are "in" and "out" """ # Membership Operator "in" - Checks if a given object has a value in it # using the keyword 'in' within an 'if statement' word = 'Baseball' if "b" in word: print("{} contains the character b".format(word)) # Membership Operator "out" - checks to see if an object does not include a specific value # is essentially the opposite of "in" # using the keyword 'not in' within an 'if statement' word = 'Baseball' if "x" not in word: print("{} does not contain the character x".format(word)) # Exercises """ 1. Checking Inclusion – Part 1: Ask the user for input, and check to see if what they wrote includes an “es”. """ # solution userInput = input("Please enter a word: ") if "es" in userInput: print("{} contains 'es'".format(userInput)) """ 2. Checking Inclusion – Part 2: Ask the user for input, and check to see if what they wrote has an “ing” at the end. Hint: Use slicing. """ # solution userInput = input("Please enter a word: ") """ 3. Checking Equality: Ask the user to input two words, and write a conditional statement to check if both words are the same. Make it case insensitive so that capitals do not matter. """ # solution """ 4. Returning Exponents: Ask for the user to input a number, and return that number squared if it is lower than 10. Hint: Investigate arithmetic expressions for exponents. """ # solution """ Elif statements - They give us the ability to run separate blocks of code depending on the condition. They are also known as "else if statements". Elif statement is used to declare another decision based on a given condition. Elif statements must be associated with an if statement. Python works in top to bottom order, so it checks the first if statement; if that statement is False, it continues to the first elif statement and checks that condition. If that condition returns False as well, it continues to the next conditional statement until there are no more to check. However, once a single conditional statement returns True, all other conditionals are skipped, even if they are True. It works so that the first conditional to return True is the only block of code that runs. """ # checking more than one elif conditional statement x, y = 5, 10 if x > y: print("x is greater") elif (x+10) < y: # checking if 15 is less than 10 print("x is less") elif(x+5) == y: # checking if 10 is equal to 10 print("equal") """ Note: Within the conditional, we perform addition, but we wrap it within parenthesis so that it executes te math operation first. """ # Conditionals Within Conditionals # writing multiple conditionals within each other - multiple block levels x, y, z = 5, 10, 5 if x > y: print("greater") elif x <= y: if x == z: print("x is equal to z") # resulting output elif x != z: print("x is not equal to z") # won't get hit # If Statements vs. Elif Statements """ A major difference that you’ll need to understand going forward is the use for elif statements against using multiple if statements. All elif statements are connected to one original if statement, so that once a single conditional is True, the rest do not run. """ # testing output of two if statements in a row that are both true x, y, z = 5, 10, 5 if x < y: print("x is less") if x == z: print("x is equal") # testing output of an if and elif statement that are both true x, y, z = 5, 10, 5 if x < y: print("x is less") elif x == z: print("x is equal to z") # Exercises """1. Higher/Lower: Ask the user to input a number. Type convert that number, and use an if/elif statement to print whether it’s higher or lower than 100. """ # solution """ 2. Find the Solution: Given the following code, fix any/all errors in order to make it output “lower”: x, y = 5, 10 if x > y: print("greater") try x < y: print("lower") """ # solution # Else Statements """ This is the default action of a decision. Else conditional statements are the end all be all of the if statement. Sometimes you’re not able to create a condition for every decision you want to make, so that’s where the else statement is useful. The else statement will cover all other possibilities not covered and will always run the code if the program gets to it. This means that if an elif or if statement were to return True, then it would never run the else; however, if they all return False, then the else clause would run no matter what every time. """ # using an else statement name = "John" if name == "Jacob": print("Hello Jacob!") else: print("Hello {}!".format(name)) # Complete Conditional Statement # writing a full conditional statement with if, elif, else name = "John" if name[0] == "A": print("Name starts with an A") elif name[0] == "B": print("Name starts with a B") elif name[0] == "J": print("Name starts with a J") else: # Covers all other possibilities print("Name starts with a {}".format(name[0])) # Exercises """ 1. Fix the Errors: Given the following code, fix any/all errors so that it outputs “Hello John” correctly: >>> name = "John" >>> if name == "Jack": >>> print("Hello Jack") >>> elif: >>>> print("Hello John") """ # solution """ 2. User Input: Ask the user to input the time of day in military time without a colon (1100 = 11:00 AM). Write a conditional statement so that it outputs the following: a. “Good Morning” if less than 1200 b. “Good Afternoon” if between 1200 and 1700 c. “Good Evening” if equal or above 1700 """ # solution # solution timeInput = int(input("Please enter the time in 24hr format: ")) if timeInput < 1200: print("Good Morning") elif 1200 < timeInput < 1700: print("Good Afternoon") else: print("Good Evening")
# Creating a User Database with CSV Files # import all necessary packages import csv from IPython.display import clear_output # handle user registration and writing to csv def registerUser(): with open("users.csv", mode="a", newline="") as f: writer = csv.writer(f, delimiter=",") print("To register, please enter your info:") email = input("E-mail: ") password = input("Password: ") password2 = input("Re-type password: ") clear_output() if password == password2: writer.writerow([email, password]) print("You're now registered!") else: print("Something went wrong. Try again.") # Handling User Login # ask for use info and return true to login or false if incorrect info def loginUser(): print("To login, please enter your info: ") print("+"*50) email = input("E-mail: ") password = input("Password: ") clear_output() with open("users.csv", mode="r") as f: reader = csv.reader(f, delimiter=",") for row in reader: if row == [email, password]: print("You are now logged in!") print("+"*50) return True print("Something went wrong. Try again.") print("+"*50) return False # adding changing of passwords functionality def changePassword(): with open("users.csv", mode="a", newline="") as f: writer = csv.writer(f, delimiter=",") email = input("Please enter your email: ") print("Please enter your new password:") password = input("Password: ") password2 = input("Confirm new password: ") clear_output() if password == password2: writer.writerow([email, password]) print("Your password has been successfully changed!") print("+"*50) else: print("Something went wrong. Try again.") print("+"*50) # Creating the Main Loop - handles system menu and what to show based on the user being logged in or not # variables for main loop active = True logged_in = False # main loop while active: if logged_in: print("1. Logout\n2. Quit\n3. Change Password") else: print("1. Login\n2. Register\n3. Quit") choice = input("What would you like to do? ").lower() clear_output() print("+"*50) if choice == "register" and logged_in == False: registerUser() elif choice == "login" and logged_in == False: logged_in = loginUser() elif choice == "quit": active = False print("Thanks for using our software!") print("+"*50) elif choice == "logout" and logged_in == True: logged_in = False print("You're now logged out.") print("+"*50) elif choice == "change password" and logged_in == True: logged_in = changePassword() else: print("Sorry, please try again!") print("+"*50)
import random secret = random.randint(1, 100) guess, tries = 0, 0 #for i in range(6): while tries < 6: print("pls guess the number:") guess = int(input()) if guess == secret: print("You are a lucky man! You guessed it! The number is %d" % secret) print("You guessed %d times!" % (tries+1)) break elif guess > secret: print("You guessed is too larger!") elif guess < secret: print ("you guessed is too small!") tries += 1 else: print("You wasted too many times!") print("The number is %d" % secret)
n = int(input("Number of white balls: ")) m = int(input("Number of black balls: ")) k = int(input("Number of sampled balls: ")) ballsNumber = n + m # number of all balls twoWhite = 1 twoBlack = 1 if n>=k: tmp = ballsNumber i = k while i>0: twoWhite *= (n/tmp) n -= 1 tmp -= 1 i -= 1 else: twoWhite = 0 if m>=k: tmp = ballsNumber i = k while i>0: twoBlack *= (m/tmp) m -= 1 tmp -= 1 i -= 1 else: twoBlack = 0 print("Probability of 2 balls of the same color: ", twoWhite+twoBlack)
def find_max_crossing_subarray(A, low, mid, high): left-sum = -floot('inf') sum = 0 for i in range(mid,low-1, -1): sum = sum + A[i] if sum > left-sum left-sum = sum max-left = i right-sum = -floot('inf') sum = 0 for j in range(mid+1,high+1): sum = sum + A[j] if sum > right-sum: right-sum = sum max-right = j return [max-left, max-right, left-sum + right-sum] import math def find_maximum_subarray(A, low, high): if high == low: return [low, high, A[low]] else: mid = floor((low + high) / 2) left-maximum = find_maximum_subarray(A, low, mid) right-maximum = find_maximum_subarray(A, mid + 1, high) cross-maximum = find_max_crossing_subarray(A, low, mid, high) if left-maximum[3] >= right-maximum[3] and left-maximum[3] >= cross-maximum[3]: return left-maximum elif right-maximum[3] >= left-maximum[3] and right-maximum[3] >= cross-maximum[3]: return right-maximum else: return cross-maximum
import numpy as np import sympy def riemann_curvature_tensor(list2d, syms): """ Function to calculate Riemann Curvature Tensor of a given metric Parameters ---------- list2d : list d list (Matrix) representing metric, containing ~sympy expressions syms : list 1d list containing representaion of [x0,x1,x2...] in ~sympy expressions Returns ------- list 4d list of ~sympy expressions containing components of Riemann Tensor """ christs = christoffels(list2d, syms) dims = len(syms) riemann_list = (np.zeros(shape=(dims, dims, dims, dims), dtype=int)).tolist() _counterlist = [i for i in range(dims ** 4)] for i in _counterlist: # t,s,r,n each goes from 0 to (dims-1) # hack for codeclimate. Could be done with 4 nested for loops n = i % dims r = (int(i / dims)) % (dims) s = (int(i / (dims ** 2))) % (dims) t = (int(i / (dims ** 3))) % (dims) temp = sympy.diff(christs[t][s][n], syms[r]) - sympy.diff( christs[t][r][n], syms[s] ) for p in range(dims): temp += (christs[p][s][n] * christs[t][p][r]) - christs[p][r][n] * christs[ t ][p][s] riemann_list[t][s][r][n] = sympy.simplify(temp) return riemann_list def christoffels(list2d, syms): """ Function to calculate christoffel symbols of a given metric Parameters ---------- list2d : list 2d list (Matrix) representing metric, containing ~sympy expressions syms : list 1d list containing representaion of [x0,x1,x2...] in ~sympy expressions Returns ------- list 3d list of ~sympy expressions containing christoffel symbols """ dims = len(syms) christlist = (np.zeros(shape=(dims, dims, dims), dtype=int)).tolist() mat = sympy.Matrix(list2d) mat_inv = mat.inv() _counterlist = [i for i in range(dims ** 3)] for t in _counterlist: # i,j,k each goes from 0 to (dims-1) # hack for codeclimate. Could be done with 3 nested for loops k = t % dims j = (int(t / dims)) % (dims) i = (int(t / (dims ** 2))) % (dims) temp = 0 for n in range(dims): temp += (mat_inv[i, n] / 2) * ( sympy.diff(list2d[n][j], syms[k]) + sympy.diff(list2d[n][k], syms[j]) - sympy.diff(list2d[j][k], syms[n]) ) christlist[i][j][k] = temp return christlist def _simplify_tensor_helper(v): returnval = None if isinstance(v, list): newlist = list() for t in v: newlist.append(_simplify_tensor_helper(t)) returnval = newlist else: returnval = sympy.simplify(v) return returnval def simplify_tensor(ndlist): """ Returns a N-Dimensional list of simplified symbolic tensor Parameters ---------- ndlist : list N-Dimensional list of sympy expressions representing some tensor Returns ------- list N-Dimensional list """ return _simplify_tensor_helper(ndlist) def simplify_christoffels(list3d, dims=4): """ Returns a 3d list of simplified christoffel symbols. Parameters ---------- list3d : list 3d list containing christoffel symbols expression dims : int dimension of space, defaults to 4 Returns ------- list 3d list containing simplified christoffel symbols """ _counterlist = [i for i in range(dims ** 3)] new_list3d = (np.zeros(shape=(dims, dims, dims), dtype=int)).tolist() for t in _counterlist: k = t % dims j = (int(t / dims)) % (dims) i = (int(t / (dims ** 2))) % (dims) new_list3d[i][j][k] = sympy.simplify(list3d[i][j][k]) return new_list3d def schwarzschild_christoffels(symbolstr="t r theta phi"): """ Returns the 3d list of christoffel symbols of Schwarzschild Metric. Parameters ---------- symbolstr : string symbols to be used to define schwarzschild space, defaults to 't r theta phi' Returns ------- list 3d list of christoffel symbols for schwarzschild metric """ list2d = [[0 for i in range(4)] for i in range(4)] syms = sympy.symbols(symbolstr) c, a = sympy.symbols("c a") list2d[0][0] = 1 - (a / syms[1]) list2d[1][1] = -1 / ((1 - (a / syms[1])) * (c ** 2)) list2d[2][2] = -1 * (syms[1] ** 2) / (c ** 2) list2d[3][3] = -1 * (syms[1] ** 2) * (sympy.sin(syms[2]) ** 2) / (c ** 2) return christoffels(list2d, syms) def kerr_christoffels(symbolstr="t r theta phi"): """ Returns the 3d list of christoffel symbols of Kerr metric(BL coordinates) in Plank units : G=1, c=1. Parameters ---------- symbolstr : string symbols to be used to define kerr space in BL coordinates, defaults to 't r theta phi' Returns ------- list 3d list of christoffel symbols for kerr metric """ list2d = [[0 for i in range(4)] for i in range(4)] syms = sympy.symbols(symbolstr) a, R = sympy.symbols("a R") A = syms[1] ** 2 - R * syms[1] + a ** 2 sigma = syms[1] ** 2 + (a ** 2) * (sympy.cos(syms[2]) ** 2) list2d[0][0] = (R * syms[1] / sigma) - 1 list2d[1][1] = sigma / A list2d[2][2] = sigma list2d[3][3] = ( (sympy.sin(syms[2]) ** 2) * ((a ** 2 + syms[1] ** 2) ** 2 - (a ** 2) * (A * (sympy.sin(syms[2]) ** 2))) ) / sigma list2d[3][0] = -1 * (R * a * (syms[1])) * (sympy.sin(syms[2]) ** 2) / sigma list2d[0][3] = list2d[3][0] return christoffels(list2d, syms)
import numpy as np import random import PriorityQueue EMPTY = 0 WALL = 1 GHOST = 2 PACMAN = 3 class Board: def __init__(self, row, column): self.row = row self.column = column self.board = np.zeros(row*column).reshape(row, column) self.board[0][0] = PACMAN #default - can be changed by using method putPacman #to randomly place walls and ghosts def randomize(self): for i in range(self.row): for j in range(self.column): if self.board[i][j] != PACMAN: self.board[i][j] = random.randint(0,2) #to replace pacman def putPacman(self, location): if location[0] >= self.row or location[1] >= self.column or location[0] < 0 or location[1] < 0 or self.board[location[0]][location[1]] != EMPTY: print("Cannot put Pacman in cell: " + location.__str__()) return #delete existing pacman for i in range(0, self.row): for j in range(0,self.column): if self.board[i][j] == PACMAN: self.board[i][j] = 0 break self.board[location[0]][location[1]] = PACMAN def putGhost(self, locations): for item in locations: if item[0] < self.row and item[1] < self.column and item[0] >= 0 and item[1] >= 0 and self.board[item[0]][item[1]] == EMPTY: self.board[item[0]][item[1]] = GHOST else: print("Cannot put ghost in cell: " + item.__str__()) def putWalls(self, locations): for item in locations: if item[0] < self.row and item[1] < self.column and item[0] >= 0 and item[1] >= 0 and self.board[item[0]][item[1]] == EMPTY: self.board[item[0]][item[1]] = WALL else: print("Cannot put Wall in cell: " + item.__str__()) def putEmpty(self, locations): for item in locations: if item[0] < self.row and item[1] < self.column and item[0] >= 0 and item[1] >= 0 and self.board[item[0]][item[1]] != PACMAN: self.board[item[0]][item[1]] = WALL else: print("Cannot put Clear cell: " + item.__str__()) def findPacman(self): for i in range(0, self.row): for j in range(0,self.column): if self.board[i][j] == PACMAN: return [i,j] #return a list of possible moves from an exsiting cell in the matrix def getSuccessors(self, state): x = state[0] y = state[1] succ = [] if x > 0 and self.board[x-1, y] != WALL: succ.append([x-1, y]) if x < self.row - 1 and self.board[x+1, y] != WALL: succ.append([x+1, y]) if y > 0 and self.board[x, y-1] != WALL: succ.append([x, y-1]) if y < self.column - 1 and self.board[x, y+1] != WALL: succ.append([x, y+1]) return succ def ghostList(self): ghosts = [] for i in range(0, self.row): for j in range(0, self.column): if self.board[i][j] == GHOST: ghosts.append([i, j]) return ghosts #prints out shortest distance of all reachable ghosts def findGhosts(self): ghosts = self.ghostList() frontier = PriorityQueue.PriorityQueue() visited = [] state = self.findPacman() node = {} node["state"] = state node["cost"] = 0 frontier.push(node, node["cost"]) # push beginning state with its cost into queue # loop through queue using cost method while not frontier.isEmpty() and not ghosts.__len__() <= 0: node = frontier.pop() state = node["state"] cost = node["cost"] if state in visited: continue visited.append(state) if self.board[state[0]][state[1]] == GHOST: print("shortest distance to Ghost: " + repr(state) + " is " + repr(node["cost"])) ghosts.remove([state[0], state[1]]) continue for move in self.getSuccessors(state): # for each child of the node if move not in visited: # if haven't visit it sub_node = {} # create a node of it to push it to frontier sub_node["state"] = move sub_node["cost"] = node["cost"] + 1 frontier.push(sub_node, sub_node["cost"]) for item in ghosts: print("shortest distance to Ghost: " + repr(item) + " is infinity") def heuristic(self, state, ghost): manhattanDistance = abs(state[0] - ghost[0]) + abs(state[1] - ghost[1]) return manhattanDistance #does the same thing as findGhosts by using a heuristic function - run time is faster def findGhostsHeuristic(self): ghosts = self.ghostList() pacmanState = self.findPacman() for item in ghosts: node = {} node["state"] = pacmanState node["cost"] = 0 frontier = PriorityQueue.PriorityQueue() visited = [] frontier.push(node, node["cost"]) # push beginning state with its cost into queue # loop through queue using cost method while True: if frontier.isEmpty(): print("shortest distance to Ghost: " + repr(item) + " is infinity") break node = frontier.pop() state = node["state"] cost = node["cost"] if state in visited: continue visited.append(state) if [state[0],state[1]] == item: print("shortest distance to Ghost: " + repr(state) + " is " + repr(node["cost"])) break if self.board[state[0]][state[1]] == GHOST: continue for move in self.getSuccessors(state): # for each child of the node if move not in visited: # if haven't visit it sub_node = {} # create a node of it to push it to frontier sub_node["state"] = move sub_node["cost"] = node["cost"] + 1 frontier.push(sub_node, sub_node["cost"] + self.heuristic(move, item))
#Write a function named feed_to_inches that accepts a number of feet as an argument and returns the number of inches in that many feet def feet_to_inches(feet): return 12.0 * feet # Function that gathers data from user and calculates def main(): feet = float(input('Enter the number of feet you would like converted to inches: ')) inches = feet_to_inches(feet) print('There are', inches, "inches in", feet, "feet.") # Call the function to execute main()
#Begin Wifi troubleshooting print('Welcome to the Wifi fixer 9000.') begin = input("Reboot the computer and try to connect. Did that fix the problem? Yes/No: ") #If answer yes, end program with you're welcome. Otherwise, proceed to the next step if begin == "Yes" or begin == "yes": print("You're welcome.") else: router = input("Reboot the router and try to connect. Did that fix the problem? Yes/No: ") if router == "Yes" or router == "yes": print("You're welcome.") else: cables = input("Make sure the cables between the router & modem are plugged in firmly. Did that fix the problem? Yes/No: ") if cables == "Yes" or cables == "yes": print("You're welcome.") else: location = input("Move the router to a new location and try to connect. Did that fix the problem? Yes/No: ") if location == "Yes" or location == "yes": print("You're welcome.") else: print("Get a new router.")
""" This module handles logic for tokenizing rules scripts into tokens, ready for parsing """ import regex def tokenize_string(string): """ Splits a given string into tokens, ready for parsing Arguments: string - The string to split Returns: A list of tokens from the string """ #This regex splits on borders between tokens split_anchors = [r'\s+(?=(?:[^\'"]*[\'"][^\'"]*[\'"])*[^\'"]*$)', r'(?=[()\[\]{};=&\|,])(?=(?:[^\'"]*[\'"][^\'"]*[\'"])*[^\'"]*$)', r'(?<=[()\[\]{};=&\|,])(?=(?:[^\'"]*[\'"][^\'"]*[\'"])*[^\'"]*$)'] border_regex = '|'.join(split_anchors) tokens = regex.split(border_regex, string, flags=regex.VERSION1) #Remove empty tokens tokens = [token for token in tokens if token and len(token) > 0] return tokens
def phoneLetter(digs): if not digs: return [] keyboard = { "2": "abc", "3": "def", "4": "ghi", "5": "jkl", "6": "mno", "7": "pqrs", "8": "tuv", "9": "wxyz" } res = [] if len(digs) == 0: return [] if len(digs) == 1: return keyboard[digs] result = phoneLetter(digs[1:]) for i in result: for j in keyboard[digs[0]]: res.append((j + i)) return res if __name__ =='__main__': print(phoneLetter("23"))
# import the random module import random # generate a random value between 1 and 6 for each of the three die # store the three values in a list playerDie1 = random.randint(1,6) playerDie2 = random.randint(1,6) playerDie3 = random.randint(1,6) playerDice = [playerDie1, playerDie2, playerDie3] # Display the value of each of die print(playerDice) playerTotal = 0 # add up the value of each of the player die and display the total for x in playerDice: playerTotal=playerTotal+x print("Player's total: "+ str(playerTotal)) # generate a random value between 1 and 6 for each of the three die # store the three values in a list computerDie1 = random.randint(1,6) computerDie2 = random.randint(1,6) computerDie3 = random.randint(1,6) computerDice = [computerDie1, computerDie2, computerDie3] # add up the value of each of the computer die and display the total print(computerDice) computerTotal = 0 for y in computerDice: computerTotal=computerTotal+y print("computer's total: "+ str(computerTotal)) # If the total of the player dice is more than 12 the player looses if playerTotal > 12: print("Busted. You lose") # If the total of the player dice is less than 12 the player is offered to play again else: answer = input("Would you like to keep playing? (Y/N)") # If the player answers Y ask the which die they want to play if answer == "Y": play1 = input("Which die would you like to throw again?") # Play the die the user has chosen # Replace the old value for that die with the new value in the list if play1 == "1": die1 = random.randint(1,6) playerDice[0]=die1 elif play1 == "2": die2 = random.randint(1,6) playerDice[1]=die2 else: die3 = random.randint(1,6) playerDice[2]=die3 # Add up the value of each of the player die and display the total playerTotal = 0 for x in playerDice: playerTotal=playerTotal+x # Assess the result # If the total of the player dice is more than 12, the player has lost # display the value of each die # display the player total # display the looser message if playerTotal > 12: print(playerDice) print("Player's total: "+ str(playerTotal)) print("Busted. You lose") # If the total of the computer dice is more than 12, the computer has lost # display the value of each die # display the player total # display the computer total # display the winner message elif computerTotal > 12: print(playerDice) print("Player's total: "+ str(playerTotal)) print("Computer's total: "+ str(computerTotal)) print("Computer busted. You win!") # If the total of the player dice is equal to 12, the player has won # display the value of each die # display the player total # display the computer total # display the winner message elif playerTotal == 12: print(playerDice) print("Player's total: "+ str(playerTotal)) print("Computer's total: "+ str(computerTotal)) print("You win!") # If the total of the computer dice is less than 12 AND the player total is more than the computer total, the player has won # display the value of each die # display the player total # display the computer total # display the winner message elif computerTotal < 12 and playerTotal > computerTotal: print(playerDice) print("Player's total: "+ str(playerTotal)) print("Computer's total: "+ str(computerTotal)) print("You win!") # If the total of the computer dice is less than 12 AND the player total is less than the computer total, the player has lost # display the value of each die # display the player total # display the computer total # display the loser message else: print(playerDice) print("Player's total: "+ str(playerTotal)) print("Computer's total: "+ str(computerTotal)) print("You lose!")
# This program will demonstrate the use of variables in python (just few of them) x = 'Dipak Bari' y = 27 print(x) print(y)
print("Demonstrates the indentations and their values in Python!") def main(): print("Inside the main function") #This will called later print("Doesn't relate with main function") #This will called first at executioin if __name__ == "__main__": main() #executing the main function
# Key to sort array by number def sort_key(val): return val[1] # Key to sort array by alphabet def sort_key2(val): return val[0] if __name__ == '__main__': # adds inputs to an array arr = [] for _ in range(int(input())): name = input() score = float(input()) arr.append([name, score]) arr.sort(key=sort_key) # gets min value min = arr[0][1] # puts second min value for x in arr: if x[1] > min: second_min = x[1] pos = x break #adds all second min value to answer array answer = [] for i in arr[1:]: if i[1] == second_min: answer.append(i) if i[1] > second_min: break #sorts asnwer array alphabetically and prints output answer.sort(key=sort_key2) for z in answer: print(z[0])
# append times tables to existing file, first col right justified with open(".\\Section 10\\challenge.txt", 'w') as existing: print("Existing", file=existing) with open(".\\Section 10\\challenge.txt", 'a') as append: for i in range(1, 13): # what does > do exactly? doesnt seem nevessary print("{0:>2} times 2 is {1}".format(i, 2 * i), file=append)
for i in range(17): print("{0:>2} in binary is {0:>08b}".format(i)) # 0b to indicate binary x = 0b101010 print(x) # 42
ipAddress = "192.168.0.1" print(ipAddress.count(".")) parrot_list = ["not pinin'", "no more", "a stiff", "bereft of life"] parrot_list.append("a Norwegian Blue") for state in parrot_list: print("This parrot is " + state) even = [2, 4, 6, 8] odd = [1, 3, 5, 7, 9] numbers = even + odd # concats numbers.sort() # in place, doesnt return modified list, returns None sortedNums = sorted(numbers) # returns a new list print(numbers) if numbers == sortedNums: print("equal") # hit if numbers are sorted (SequenceEqual) else: print("not equal") # hit if numbers are unsorted # both empty lists, are equal list_1 = [] list_2 = list() if list_1 == list_2: print("lists equals") print(list("the lists are equal")) # list of chars even = [2, 4, 6, 8] another_even = even another_even.sort(reverse=True) print(even) # prints 8, 6, 4, 2 print(another_even is even) # true print(even is list(even)) # false, checks for memory loc print(even == another_even) # true even = [2, 4, 6, 8] odd = [1, 3, 5, 7, 9] numbers = [even, odd] print(numbers) # list of the two lists for number_set in numbers: print(number_set) for value in number_set: print(value)
for i in range(10): print(i) # same as above i = 0 while i < 10: print(i) i += 1 available_exits = ["east", "north east", "south"] chosen_exit = "" while chosen_exit not in available_exits: chosen_exit = "east" # choose a direction, could be from input # point is that you don't know in advance when to exit # e.g. reading from file if chosen_exit == "quit": print("Game over") break else: print("Got out") import random answer = random.randint(1, 10) guess = 0 while guess != answer: if guess < answer: print("Guess higher") guess = answer else: print("Guess lower") else: print("Well done")
# shelve good if you don't want to read things # entirely into memory before pickling them # shelf is a dict with string key and picklable val # calling file needs to be called something other than shelve.py import shelve # creates bak, dat and dir files i.e. a database with shelve.open(".\\Section 10\\ShelfTest") as fruit: fruit['orange'] = "a sweet, orange, citrus fruit" fruit['lemon'] = "a sour, yellow cirtus fruit" print(fruit['lemon']) # this will overwrite the previous value fruit['lemon'] = "nice with vodka" # this gives a ValueError as invalid op on a closed shelf # can manually call open and .close() if more control required # print(fruit['lemon']) # not a dictionary, so can't create a shelf with a literal statement print(fruit) with shelve.open(".\\Section 10\\ShelfTest") as fruit: fruit['orange'] = "a sweet, orange, citrus fruit" fruit['lemn'] = "a sour, yellow cirtus fruit" # shelves persist so we can end up with undesired keys from typos print(fruit['lemon']) print(fruit['lemn']) # can remove though! del fruit['lemn'] # print(fruit['lemn']) # now doesn't work, KeyError # shelf is unordered so need to sort keys first fruit = shelve.open(".\\Section 10\\ShelfTest") ordered_keys = sorted(list(fruit.keys())) for f in ordered_keys: print(f + ": " + fruit[f]) print(fruit.values()) # ValuesView, no details printed for f in fruit.items(): print(f) # List of tuples print(fruit.items()) # ItemsView, no details printed fruit.close() # overall a shelf acts a bit like a dictionary, but keys must be strings
'''1. Write a Python function to find the Max of three numbers.''' # def max_func(a,b,c): # if a > b and a > c: # print("{} is greater".format(a)) # elif b > a and b > c: # print("{} is greater".format(b)) # else: # print("{} is greater".format(c)) # max_func(10,20,30) # max_func(15,20,5) # max_func(20,10,5) '''2. Write a Python function to sum all the numbers in a list''' # def total(a): # s = 0 # for x in range(len(a)): # s += a[x] # print(s) # total([10, 20, 30]) # total([21, 19, 20]) '''3. Write a Python function to multiply all the numbers in a list.''' # def multi(a): # s = 1 # for x in range(len(a)): # s *= a[x] # print(s) # multi([10, 20, 30]) # multi([21, 19, 20]) '''4. Write a Python program to reverse a string''' # def rev(a): # print("reverse",a[::-1]) # rev('1234abcd') '''5. Write a Python function to calculate the factorial of a number (a non-negative integer). The function accepts the number as an argument''' # def fact(n): # if n == 0 : # return 1 # else: # return n * fact(n-1) # print("the factorail is:",fact(4)) '''6. Write a Python function to check whether a number is in a given range.''' # def check(n): # if n in range(1,10): # print("{} it is within range ".format(n)) # else: # print("{} out of range".format(n)) # check(5) # check(11) '''7. Write a Python function that accepts a string and calculate the number of upper case letters and lower case letters''' # def no_string(str1): # upper = 0 # lower = 0 # for i in str1: # if i.islower(): # lower += 1 # elif i.isupper(): # upper += 1 # print("lower characters",lower) # print("upper characters",upper) # print(no_string("This is James")) '''8**. Write a Python function that takes a list and returns a new list with unique elements of the first list.''' # def unique_elements(u): # e = set(u) # print("unique elements: ", e ) # unique_elements([1,2,3,3,3,4]) '''9. Write a Python function that takes a number as a parameter and check the number is prime or not''' # def prime(p): # if p == 0: # return False # elif p == 1: # return True # for n in range(2,p): # if p % n == 0: # return "{} is not prime no".format(p) # else: # return "{} is prime no".format(p) # print(prime(10)) # print(prime(5)) '''10. Write a Python program to print the even numbers from a given list''' # def even(e): # a = [] # for i in e: # if i % 2 == 0: # a.append(i) # return a # print(even([1, 2, 3, 4, 10, 6])) '''11. Write a Python function to check whether a number is perfect or not.''' # def perfect(a): # result = 0 # for i in range(1,a): # if a % i == 0: # result += i # return result == a # print(perfect(6)) '''12. Write a Python function that checks whether a passed string is palindrome or not''' # def palidrome(s): # s = s.lower() # if s == s[::-1]: # print("{} is palideome".format(s)) # else: # print("{} is not palideome".format(s)) # palidrome('mom') # palidrome('jane') '''13. Write a Python function that prints out the first n rows of Pascal's triangle.(***)''' # def pascal(n): # row = [1] # y = [0] # for i in range(max(n,0)): # print(row) # row = [l+r for l,r in zip(row + y,y + row)] # return n>1 # pascal(6) '''14. Write a Python function to check whether a string is a pangram or not.(***) ''' # import string,sys # def pangram(str1, alphabeth = string.ascii_lowercase): # alphabeth= set(alphabeth) # return alphabeth <= set(str1.lower()) # print(pangram('The quick brown fox jumps over lazy dog')) '''15. Write a Python program that accepts a hyphen-separated sequence of words as input and prints the words in a hyphen-separated sequence after sorting them alphabetically.((***))''' # def hyphen(str1): # item = [n for n in str1.split('-')] # item.sort() # print('-'.join(item)) # hyphen('green-red-yellow-black-white') '''16. Write a Python function to create and print a list where the values are square of numbers between 1 and 30 (both included).''' # def square(): # s = [x**2 for x in range(0,21)] # print(s) # square() '''17. Write a Python program to make a chain of function decorators (bold, italic, underline etc.) in Python.''' # def bold(fn): # def wrapped(): # return "<b>" + fn() +"</b>" # return wrapped # def italic(fn): # def wrapped(): # return "<i>" + fn() +"</i>" # return wrapped # def underline(fn): # def wrapped(): # return "<u>" + fn() +"</u>" # return wrapped # @bold # @italic # @underline # def hello(): # return "hello world" # print(hello()) '''18. Write a Python program to execute a string containing Python code.''' # a = "" # def p (a,b): # print(a+b) # p(10,20) # "" '''19. Write a Python program to access a function inside a function''' # def fun(): # print("hello") # def func1(a,b): # print(a+b) # return func1(10,20) # fun() '''20. Write a Python program to detect the number of local variables declared in a function. ''' # def local_var(): # a = 10 # str1 = 'Hello' # print(local_var.__code__.co_nlocals)
import random import time # The following code defines how to remove spelling and punctuation. def removepunc(listx): def removeall (listy, removed): while listy.count (removed) > 0: listy.remove(removed) return(listy) listx = removeall(listx, ".") listx = removeall(listx, ",") listx = removeall(listx, "'") listx = removeall(listx, "!") listx = removeall(listx, "?") listx = removeall(listx, "'") listx = removeall (listx, "/") return listx def formstring (listz): count = 0 word = "" while count < len(listz): word += listz[count] count += 1 return word def replacelist (list, startingvalue, endingvalue): toReturn = [] for x in list: if x == startingvalue: toReturn += [endingvalue] else: toReturn += [x] return toReturn # The following code defines how combat works def combat(cstats, cdamagemin, cdamagemax, cweapon, etype, elocation, cmagic, etitle): # The following code defines how to remove punctuation def removepunc(listx): def removeall (listy, removed): while listy.count (removed) > 0: listy.remove(removed) return(listy) listx = removeall(listx, ".") listx = removeall(listx, ",") listx = removeall(listx, "'") listx = removeall(listx, "!") listx = removeall(listx, "?") listx = removeall(listx, "'") listx = removeall (listx, "/") listx = removeall(listx, " ") return listx def formstring (listz): count = 0 word = "" while count < len(listz): word += listz[count] count += 1 return word # The following code defines how to make random choices from a list. def randchoice(listy): numy = random.randint(1, len(listy)) - 1 return listy[numy] # This code parses your stats into its parts chealth = cstats[0] cinventory = cstats[1] carmormax = cstats[2] carmor = cstats[2] cmana = cstats[3] # This code defines your enemies' stats based on its' type. if etype == "Guard": ehealth = 12 ehealthmax = 12 eatkmin = 2 eatkmax = 10 earmor = 4 eweaponname = "Spear" earmorname = "Armor" einventory = list(["Spear", "Mail Armor"]) eai = "Defensive" elif etype == "Soldier": ehealth = 12 ehealthmax = 12 eatkmin = 2 eatkmax = 10 earmor = 4 eweaponname = "Spear" earmorname = "Armor" einventory = list(["Spear", "Mail Armor"]) eai = "Aggressive" elif etype == "Wolf": ehealth = 7 ehealthmax = 7 eatkmin = 2 eatkmax = 5 earmor = 1 eweaponname = "Bite" earmorname = "Fur" einventory = list([(WolfCorpseName)]) eai = "Aggressive" # This code writes a description based on the location and enemy type. if elocation == "Field": starterdescription = (etitle+" stands in the grass ahead of you, bearing its "+str.lower(eweaponname)+".") # This introduces the combat print (starterdescription) # This defines any combat variables ehit = 0 burnout = 0 # This runs the combat while chealth > 0 and ehealth > 0 and health > 0: # This code asks you what you want to do. print ("What do you do?") print (" 1: Nothing.") print (" 2: Run away.") print (" 3: Attack.") if cmagic == 1: print (" 5: Cast a spell.") caction = input ("") ''' # This code runs if you want to use an item. if caction == "2": # This code asks you what items you want to use. print ("You have the following items in your inventory:") count = 0 for item in inventory: count += 1 print ("Name the item you want to use.") citem = input ("") ''' # This code runs if you try to run if caction == "2": if eai == "Aggressive" and random.randint(1,2) == 1: print("You run, but "+str.lower(etitle)+" chases you.") elif eai == "Aggressive": print ("You run, and get away.") break elif eai == "Defensive": print ("You run, and "+str.lower(etitle)+" does not give chase.") break # This code runs if you attack. elif caction == "3": print ("You attack with your "+str.lower(cweapon)) damage = random.randint(cdamagemin, cdamagemax) ehit = 1 if damage > earmor: print ("Your attack hits "+str.lower(etitle)+", dealing "+str(damage)+" damage!") ehealth -= damage else: print ("Your attack bounces off "+str.lower(etitle)+"'s "+str.lower(earmorname)+".") earmor -= 1 # This code runs if you try to cast a spell. elif caction == "4" and cmagic == 1: print ("Enter your magic phrase.") cspell = formstring(removepunc(list(str.lower(input (""))))) # This handles the various spells in the game if cspell == "laedote" and cmana >= 10: damage = random.randint(3, 9) print("You fire a bolt of magic towards "+str.lower(etitle)+", dealing "+str(damage)+" damage.") ehealth -= damage ehit = 1 burnout += random.randint(1, 2) cmana -= 10 elif cspell == "sanome" and cmana >= 20: print ("A wave of healing passes over you, causing you to regain 3 hitpoints.") chealth += 3 if chealth > 12: chealth = 12 burnout += random.randint(1, 2) cmana -= 20 elif cspell == "medeortibi" and cmana >= 20: print ("A wave of healing passes over "+str.lower(etitle)+", causing it to regain 3 hitpoints.") ehealth += 3 if ehealth > ehealthmax: ehealth = ehealthmax burnout += random.randint(1, 2) cmana -= 20 # This handles magic explosions caused by improper casting else: damage = random.randint(4, 10) print("The magic explodes in your face, dealing "+str(damage)+" damage to you.") chealth -= damage burnout += 2 # This handles burnout if burnout > 3: damage = random.randint(1, int(burnout)) print("As you cast the spell, it drains your spirit energy with it's power, dealing "+str(int(burnout))+" damage to you.") chealth -= damage # This code lets you wait for an enemy response. else: print ("You wait for "+str.lower(etitle)+" to react.") if caction != 4: burnout -= 1 if burnout <= 0: burnout = 0 print () # This code determines the enemy reaction. if ehealth > 0: if eai == "Aggressive": print (etitle+" attacks you with its "+str.lower(eweaponname)+".") damage = random.randint(eatkmin, eatkmax) if damage > carmor: print ("The attack hits you, dealing "+str(damage)+" damage!") chealth -= damage else: print ("The attack bounces off of your armor.") carmor -= 1 elif eai == "Defensive": if ehit == 0: print (etitle+" waits to see what you do next.") else: print (etitle+" attacks you with its "+str.lower(eweaponname)+".") damage = random.randint(2, 10) if damage > carmor: print ("The attack hits you, dealing "+str(damage)+" damage!") chealth -= damage else: print ("The attack bounces off of your armor.") carmor -= 1 # This code performs upkeep at the end of the round print() print ("You have "+str(int(chealth))+" health remaining.") if magic == 1: print ("You have "+str(int(cmana))+" mana remaining.") print() if ehealth <= 0: print ("You slay "+str.lower(etitle)+"!") print ("You get "+str(einventory)+"!") cinventory += einventory print () # This code forms your stats from its parts cstats = list([chealth, cinventory, carmormax, cmana]) return cstats # The following code defines how to choose a random element from a list. def randchoice(listy): numy = random.randint(1, len(listy)) - 1 return listy[numy] print("Welcome to...\n") title = open("title", 'r') #file with ASCII art I made print(title.read()) while True: #everything is in a giant while loop so that the game can be reset afterward. # The following code sets fruit names. BasicFruitName = "A "+randchoice(list(["spherical", "tubular", "bulbous"]))+" "+randchoice(list(["red", "green", "yellow"]))+" fruit" SecondaryFruitName = "" while SecondaryFruitName == "" or SecondaryFruitName == BasicFruitName: SecondaryFruitName = "A "+randchoice(list(["spherical", "tubular", "bulbous"]))+" "+randchoice(list(["red", "green", "yellow"]))+" fruit" TertiaryFruitName = "" while TertiaryFruitName == "" or TertiaryFruitName == BasicFruitName or TertiaryFruitName == SecondaryFruitName: TertiaryFruitName = "A "+randchoice(list(["spherical", "tubular", "bulbous"]))+" "+randchoice(list(["red", "green", "yellow"]))+" fruit" # The following code sets berry names. BasicBerryName = "A "+randchoice(list(["red", "green", "blue", "black", "white", "pink", "purple", "magenta"]))+" berry" PoisonBerryName = BasicBerryName while PoisonBerryName == BasicBerryName: PoisonBerryName = "A "+randchoice(list(["red", "green", "blue", "black", "white", "purple", "pink", "magenta"]))+" berry" # The following code sets flax and flax fabric names. FlaxName = "A "+randchoice(list(["small", "large", "wide", "tall", "clustered"]))+" "+randchoice(list(["red", "white", "pink", "purple", "blue", "orange", "yellow", "black"]))+" flower with a "+randchoice(list(["tall", "short", "rough"]))+" stem" FlaxFibreColor = randchoice(list(["brown", "white", "black", "grey", "tan"])) FlaxTwineName = "Some "+FlaxFibreColor+" twine" FlaxFabricName = "A fibrous "+FlaxFibreColor+" fabric" FlaxClothesName = "Clothes made from "+str.lower(FlaxFabricName) FlaxSeedName = "A "+randchoice(list(["hard", "round", "sharp", "soft"]))+" "+randchoice(list(["golden", "brown", "tan", "black"]))+" seed" FlaxFibreName = "A "+FlaxFibreColor+" fibre" # The following code sets fabric names. BasicFabricName = "A "+randchoice(list(["soft", "rough", "fleecy"]))+" "+randchoice(list(["red", "white", "brown", "black", "grey", "tan"]))+" fabric" # The following code sets items made of various materials names BasicClothesName = "Clothes made from " + str.lower(BasicFabricName) # The following code sets Wolf related names WolfFurColor = randchoice(["Grey", "White", "Black", "Brown"]) WolfName = "A " + str.lower(WolfFurColor)+" wolf" RawWolfMeatName = "Raw wolf meat" CookedWolfMeatName = "Cooked wolf meat" BurntWolfMeatName = "Burnt wolf meat" WolfCorpseName = "Wolf corpse" WolfHideName = "A " + str.lower(WolfFurColor) + " wolf hide" # WolfFurName = "A piece of "+str.lower(WolfFurColor)+" fur" # WolfFangName = "A "+randchoice(["curved", "long", "serrated"])+" fang" # WolfCorpseName = "The corpse of "+str.lower(WolfName) # WolfMeatName = "The uncooked meat of "+str.lower(WolfName) #The following code sets mushroom names. BasicShroomName = "A " + randchoice(["red", "spotted", "purple", "brown", "white"]) + " mushroom" TrippyShroomName = BasicShroomName while TrippyShroomName == BasicShroomName: TrippyShroomName = "A " + randchoice(["red", "spotted", "purple", "brown", "white"]) + " mushroom" # The following code sets wood names. BasicWoodName = "A "+ randchoice((["dark", "light", "red", "pale"]))+" wood" BasicTwigName = "A twig made of "+str.lower(BasicWoodName) BasicBranchName = "A branch made of "+str.lower(BasicWoodName) RabbitsClubName = "A rabbit's club made of " + str.lower(BasicWoodName) # The following code sets your characters abilities health = 12 inventory = list ([BasicFruitName, BasicFruitName, BasicFruitName, SecondaryFruitName, BasicClothesName]) armor = 0 mana = 10 magic = 0 hunger = 75 ClothesName = [BasicClothesName] sleeptime = 0 warm = 0 furnace = 0 timediff = 0 time = 0 inittime = 0 tripping = False weapon = "Fists" damagemin = 1 damagemax = 4 event = 0 luck = 0 fire = 0 firetime = -1 #If the player makes a campfire, this is the # of hours since the fire has been started. It dies down after 24 hours of not being fed. The player can feed it with twigs and branches. starving = 0 # The following code forms your stats from its parts stats = list([health, inventory, armor, mana]) # The following code begins the game print ("Foreign World") print () print () print () print () print () print () print () # This code runs the game while True: inittime = time if health < 1: break # This code asks what you want to do print("So far, you have survived for " + str(4*time) + " hours.") print("Your health: " + str(health) + "/12") # print(sleeptime) if sleeptime>62: print("You are extremely tired! You need to sleep very soon.") elif sleeptime>48: print("You are very tired.") elif sleeptime>17: print("You are pretty tired.") print("Your hunger level: " + str(hunger) + "/100 (higher is more full)") if fire == 1: print("Your fire should burn for " + str(firetime) + " more hours.") if luck > 0: print("Your good luck score: " + str(luck)) hungerstr = "You are not hungry." if warm == 0: randchance = random.randint(1, 3) if randchance == 1: print ("You are freezing.") health -= timediff else: print ("You are cold.") if (time > 6 and event == 0) or (random.randint(1, 40) == 1 and event == 1): print() stats = list([health, inventory, armor, mana]) stats = combat(stats, damagemin, damagemax, weapon, "Wolf", "Field", magic, WolfName) health = stats[0] inventory = stats[1] armor = stats[2] mana = stats[3] if health < 1: break event = 1 print ("What do you want to do?") print (" i: Inspect your Inventory") print (" e: Eat something") print (" g: Change garments") print (" s: Search for things") print (" r: Rest") print (" c: Craft") print (" h: Hunt") if fire == 1: print(" f: Feed the campfire") # print (" w: Change weapons") print (" ?: Help") action = str.lower(input ("")) print() # This code executes eating if action == "e": foodnames = [BasicFruitName, SecondaryFruitName, TertiaryFruitName, PoisonBerryName, BasicBerryName, FlaxSeedName] # This code asks what you want to eat caneat = "" print ("What do you want to eat?") if BasicFruitName in inventory: caneat += (" 1: "+BasicFruitName + "\n") if SecondaryFruitName in inventory: caneat += (" 2: "+SecondaryFruitName + "\n") if TertiaryFruitName in inventory: caneat += (" 3: "+TertiaryFruitName + "\n") if PoisonBerryName in inventory: caneat += (" 4: "+PoisonBerryName + "\n") if BasicBerryName in inventory: caneat += (" 5: "+BasicBerryName + "\n") if FlaxSeedName in inventory: caneat += (" 6: "+FlaxSeedName + "\n") if RawWolfMeatName in inventory: caneat += (" 7: " + RawWolfMeatName + "\n") if BurntWolfMeatName in inventory: caneat += (" 8: " + BurntWolfMeatName + "\n") if CookedWolfMeatName in inventory: caneat += (" 9: " + CookedWolfMeatName + "\n") if "Raw rabbit meat" in inventory: caneat += (" 10: Raw rabbit meat" + "\n") if "Cooked rabbit meat" in inventory: caneat += (" 11: Cooked rabbit meat" + "\n") if "Burnt rabbit meat" in inventory: caneat += (" 12: Burnt rabbit meat" + "\n") if BasicShroomName in inventory: caneat += (" 13: " + BasicShroomName + "\n") if TrippyShroomName in inventory: caneat += (" 14: " + TrippyShroomName + "\n") if caneat == "": print ("Sorry, you need to gather food to eat.") else: print("What do you want to eat?") action = input(caneat) print() # This code runs the results of what you eat. if action == "1" and BasicFruitName in inventory: print ("You eat "+str.lower(BasicFruitName)) inventory.remove(BasicFruitName) hunger += 15 health += 0.5 if action == "2" and SecondaryFruitName in inventory: print ("You eat "+str.lower(SecondaryFruitName)) inventory.remove(SecondaryFruitName) hunger += 20 health += 0.5 if action == "3" and TertiaryFruitName in inventory: print ("You eat "+str.lower(TertiaryFruitName)) inventory.remove(TertiaryFruitName) hunger += 20 health += 0.5 if action == "4" and PoisonBerryName in inventory: print ("You eat "+str.lower(PoisonBerryName)+". It makes you feel sick.") inventory.remove(PoisonBerryName) health -= random.randint(1, 3) if action == "5" and BasicBerryName in inventory: print ("You eat "+str.lower(BasicBerryName)) inventory.remove(BasicBerryName) hunger += 5 health += 0.25 if action == "6" and FlaxSeedName in inventory: print ("You eat "+str.lower(FlaxSeedName)) inventory.remove(FlaxSeedName) hunger += 2 health += 0.25 if action == "7" and RawWolfMeatName in inventory: inventory.remove(RawWolfMeatName) if random.randint(0, 1) == 0: #Sometimes it should make you sick, sometimes it shouldn't. print("You eat the " + RawWolfMeatName) hunger += 15 health += 1 else: print("You eat the " + RawWolfMeatName + "It makes you feel sick.") health -= random.randint(2, 4) if action == "8" and BurntWolfMeatName in inventory: print ("You eat the " + BurntWolfMeatName + "It tastes disgusting.") inventory.remove(BurntWolfMeatName) hunger += 10 health += 1 if action == "9" and CookedWolfMeatName in inventory: print ("You eat the " + CookedWolfMeatName) inventory.remove(CookedWolfMeatName) hunger += 30 health += 5 if action == "10" and "Raw rabbit meat" in inventory: inventory.remove("Raw rabbit meat") if random.randint(0, 1) == 0: #Sometimes it should make you sick, sometimes it shouldn't. print("You eat the raw rabbit meat.") hunger += 10 health += 1 else: print("You eat the raw rabbit meat. It makes you feel sick.") health -= random.randint(2, 4) if action == "11" and "Cooked rabbit meat" in inventory: print ("You eat the cooked rabbit meat.") inventory.remove("Cooked rabbit meat") hunger += 17 health += 2 if action == "12" and "Burnt rabbit meat" in inventory: print ("You eat the burnt rabbit meat. It tastes disgusting.") inventory.remove("Burnt rabbit meat") hunger += 7 if action == "13" and BasicShroomName in inventory: print ("You eat the mushroom.\n") inventory.remove(BasicShroomName) hunger += 5 if action == "14" and TrippyShroomName in inventory: print ("You eat the mushroom. It makes you see pretty colors.\n") inventory.remove(TrippyShroomName) hunger += 5 if random.randint(1, 2) == 1: WolfName = "A unicorn" WolfCorpseName = "Unicorn corpse" CookedWolfMeatName = "Cooked unicorn meat" RawWolfMeatName = "Raw unicorn meat" BurntWolfMeatName = "Burnt unicorn meat" else: WolfName = "A dragon" WolfCorpseName = "Dragon corpse" CookedWolfMeatName = "Cooked dragon meat" RawWolfMeatName = "Raw dragon meat" BurntWolfMeatName = "Burnt dragon meat" #These next lines make sure that you don't have more than 100 hunger and 12 health. if hunger > 100: hunger = 100 if health > 12: health = 12 #This code executes searching your inventory elif action == "i": print ("You are wearing: ") for x in ClothesName: print(x) print("\nYour inventory:\n") count = 0 for item in inventory: count += 1 print(str(count) + ". " + item) #This code executes changing clothing elif action == "g": # This code asks you want you want to wear print ("What do you want to wear?") if BasicClothesName in inventory and (not BasicClothesName in ClothesName): print (" bc: "+ BasicClothesName) if FlaxClothesName in inventory and (not FlaxClothesName in ClothesName): print (" fc: "+ FlaxClothesName) if "A fur coat" in inventory and (not "A fur coat" in ClothesName): print (" co: A warm fur coat") if "A good luck charm" in inventory and (not "A good luck charm" in ClothesName): print (" gl: A good luck charm") action = input("") if action == "bc" and BasicClothesName in inventory: print ("You put on "+str.lower(BasicClothesName)+".") ClothesName += [BasicClothesName] if fire == 0: warm = 0 elif action == "fc" and FlaxClothesName in inventory: print ("You put on "+str.lower(FlaxClothesName)+".") ClothesName += [FlaxClothesName] if fire == 0: warm = 0 elif action == "co" and "A fur coat" in inventory: print ("You put on the fur coat. It is warm.") ClothesName += ["A fur coat"] warm = 1 elif action == "gl": print ("You put on the good luck charm. It gives you a +5 good luck score!") ClothesName += ["A good luck charm"] luck = 5 #This code executes searching elif action == "s": # This code asks what you want to search for. print ("What do you want to search for?") print (" b: Berries") print (" f: Flowers") print (" s: Mushrooms") print (" t: Twigs and Branches") action = input ("") print ("You have spent some time searching.") if str.lower(action) == "b": count = random.randint(3, 7) while count > 0: find = randchoice(list([BasicBerryName, BasicBerryName, PoisonBerryName])) inventory += [find] print ("You have found "+str.lower(find)+"!") count -= 1 elif str.lower(action) == "f": count = random.randint(1, 4) while count > 0: find = randchoice(list([FlaxName, FlaxName, FlaxName])) inventory += [find] print ("You have found "+str.lower(find)+"!") count -= 1 elif str.lower(action) == "s": count = random.randint(2, 4) while count > 0: find = randchoice(list([BasicShroomName, BasicShroomName, BasicShroomName, BasicShroomName, TrippyShroomName])) #Trippy shrooms replace the word "dragon" with the word "wolf" for a few hours and summon one. inventory += [find] print ("You have found " + str.lower(find) + "!") count -= 1 elif str.lower(action) == "t": count = random.randint(1, 3) while count > 0: find = randchoice(list([BasicTwigName, BasicTwigName, BasicTwigName, BasicTwigName, BasicTwigName, BasicBranchName, BasicBranchName])) inventory += [find] print ("You have found "+str.lower(find)+"!") count -= 1 time += 0.25 hunger -= 10 #This code executes processing raw materials elif action == "p": #This code asks what you want to process print ("What do you want to process?") if FlaxName in inventory: print (" 1: "+str.lower(FlaxName)) action = input("") # This code executes resting elif action == "r": print ("You rest for a while, and are now well rested.") time += 2.5 sleeptime = 0 hunger -= 3 timediff = 0 inventory = replacelist(inventory, RawWolfMeatName, "Raw wolf meat") inventory = replacelist(inventory, CookedWolfMeatName, "Cooked wolf meat") inventory = replacelist(inventory, BurntWolfMeatName, "Burnt wolf meat") inventory = replacelist(inventory, WolfHideName, "A " + str.lower(WolfFurColor) + " wolf hide") inventory = replacelist(inventory, WolfCorpseName, "Wolf corpse") WolfName = "A " + str.lower(WolfFurColor) + " wolf" RawWolfMeatName = "Raw wolf meat" CookedWolfMeatName = "Cooked wolf meat" BurntWolfMeatName = "Burnt wolf meat" WolfCorpseName = "Wolf corpse" WolfHideName = "A " + str.lower(WolfFurColor) + " wolf hide" # This code executes crafting elif action == "c": cancraft = "" #This is similar to the string "canbuild." It remains empty unless you can craft something. if FlaxName in inventory: cancraft += (" fl: Extract seeds from "+str.lower(FlaxName) + ".\n") if FlaxFibreName in inventory: cancraft += (" tw: Spin twine out of "+str.lower(FlaxFibreName)+".\n") if inventory.count(FlaxTwineName) >= 4: cancraft += (" ft: Weave fabric out of "+str.lower(FlaxTwineName)+".\n") if inventory.count(FlaxFabricName) >= 7: cancraft += (" fc: Weave fabric out of "+str.lower(FlaxClothesName)+".\n") if WolfCorpseName in inventory: cancraft += (" sw: Skin the "+ str.lower(WolfCorpseName) + "\n") if "Wolf hide" in inventory: cancraft += (" wc: Make a fur coat out of wolf hide.\n") if "Raw wolf meat" in inventory and fire == 1: cancraft += (" cw: Cook the wolf meat over the fire.\n") if (inventory.count(BasicTwigName)) > 3 and (inventory.count(BasicBranchName)) > 1: cancraft += (" cf: A basic campfire consisting of 4 twigs and 2 branches.\n") if BasicBranchName in inventory: cancraft += (" rc: " + RabbitsClubName + " for hunting game.\n") if "Rabbit corpse" in inventory: cancraft += (" sr: Skin a rabbit's corpse\n") if "Raw rabbit meat" in inventory: cancraft += (" cr: Cook the raw rabbit meat\n") if "Rabbit foot" in inventory and FlaxTwineName in inventory: cancraft += (" gl: Make a \"Good luck\" charm") if cancraft == "": print ("Sorry, you cannot craft anything with your current inventory.") else: print(cancraft) action = input("What do you want to craft?") if action == "fl" and FlaxName in inventory: count = random.randint(0, 5) while count > 0: inventory += [FlaxSeedName] print ("You have extracted " + str.lower(FlaxSeedName) + ".") count -= 1 count = random.randint(1, 2) while count > 0: inventory += [FlaxFibreName] print ("You have extracted " + str.lower(FlaxFibreName) + ".") count -= 1 inventory.remove(FlaxName) time += 1 hunger -= 3 # This code makes flaxen twine if action == "tw" and FlaxFibreName in inventory: inventory.remove(FlaxFibreName) inventory += [FlaxTwineName] print ("You spin "+FlaxTwineName+".") time += 0.1 # This code makes flaxen fabric elif action == "ft" and inventory.count(FlaxTwineName) > 3: inventory.remove(FlaxTwineName) inventory.remove(FlaxTwineName) inventory.remove(FlaxTwineName) inventory.remove(FlaxTwineName) inventory += [FlaxFabricName] print ("You weave "+str.lower(FlaxFabricName)+".") time += 0.5 hunger -= 2 # This code makes flaxen clothes elif action == "fc" and inventory.count(FlaxFabricName) > 7: recurrence = 8 while recurrence > 0: inventory.remove(FlaxFabricName) recurrence -= 1 inventory += [FlaxClothesName] print ("You make "+str.lower(FlaxClothesName)+".") time +=0.75 hunger -= 3 elif action == "sw" and WolfCorpseName in inventory: time += 0.75 hunger -= 3 inventory.remove(WolfCorpseName) inventory += [WolfHideName, RawWolfMeatName] print ("You skin the animal.") elif action == "wc" and WolfHideName in inventory: print ("You make a fur coat from the animal hide.") inventory.remove(WolfHideName) time += 0.75 hunger -= 3 inventory += ["A fur coat"] elif action == "cw" and "Raw wolf meat" in inventory: inventory.remove("Raw wolf meat") if random.randint(1, 3) == 1: print("You burn the meat to a crisp.") inventory += [BurntWolfMeatName] else: print("You carefully cook the meat. It looks delicious.") inventory += [BurntWolfMeatName] time += 0.75 hunger -= 3 elif action == "cf"and (inventory.count(BasicTwigName)) > 3 and (inventory.count(BasicBranchName)) > 1: # This code consumes twigs. count = 4 while count > 0: if BasicTwigName in inventory: inventory.remove(BasicTwigName) count -= 1 # This code consumes branches count = 2 while count > 0: if BasicBranchName in inventory: inventory.remove(BasicBranchName) count -= 1 # This code creates the campfire and applies it's properties. fire = 1 if furnace < 1: furnace = 1 # This code manages the time and hunger incurred by building the campfire. time += 1 hunger -= 5 warm = 1 firetime = 24 elif action == "rc" and BasicBranchName in inventory: print("You make " + str.lower(RabbitsClubName) + ". Now you can hunt rabbits!") inventory.remove(BasicBranchName) inventory += [RabbitsClubName] time += 1 hunger -= 5 elif action == "sr" and "Rabbit corpse" in inventory: #This code skins a rabbit corpse print ("You skin the rabbit's corpse. Now, you have a rabbit hide, a rabbit's foot, and raw rabbit meat.") inventory.remove("Rabbit corpse") inventory += ["Rabbit hide", "Rabbit foot", "Raw rabbit meat"] time += 1 hunger -= 5 elif action == "cr" and "Raw rabbit meat" in inventory and fire == 1: inventory.remove("Raw rabbit meat") if random.randint(1, 3) == 1: print("You burn the rabbit meat to a crisp.") inventory += ["Burnt rabbit meat"] else: print("You carefully cook the rabbit meat. It looks delicious.") inventory += ["Cooked rabbit meat"] time += 0.75 hunger -= 3 elif action == "gl" and "Rabbit foot" in inventory and FlaxTwineName in inventory: inventory.remove("Rabbit foot") inventory.remove(FlaxTwineName) print("You make a good luck charm! Wear it to get good luck.") inventory += ["A good luck charm"] elif action == "h": #This code facilitates hunting. canhunt = "" if RabbitsClubName in inventory: canhunt += "r: Hunt rabbits\n" if canhunt == "": print("Sorry, you need to craft a weapon in order to hunt.") else: print("What do you want to hunt?") action = input(canhunt) if str.lower(action) == "r" and RabbitsClubName in inventory: outcome = random.randint(1, 3) if outcome == 1: print ("You see a rabbit and throw your club at it. You hit it! You collect the rabbit corpse.") inventory += ["Rabbit corpse"] elif outcome == 2: print ("You see a rabbit and throw your club at it. You miss.") else: print ("You go looking for game but you cannot find anything.") health -= 1 hunger -= 10 elif action == "f" and fire == 1: canfeed = "" if BasicBranchName in inventory: canfeed += " b: " + str.lower(BasicBranchName) + "\n" if BasicTwigName in inventory: canfeed += " t: " + str.lower(BasicTwigName) + "\n" if canfeed == "": print("Sorry, you need a twig or a branch to feed the fire with.") else: print("What do you want to feed the fire with?") print("The fire will last for " + str(firetime) + "more hours.") action = input(canfeed) if action == "b" and BasicBranchName in inventory: inventory.remove(BasicBranchName) firetime += 4 if action == "t" and BasicTwigName in inventory: inventory.remove(BasicTwigName) firetime += 2 elif action == "?": print("Welcome to Foreign world! This is an in-depth explanation of how the commands work. \n" "i - This lists your inventory.\n" "e - This lets you eat something from your inventory. It adds to your health levels and subtracts from your hunger levels. Note that some foods are poisonous. Every time you restart the game, the colors of poisonous foods change.\n" "g - This lets you change clothes if you have made any new clothes (using the craft command)\n" "s - This lets you gather items for your inventory. You can search for berries, flowers, and twigs/branches.\n" "r - If the game says you are tired, this will make you slightly less tired. But beware of wolves!\n" "c - Lets you make/cook/process things. See below for a crafting guide.\n" "h - Hunting requires a weapon, such as a rabbit's club. If done successfully, you get an animal corpse." # "w - Change weapons, if you have any weapons in your inventory.\n\n\n" "A good way to start is to gather enough twigs and branches to start a fire." "Have fun!\n") print() timediff = time-inittime firetime -= timediff*4 sleeptime += timediff*4 if sleeptime>120: #After 5 days without sleeping you start to hallucinate print("You haven't slept for 5 days! You start to see vivid colors.") tripping = True triptime = sys.maxsize #You should only stop hallucinating if you go to sleep if firetime <= 0 and fire == 1: print("Your fire died out! Remember to feed it with twigs and branches.") fire = 0 if not ("A fur coat" in ClothesName): warm = 0 if health <= 0: print ("Your health is below 0! You die!") break if hunger > 0: starving = 0 if hunger <= 0 and starving == 0: print ("You are starving! You need to eat something quick!") hunger = 1 starving = 1 if hunger <= 0 and (not starving == 0): print ("You died of hunger!") break exitinput = input("You died! You lasted for "+str(int(4*time))+" hours. Press enter to play again, or type \"quit\" to quit.") if exitinput.lower() == "quit": break
valor_1 = 100 valor_2 = 14 #soma valor_soma = valor_1 + valor_2 print 'O valor da soma eh ', valor_soma #subtracao valor_sub = valor_1 - valor_2 print 'O valor da subtracao eh ', valor_sub #divisao valor_div = valor_1 / valor_2 print 'O valor da divisao eh ', valor_div #multiplicacao valor_mult = valor_1 * valor_2 print 'O valor da multiplicacao eh ', valor_mult #exponenciacao valor_expo = valor_1 ** valor_2 print 'O valor da exponenciacao eh ', valor_expo #resto da divisao por 2 valor_resto = valor_1 % 2 if(valor_resto == 0): print valor_1,'eh par!' else: print valor_1,'eh impar!'
#declarando uma lista vazia lista = [] #Adicionar elementos lista.append('Joelma') lista.append('Chimbinha') lista.append('Safadao') lista.append('Annita') print lista #inserir elemento em uma posicao especifica lista.insert(0,'Mc Troinha') print lista #remover um elemento pelo valor lista.remove('Annita') print lista #pegando posicao do elemento pelo valor local = lista.index('Safadao') print local #removendo um elemento pelo index del(lista[local]) print lista #invertendo ordem da lista lista.reverse() print lista #ordenando uma lista lista.sort() print lista
####################################################################################### # File: chatroom.py # Author: Wameedh Mohammed Ali # Purpose: CSC645 Assigment #1 TCP socket programming # Description: This class represents a chat room object that users can create. It stores # a list of users connected to the chat room and the owner of the room info. # It would also manages adding and removing users from the chat # Running: Python 2: python server.py # Python 3: python3 server.py # Usage : chatroom = Chatroom(owner_name, owner_id, room_id) # ######################################################################################## class Chatroom(object): """ Object Chatroom represents a chatroom users can access. A chatroom object has the following: - Owner id - Owner name - Room id - a list of users And three methods - add_user() - remove_user() - get_room_id() """ def __init__(self, owner_name, owner_id, room_id): self.owner_id = owner_id self.room_id = room_id self.owner_name = owner_name self.users = {} def add_user(self, user_id, user): self.users.update({user_id: user}) def remove_user(self, user_id): self.users.pop(user_id) def get_room_id(self): return self.room_id
import sqlite3 conn = sqlite3.connect("db.db") c = conn.cursor() def select_with_fetchone(): cmd = "SELECT * FROM users WHERE user_id=%d" % 1000 c.execute(cmd) result = c.fetchone() print(result) def select_with_fetchall(): cmd = "SELECT * FROM users" c.execute(cmd) result = c.fetchall() print(result) def insert(): cmd = "INSERT INTO users(user_id, state) VALUES (%d, '%s')" % (123, "registration") c.execute(cmd) conn.commit() print("inserted") def update(): cmd = "UPDATE users SET state='%s' WHERE user_id=%d" % (" ", 123) c.execute(cmd) conn.commit() print("updated") def delete(): cmd = "DELETE FROM users WHERE user_id=%d" % 123 c.execute(cmd) conn.commit() print("deleted") a = input() select_with_fetchone() a = input() select_with_fetchall() a = input() insert() a = input() update() a = input() delete()
import random adivina = random.randint(1,10) numeroPersona = int(input("Dime un numero: ")) if numeroPersona > 10 or numeroPersona < 0: print("Te has pasado de los limites entre 0 y 10") if numeroPersona == adivina: print("Enhorabuena as adivinado el numero") else: print("Has fallado") print("El numero ganador era {}".format(adivina))
num_repeticiones = int(input("Cuantas repeticiones quieres")) for a in range(num_repeticiones): print("Hola") for a in range (1, num_repeticiones +1): print(a)
import wat # """ # atdo Exception # """ class myException(Exception): def __init__(self, msg, num): self.msg = msg self.num = num try: raise myException('aaaa', 3) except myException as e: print('------') wat.d(e.msg, e.num)
# coding:utf8 # # aa=None # # def d(): # aa=23 # # def e(): # print aa # # d() # # e() s='1234你好 ' print s.__len__() print s.decode('utf-8').__len__() print s.decode('utf-8').encode('gbk').__len__()
'''Python generator: This is an example of python generator. It's very handy to write memory efficient codes because it doesn't holdv values into memory, it just uses them when it needs it. To illustrate it, let's write a Fibonacci sequence generator using that concept''' def gen_fibonacci(n): #Starting by the initial value that can be 0 or 1 (doesn't really matter) a = 1 b = 1 for i in range(n): yield a a,b = b,a+b for number in gen_fibonacci(10): print(number) # Without using this concept, we would have ended up sayign something like ...... def gen_fibonacci(b): a = 1 b = 1 output = [] for i in range(b): output.append(a) a,b=b,a+b return output #We would have had the same output but with less memory efficiency
from turtle import Turtle,Screen class Paddle(Turtle): def __init__(self,x,y): super().__init__() self.penup() self.color("white") self.shape("square") self.shapesize(stretch_wid=1,stretch_len=5) self.goto(x,y) def Left(self): if (self.xcor()!=-320): self.forward(-40) def Right(self): if (self.xcor() != 320): self.forward(40)
""" Complexity: O(log(n)) return: Index of Peek """ def PeekFinder1D(Array, low, high): mid = int((low + high) / 2) if mid < high and Array[mid] < Array[mid + 1]: return PeekFinder1D(Array, mid+1, high) elif mid > 0 and Array[mid] < Array[mid - 1]: return PeekFinder1D(Array, 0, mid - 1) else: return mid def PeekFinder2D(Array, lCol, rCol): #Column = int(Col/2) Column = int((lCol + rCol)/2) maxIndex = 0 maxElem = Array[maxIndex][Column] for i in range(len(Array)): if maxElem < Array[i][Column]: maxElem = Array[i][Column] maxIndex = i if Column > lCol and Array[maxIndex][Column-1] > Array[maxIndex][Column]: return PeekFinder2D(Array, lCol, Column - 1) elif Column < rCol and Array[maxIndex][Column+1] > Array[maxIndex][Column]: return PeekFinder2D(Array, Column + 1, rCol) else: return (maxIndex, Column) def test1D(): Array = [6,5,3,2,5] print(PeekFinder1D(Array, 0, len(Array)-1)) def test2D(): #Array = [0] * 4 #for i in range(4): # Array[i] = [0] * 4 # for j in range(4): # Array[i][j] = int(input("Enter Value at" + str(i) + "," + str(j) + ": ")) # print("\n") Array = [ [10,9,8,10,10], [19,99,19,12,11], [15,19,9,11,21], [16,5,17,19,20], [16,4,17,19,20] ] print(PeekFinder2D(Array,0,4)) test2D()
""" Python Review of classes """ import math class MyFirstClass: pass class Point: """ Represents a point in a 2-D geometric coordinates """ def __init__(self, x=0, y=0): """ Initializes the position of a new point. If they are not specified, the point defaults to the origin :param x: x coordinate. Default = 0 :param y: y coordinate. Default = 0 """ self._x = x self._y = y # Add some instance methods: Do something def reset(self): """ Reset the point to the origin location in 2D Space :return: Nothing """ self._x = 0 self._y = 0 def get_point(self): """ Get current x and y coordinate values of the 2D point :return: """ return self._x, self._y def set_point(self, x, y): """ Move point to a new location in a 2D space :param x: x coordinate :param y: y coordinate :return: nothing """ self._x = x self._y = y def calculate_distance(self, other_point): """ Calculate the distance from this point to a second point passed as a parameter. This method uses Pythagorean Theorem to calculate the distance between two points :param other_point: second point to calculate :return: Distance between two points (float) """ return math.sqrt( (self._x - other_point._x)**2 + (self._y - other_point._y)**2) def main(): p1 = Point() # take default p2 = Point(2, 5) # set values # Add information # p1.x = 5 # p1.y = 4 # p2.x = 3 # p2.y = 6 print(p1._x, p1._y) #p1.reset() print(p2._x, p2._y) print(p2.calculate_distance(p1)) p1.set_point(3, 2) print(p1.get_point()) print(p2.get_point()) print(p2.calculate_distance(p1)) if __name__ == '__main__': main()
def my_range(start, end): while start < end: yield start start += 1 range_object = my_range(0, 5) # iterator = iter(range_object) # print(next(iterator)) # print(next(iterator)) # print(next(iterator)) # print(next(iterator)) # print(next(iterator)) # print(next(iterator)) # for i in my_range(0, 10): # print(i) def test_generator(start, end): while start < end: print('The beginning of loop') yield start start += 1 print('The end of iteration') gen = test_generator(0, 3) iterator = iter(gen) print(next(iterator)) print('------------------------') print(next(iterator)) print('------------------------') print(next(iterator)) my_gen_exp = (x for x in range(10)) print(my_gen_exp) result = list(my_gen_exp) print(result)
to_square = lambda x, y: (x ** 2, y ** 2) result = to_square(2, 4) print(result) def confirmer(func_obj, arg): return func_obj(arg) result = confirmer(lambda x: x ** 2, 10) print(result) list_of_numbers = [1, 2, 4, 8, 16] list_of_numbers_2 = [2, 3, 5, 9, 17] squares = [] for num in list_of_numbers: squares.append(num ** 2) print(squares) result = list(map(lambda x: x ** 2, list_of_numbers)) print(result) print(list(map(lambda x, y: x + y if x + y > 10 else None, list_of_numbers, list_of_numbers_2))) list_of_numbers = [100, 200, 300, 90, 80, 600] print(list(filter(lambda x: x >= 100, list_of_numbers))) dict_of_numbers = { 1: 2, 3: 4, 5: 6 } #print(list(map(lambda k: (k[0] ** 2, k[1] ** 2), dict_of_numbers.items())))
final_list = [] for i in range(100): final_list.append(i) print(final_list) result = [1 if x > 50 else 0 for x in range(100) if x % 2 == 0] print(result) source_list = [1, 2, 4, 8, 16, 32] result_dict = {i ** 2: i ** 3 for i in source_list} print(result_dict) result_set = {i for i in range(100)} print(result_set) result_tuple = (x for x in range(100)) print(result_tuple) x = None
""" Inheriting from the class Point, a canvas data attribute is added to Point and a method to draw the point on the canvas. The main program pops a new window with a canvas and draws ten random points on the canvas. """ from tkinter import Tk, Canvas from random import randint from class_point import Point class ShowPoint(Point): """ Extends the class Point with a draw method on a Tkinter Canvas. """ def __init__(self, cnv, x=0, y=0): """ Defines the point (x, y) and stores the canvas cnv. """ Point.__init__(self, x, y) self.canvas = cnv def draw(self): """ Draws the point on canvas. """ (xpt, ypt) = (self.xpt, self.ypt) self.canvas.create_oval(xpt-2, ypt-2, \ xpt+2, ypt+2, fill='SkyBlue2') def main(): """ Shows 10 random points on canvas. """ top = Tk() dim = 400 cnv = Canvas(top, width=dim, height=dim) cnv.pack() points = [] for _ in range(10): xrd = randint(6, dim-6) yrd = randint(6, dim-6) points.append(ShowPoint(cnv, xrd, yrd)) for point in points: point.draw() top.mainloop() if __name__ == "__main__": main()
import unittest from TrainTestVal_2 import * import pandas as pd from load_adult_data import * data = main() """ ### The following lines if for use if we want to use load_adult_data instead of manually ### ### loading pandas DataFrames ### names = ['age', 'workclass', 'fnlwgt', 'education', 'education-num', 'marital-status', 'occupation', 'relationship', 'race', 'sex', 'capital-gain', 'capital-loss', 'hours-per-week', 'native-country', 'income'] df = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data', header=None, names=names, index_col=False) df = df[['age', 'workclass', 'education', 'sex', 'hours-per-week', 'occupation', 'income']] """ class TrainTestValTests(unittest.TestCase): """ Tests the train_test_val function which returns the length of the dataset, in this case the adult dataset from UCI which is imported at the top and then instantiated with variable data. """ def test_sizes(self): self.assertEqual(train_test_val_2(data), len(data)) #def test_sizes_2(self): if __name__ == '__main__': unittest.main()
import math, copy, string import random # CMU Graphics file from https://www.cs.cmu.edu/~112/notes/notes-animations-part1.html from cmu_112_graphics_final import * from tkinter import * from PIL import Image # Word class stores the word dictionary and checks word membership class Word(object): # General readFile structure taken from: http://www.cs.cmu.edu/~112/notes/notes-strings.html#basicFileIO @staticmethod def readFile(path): with open(path, "rt") as f: return f.read() def __init__(self, word, bag): self.word = word.lower() # english3.txt taken from: http://www.gwicks.net/dictionaries.htm self.contentsRead = Word.readFile("english3.txt") self.dictionaryToUse = self.changeDictionaryTxtToSet() self.bag = bag self.len34DictSet = self.createLen34Set() # set of len 3 and len 4 words self.len4DictSet = self.createLen4Set() # set of len 4 words self.len3DictSet = self.createLen3List() # set of len 3 words self.len5DictSet = self.createLen5Set() # set of len 5 words def changeDictionaryTxtToSet(self): setToReturn = set() for line in self.contentsRead.splitlines(): setToReturn.add(line) return setToReturn def createLen3List(self): setToReturn = set() for word in self.dictionaryToUse: if len(word) == 3: setToReturn.add(word) return setToReturn def createLen4Set(self): setToReturn = set() for word in self.dictionaryToUse: if len(word) == 4: setToReturn.add(word) return setToReturn def createLen34Set(self): setToReturn = set() for word in self.dictionaryToUse: if (len(word) == 3) or (len(word) == 4): setToReturn.add(word) return setToReturn def createLen5Set(self): setToReturn = set() for word in self.dictionaryToUse: if (len(word) == 5): setToReturn.add(word) return setToReturn def checkWordInDictionary(self): if self.word in self.dictionaryToUse: return True else: return False
annual_salary = int(input("Enter your annual salary : ")) salary = annual_salary lower = 0 upper = 10000 saving_percent = 5000 down_payment = 250000 steps = 0 while True: savings = 0 salary = annual_salary portion = (annual_salary / 12) * (saving_percent / 10000) for r in range(1, 37): savings += portion savings += savings * (0.04 / 12) if r % 6 == 0: salary += salary * 0.07 portion = (salary / 12) * (saving_percent / 10000) if abs(down_payment - savings) <= 10000: break if down_payment < savings: upper = saving_percent else: lower = saving_percent saving_percent = (upper + lower) // 2 steps += 1 print("Percent : ", saving_percent / 10000) print("Steps : ", steps)
# -*- coding: utf-8 -*- # l=[{'a':2,'b':2},{'a':1,'b':3}] # def combine_dic(l): # if l[0]['a']==l[1]['a'] and l[0]['b']!=l[1]['b']: # l[0]['b'] = str(l[0]['b'])+'#'+str(l[1]['b']) # l = l[0] # return l # else: # return -1 # print(combine_dic(l)) # l.append(1) # print(l) # l.pop() # print(l) # print(l[-1]) import sys def main(args): print(args) if __name__=='__main__': print("执行如下代码__name__=='__main__'") main(sys.argv[1:])
# -*- coding: utf-8 -*- # 如何创建一个链表 class Node(object): '''节点''' def __init__(self, elem): self.elem = elem self.next = None class Singerlinkerlist(object): '''单链表''' def __init__(self, node=None): self._head = node def is_empty(self): '''判断是否为空''' return self._head == None def length(self): '''求长度''' # cur游标,遍历节点 cur = self._head # count计数 count = 0 while cur != None: count += 1 cur = cur.next return count def travel(self): '''遍历''' # cur游标,遍历节点 cur = self._head while cur != None: print(cur.elem, end=" ") cur = cur.next def append(self, item): '''尾部插入节点''' node = Node(item) if self.is_empty(): self._head = node else: cur = self._head while cur.next != None: cur = cur.next cur.next = node def add(self, item): '''在链表头部添加元素''' node = Node(item) node.next = self._head self._head = node def insert(self, pos, items): '''任意位置添加参数 pos 从零开始 ''' pre = self._head node = Node(items) if pos <= 0: self.add(items) elif pos > self.length(): self.append(items) else: for j in range(pos - 1): pre = pre.next node.next = pre.next pre.next = node def search(self, item): '''查找''' cur = self._head while cur != None: if cur.elem == item: return True else: cur = cur.next return False if self.length() == 0: print('It is empty') def remove(self, item): '''删除节点''' cur = self._head pre = None while cur != None: if cur.elem == item: #先判断是否为头结点 if cur==self._head: self._head=cur.next else: pre.next = cur.next break else: pre = cur cur = cur.next if __name__ == "__main__": li = Singerlinkerlist() print(li.is_empty()) print(li.length()) li.append(1) print(li.is_empty()) print(li.length()) li.append(2) li.append(3) li.add(4) li.insert(100, 100) li.travel() li.search(9) li.remove(4) li.travel()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Aug 18 17:59:17 2021 @author: rachel """ # Python3 code for implementation of Newton # Raphson Method for solving equations # An example function whose solution # is determined using Bisection Method. # The function is x^3 - x^2 + 2 def func2( x, CS ): A = CS[0] B = CS[1] return x * x + B*x + A # Derivative of the above function # which is 3*x^x - 2*x def derivFunc2( x, CS ): A = CS[0] B = CS[1] return 2 * x + B # Function to find the root def newtonRaphson2( x, CS ): CS = CS h = func2(x, CS) / derivFunc2(x, CS) while abs(h) >= 0.0001: h = func2(x, CS)/derivFunc2(x, CS) x = x - h return x # Driver program to test above def rootFinder2(guess, CS): CS = CS x0 = guess # Initial values assumed r1 = newtonRaphson2(x0, CS) r2 = CS[2] - r1 return r1,r2 R1, R2 = rootFinder2(guess = 2, CS = CS) # This code is contributed by "Sharad_Bhardwaj"
import numpy as np import pandas as pd def cluster(X, max_num_clusters=3, exact_num_clusters=None): '''Applies clustering on reduced data, i.e. data where power is greater than threshold. Parameters ---------- X : pd.Series or single-column pd.DataFrame max_num_clusters : int Returns ------- centroids : ndarray of int32s Power in different states of an appliance, sorted ''' # Find where power consumption is greater than 10 data = _transform_data(X) # Find clusters centroids = _apply_clustering(data, max_num_clusters, exact_num_clusters) centroids = np.append(centroids, 0) # add 'off' state centroids = np.round(centroids).astype(np.int32) centroids = np.unique(centroids) # np.unique also sorts # TODO: Merge similar clusters return centroids def _transform_data(data): '''Subsamples if needed and converts to column vector (which is what scikit-learn requires). Parameters ---------- data : pd.Series or single column pd.DataFrame Returns ------- data_above_thresh : ndarray column vector ''' MAX_NUMBER_OF_SAMPLES = 2000 MIN_NUMBER_OF_SAMPLES = 20 DATA_THRESHOLD = 10 data_above_thresh = data[data > DATA_THRESHOLD].dropna().values n_samples = len(data_above_thresh) if n_samples < MIN_NUMBER_OF_SAMPLES: return np.zeros((MAX_NUMBER_OF_SAMPLES, 1)) elif n_samples > MAX_NUMBER_OF_SAMPLES: # Randomly subsample (we don't want to smoothly downsample # because that is likely to change the values) random_indices = np.random.randint(0, n_samples, MAX_NUMBER_OF_SAMPLES) resampled = data_above_thresh[random_indices] return resampled.reshape(MAX_NUMBER_OF_SAMPLES, 1) else: return data_above_thresh.reshape(n_samples, 1) def _apply_clustering_n_clusters(X, n_clusters): """ :param X: ndarray :param n_clusters: exact number of clusters to use :return: """ from sklearn.cluster import KMeans k_means = KMeans(init='k-means++', n_clusters=n_clusters) k_means.fit(X) return k_means.labels_, k_means.cluster_centers_ def _apply_clustering(X, max_num_clusters, exact_num_clusters=None): ''' Parameters ---------- X : ndarray max_num_clusters : int Returns ------- centroids : list of numbers List of power in different states of an appliance ''' # If we import sklearn at the top of the file then it makes autodoc fail from sklearn import metrics # Finds whether 2 or 3 gives better Silhouellete coefficient # Whichever is higher serves as the number of clusters for that # appliance num_clus = -1 sh = -1 k_means_labels = {} k_means_cluster_centers = {} k_means_labels_unique = {} # If the exact number of clusters are specified, then use that if exact_num_clusters is not None: labels, centers = _apply_clustering_n_clusters(X, exact_num_clusters) return centers.flatten() # Exact number of clusters are not specified, use the cluster validity measures # to find the optimal number for n_clusters in range(1, max_num_clusters): try: labels, centers = _apply_clustering_n_clusters(X, n_clusters) k_means_labels[n_clusters] = labels k_means_cluster_centers[n_clusters] = centers k_means_labels_unique[n_clusters] = np.unique(labels) try: sh_n = metrics.silhouette_score( X, k_means_labels[n_clusters], metric='euclidean') if sh_n > sh: sh = sh_n num_clus = n_clusters except Exception: num_clus = n_clusters except Exception: if num_clus > -1: return k_means_cluster_centers[num_clus] else: return np.array([0]) return k_means_cluster_centers[num_clus].flatten() def hart85_means_shift_cluster(pair_buffer_df, columns): from sklearn.cluster import MeanShift # Creating feature vector cluster_df = pd.DataFrame() power_types = [col[1] for col in columns] if 'active' in power_types: cluster_df['active'] = pd.Series( pair_buffer_df.apply( lambda row: ( (np.fabs( row['T1 Active']) + np.fabs( row['T2 Active'])) / 2), axis=1), index=pair_buffer_df.index) if 'reactive' in power_types: cluster_df['reactive'] = pd.Series( pair_buffer_df.apply( lambda row: ( (np.fabs( row['T1 Reactive']) + np.fabs( row['T2 Reactive'])) / 2), axis=1), index=pair_buffer_df.index) if 'apparent' in power_types: cluster_df['apparent'] = pd.Series( pair_buffer_df.apply( lambda row: ( (np.fabs( row['T1 Apparent']) + np.fabs( row['T2 Apparent'])) / 2), axis=1), index=pair_buffer_df.index) X = cluster_df.values.reshape((len(cluster_df.index), len(columns))) ms = MeanShift(bin_seeding=True) ms.fit(X) labels = ms.labels_ cluster_centers = ms.cluster_centers_ labels_unique = np.unique(labels) return pd.DataFrame(cluster_centers, columns=columns)
""" doc_inherit decorator Usage: class Foo(object): def foo(self): "Frobber" pass class Bar(Foo): @doc_inherit def foo(self): pass class Baz(Bar): @doc_inherit def foo(self): pass Now, Bar.foo.__doc__ == Bar().foo.__doc__ == Foo.foo.__doc__ == "Frobber" and Baz.foo.__doc__ == Baz().foo.__doc__ == Bar.foo.__doc__ == Foo.foo.__doc__ From: http://code.activestate.com/recipes/576862-docstring-inheritance-decorator/ and: https://stackoverflow.com/a/38414303/8289769 """ import inspect from functools import wraps class DocInherit(object): """ Docstring inheriting method descriptor The class itself is also used as a decorator """ def __init__(self, mthd): self.mthd = mthd self.name = mthd.__name__ def __get__(self, obj, cls): for parent in cls.__mro__[1:]: overridden = getattr(parent, self.name, None) if overridden: break @wraps(self.mthd, assigned=('__name__', '__module__')) def f(*args, **kwargs): if obj: return self.mthd(obj, *args, **kwargs) else: return self.mthd(*args, **kwargs) doc = inspect.getdoc(overridden) f.__doc__ = doc return f doc_inherit = DocInherit
n1=int(input()) arr1=list() for x in range(n1): arr2=list(map(int,input().split())) arr1=arr1+arr2 arr1=sorted(arr1) for s in arr1: print(s,end=" ")
v=input() if v==v[::-1]: print("yes") else: value=v.strip("0") if value==value[::-1]: print("yes") else: value=v.lstrip("0") if value==value[::-1]: print("yes") else: print("no")
#coding=utf-8 import urllib.parse import urllib.request URL = 'https://www.python.org' resp = urllib.request.urlopen(URL) # print(resp.read().decode('utf-8')) print(type(resp)) print(resp.status) print(resp.getheaders()) print(resp.getheader('Server')) URL = 'http://httpbin.org/post' data = {'word':'hello'} # 将字典转换为 url 参数的字符串 dataToStr = urllib.parse.urlencode(data) # 参数需要转换为字节码 dataToBytes = bytes(dataToStr, encoding='utf-8') resp = urllib.request.urlopen(URL,data=dataToBytes) # decode 是将 bytes 数据转换为 string print(resp.read().decode('utf-8'))
#! /usr/bin/python # -*- coding:utf-8 -*- import sys import os from xldef import * from 小岚显示功能扩展js基准利率 import * def rabbit_purple_radish(): one_type = input("\n一表看一年,才知没有钱~\n此功能用于基础图表显示\n") while True: if one_type == '基准利率': map_show() break elif one_type == '退出': print("正在结束该功能!") break elif one_type.replace(' ', '') == '': one_type = input("想看什么图?兔仔我画给你看!" + "\n不说话我就不开心!") continue print("已关闭此功能!") def rabbit_radish(): while True: one_type = input("\n这次萝卜要放哪呢? ") if one_type == '放老家': try: deposit_str = float(input('-' * 100 + "\n给小岚多少萝卜? ")) deposit_time = float(input('-' * 100 + "\n要放多久? ")) except ValueError: print('-' * 100 + "存就要放萝卜哦!") else: list_time_deposit(deposit_str, deposit_time) continue elif one_type == '贷款萝卜': try: loan_str = float(input('-' * 100 + "\n贷多少? ")) loan_time = float(input('-' * 100 + "\n什么时候还? ")) except ValueError: print('-' * 100 + "说清楚贷多少萝卜哦!") else: list_time_loan(loan_str, loan_time) continue elif one_type == '买窝用': try: cpf_str = float(input('-' * 100 + "\n贷多少? ")) cpf_time = float(input('-' * 100 + "\n什么时候还? ")) except ValueError: print("既然想有窝,萝卜是不可少的!") else: list_time_cpf(cpf_str, cpf_time) continue else: if one_type == '离开': print("谢谢!小岚会更好!@发现美的眼睛赶紧变优秀!") break elif one_type == '历史萝卜': print("\n小岚提示\n\t\t___无称不成率,无较不成利___") print(time_list_stamp) else: print("\t要么亲没说对,要么...") print("\t反正不是小岚的错!") def rabbit_white_radish(): while True: two_type = input("这可是小岚的拿手本领!好看的萝卜表,有趣的动画!\n" + "需要生成什么样的萝卜表? ") if two_type == '基准利率': bir() elif two_type == '历年利率': pass elif two_type == '重新输入': continue else: if two_type == '计算': print("该功能正在关闭,稍后跳转到计算功能中……") break # 对历史数据进行加密处理 # 编写数据组,格式化输出历史数据 def plus_wall(): rabbit_purple_radish() rabbit_radish() rabbit_white_radish()
num_input = input("Please enter a number?") ones = { '0': "zero", '1': "one", '2': "two", } n_as_word = ones.get(num_input) print(n_as_word)
if __name__== '__main__': stu = [] pythonStu = [] for _ in range(int(input("How many students"))): name = input("Name: ") score = float(input("Score: ")) single = [name,score] pythonStu.append(single) pythonStu=sorted(pythonStu, key=lambda stud: (stud[1])) minim = pythonStu[0][1] i = 0 while pythonStu[i][1] == minim: if i < (len(pythonStu)-1): i += 1 else: print("No second Students") exit(0) secondmin=pythonStu[i][1] while pythonStu[i][1]==secondmin: stu.append(pythonStu[i][0]) if i < (len(pythonStu)-1): i += 1 else: break stu.sort() print('Seconds: ') for name in stu: print(name)
class A: """Classe A, pour illustrer notre exemple d'héritage""" pass # On laisse la définition vide, ce n'est qu'un exemple class B(A): """Classe B, qui hérite de A. Elle reprend les mêmes méthodes et attributs (dans cet exemple, la classe A ne possède de toute façon ni méthode ni attribut)""" pass class Personne: """Classe représentant une personne""" def __init__(self, nom): """Constructeur de notre classe""" self.nom = nom self.prenom = "Martin" def __str__(self): """Méthode appelée lors d'une conversion de l'objet en chaîne""" return "{0} {1}".format(self.prenom, self.nom) class AgentSpecial(Personne): """Classe définissant un agent spécial. Elle hérite de la classe Personne""" def __init__(self, nom, matricule): """Un agent se définit par son nom et son matricule""" # On appelle explicitement le constructeur de Personne : Personne.__init__(self, nom) self.matricule = matricule def __str__(self): """Méthode appelée lors d'une conversion de l'objet en chaîne""" return "Agent {0}, matricule {1}".format(self.nom, self.matricule) # class MaClasseHeritee(MaClasseMere1, MaClasseMere2): # L'ordre de définition des classes mères importe # Hierarchie des exceptions: https://docs.python.org/3/library/exceptions.html class MonException(Exception): """Exception levée dans un certain contexte… qui reste à définir""" def __init__(self, message): """On se contente de stocker le message d'erreur""" self.message = message def __str__(self): """On renvoie le message""" return self.message class ErreurAnalyseFichier(Exception): """Cette exception est levée quand un fichier (de configuration) n'a pas pu être analysé. Attributs : fichier -- le nom du fichier posant problème ligne -- le numéro de la ligne posant problème message -- le problème proprement dit""" def __init__(self, fichier, ligne, message): """Constructeur de notre exception""" self.fichier = fichier self.ligne = ligne self.message = message def __str__(self): """Affichage de l'exception""" return "[{}:{}]: {}".format(self.fichier, self.ligne, \ self.message) if __name__ == '__main__': agent = AgentSpecial("Fisher", "18327-121") agent.nom print(agent) # les méthodes sont définies dans la classe alors que # les attributs sont directement déclarés dans l'instance d'objet print(agent.prenom) print(Personne.__str__(agent)) print(AgentSpecial.__str__(agent)) print(issubclass(AgentSpecial, Personne)) # AgentSpecial hérite de Personne print(issubclass(AgentSpecial, object)) print(issubclass(Personne, object)) print(issubclass(Personne, AgentSpecial)) # Personne n'hérite pas d'AgentSpecial print(isinstance(agent, AgentSpecial)) # Agent est une instance d'AgentSpecial print(isinstance(agent, Personne)) # Agent est une instance héritée de Personne # Tutorials on errors / exceptions: https://docs.python.org/3/tutorial/errors.html # raise MonException("OUPS... j'ai tout cassé") raise ErreurAnalyseFichier("plop.conf", 34, \ "Il manque une parenthèse à la fin de l'expression")
class Personne: """Classe définissant une personne caractérisée par : - son nom ; - son prénom ; - son âge ; - son lieu de résidence""" def __init__(self, nom, prenom): """Constructeur de notre classe""" self.nom = nom self.prenom = prenom self.age = 33 self._lieu_residence = "Paris" # Notez le souligné _ devant le nom def _get_lieu_residence(self): """Méthode qui sera appelée quand on souhaitera accéder en lecture à l'attribut 'lieu_residence'""" print("On accède à l'attribut lieu_residence !") return self._lieu_residence def _set_lieu_residence(self, nouvelle_residence): """Méthode appelée quand on souhaite modifier le lieu de résidence""" print("Attention, il semble que {} déménage à {}.".format( \ self.prenom, nouvelle_residence)) self._lieu_residence = nouvelle_residence def _del_lieu_residence(self): """Méthode appelée quand on souhaite supprimer le lieu de résidence""" print("On supprime l'attribut lieu_residence !") del self._lieu_residence def _help_lieu_residence(self): """Méthode appelée quand on souhaite obtenir de l'aide sur la propriété lieu de résidence""" chaine = "C'est un lieu de résidence" print(chaine) # On va dire à Python que notre attribut lieu_residence pointe vers une propriété lieu_residence = property(_get_lieu_residence, _set_lieu_residence, \ _del_lieu_residence, _help_lieu_residence) if __name__ == '__main__': bernard = Personne(nom="Nanard", prenom="Bernard") print("bernard.nom:",bernard.nom) print("bernard.nom:",bernard.prenom) print("bernard.nom:",bernard.age) bernard.lieu_residence bernard.lieu_residence = "Berlin" bernard._lieu_residence = "Nouméa" print("bernard.lieu_residence:",bernard._lieu_residence) help(bernard.lieu_residence) # del bernard.lieu_residence
import math angle = 0 angle2 = angle-45 angle3 = angle-90 a=50 c=50*math.sqrt(2) def setup(): size(360,360) def posLine1(): global x1,y1, angle x1 = a*math.sin(math.radians(angle)) y1= a*math.sin(math.radians(90-angle)) def posLine2(): global x2,y2, angle2 x2 = c*math.sin(math.radians(angle2)) y2= c*math.sin(math.radians(90-angle2)) def posLine3(): global x3,y3, angle3 x3 = a*math.sin(math.radians(angle3)) y3= a*math.sin(math.radians(90-angle3)) def lineSetup(): strokeWeight(5) line1 = line(180,180,x1+180,y1+180) strokeWeight(1) line2 = line(180,180,x3+180,y3+180) line3 = line(x3+180,y3+180, x2+180,y2+180) line4 = line(x2+180,y2+180,x1+180,y1+180) def dotSetup(): dot1 = ellipse (x1+180,y1+180,5,5) dot2 = ellipse (x2+180,y2+180,5,5) dot3 = ellipse (x3+180,y3+180,5,5) def draw(): background(255) delay(17) posLine1() posLine3() posLine2() global x1, y1,x2,y2,x3,y3 ellipse(180,180,5,5) lineSetup() dotSetup()
prompt = 'Please entere a score between 0.0 and 1.0: ' score = raw_input(prompt) try: score = float(score) if score >= 0.9 and score <= 1.0: grade = 'A' elif score >= 0.8 and score < 0.9: grade = 'B' elif score >= 0.7 and score < 0.8: grade = 'C' elif score >= 0.6 and score < 0.7: grade = 'D' elif score < 0.6: grade = 'F' else: grade = 'Bad score' print 'Grade: ', grade except: print 'Please enter proper score between 0.0 and 1.0!'
## Problem 23 - Non-abundant sums ## A perfect number is a number for which the sum of its proper divisors ## is exactly equal to the number. For example, the sum of the proper ## divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number. ## A number n is called deficient if the sum of its proper divisors is ## less than n and it is called abundant if this sum exceeds n. ## As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, ## the smallest number that can be written as the sum of two abundant numbers ## is 24. By mathematical analysis, it can be shown that all integers greater ## than 28123 can be written as the sum of two abundant numbers. However, ## this upper limit cannot be reduced any further by analysis even though it is known ## that the greatest number that cannot be expressed as the sum of two abundant numbers is less than this limit. ## Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers. from pylab import * import math import time start=time.clock() n=6 result=[] while n <=28123: a=1 f=math.floor(sqrt(n)) for i in range(2,int(f)+1): if n%i==0: if i!=n/i: a=a+i+n/i if i==n/i: a=a+i if a>n: result.append(n) n+=1 n=1 s=0 result=asarray(result) limit=28123 tt=0 a=[] while n <=limit: count=0 temp=result[result<n] for j in range(len(temp)): if len(temp[temp==n-temp[j]])==1: count+=1 break if count==0: s+=n tt+=1 a.append(n) if tt%100==0: print s,n n+=1 end=time.clock() print(end-start)
import AES as aes # Import AES to implement OFB import random # It is used to generate random integer WORD_LENGTH = 4 # Length of matrix SIZE = 16 # Length of the texts # It generates a random initialization vector with size 16 def generate_initialization_vector(): in_vector = [0 for x in range(SIZE)] for i in range(SIZE): in_vector[i] = random.randint(1, 101) return in_vector # It splits the text 16 bytes by 16 bytes # It adds 'X' to the text if it is not multiple of 16 def split_plain_text(string): plain_text_arr = [string[i:i + SIZE] for i in range(0, len(string), SIZE)] size_of_last_part = len(plain_text_arr[len(plain_text_arr) - 1]) added_item_count = SIZE - size_of_last_part last_item_index = len(plain_text_arr) - 1 for i in range(added_item_count): plain_text_arr[last_item_index] = plain_text_arr[last_item_index] + 'X' return plain_text_arr, added_item_count # It takes a hex string matrix and converts it to a hex string array def reverse_matrix_to_hex_string_arr(matrix): arr = ['' for x in range(SIZE)] index = 0 for i in range(WORD_LENGTH): for j in range(WORD_LENGTH): arr[index] = matrix[j][i] index = index + 1 return arr # It converts the string array to string # It remove the 'X's if it was added def merge_strings(str_arr, remove_count): text = "" if remove_count == 0: for string in str_arr: text = text + string else: final = str_arr.pop(len(str_arr) - 1) for string in str_arr: text = text + string for i in range(SIZE - remove_count): text = text + final[i] return text # It converts the string array to string # It does not remove the 'X's def merge_strings_without_remove_item(str_arr): text = "" for string in str_arr: text = text + string return text # It is encryption operation for the OFB # It takes the main key, message and the initialization vector # It returns count of added 'X's and encrypted message as hex string 2d array def OFB_encryption(key_val, text_val, iv_enc_val): plain_text_arr, added_item_count = split_plain_text(text_val) key_in_hex = aes.translate_string_into_hex_str(key_val) all_round_key = aes.find_all_round_keys(key_in_hex) cipher_text_arr = [] hex_iv_enc = aes.make_int_arr_to_hex(iv_enc_val) current_enc_output = aes.encrypt(hex_iv_enc, all_round_key) hex_plain_text = aes.translate_string_into_hex_str(plain_text_arr[0]) hex_plain_text_matrix = aes.generate_4x4_matrix(hex_plain_text) current_enc_output_matrix = aes.generate_4x4_matrix(current_enc_output) cipher_text_matrix = aes.add_round_key(current_enc_output_matrix, hex_plain_text_matrix) cipher_text = reverse_matrix_to_hex_string_arr(cipher_text_matrix) cipher_text_arr.append(cipher_text) for i in range(1, len(plain_text_arr)): current_enc_output = aes.encrypt(current_enc_output, all_round_key) hex_plain_text = aes.translate_string_into_hex_str(plain_text_arr[i]) hex_plain_text_matrix = aes.generate_4x4_matrix(hex_plain_text) current_enc_output_matrix = aes.generate_4x4_matrix(current_enc_output) cipher_text_matrix = aes.add_round_key(current_enc_output_matrix, hex_plain_text_matrix) cipher_text = reverse_matrix_to_hex_string_arr(cipher_text_matrix) cipher_text_arr.append(cipher_text) return cipher_text_arr, added_item_count # It is decryption operation for the CBC # It takes the main key, encrypted message, initialization vector and count of added 'X's to remove # It returns count of added 'X's and encrypted message as hex string 2d array def OFB_decryption(key_val, cipher_text_arr, iv_dec_val, remove_count): key_in_hex = aes.translate_string_into_hex_str(key_val) all_round_key = aes.find_all_round_keys(key_in_hex) plain_text_arr = [] hex_iv_dec = aes.make_int_arr_to_hex(iv_dec_val) current_enc_output = aes.encrypt(hex_iv_dec, all_round_key) current_enc_output_matrix = aes.generate_4x4_matrix(current_enc_output) cipher_text_matrix = aes.generate_4x4_matrix(cipher_text_arr[0]) plain_text_matrix = aes.add_round_key(current_enc_output_matrix, cipher_text_matrix) plain_text_hex = reverse_matrix_to_hex_string_arr(plain_text_matrix) plain_text_str = aes.translate_hex_into_str(plain_text_hex) plain_text_arr.append(plain_text_str) for i in range(1, len(cipher_text_arr)): current_enc_output = aes.encrypt(current_enc_output, all_round_key) current_enc_output_matrix = aes.generate_4x4_matrix(current_enc_output) cipher_text_matrix = aes.generate_4x4_matrix(cipher_text_arr[i]) plain_text_matrix = aes.add_round_key(current_enc_output_matrix, cipher_text_matrix) plain_text_hex = reverse_matrix_to_hex_string_arr(plain_text_matrix) plain_text_str = aes.translate_hex_into_str(plain_text_hex) plain_text_arr.append(plain_text_str) resolved_text_val = merge_strings(plain_text_arr, remove_count) return resolved_text_val
import pygame import column_logic import random #These two constants are the row and column of the game ROW_NUM = 13 COLUMN_NUM = 6 class ColumnGame: ''' This is a class represents the user interface of the column game, which displays tha game ''' def __init__(self): self._running = True self._state = column_logic.GameState(ROW_NUM, COLUMN_NUM) def run(self) -> None: ''' This function runs the program, displaying the graphic user interface ''' pygame.init() self._resize_surface((600,780)) clock = pygame.time.Clock() while self._running: counter = 0 interval = 5 while counter < interval: if self._state.faller_pos == None: self._insert_a_faller() clock.tick(9) self._handle_events() self._redraw() counter += 1 self._state.one_tick() while self._state.match == True: clock.tick(9) self._redraw() self._state.one_tick() if self._state.game_over == True: self._end_game() pygame.quit() def _handle_events(self) -> None: ''' This function handle the events that can happen when the user does certain operations ''' for event in pygame.event.get(): if event.type == pygame.QUIT: self._end_game() elif event.type == pygame.VIDEORESIZE: self._resize_surface(event.size) elif event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: self._state.move_left() if event.key == pygame.K_RIGHT: self._state.move_right() if event.key == pygame.K_SPACE: self._state.rotate() def _draw_background(self) -> None: ''' Draw the background on the display ''' surface = pygame.display.get_surface() width = surface.get_width() height = surface.get_height() left_frac_x = 0 right_frac_x = 0.8 width_frac = 0.2 height_frac = 1 pygame.draw.rect(surface, pygame.Color(123,123,123), pygame.Rect((0,0),(width_frac*width,height))) pygame.draw.rect(surface, pygame.Color(123,123,123), pygame.Rect((right_frac_x*width,0),(width_frac*width,height))) def _draw_gems(self, game_state: column_logic.GameState) -> None: ''' Draw the gems on the display ''' surface = pygame.display.get_surface() width = surface.get_width() height = surface.get_height() for r in range(ROW_NUM): for c in range(COLUMN_NUM): gem = self._state.get_gem_from_board(r,c) if gem != None: color = self._handle_gem_color(gem) top_left_frac_x = 0.2+0.1*c top_left_frac_y = 0.077*r width_frac = 0.16667 height_frac = 0.077 background_width = 0.4*width display_rect = pygame.Rect((top_left_frac_x*width, top_left_frac_y*height), (width_frac*(width-background_width),height_frac*height)) pygame.draw.rect(surface, color, display_rect) def _handle_gem_color(self, gem: column_logic.Gem) -> pygame.Color: ''' This function reads the Gem object's color, which is a string and returns a Color object relative to the Gem's color This function also handles the color of the gem when it is landed and matched ''' if gem.status == column_logic.LANDED: if gem.color == 'S': return pygame.Color(255-60,0,0) if gem.color == 'T': return pygame.Color(182-60,102-60,0) if gem.color == 'V': return pygame.Color(85-60,122-60,0) if gem.color == 'W': return pygame.Color(0, 150-60,150-60) if gem.color == 'X': return pygame.Color(0,0,223-60) if gem.color == 'Y': return pygame.Color(173-60,0,77) if gem.color == 'Z': return pygame.Color(0,255-60,0) elif gem.status == column_logic.MATCH: return pygame.Color(0,0,0) else: if gem.color == 'S': return pygame.Color(235,0,0) if gem.color == 'T': return pygame.Color(162,82,3) if gem.color == 'V': return pygame.Color(65,102,0) if gem.color == 'W': return pygame.Color(0, 130,130) if gem.color == 'X': return pygame.Color(0,33,203) if gem.color == 'Y': return pygame.Color(153,0,77) if gem.color == 'Z': return pygame.Color(0,235,0) def _redraw(self) -> None: ''' This function redraw the display in order to update the state of the game ''' surface = pygame.display.get_surface() surface.fill(pygame.Color(255,255,255)) self._draw_background() self._draw_gems(self._state) pygame.display.flip() def _insert_a_faller(self) -> None: ''' This function randomly create faller when there is no faller on the display ''' random_column = round(random.random()*5) random_gems = [] for i in range(3): random_gems.append(column_logic.Gem(column_logic.VALID_COLORS[round(random.random()*6)],column_logic.FALLER)) self._state.create_a_faller(random_column, random_gems) def _end_game(self) -> None: ''' This function changes the indicator of whether the game should keep running to False ''' self._running = False def _resize_surface(self, size: (int, int)) -> None: ''' This function takes in a size of the display and resizes the display to that size ''' pygame.display.set_mode(size, pygame.RESIZABLE) if __name__ == '__main__': ColumnGame().run()
#Name: Eric Liu #StudentID: 56277704 from pathlib import Path from shutil import copyfile #Part 1 #Read a line of input that specifies which files are eligible to be found #Input #D, followed by a space, followed by the path to a directory #R, followed by a space, followed by the path to a directory #Output #Starts with D -> List of all files in that directory, but no subdirectories #Starts with R -> List of all files in that directory, along with all of the #files in its subdirectories, all of the files in their subdirectories, and so on def find_files(directory: str) -> [Path]: """return a list of Path of files that are under consideration """ p = Path(directory[2:]) if p == Path(''): raise if directory[0:2] == 'D ': return d_find_files(p) if directory[0:2] == 'R ': return r_find_files(p) else: raise def d_find_files(directory: Path) -> [Path]: lst = [] for thing in directory.iterdir(): if thing.is_file(): lst.append(thing) lst.sort(key = lex_order) return lst def r_find_files(directory: Path) -> [Path]: lst = [] dlst = [] for thing in directory.iterdir(): if thing.is_file(): lst.append(thing) if thing.is_dir(): dlst.append(thing) lst.sort(key = lex_order) dlst.sort(key = lex_order) for folder in dlst: lst += r_find_files(folder) return lst def lex_order(p: Path) -> str: """Because for Path object in Windows, when comparing two paths, paths are not case-sensitive. e.g. Path('a') == Path('A') -> True Therefore, this function uses as a key of the list.sort() function to make the Paths in a list are in lexicographical ordering. """ if p.is_file(): return p.name if p.is_dir(): return p.parts[-1] #Part 2 #reads a line of input that describes the search characteristics that will be #used to decide whether files are "interesting" #Input: #A #N, followed by a space, followed by the name of the files #E, followed by a space, followed by the desired extension #T, followed by a space, followed by the given text #<, followed by a space, followed by a non-negative integer(size threshold) #>, followed by a space, followed by a non-negative integer(size threshold) #Output: #Starts with A -> a list of all files found in the previous step #Starts with N -> a list of all files whose names exactly match a particular name #Starts with E -> a list of all files with given extension #Starts with T -> a list of all files that contain the given text #Starts with < -> a list of all files whose size are less than a specified threshold #Starts with > -> a list of all files whose size are greater than a specified threshold def choose_files(flst: [Path], fneed: str) -> [Path]: """Return a list of Path of files that are interesting """ if fneed == 'A': return a_choose_files(flst) if fneed[0:2] == 'N ': return n_choose_files(flst, fneed[2:]) if fneed[0:2] == 'E ': return e_choose_files(flst, fneed[2:]) if fneed[0:2] == 'T ': return t_choose_files(flst, fneed[2:]) if fneed[0:2] == '< ': return l_choose_files(flst, int(fneed[2:])) if fneed[0:2] == '> ': return g_choose_files(flst, int(fneed[2:])) else: raise def a_choose_files(flst: [Path]) -> [Path]: return flst def n_choose_files(flst: [Path], fname: str) -> [Path]: lst = [] for file in flst: if file.name == fname: lst.append(file) return lst def e_choose_files(flst: [Path], fext: str) -> [Path]: lst = [] for file in flst: if file.suffix == fext or file.suffix == '.'+fext: lst.append(file) return lst def t_choose_files(flst: [Path], ftxt: str) -> [Path]: lst = [] for file in flst: try: f = file.open() text = f.read() if ftxt in text: lst.append(file) except: continue return lst def l_choose_files(flst: [Path], fsize: int) -> [Path]: lst = [] for file in flst: if file.stat().st_size < fsize: lst.append(file) return lst def g_choose_files(flst: [Path], fsize: int) -> [Path]: lst = [] for file in flst: if file.stat().st_size > fsize: lst.append(file) return lst #Part 3 #reads a line of input that describes the action that will be taken on each interesting file #Input: #F #D #T #Output: #F -> print the first line of text from the file if it's a text file; #print NOT TEXT if it is not #D -> make a duplicate copy of the file and store it in the same directory where the original resides, #but the copy should have .dup (short for "duplicate") appended to its filename #T -> modify its last modified timestamp to be the current date/time def action_handler(flst: [Path], act: str) -> None: """take an certain action of the files in a list """ if act == 'F': for file in flst: try: with file.open('r') as f: text = f.readline() if text != '' and text[-1] == '\n': text = text[:-1] print(text) except: print('NOT TEXT') if act == 'D': for file in flst: suf = file.suffix + '.dup' dst = file.with_suffix(suf) copyfile(file, dst) if act == 'T': for file in flst: file.touch() else: raise ################################################################################# if __name__ == '__main__': ##Find the files that are in consideration while True: directory = input() try: files_list = find_files(directory) for file in files_list: print(file) break except: print('ERROR') ##Find the files that are "interesting" and should have action taken on them later while True: files_needed = input() try: files_list = choose_files(files_list, files_needed) for file in files_list:print(file) break except: print('ERROR') ##Take action of the files while True: action = input() action_handler(files_list, action) break
from datetime import datetime import wikipedia import speech_recognition as sr # to talk to alexa import pyttsx3 # pyttsx3 means python text to speech, use this so alexa can talk to us import pywhatkit # to open applications like youtube import pyjokes # used to tell jokes listener = sr.Recognizer() # this listener will be able to recognize your voice engine = pyttsx3.init() # this engine will talk to us, init means to initialize the engine voices = engine.getProperty('voices') engine.setProperty('voice', voices[1].id) # the previous line and the current line is used to change the male voice of alexa to female # engine.say('Hi, I am Alexa') # engine.say('What can I do for you') # engine.runAndWait() def talk(text): engine.say(text) engine.runAndWait() def take_command(): # take command from us try: # sometimes the microphone might not work or there is any other trouble with sr.Microphone() as source: # using the microphone as the source, this will be the source of the audio print('listening...') voice = listener.listen(source) # calling the speech recognition to listen to this source command = listener.recognize_google(voice) # using the google api to covert the voice to text command = command.lower() # make the command to the lowercase if 'alexa' in command: # if the command has the name alexa in it then only print the command command = command.replace('alexa', '') # put the empty string in the command instead of alexa print(command) except: # don't do anything when the exception happens # print('hi') pass return command def run_alexa(): # run the alexa command = take_command() # use the function to take the command from the user print(command) if 'play' in command: # if we want to play a song song = command.replace('play','') talk('playing' + song) # print('playing' + song) pywhatkit.playonyt(song) # playonyt means play on youtube and pass in the song elif 'time' in command: time = datetime.datetime.now().strftime('%I:%M %p') # %I is the 12 hour format and %p is for the am or pm print(time) talk(time) elif 'who the heck is' in command: person = command.replace('who the heck is', '') info = wikipedia.summary(person, 1) # get 1 line of information from the wikipedia from the wikipedia print(info) talk(info) elif 'date' in command: talk('sorry, I have a headache') elif 'are you single' in command: talk('No, I am in relationship with WIFI') elif 'joke' in command: talk(pyjokes.get_joke()) else: talk('Please say the command again') while True: # continue running alexa run_alexa()
animals = { "Dog":"Bow Bow", "Cat":"Mewow" } #add items it= animals["Cow"]="Maa" print(animals) #add items using python in-built function it = animals.update({"Cat":"Mewow Mewow"}) print(animals)
from moduloT2 import * n = int(input("Introduzca un número: ")) fac = factorial(n) primo = esPrimo(n) print("El factorial de " + str(n) + " es: " + str(fac)) if primo: print(str(n) + " es primo") else: print(str(n) + " no es primo")
""" 文件读写工具 --- read_file(file_path): 读取单个文件数据 read_folder(folder_path, file_suffix={'txt', 'csv', 'dat'}): 读取文件夹指定后缀文件 """ from os import listdir from os.path import isfile, join def read_file(file_path): """ 读取文件内容 """ pieces = [] with open(file_path, 'r', encoding='utf-8') as f: for line in f: pieces.append(line.strip()) return pieces def write_file(data, file_path): """ 保存文件内容 """ with open(file_path, 'w', encoding='utf-8') as f: f.write('\n'.join(data)) def get_folder_files(folder_path, file_suffix={'txt', 'csv', 'dat'}): """ 获取目录下的所有文件 """ if isinstance(file_suffix, set): files = [f for f in listdir(folder_path) if isfile(join(folder_path, f))] files = [join(folder_path, f) for f in files if f.split('.')[-1] in file_suffix] else: raise Exception("""file suffix error, do like file_suffix={'txt', 'csv', 'dat'}""") print('\n'.join(['corpus folder files:'] + [' |%s' % x for x in files])) return files def read_folder(folder_path, file_suffix={'txt', 'csv', 'dat'}): """ 读取所有的数据 """ files = get_folder_files(folder_path, file_suffix) pieces = [] for file in files: pieces += read_file(file) return pieces
# -*- coding: utf-8 -*- """ Created on Wed Mar 6 08:48:27 2019 Problem Set 5 Problem 1: Periodic Points of a Word Problem 2: Connected Components of Function """ from nose.tools import ok_ # ============================================================================= # Problem 1 # Given a word of length n, the program computes to find a set of periodic points # which is defined by a point that is in the given word. Periodic points of the # associated function is found by using lp_orbits to find the cycles, and add # each of the cycle to a set which will be returned by the program. # ============================================================================= def lp_apply(p, i): n = len(p) if 0 <= i and i < n: return p[i] def lp_orbit(p, i): n = len(p) if 0 <= i and i <n: rv = [i] j = lp_apply(p, i) #if the rv length exceeds the list length, it indicates that there #is repeating elements while j != i and len(rv) <= n: if j in rv[1:]: return None rv.append(j) j = lp_apply(p, j) return rv def lp_orbits(p): n = len(p) seen = set() orbits = [] for i in range(n): if i not in seen: o = lp_orbit(p, i) if o != None: seen |= set(o) orbits.append(o) orbits.sort(key = len) return orbits def periodic_points(f): periodic_set = set() cycle_f = lp_orbits(f) for cycle in cycle_f: #cycle is all the periodic points of f, thus take the union of all the #cycles computed by lp_orbits periodic_set |= set(cycle) return periodic_set #Code Tests ok_({0, 3, 4, 5} == periodic_points([5, 3, 4, 0, 3, 4])) ok_({1, 2, 3, 4} == periodic_points([3, 2, 4, 1, 3])) ok_({0, 1, 4} == periodic_points([1, 0, 1, 2, 4, 0])) ok_({0, 1, 2, 3} == periodic_points([3, 0, 1, 2])) # ============================================================================= # Problem 2 # Given with a list of points, the two points, i and j, are eventually colliding # under the function. Two points will be connected by an edge between that # particular point and f(particular point). This program returns the total number # of connected components based on the function using the module from networkx. # ============================================================================= import networkx as nx def count_components(f): g = nx.Graph() g.add_nodes_from(range(len(f))) for node in range(len(f)): g.add_edge(node, f[node]) num_connected_components = nx.number_connected_components(g) return num_connected_components #Code Tests ok_(3 == count_components([0, 2, 4, 5, 1, 3])) ok_(2 == count_components([1, 2, 4, 3, 2])) ok_(2 == count_components([6, 3, 2, 1, 0, 3, 2])) ok_(1 == count_components([1, 2, 3, 1, 2])) ok_(6 == count_components([1, 0, 1, 0, 4, 5, 6, 7, 8]))
# Benjamin Chappell # Class used to classify all the actions one can take in poker from enum import Enum, auto class ActionTypes(Enum): FOLD = 0 CHECK = auto() CALL = auto() RAISE = auto() shove = auto() class Action: # Move is an enum value designating fold, check, call, raise, shove # amount is equal to the amount raising or shoving def __init__(self, move, amount=-1) -> None: self.move = move self.amount = amount def __str__(self) -> str: return "Move: %s; Amount: %d" % (ActionTypes(self.move).name, self.amount)
# Benjamin Chappell # Hand value storage from enum import Enum from rank import Rank class HandClass(Enum): HIGH = 0 PAIR = 1 TWO_PAIR = 2 SET = 3 STRAIGHT = 4 FLUSH = 5 BOAT = 6 QUADS = 7 SFLUSH = 8 RFLUSH = 9 class Hand: def __init__(self, type, rank, rank2=False) -> None: self.type = type self.rank = rank self.rank2 = rank2 if self.rank == 0: self.rank += 13 for i in range(0, len(rank2)): if rank2[i] == 0: rank2[i] += 13 def __str__(self) -> str: s = "Class: %s; Rank: %s; Secondary Rank: " % (self.type, Rank(self.rank%13).name) for i in range(0, len(self.rank2)): s = s + Rank(self.rank2[i]%13).name + ", " return s # Compares 2 hand objects # if hand1 is greater than hand2, return True, hand2 greater than hand1 return False # If the two hands are equal, return -1 def compare(self, hand2): if self.type.value != hand2.type.value: return self.type.value > hand2.type.value else: if self.rank != hand2.rank: return self.rank > hand2.rank for i in range(0, len(self.rank2)): if self.rank2[i] != hand2.rank2[i]: return self.rank2 > hand2.rank2 return -1
from tkinter import * root = Tk() root.title('车牌识别系统') frame1 = Frame(root) frame2 = Frame(root) frame3 = Frame(root) var = StringVar() var.set('欢迎进入车牌识别系统') img = PhotoImage(file='D:/bg_GUI.png') # img_label = Label(frame1, image=img) # img_label.pack(side=RIGHT) Label(frame1, image=img).grid(row=1, column=1, sticky=W, padx=50, pady=30) Label(frame3, textvariable=var).grid(row=3, column=1, sticky=W, padx=5, pady=5) Label(frame1, text='请输入图片编号:').grid(row=0, column=0) e1 = Entry(frame1) e1.grid(row=0, column=1, padx=10, pady=5) Button(frame2, text='开始识别', width=10, command=root.quit).grid(row=2, column=1, sticky=W, padx=50, pady=50) frame1.pack(padx=100, pady=50) frame2.pack(padx=100, pady=50) frame3.pack(padx=10, pady=10) mainloop()
def prefix_suffix(string): if not string: return 0 arr = [0] * (len(string) + 1) for i in range(2, len(arr)): arr[i] = arr[i - 1] while string[i - 1] != string[arr[i]] and arr[i] > 0: arr[i] = arr[arr[i]] if string[i - 1] == string[arr[i]]: arr[i] += 1 return arr[-1] if __name__ == '__main__': string = 'a' print('Test #1 is', 'Ok.' if prefix_suffix(string) == 0 else 'Fail.') string = '' print('Test #2 is', 'Ok.' if prefix_suffix(string) == 0 else 'Fail.') string = 'asdfghasdfgh' print('Test #3 is', 'Ok.' if prefix_suffix(string) == 6 else 'Fail.') string = 'aaa' print('Test #4 is', 'Ok.' if prefix_suffix(string) == 2 else 'Fail.') string = 'aaaabaaaaaa' print('Test #5 is', 'Ok.' if prefix_suffix(string) == 4 else 'Fail.') string = 'aaaaaa' print('Test #6 is', 'Ok.' if prefix_suffix(string) == 5 else 'Fail.') string = 'abacabadabacaba' print('Test #7 is', 'Ok.' if prefix_suffix(string) == 7 else 'Fail.') string = 'aaabaaaaa$aaaabaaaa' print('Test #8 is', 'Ok.' if prefix_suffix(string) == 8 else 'Fail.')
#!/usr/local/bin/python def iterate_word(word): for x in range(0,len(word)): print("Forward:" , word[x], "Reverse", word[(len(word) -x -1)]) iterate_word('alphabet') # doing this with list comprehension returning reversed tuple pairs: In [240]: [(word[x], word[(len(word) - x - 1)]) for x in range(0,len(word))] Out[240]: [('a', 't'), ('l', 'e'), ('p', 'b'), ('h', 'a'), ('a', 'h'), ('b', 'p'), ('e', 'l'), ('t', 'a')] # as a function: In [241]: def iter_string(word): ...: return [(word[x], word[(len(word) - x - 1)]) for x in range(0,len(word))] ...: In [242]: iter_string('alphabet') Out[242]: [('a', 't'), ('l', 'e'), ('p', 'b'), ('h', 'a'), ('a', 'h'), ('b', 'p'), ('e', 'l'), ('t', 'a')]
""" Use any Object-Oriented language to complete this task. # Create a class named LuckyNumber. # The constructor for LuckyNumber should take a single argument: a string called first_name (e.g.: "Marc"). # In the LuckyNumber class create two methods, generate_data and display_data, that take no arguments. # The generate_data method should create and return a new object everytime it is called. (e.g. Python dictionary, Java Map) # The object returned by generate_data method should contain 2 things: # 1) A field named "date" with the current date in string format. # 2) A field named "lucky_number" with a random floating point number between 0-100 in string format (2 decimal places). # e.g. { "date": "23 Nov 2021", "lucky_number": "55.67" } # The display_data method should do two things: # 1) Call the generate_data method to retrieve a new date and lucky_number. # 2) Print a message addressed to first_name, along with the date and lucky number. # e.g.: "Hello Marc, your lucky number for 23 Nov 2021 is: 55.67" # Finally, create an object of type LuckyNumber and call the display_data method. """ import random from datetime import datetime names = ['Marc','Alice','Bob','Charlie','Dave','Eve'] def myrand(): return round(random.uniform(1,101),2) def mynow(): return datetime.now().strftime('%Y-%m-%d') class LuckyNumber(): def __init__(self,first_name): self.first_name = first_name # def generate_data(): return {'date':mynow(), 'lucky_number':myrand()} # def display_data(self): name = self.first_name mydata = LuckyNumber.generate_data() date, num = mydata['date'], mydata['lucky_number'] return f"Hello, {name}, your lucky number for {date} is {num}" # demo #In [94]: foo = LuckyNumber("Alice") # #In [95]: foo.first_name #Out[95]: 'Alice' # #In [96]: foo.display_data() #Out[96]: 'Hello, Alice, your lucky number for 2021-12-02 is 74.63' # #
""" - In a street there are five houses, painted five different colors. - In each house lives a person of different nationality. - These five homeowners each drink a different kind of beverage, smoke different brand of cigar and keep a different pet. - The British man lives in a red house. - The Swedish man keeps dogs as pets. - The Danish man drinks tea. - The Green house is next to, and on the left of the White house. - The owner of the Green house drinks coffee. - The person who smokes montecristo rears birds. - The owner of the Yellow house smokes Cao. - The man living in the center house drinks milk. - The Norwegian lives in the first house (first house left to right). - The man who smokes Blends lives next to the one who keeps cats. - The man who keeps horses lives next to the man who smokes Cao. - The man who smokes Partagas drinks beer. - The German smokes Cohiba. - The Norwegian lives next to the blue house. - The Davidoff smoker lives next to the one who drinks water. """ from constraint import * # create the object problem = Problem() # variable lists nation = ["british","swedish","norwegian","german","danish"] house = ["red", "green","yellow","blue","white"] pet = ["dog","cat","fish","horse","bird"] order = ["first","second","third","fourth","fifth"] drink = ["beer","milk","water","coffee","tea"] cigar = ["cohiba","montecristo","cao","davidoff","partagas"] # create the meta list criteria = nation + house + pet + drink + cigar # add the house order problem.addVariables(criteria,[1,2,3,4,5]) # apply the lists print('apply the lists') problem.addConstraint(AllDifferentConstraint(), nation) problem.addConstraint(AllDifferentConstraint(), house) problem.addConstraint(AllDifferentConstraint(), pet) problem.addConstraint(AllDifferentConstraint(), drink) problem.addConstraint(AllDifferentConstraint(), cigar) # add constraints print('adding constraints') problem.addConstraint(lambda b, r: b == r, ['british','red']) problem.addConstraint(lambda s, d: s == d,['swedish','dog']) problem.addConstraint(lambda c, g: c == g,['coffee','green']) problem.addConstraint(lambda d, t: d == t,['danish','tea']) problem.addConstraint(lambda g, w: g-w == 1,['green','white']) problem.addConstraint(lambda p, b: p == b, ['montecristo','bird']) problem.addConstraint(lambda d, y: d == y, ["cao","yellow"]) problem.addConstraint(InSetConstraint([3]), ["milk"]) problem.addConstraint(InSetConstraint([1]), ["norwegian"]) problem.addConstraint(lambda d, h: abs(d-h) == 1, ("cao","horse")) problem.addConstraint(lambda b, c: abs(b-c) == 1, ("davidoff","cat")) problem.addConstraint(lambda bm, b: bm == b, ["partagas","beer"]) problem.addConstraint(lambda g, p: g == p, ["german","cohiba"]) problem.addConstraint(lambda k, h: abs(k-h) == 1, ["norwegian","blue"]) # get solution print('getting solutions') solution = problem.getSolutions()[0] # print out list print('printing list') for i in range(1,6): for x in solution: if solution[x] == i: print(str(i), x) """ apply the lists adding constraints getting solutions printing list 1 cao 1 norwegian 1 yellow 1 cat 1 water 2 horse 2 blue 2 danish 2 tea 2 davidoff 3 red 3 british 3 montecristo 3 bird 3 milk 4 white 4 swedish 4 dog 4 beer 4 partagas 5 green 5 coffee 5 german 5 cohiba 5 fish """
class Node(object): def __init__(self,value): self.value = value self.next = None class Stack(object): def __init__(self): self.head = None def push(self,value): """ Somethis is borked in which self.head has no value """ if self.head is None: self.head = Node(value) print(value) return True else: cursor = self.head while cursor.next is not None: cursor = cursor.next cursor.next = Node(value) print(value) return True def pop(self): if self.head is None: return None elif self.head.next is None: cursor = self.head.value self.head = None return cursor else: cursor = self.head.value self.head = self.head.next return cursor def print(self): if self.head is None: print('No stack head, quitting') return False print("stack elements are") cursor = self.head while cursor.next is not None: print(cursor.value, end=">>") cursor = cursor.next print(cursor.value, end="<<") def top(self): return self.head def size(self): cursor = self.head count = 0 while cursor is not None: count += 1 cursor = cursor.next return count def isEmpty(self): if self.head is None: return True else: return False def find(self, key): if self.head is not None: cursor = self.head while cursor.next.value != key: cursor = cursor.next if cursor.next == None: print(f'{key} not found in list') return False print(f'found {key}') return True else: print('List is empty') return False def remove(self, key): if self.head is not None: cursor = self.head while cursor.next.value != key: cursor = cursor.next if cursor.next == None: print(f'{key} not found in list') return False cursor.next = cursor.next.next return key else: print('List is empty') return False def prepend(self,value): if self.head is not None: new = Node(value) cursor = self.head new.next = cursor self.head = new return value else: print('list is empty') return False def append(self, value): if self.head is not None: new = Node(value) cursor = self.head while cursor.next is not None: cursor = cursor.next cursor.next = Node(value) print(value) return True else: self.head = Node(value) return value def replace(self, key, value): if self.head is not None: cursor = self.head while cursor.next.value != key: cursor = cursor.next if cursor.next == None: print(f'{key} not found in list') return False new = Node(value) cursor.next.value = value return value def insertbefore(self,key, value): if self.head is not None: cursor = self.head while cursor.next.value != key: cursor = cursor.next if cursor.next == None: print(f'{key} not found in list') return False new = Node(value) new.next = cursor.next cursor.next = new return value def insertafter(self, key, value): if self.head is not None: cursor = self.head while cursor.next.value != key: cursor = cursor.next if cursor.next == None: print(f'{key} not found in list') return False new = Node(value) new.next = cursor.next.next cursor.next.next = new return value def printreverse(self): reverse = [] cursor = self.head while cursor.next is not None: reverse.append(cursor.value) cursor = cursor.next reverse.append(cursor.value) return reverse[::-1]
#!/usr/local/bin/python import random #Create an array X and fill the array with 10 values, each value being a random integer between 0 to 100. For example when your program is done, X could be something like this: [35, 15, 3, 39, 53, 93, 25, 39, 59, 21].Create an array X and fill the array with 10 values, each value being a random integer between 0 to 100. For example when your program is done, X could be something like this: [35, 15, 3, 39, 53, 93, 25, 39, 59, 21]. my_array = [] for loop in range(0,9): num = random.randrange(1,100) my_array.append(num) loop += 1 print(my_array) # a more pythonic way to do this with list comprehension myarr = [random.randint(1,101) for x in range(11)]
""" a turn based number guesser player between a human and the computer. At numbers < 100, The computer should solve the problem in 5 turns or less Usage: python computer_human_number_guesser.py """ import random def getguess(): """ get the guess from the player """ guess = int(input("What's your guess - 1-100?, q: ")) if ((guess <100) and (guess > 0)): return guess else: print("need an integer 1-100") return getguess() def compguess(lastguess): """ computer guesses by creating smaller ranges narrowing lo and hi values divided by 2 """ global guesses, lo, hi if lastguess > num: hi = lastguess elif lastguess < num: lo = lastguess + 1 guess = (lo + hi) //2 guesses.append(guess) return guess def otherguy(): """ helper to switch turns """ if turn == 'person': return 'computer' return 'person' def outcome(guess): """ who won? """ global turn,inplay if guess > num: outcome = 'too high' else: outcome = 'too low' if guess == num: inplay = False return turn, 'correctly guessed', num else: turn = otherguy() return f"{guess} was {outcome}. Now it's {turn}'s turn" def newgame(): """ set the global variables for a new game """ global num, turn, inplay, guesses, lastguess, lo, hi num, turn, inplay, guesses, lastguess, lo, hi = random.randint(1,101),'person',True,[], random.randint(30,70), 1, 100 def main(): """ main turn based logic """ global guesses, turn, inplay, lastguess while inplay: if turn == 'person': guess = getguess() print(outcome(guess)) elif turn =='computer': guess = compguess(lastguess) lastguess = guess print(f"{turn}'s",outcome(guess)) print("Computer's tally",lastguess, guesses, len(guesses), 'moves so far') if __name__ == '__main__': print("*" *20) print("starting game") print("you're playing the computer - enter a number between 1 and 100 to take your turn.") print("if you miss, the computer will try.") print("*" *20) newgame() # for debugging # print(num, turn, inplay, guesses) while True: if inplay == True: main() else: print('Game Over!') break
#!/usr/local/bin/python """ shift values one position to the right. In this cast you wind up with the same final array """ my_array = [8,3, 33, 42, 10, 14, 2, 21, 4] loop = 0 while loop < len(my_array): print(my_array) my_array.append(my_array[0]) my_array.pop(0) print(my_array) loop += 1 # doing something more useful, as a function: In [161]: myarr Out[161]: [ 53, 32, 26, 90, 57, 44, 61, 81, 38, 15, 69] In [162]: def prepend_to_array(arr,n): ...: arr.append(0) ...: for x in range(len(arr) -1,-1,-1): ...: arr[x] = arr[x -1] ...: arr[0] = n ...: return arr ...: In [163]: prepend_to_array(myarr,2222) Out[163]: [2222, 53, 32, 26, 90, 57, 44, 61, 81, 38, 15, 69] # the pythonic way: In [181]: myarr.insert(0,4444) In [182]: myarr Out[182]: [4444, 2222, 53, 32, 26, 90, 57, 44, 61, 81, 38, 15, 69]
#!/usr/bin/env python3 low = 353096 high = 843212 num_possible = 0 # Teil 1 for n in range(low + 1, high): digits = list(str(n)) prev_digit = 0 has_ascending_digits = True has_double_digit = False for digit in digits: digit = int(digit) # Folgende Ziffer kleiner als vorherige if digit < prev_digit: has_ascending_digits = False break # Ziffer identisch zu vorheriger if digit == prev_digit: has_double_digit = True prev_digit = digit if has_double_digit and has_ascending_digits: #print("Valid:", str(n)) num_possible += 1 else: #print("Invalid:", str(n)) pass # 579 print(num_possible, "Kombinationen im Bereich von (", low, ",", high, "); Teil 1") # Teil 2 num_possible = 0 for n in range(low + 1, high): digits = list(str(n)) has_double_digit = False has_ascending_digits = True double_digits = {0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7:0, 8: 0, 9: 0} prev_digit = 0 for digit in digits: digit = int(digit) # Folgende Ziffer kleiner als vorherige if digit < prev_digit: has_ascending_digits = False break # Ziffer identisch zu vorheriger if digit == prev_digit: double_digits[digit] += 1 prev_digit = digit for num in double_digits.values(): if num == 1: has_double_digit = True break if has_double_digit and has_ascending_digits: #print("Valid:", str(n)) num_possible += 1 else: #print("Invalid:", str(n)) pass # 358 print(num_possible, "Kombinationen im Bereich von (", low, ",", high, "); Teil 2")
fibs(lengths): 'return the list of Fibonacci sequence' fiblist = [0, 1] for i in range(lengths-2): fiblist.append(fiblist[-2]+fiblist[-1]) return fiblist print fibs(11)
#Aliasing in python, short hand for pyplot import matplotlib.pyplot as plt #x/y values of graph input_values = [1, 2, 3, 4, 5] squares = [1, 4, 9, 16, 25] #Uses one of the style available from plt.style.available #plt.style.use('seaborn') #plt.style.use('fivethirtyeight') plt.style.use('Solarize_Light2') #Common matplotlib convention #This function generates 1 or more plots in the same figure. #It returns a tuple containing a figure and axes object(s) #figure represents the entire figure or collection of plots #ax represents a single plot in the figure and is the variable you use most of the time fig, ax = plt.subplots() #use plot() to plot the data passed in to the axes ax.plot(input_values, squares, linewidth=3) #You can adjust visualization of all features in matplotlib #Set chart title and label axes. ax.set_title("Square Numbers", fontsize=24) ax.set_xlabel("Value", fontsize=14) ax.set_ylabel("Square of Value", fontsize=14) #Set size of tick labels. ax.tick_params(axis='both', labelsize=14) #.show() opens matplotlibs viewer and displays the plot plt.show()
#!/usr/bin/python3 def uppercase(str): print("{}".format(str.upper()))
#Diocelina sierra martinez #22/11/16 #ejercicio 3 area=input("encontrar el radio:") pi=3.1416 r=4 resultado=pi*r**2 print "el area del circulo es"resultado #el volumen de la esfera esfera=input("encontrar el volumen:") formula=4/3*pi*r**3 print "el volumen de la esfera es"formula
#Diocelina Sierra Martinez #01/112/16 import math as r def cos(ang): return r.cos(r.radians(ang)) def sin(ang): return r.sin(r.radians(ang)) def acos(ang): return r.acos(r.radians(acos)) a1=float(input ("Introduzca latitud: ")) b1=float(input ("Introduzca longitud: ")) a2=float(input ("Introduzca latitud: ")) b2=float(input ("Introduzca longitud: ")) def distancia(x1,y1,x2,y2): a=6371.01*r.acos(r.sin(x1)*r.sin(x2)+r.cos(x1)*r.cos(x2)*r.cos(y1-y2)) print a distancia(a1,b2,a1,b2)
def grid_traverse(x=0, y=0, min_sum=0): global N, grid, result if x == N-1 and y == N-1: min_sum += grid[y][x] result = min(result, min_sum) return if x < N and y < N: min_sum += grid[y][x] grid_traverse(x+1, y, min_sum) grid_traverse(x, y+1, min_sum) else: return for i in range(int(input())): N = int(input()) grid = [list(map(int, input().split())) for _ in range(N)] print(grid) result = 5000 grid_traverse() print(f'#{i+1} {result}')
def is_correct(u): stack = [] if u[0] == ')': return False for br in u: if br == ')': if not stack: return False else: stack.pop() else: stack.append(br) if not stack: return True else: return False def change_correct(v): left_cnt, right_cnt = 0, 0 if not v: return "" for idx, br in enumerate(v): if br == '(': left_cnt += 1 else: right_cnt += 1 if left_cnt == right_cnt: slice_idx = idx + 1 break u = v[:slice_idx] v = v[slice_idx:] if is_correct(u): return u + change_correct(v) else: ret = '(' + change_correct(v) + ')' u_removed = list(u[1:len(u) - 1]) for idx, br in enumerate(u_removed): if br == '(': u_removed[idx] = ')' else: u_removed[idx] = '(' ret += ''.join(u_removed) return ret def solution(p): answer = '' return change_correct(p)
from collections import deque def solution(begin, target, words): if target not in words: return 0 change_dic = {} si_cnt = 0 for word1 in words + [begin]: for word2 in words: for i in range(len(word1)): if word1[i] == word2[i]: si_cnt += 1 if si_cnt == len(word1) - 1: change_dic[word1] = change_dic.get(word1, []) + [word2] si_cnt = 0 # print(change_dic) queue = deque([[begin, 0]]) visited = set() while queue: front, degree = queue.popleft() degree += 1 for w in change_dic[front]: if w == target: return degree elif w not in visited and degree < len(words): visited.add(w) queue.append([w, degree]) return 0
def binary_search(target, l, r, num_list, flag): m = (l + r) // 2 if num_list[m] == target: return m+1 if l > r: return False if target < num_list[m]: if flag == 'R': flag = 'L' idx = binary_search(target, l, m - 1, num_list, flag) else: return False else: if flag == 'L': flag = 'R' idx = binary_search(target, m + 1, r, num_list, flag) else: return False return idx for t in range(1, int(input())+1): AN, BN = map(int, input().split()) A = sorted(list(map(int, input().split()))) B = list(map(int, input().split())) cnt = 0 for b in B: if b < A[(0 + len(B)-1) // 2]: first_f = 'R' else: first_f = 'L' if binary_search(b, 0, len(A)-1, A, first_f): cnt += 1 print(f'#{t} {cnt}')
#Write your code below this line 👇 #Hint: Remember to import the random module first. 🎲 import random random_coinflip = random.randint(0,1) if random_coinflip == 0: print("Tails") else: print("Heads")
import time starttime = time.time() y = 1 sum = 0 for i in range(1, 101): y *= i print(y) numbers = str(y) for i in range(0, len(numbers)): sum += int(numbers[i:i + 1]) print(sum) print('Time:', time.time() - starttime)
import time from eulerfunctions import isprime starttime = time.time() x = 2 count = 0 while count < 10001: if isprime(x): count += 1 x += 1 print('Prime #', count, ' - ', x - 1) print('Time: ', time.time() - starttime)
import time import math from eulerfunctions import isprime starttime = time.time() sum = 0 for i in range(1, 2000001): if isprime(i): sum += i print('Answer :', sum) print('Time :', time.time() - starttime)
i = 1 foo = 0 while i < 1000: if i % 3 == 0 or i % 5 == 0: foo += 1 i += 1 print(foo)
import math from fractions import Fraction # x is the value of d in x^2-dy^2=1, and y is the how many times to recurse through the values. # it will output a tuple of num,dom. Increase the value of y until num=x and dom=y are valid answers. def pell(x, y): xsqr = math.sqrt(x) if int(xsqr) == xsqr: return 0 olist = [(0, 1, math.floor(xsqr))] i = 0 for foo in range(y): i += 1 m = int(olist[i - 1][1] * olist[i - 1][2] - olist[i - 1][0]) d = int((x - m ** 2) / olist[i - 1][1]) a = math.floor((olist[0][2] + m) / d) olist.append((m, d, a)) elist = [i[2] for i in olist] runsum = Fraction(0) for i in range(len(elist) - 1, -1, -1): if i == len(elist) - 1: c = elist[i] else: c = elist[i] + (1 / runsum) runsum = Fraction(c) return runsum.numerator, runsum.denominator high = 0 highnum = 0 for d in range(1, 1001): x = math.sqrt(d) if int(x) == x: continue i = 0 while True: foo = pell(d, i) if (foo[0] ** 2 - d * foo[1] ** 2) == 1: print(d, ':', foo[0]) if foo[0] > high: high = foo[0] highnum = d break else: i += 1 print('High d is', highnum, 'with a x of', high)
class Solution: def selfDividingNumbers(self, left: int, right: int) -> List[int]: self_div_nums = list() while not left > right: isSDN = True for x in str(left): if int(x) == 0: isSDN = False break if left % int(x) != 0: isSDN = False break if isSDN == True: self_div_nums.append(left) left += 1 return self_div_nums
class Solution: def setZeroes(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ x_index = set() y_index = set() for x in range(0, len(matrix)): for y in range(0, len(matrix[x])): if matrix[x][y] == 0: x_index.add(x) y_index.add(y) for x in x_index: matrix[x] = [0] * len(matrix[x]) for y in y_index: for i in range(0, len(matrix)): matrix[i][y] = 0
class Frontier(): def __init__(self): self.frontier = [] def newFrontier(self,state): self.frontier.append(state) def giveFrontier(self): return self.frontier[len(self.frontier)-1] class TicTacToe(): def __init__(self,initialturn,difficulty): self.initialturn = bool(initialturn) self.findDifficultyLevel(difficulty) self.sol = dict() self.frontier = Frontier() self.initialstate = [[' ','#',' ','#',' '],['#','#','#','#','#'],[' ','#',' ','#',' '],['#','#','#','#','#'],[' ','#',' ','#',' ']] self.height = len(self.initialstate) self.width = max(len(value) for value in self.initialstate) def findDifficultyLevel(self,difficulty): if difficulty == -1: self.dificultylevel = 1 return self.dificultylevel elif difficulty == 0: self.dificultylevel = 3 return self.dificultylevel elif difficulty == 1: self.dificultylevel = 7 return self.dificultylevel def printboard(self,state): for i in range(self.height): for j in range(self.width): try: if state[i][j] == '#': if i%2 != 0: print('-',end='') else: print('|',end='') else: print(state[i][j], end='') except IndexError: print(" ",end='') print() print() def player(self,state): countx = 0 counto = 0 for i in range(self.height): for j in range(self.width): if state[i][j] == 'X': countx +=1 elif state[i][j] == 'O': counto+=1 if countx > counto: return 0 elif countx == counto: if self.initialturn == False: return 0 else: return 1 else: return 1 def actions(self,state): actions = [] for i in range(self.height): for j in range(self.width): if state[i][j] == ' ': actions.append((i,j)) return actions def result(self,state,action): if self.player(state) == 0: state[action[0]][action[1]] = "O" elif self.player(state) == 1: state[action[0]][action[1]] = 'X' return state def terminal(self,state): # Checking for the row for i in range(self.height): countx = 0 counto = 0 for j in range(self.width): if state[i][j] == 'X': countx += 1 elif state[i][j] == 'O': counto += 1 if countx == 3 or counto == 3: return True # Checking for the column for i in range(self.height): countx = 0 counto = 0 for j in range(self.width): if state[j][i] == "X": countx += 1 elif state[j][i] == "O": counto += 1 if countx == 3 or counto == 3: return True # checking for top left to bottom right if (state[0][0] == 'X' and state[2][2] == 'X' and state[4][4] == 'X') or (state[0][0] == 'O' and state[2][2] == 'O' and state[4][4] == 'O'): return True # checking for top right to bottom left daigonal if (state[4][0] == 'X' and state[2][2] == 'X' and state[0][4] == 'X') or (state[4][0] == 'O' and state[2][2] == 'O' and state[0][4] == 'O'): return True # checking that all the feild are filled or not countspace = 0 for i in range(self.height): for j in range(self.width): if state[i][j] == ' ': countspace += 1 if countspace == 0: return True return False def utility(self,state): # Checking for the row for i in range(self.height): countx = 0 counto = 0 for j in range(self.width): if state[i][j] == 'X': countx += 1 elif state[i][j] == 'O': counto += 1 if countx == 3: return 1 elif counto == 3: return -1 # Checking for the column for i in range(self.height): countx = 0 counto = 0 for j in range(self.width): if state[j][i] == "X": countx += 1 elif state[j][i] == "O": counto += 1 if countx == 3: return 1 elif counto == 3: return -1 # checking for top left to bottom right if state[0][0] == 'X' and state[2][2] == 'X' and state[4][4] == 'X': return 1 elif state[0][0] == 'O' and state[2][2] == 'O' and state[4][4] == 'O': return -1 # checking for top right to bottom left daigonal if state[4][0] == 'X' and state[2][2] == 'X' and state[0][4] == 'X': return 1 elif state[4][0] == 'O' and state[2][2] == 'O' and state[0][4] == 'O': return -1 return 0 def playerturn(self,state): userinput = input('Your turn :- ') useraction = (int(userinput[0]),int(userinput[2])) if not isinstance(useraction,tuple): print('Please provide valid input as row,column') else: return self.result(state,useraction) def aiturn(self): state = self.frontier.giveFrontier().copy() minvalue = 10000 bestaction = None for action in self.actions(state): board = self.result(self.frontier.giveFrontier(),action) value = self.minimax(board,True,0) board[action[0]][action[1]] = " " if value < minvalue: minvalue = value bestaction = action self.frontier.newFrontier(self.result(self.frontier.giveFrontier(),bestaction)) def minimax(self,board,ismax,depth): if depth == self.dificultylevel: return self.utility(board) if self.terminal(board): return self.utility(board) if ismax: v = -10000 for action in self.actions(board): v = max(v,self.minimax(self.result(board,action),False,depth=depth+1)) board[action[0]][action[1]] = ' ' return v elif not ismax: v = 10000 for action in self.actions(board): v = min(v,self.minimax(self.result(board,action),True,depth=depth+1)) board[action[0]][action[1]] = ' ' return v def startgame(self): self.frontier.newFrontier(self.initialstate) while self.terminal(self.frontier.giveFrontier()) == False: if self.player(self.frontier.giveFrontier()) == 1: self.frontier.newFrontier(self.playerturn(self.frontier.giveFrontier())) self.printboard(self.frontier.giveFrontier()) elif self.player(self.frontier.giveFrontier()) == 0: self.aiturn() self.printboard(self.frontier.giveFrontier()) print() print('Welcome to the TicTacToe Game ') print() print("You are going to be (X) player and AI going to be (O) player ") print() print("You have to select the positon where you want to play by providing row and column") print("row start from 0,2,4 and column always be either 0,2,4") print() print('please select difficulty level :- -1 for easy , 0 for normal and 1 for hard ') while True: difficulty = int(input("Difficulty Level :- ")) if difficulty == -1 or difficulty == 0 or difficulty == 1: break else: print() print('Please give valid input') print() print('please select turn :- press 1 for your initial turn and press 0 for ai initial turn') initialturn = int(input("Ans :- ")) tictactoe = TicTacToe(initialturn,difficulty) tictactoe.startgame()