text
stringlengths
37
1.41M
print "I will now count my chickens:" # print Hens count as summ of 25 and ratio for 30 to 6 print "Hens", 25.0 + 30.0 / 6.0 # print Roosters cont as substraction of 100 and (product 25 * 3) by module 4 print "Roosters", 100.0 - 25.0 * 3 % 4 print "Now I will count the eggs:" # print formula result print 3.0 + 2.0 + 1.0 - 5.0 + 4 % 2 - 1.0 / 4.0 + 6.0 print "Is it true that 3 + 2 < 5 - 7?" # print comparison result print (3.0 + 2.0) < (5.0 - 7.0) # print sum print "What is 3 + 2?", 3.0 + 2.0 # print substraction print "What is 5 - 7?", 5.0 - 7.0 print "Oh, that's why it's False." print "How about some more." # print values with different sign comparison results print "Is it greater?", 5.0 > -2.0 print "Is it greater or equal?", 5.0 >= -.02 print "Is it less or equal?", 5.0 <= -2.0
# assign to cars integer value cars = 100 # assign to space in the car floating point value space_in_a_car = 4.0 # assign to drivers integer value drivers = 30 # assign to passangers integer value passengers = 90 # evalute substraction and assign its result to cars_not_driven cars_not_driven = cars - drivers # assign drivers value to cars_driven variable cars_driven = drivers # evalute entire capacity and assign it as a floating point value to # carpool_capacity carpool_capacity = cars_driven * space_in_a_car # evalute passengers to cars_driven ratio and assign it to # average_passengers_per_car average_passengers_per_car = passengers / cars_driven print "There are", cars, "cars available." print "There are only", drivers, "drivers available." print "There will be", cars_not_driven, "empty cars today." print "We can transport", carpool_capacity, "people today." print "We have", passengers, "to carpool today." print "We need to put about", average_passengers_per_car, "in each car."
def sort_nd(l: list, d: int): ''' N-dimentional merge-sort l: input list n: dimention to sort by ''' n = len(l) if n==1: return l else: mid = n//2 left = sort_nd(l[ :mid], d) right = sort_nd(l[mid: ], d) i, j = 0, 0 result = [] while i < len(left) and j < len(right): if left[i][d] < right[j][d]: result.append(left[i]) i += 1 else: result.append(right[j]) j+=1 result += left[i:] result += right[j:] return result def closest_pair(P: list): ''' Take a list of points as an input Use divide&conquer to find two closest points Complexity: O(nlogn) ''' # Sort points by x-coordinate Px = sort_nd(P, 0) Py = sort_nd(P, 1) # Invoke a recursive divide&conquer algorithm for the closest pair # Return only the pair of points, since distance is not computed here return _closest_pair(Px, Py)[1] def _closest_pair(Px, Py): ''' Takes two lists of SORTED by X and by Y corrdinates points and find two closest points by divide&conquer approach ''' n = len(Px) if n < 2: return [float("inf"), (None, None)] else: Lx = Px[ :n//2] # Left half of Px Rx = Px[n//2: ] # Right half of Px median = Lx[-1][0] # the most extreme x coordinate in our left half # Instead of resorting Lx and Rx by Y-coordinate, we can save some # time and achieve the same result by simply taking an already sorted # list P by Y-coordinate (Py) and subsampling those poins whose # X-coordinates lie on the left (Ly) or on the right (Ry) from the median Ly = [p for p in Py if p[0] <= median] Ry = [p for p in Py if p[0] > median] # Recursively invoke _closest_pair for the Left and Right halves of P [delta1, pair1] = _closest_pair(Lx, Ly) [delta2, pair2] = _closest_pair(Rx, Ry) # If min distance is in any half pair # Initialize the starting point [delta, pair_min] = [delta1, pair1] if delta < delta1: [delta, pair_min] = [delta2, pair2] # If min distance is in split pair # Using list comprehensions, find an Sy subset of sorted by # Y-coordinate points that are no more than delta away from # the median X-coordinate Sy = [p for p in Py if p[0]>median-delta and p[0]<median+delta] n_Sy = len(Sy) # Start walking up through Sy for i, p1_Sy in enumerate(Sy[ :-1]): # For every y in Sy we only have to consider 7 closest points for j, p2_Sy in enumerate(Sy[i+1 : i+8 if i+8<n_Sy else n_Sy]): if p2_Sy[1]-p1_Sy[1] < delta: # If we found a closer pair, update the result [delta, pair_min] = [p2_Sy[1]-p1_Sy[1], [p1_Sy, p2_Sy]] '''Alternative for i in range(len(Sy[ :-1])): k=i+1 while k<n_Sy and Sy[k][1]-Sy[i][1]<d_min: if Sy[k][1]-Sy[i][1]<closest: [closest, closest_pair] = [Sy[k][1]-Sy[i][1], [Sy[k],Sy[i]]] k += 1 ''' return [delta, pair_min] import math def closest_pair_brute(P: list): ''' Take a list of points as an input Use brute force method to calculate a distance between every pair of points in the list, exclusing self-pairs Complexity: O(n^2) ''' if len(P)<2: # If there are less then two points, the distance is infinity return float("inf"), (None, None) else: # Find starting distance between p1 and p2 min_dist = math.sqrt((P[1][0]-P[0][0])**2 + (P[1][1]-P[0][1])**2) # Define starting pair of points that has min distance min_pair = [P[0], P[1]] # Iterate through all the points in a triangular manner for i, p1 in enumerate(P[ :-1]): for j, p2 in enumerate(P[i+1: ]): # For each pair calculate distance d = math.sqrt((p2[0]-p1[0])**2 + (p2[1]-p1[1])**2) # Check whether this distance is smaller than min distance if d < min_dist: # If we found a smaller distance # Update min distance and a pair of corresponding points min_dist = d min_pair = [p1, p2] # Return the result as a list of [min dist and min pair of points] return [min_dist, min_pair] L=[(0,0),(7,6),(2,20),(12,5),(16,16),(5,8),\ (19,7),(14,22),(8,19),(7,29),(10,11),(1,13),(11,1)] print(closest_pair(L)) print(closest_pair_brute(L))
# tuple_stocks.py import datetime from collections import namedtuple def middle(stock, date): symbol, current, high, low = stock return (((high + low) / 2), date) def main(): # stock = "FB", 177.46, 178.67, 175.79 # stock2 = ("FB", 177.46, 178.67, 175.79) # print(stock) # print(stock2) # (mid_value, date) = middle(("FB", 177.46, 178.67, 175.79), # datetime.date(2018, 8, 27)) # print('mid_value:', mid_value) # print('date:', date) # a_tuple = (stock, stock2) # print('a_tuple:', a_tuple) # stock = "FB", 177.46, 0.67, 175.79 # print('a_tuple:', a_tuple) # stock = "FB", 75.00, 75.03, 74.90 # high = stock[2] # print(high) # print(stock[1:3]) Stock = namedtuple("Stock", ["symbol", "current", "high", "low"]) stock = Stock("FB", 177.46, high=178.67, low=175.79) print(stock.high) symbol, current, high, low = stock print(current) # stock.current = 74.98 if __name__ == '__main__': main()
# using_dictionaries.py stocks = { "GOOG": (1235.20, 1242.54, 1231.06), "MSFT": (110.41, 110.45, 109.84), } class AnObject: def __init__(self, avalue): self.avalue = avalue def main(): # print(stocks["GOOG"]) # # print(stocks["RIM"]) # print(stocks.get("RIM")) # print(stocks.get("RIM", "NOT FOUND")) # print(stocks.setdefault("GOOG", "INVALID")) # print(stocks["GOOG"]) # print(stocks.setdefault("BBRY", (10.87, 10.76, 10.90))) # print(stocks["BBRY"]) # for stock, values in stocks.items(): # print(f"{stock} last value is {values[0]}") # stocks["GOOG"] = (1245.21, 1252.64, 1245.18) # print(stocks["GOOG"]) # stocks["TWIT"] = (245.21, 252.64, 245.18) # print(stocks["TWIT"]) random_keys = {} random_keys["astring"] = "somestring" random_keys[5] = "aninteger" random_keys[25.2] = "floats work too" random_keys[("abc", 123)] = "so do tuples" my_object = AnObject(14) random_keys[my_object] = "We can even store objects" my_object.avalue = 12 try: random_keys[[1,2,3]] = "we can't store lists though" except: print("unable to store list\n") for key, value in random_keys.items(): print("{} has value {}".format(key, value)) print(my_object.__dict__) if __name__ == '__main__': main()
import numpy as np def distance(v1, v2, d_type='d1'): # check same shape assert v1.shape == v2.shape, "shape of two vectors need to be same!" if d_type == 'd1': return np.sum(np.absolute(v1 - v2)) elif d_type == 'd2': return np.sum((v1 - v2) ** 2) elif d_type == 'd2-norm': return 2 - 2 * np.dot(v1, v2) elif d_type == 'cosine': return np.dot(v1, v2)/(np.linalg.norm(v1)*np.linalg.norm(v2)) elif d_type == 'square': return np.sum((v1 - v2) ** 2)
"""SQLAlchemy models for Access Academy""" from flask_bcrypt import Bcrypt from flask_sqlalchemy import SQLAlchemy bcrypt = Bcrypt() db = SQLAlchemy() class User(db.Model): """User of this app""" __tablename__ = 'users' id = db.Column( db.Integer, primary_key=True, ) username = db.Column( db.Text, nullable=False, unique=True, ) email = db.Column( db.Text, nullable=False, unique=True, ) password = db.Column( db.Text, nullable=False, ) first_name = db.Column( db.Text, nullable=False, ) last_name = db.Column( db.Text, nullable=False, ) image_url = db.Column( db.Text, default="/static/images/default-pic.png", ) def __repr__(self): """Create a readable, identifiable representation of user.""" return f"<User #{self.id}: {self.username}, {self.email}>" @classmethod def signup(cls, email, username, password, first_name, last_name, image_url): """Sign up user. Hashes password and adds user to system.""" hashed_pw = bcrypt.generate_password_hash(password).decode('UTF-8') user = User( username=username, password=hashed_pw, first_name=first_name, last_name=last_name, image_url=image_url, email=email, ) db.session.add(user) return user @classmethod def authenticate(cls, username, password): """Find user with `username` and `password`. This is a class method (call it on the class, not an individual user.) It searches for a user whose password hash matches this password and, if it finds such a user, returns that user object. If can't find matching user (or if password is wrong), returns False. """ user = cls.query.filter_by(username=username).first() if user: is_auth = bcrypt.check_password_hash(user.password, password) if is_auth: return user return False class Course(db.Model): """Course that is made up of videos curated by course creator""" __tablename__ = 'courses' id = db.Column( db.Integer, primary_key=True, ) title = db.Column( db.Text, nullable=False, ) description = db.Column( db.Text, ) creator_id = db.Column( db.Integer, db.ForeignKey('users.id', ondelete="cascade"), nullable=False, ) db.UniqueConstraint(title, creator_id) creator = db.relationship('User', backref='courses') videos = db.relationship( 'Video', secondary='videos_courses', backref='courses') videos_courses = db.relationship("VideoCourse", backref="course") def __repr__(self): """Create a readable, identifiable representation of course.""" return f"<Course #{self.id}: {self.title}, {self.creator_id}>" class Video(db.Model): """Video information and data""" __tablename__ = 'videos' id = db.Column( db.Integer, primary_key=True, ) title = db.Column( db.Text, nullable=False, ) description = db.Column( db.Text, ) # yt_video_id comes from YouTube Data API yt_video_id = db.Column( db.Text, nullable=False, ) yt_channel_id = db.Column( db.Text, nullable=False, ) yt_channel_title = db.Column( db.Text, ) thumb_url = db.Column( db.Text, ) videos_courses = db.relationship('VideoCourse', backref='video') class VideoCourse(db.Model): """Join table for videos and courses""" __tablename__ = 'videos_courses' id = db.Column( db.Integer, primary_key=True, ) course_id = db.Column( db.Integer, db.ForeignKey('courses.id', ondelete="cascade"), ) video_id = db.Column( db.Integer, db.ForeignKey('videos.id', ondelete="cascade"), ) video_seq = db.Column( db.Integer, nullable=False, ) db.UniqueConstraint(course_id, video_id, video_seq) db.UniqueConstraint(course_id, video_seq) def connect_db(app): """Connect this database to provided Flask app. You should call this in your Flask app. """ db.app = app db.init_app(app)
import sys import os import array def main(): start = 138241 end = 674034 hold_list = [] for current_passwd in range( start, end, 1 ): if has_duplicates( current_passwd ) and is_ascending( current_passwd ): hold_list.append( current_passwd ) print('Hold List size: {}'.format(len(hold_list))) def has_duplicates( current_passwd ): password_str = str(current_passwd) for i in range( 1, len( password_str) ): if password_str[ i ] == password_str[ i - 1 ]: return True return False def is_ascending( current_passwd ): password_str = str(current_passwd) for i in range( 1, len( password_str) ): if ord(password_str[ i ]) >= ord(password_str[ i - 1 ]): continue else: return False return True if __name__ == '__main__': main()
class Car: tax=0 def __init__(self, price, speed, fuel, mileage): self.price = price self.speed = speed self.fuel = fuel self.mileage = mileage self.tax=.12 if (self.price>10000): self.tax=.15 def displayAll(self): print('Price: ', self.price) print('Speed:', self.speed) print('Fuel: ', self.fuel) print('Mileage: ', self.mileage) print('Tax: ', self.tax) car1=Car(11000,50,'full',50) car1.displayAll() car2=Car(8000,50,'empty',50) car2.displayAll()
""" Name: Timothy McMahon Student number: u5530441 """ import numpy as np import sys def gen_matrix(length, b, epsilon): """ Generates an invertible, quasipositive matrix of dimensions length x length length: int b: int - the branch factor, the number of non-negligable transition probabilities epsilon: double: the small probability of transitioning to any state. This should be close to 0. """ mat = [] for j in range(length): # Initialise the matrix with epsilon entries row = [epsilon]*length # add transition probabilites to b random entries i = 0 while i < b: index = np.random.randint(length) if row[index] == epsilon: # Sample from the interval [epsilon, 1) row[index] = (1-epsilon)*np.random.random_sample() + epsilon i += 1 # Normalise row so that the sum of the entries is 1 row = np.array(row) total = row.sum() for i in range(len(row)): row[i] = row[i]/total mat.append(row) mat = np.array(mat) # Check that the matrix is invertible if np.linalg.cond(mat) < 1/sys.float_info.epsilon: return mat else: return 0 def random_mdp(length, aggregation, num_actions, noise, b, epsilon, gamma): """ Generate a random MDP that is able to be v_aggregated """ v = [] # Generate vector v of length s_phi from uniform distribution (0,100) # repeat the entries according to the aggregation factor # and add a small amount of random noise to each entry for i in range(length): num = 100*np.random.random_sample() # Add in random noise for j in range(aggregation): while True: temp_val = num + 2*noise*np.random.random_sample() - noise if temp_val > 0: break v.append(temp_val) v = np.array(v) # Generate random transition matrices, that are invertible and quasipositive transition_matrices = [] while len(transition_matrices) < num_actions: temp_mat = gen_matrix(length*aggregation, b, epsilon) if type(temp_mat) != int: transition_matrices.append(temp_mat) # Generate the vector of Q-values q_vals = {} i = 0 while len(q_vals) < num_actions: #TODO Add noise back in if it is needed (but it shouldn't be for v aggregation # unless it means the rewards are too similar or something. #noise_vec = 2*noise*np.random.random_sample(length*aggregation) - noise q_vec = np.array(np.random.random_sample(length*aggregation))*v #+ noise_vec # Double check that all values are less than the v-vector values if False not in (q_vec < v): q_vals[i] = q_vec i += 1 # Solve for the reward vectors rewards = [] transition_inverse = np.linalg.inv(transition_matrices[0]) # Solve for the optimal reward matrix/vector r # r = (T^-1 - \gamma I)v* r = np.matmul(transition_inverse - gamma*np.identity(length*aggregation), v) rewards.append(r) # find the rest of the reward vectors # r_a = T^-1(q_a - \gamma T v*) for i in range(1, num_actions): transition_inverse = np.linalg.inv(transition_matrices[i]) r = np.matmul(transition_inverse, q_vals[i] - np.matmul(gamma*transition_matrices[i], v)) rewards.append(r) # Do Value-Iteration and make sure we can learn the proper values #values = [0]*(length*aggregation) #eps = 0.0000000001 #pi = {} #while True: #delta = 0 #for state in range(length*aggregation): #temp_v = values[state] ##calculate the max value functions #val = -500 #for a in range(num_actions): ## get the probabilites and the transitions #temp_val = 0 #for s_prime in range(length*aggregation): #r = rewards[a][s_prime] #temp_val += transition_matrices[a][state][s_prime]*(r + gamma*values[s_prime]) #if temp_val > val: #val = temp_val #pi[state] = a #values[state] = val #delta = max(delta, abs(temp_v - values[state])) #if delta < eps: #break # check that the optimal policy is action 0 #pi_flag = True #for i in pi.keys(): # if pi[i] != 0: # pi_flag = False #print(v) #print(values) #print(pi) # check that the learned values are approximately the actual values #learned_flag = True #if False in np.isclose(v, values, atol=2): # learned_flag = False #if pi_flag and learned_flag: # flag = False #TODO Confirm that i can just use the one transition matrix here. # When doing this entire thing, ensure that the policy is uniform. I.e. that the optimal action # for each of the states that will be aggregated is the same. ( # This should be fine by default. If the optimal action is always the same, then we are fine return v, transition_matrices, q_vals, rewards ### Testing loop for debugging purposes #length = 4 #aggregation = 4 #num_actions = 2 #noise = 5 #b = 4 #epsilon = 0.0001 #gamma = 0.8 #eps = 0.0000000000000000001 #v, transition_matrices, q_vals, rewards = random_mdp(length, aggregation, num_actions, noise, b, epsilon, gamma) ##print(random_mdp(length, aggregation, num_actions, noise, b, epsilon, gamma)) ##print("values:") ##print(v) ##print("T:") ##print(transition_matrices) ##print() ##print(np.linalg.cond(transition_matrices)) ##print() ##print("Q:") ##print(q_vals) ##print("R:") ##print(rewards) ## Initialise the values #values = [0]*(length*aggregation) #pi = {} #while True: #delta = 0 #for state in range(length*aggregation): #temp_v = values[state] ##calculate the max value functions #val = -500 #for a in range(num_actions): ## get the probabilites and the transitions #temp_val = 0 #for s_prime in range(length*aggregation): #r = rewards[a][s_prime] #temp_val += transition_matrices[a][state][s_prime]*(r + gamma*values[s_prime]) #if temp_val > val: #val = temp_val #pi[state] = a #values[state] = val #delta = max(delta, abs(temp_v - values[state])) #if delta < eps: #break #print("values:") #print(v) #print("learned values ") #print(values) #print("Policy") #print(pi) #from scipy.linalg import eig #for a in range(num_actions): ## solve the stationary distribution p_a T_a = p_a (the left eigenvector) #e, vl = eig(transition_matrices[a], left=True, right=False) ## Pull out the eigenvalue that is equal to 1 #index = np.where(np.isclose(np.real(e), 1)) #print(index) ## create the left eigenvector (and cast to real as well) #print(vl[:,index[0][0]].T) #print(np.real(vl[:,index[0][0]].T))
''' drawX function for tic tac toe. drawX(Xturtle, x, y, d, color):drawX(Xtu where Xturtle is the turtle used to draw x - is horizontal coordinate y - is veritcle coordinate d - diameter of the X color is "red", "blue" or "green" ''' import turtle def drawX(Xturtle, x, y, d, color): Xturtle.pencolor(color) Xturtle.fillcolor(color) Xturtle.penup() Xturtle.pensize(10) Xturtle.setposition(x+d, y+d) # set position to half size down. Xturtle.pendown() Xturtle.setposition(x-d, y-d) Xturtle.penup() Xturtle.setposition(x+d, y-d) # set position to half size down. Xturtle.pendown() Xturtle.setposition(x-d, y+d) return
fullname = raw_input("Enter Your Full Name ") firstspace = fullname.find(" ",0) firstname = fullname[0:firstspace] #print("fname "+firstname) secondspace = fullname.find(" ", firstspace+1) middlename = fullname[firstspace+1:secondspace] #print("mname "+middlename) lastname = fullname[secondspace+1:] #print("lname "+lastname) initials = firstname[:1] print("initials "+firstname[:1]+ middlename[:1]+ lastname[:1])
import random option = ['rock', 'paper', 'scissor', 'Rock', 'Paper', 'Scissor'] computer = option[random.randint(0, 2)] # Function for player to play using options def plays(): playerWin = 0 computerWin = 0 ties = 0 player = True while player == True: player = input("\nEnter your choice (Rock - Paper - Scissor): ") if player == computer: print("Computer's Choice: ", computer) print("Tie!") ties += 1 elif player == 'Rock' or player == 'rock': if computer == 'Paper' or computer == 'paper': print("Computer's Choice: ",computer) print("Computer wins!") # R+P=P computerWin += 1 else: print("Computer's Choice: ", computer) print(playerName, "Wins!") # P+R=P playerWin += 1 elif player == 'Paper' or player == 'paper': if computer == 'Scissor' or computer == 'scissor': print("Computer's Choice: ", computer) print("Computer wins!") # P+S=S computerWin += 1 else: print("Computer's Choice: ", computer) print(playerName, "Wins!") # S+P=S playerWin += 1 elif player == 'Scissor' or player == 'scissor': if computer == 'Rock' or computer == 'rock': print("Computer's Choice: ", computer) print("Computer wins!") # S+R=R computerWin += 1 else: print("Computer's Choice: ", computer) print(playerName, "Wins!") # R+S=R playerWin += 1 else: print("Oops! Please enter a valid input") player = True print("\n******************Score********************") print(playerName, "\t\t", "Ties", "\t\t", "Computer") print(playerWin, "\t\t\t", ties, "\t\t\t", computerWin) print("******************************************") ans=input("\nDo you want to continue (y/n)? ") if ans =='n' or ans =='N': break print(" ROCK - PAPER - SCISSOR") print(" ======================") print('''Rules: * Rock + Paper = Paper * Paper + Scissor = Scissor * Scissor + Rock = Rock''') playerName = input("\nPlease enter your Name: ") plays()
''' find_amulet: returns the chest index of the Amulet of Rivest ARGS: magic_map(a,b): magic_map(a,b) returns true if the Amulet is the chest index i where a <= i < b. RETURN: index of chest containing amulet HINT: magic_map(a,a+1) returns true iff the Amulet is in chest a magic_map(1,float('inf')) will always return true ''' def find_amulet(magic_map): #Basically, the problem is about doing a binary search on an infinitely long array. #As we only have a function that returns true if the item is inside a specific range, #we don't have specific lower/upperbounds. Starting from 0, we increase the index by a factor #of 2 to find the upperbound in lg(n) time (index = 1 first, then 2, then 4, then 8, then 16 etc.) #Finally, we do binary search between this upperbound and lowerbound, which is upperbound/2 (or can very well be 0 as it will matter trivially) #PART 1: FINDING THE UPPERBOUND mini = 0 # print magic_map(1599,1600) i = 1 # i is kind of "upperbound" here if magic_map(mini, i): return 0 #if chest is at index 0 else: while not magic_map(mini, i): i = 2*i #increase index by factor of 2 print i #PART 2: BINARY SEARCH upperbound = i #upperbound of binary search lowerbound = i/2 #lowerbound of binary search while lowerbound<upperbound-1: midpoint = (upperbound + lowerbound)//2 if magic_map(lowerbound, midpoint): upperbound=midpoint else: lowerbound = midpoint return lowerbound #the index of the chest!
from collections import deque from heapq import * class Queue(object): # Initialize an empty queue def __init__(self): self.items = deque() # Return the length of this queue def __len__(self): return len(self.items) # Add a new item def push(self, item): self.items.append(item) # Return (and remove) the oldest item def pop(self): return self.items.popleft() class PriorityQueue(object): # Initialize an empty priority queue def __init__(self): self.items = list() self.pops = set() self.length = 0 # Return the length of this priority queue def __len__(self): return self.length # Add a new item with the given priority def push(self, item, priority): heappush(self.items, (priority, item)) self.length += 1 # Change the priority of an existing item def prioritize(self, item, priority): heappush(self.items, (priority, item)) # Return (and remove) the item with the highest (smallest) priority def pop(self): while len(self.items) > 0: (priority, item) = heappop(self.items) if item not in self.pops: self.pops.add(item) self.length -= 1 return item class SearchTree(object): # Initialize a search tree with a root node def __init__(self, root): self.levels = {root: 0} self.parents = dict() self.moves = dict() # Return whether a node appears in this tree def __contains__(self, node): return node in self.levels # Return how deep a node is in this tree def depth(self, node): return self.levels[node] # Add a leaf to this tree (or move an existing one) def connect(self, child, parent, move): self.levels[child] = self.levels[parent] + 1 self.parents[child] = parent self.moves[child] = move # Return instructions for reaching a node in this tree def branch(self, node): moves = dict() while node in self.parents: move = self.moves[node] parent = self.parents[node] moves[parent] = move node = parent return moves
#Name: Lur Bing Huii #Student ID: 6212748 #Subject Code: CSIT110 import csv filePath = "data.csv" # Display Menu and get's user input def menu(): print("1: Display modules average scores") print("2: Display modules top scorer") print("0: Exit") choice = int(input("Enter choice: ")) # Loop till a valid choice is entered if(choice < 0 or choice > 2): print("===============================================") print("Invalid choice, please enter again") print("===============================================") choice = menu() return choice # Calculate and display average scores for all subject def display_modules_average_scores(): csit110sum = 0 csit121sum = 0 csit135sum = 0 csit142sum = 0 count = 0 # Opens the data file with open(filePath) as csvfile: reader = csv.DictReader(csvfile) for row in reader: # Sum up scores csit110sum += (int)(row['CSIT110']) csit121sum += (int)(row['CSIT121']) csit135sum += (int)(row['CSIT135']) csit142sum += (int)(row['CSIT142']) count += 1 # Calculate average for all subjects csit110ave = round(csit110sum/count,2) csit121ave = round(csit121sum/count,2) csit135ave = round(csit135sum/count,2) csit142ave = round(csit142sum/count,2) # Print results print("===============================================") print("Display Modules Average Scores") print("===============================================") print("{0:<8}|{1:^9}|{2:^9}|{3:^9}".format("CSIT110", "CSIT121", "CSIT135", "CSIT142")) print("{0:^8}|{1:^9}|{2:^9}|{3:^9}".format(csit110ave, csit121ave, csit135ave, csit142ave)) print("===============================================") # Prints the all the people with the high score for a certain subject def print_module_top_scorer(subject,score): with open(filePath) as csvfile: reader = csv.DictReader(csvfile) for row in reader: if((int)(row[subject]) == score): print("{0:<8}|{1:>11} | {2:<10}".format(subject, row['first_name'], row['last_name'])) # Find and display the top scorers for all subjects def display_modules_top_scorer(): csit110max = 0 csit121max = 0 csit135max = 0 csit142max = 0 # Opens the data file with open(filePath) as csvfile: reader = csv.DictReader(csvfile) for row in reader: # Finds the highest scores for each subject if((int)(row['CSIT110']) > csit110max): csit110max = (int)(row['CSIT110']) if((int)(row['CSIT121']) > csit121max): csit121max = (int)(row['CSIT121']) if((int)(row['CSIT135']) > csit135max): csit135max = (int)(row['CSIT135']) if((int)(row['CSIT142']) > csit142max): csit142max = (int)(row['CSIT142']) # Prints results print("===============================================") print("Display modules top scorer") print("===============================================") print("{0:<8}|{1:^12}|{2:^11}".format("Module", "First Name", "Last Name")) print_module_top_scorer("CSIT110",csit110max) print_module_top_scorer("CSIT121",csit121max) print_module_top_scorer("CSIT135",csit135max) print_module_top_scorer("CSIT142",csit142max) print("===============================================") # Main program start print("===============================================") print("Welcome to Students' Result System") print("===============================================") #get user choice choice = menu() # loop till user exits program while(not (choice == 0)): if(choice == 1): display_modules_average_scores() elif(choice == 2): display_modules_top_scorer() choice = menu() print("===============================================") print("Thank you for using Students' Result System") print("===============================================")
while True: userName = input("Username: ") password = input("Password: ") if userName == 'halil' and password == 'halil': print("correct username and password") break else: print("wrong username and password") break
import random def menu(): choice = input("----------------------------------------\nWelcome To 2Password\n1 - Check Password\n2 - Generate Password\n3 - Quit\n>>> ") while choice != '1' and choice != '2' and choice != '3': choice = input("ERROR\n>>> ") print("--------------------") if choice == '1': password_check() elif choice == '2': final_pass_gen() elif choice == '3': print("\n\n--------------------\nThank you for using 2Password\n--------------------") quit() def end_of_task(): # ---------- Menu/Exit ---------- # now_what = input("\n----------------------------------------\n1 - Exit\n2 - Main Menu\n>>> ") while now_what != '1' and now_what != '2': now_what = input("ERROR\n>>> ") print("--------------------") if now_what == '1': print("\n\n--------------------\nThank you for using 2Password\n--------------------") quit() else: menu() def score_addsub(pword,p_list): # ---------- Variables ---------- #s triplet_in_p = [] digits, symbols, score, letters, bonus = 0, 0, len(pword), 0, 0 upcase, lowcase, number, symbol = False, False, False, False triplets = ["qwe", "wer", "ert", "rty", "tyu", "yui", "uio", "iop","asd", "sdf", "dfg", "fgh", "ghj", "hjk", "jkl","zxc", "xcv", "cvb", "vbn"] # ---------- Adding points for having uppercase/lowercase/numbers/symbols ---------- # for char in p_list: if 65 <= ord(char) <= 90 and not upcase: score += 5 bonus += 1 upcase = True elif 97 <= ord(char) <= 122 and not lowcase: score += 5 bonus += 1 lowcase = True elif char.isdigit() and not number: score += 5 bonus += 1 number = True elif char in p_list and char.isdigit() == False and char.isalpha() == False and not symbol: score += 5 symbol = True if bonus == 4: score += 10 # ---------- Subtracting points for having only symbols/letters/numbers ---------- # for char in p_list: if char.isdigit(): digits += 1 elif char.isalpha(): letters += 1 elif char in p_list and char.isdigit() == False and char.isalpha() == False: symbols += 1 if digits == len(pword): score -= 5 if letters == len(pword): score -= 5 if symbols == len(pword): score -=5 # ---------- Subtracting points for keyboard patterns ---------- # for triplet in triplets: if triplet in pword.lower(): triplet_in_p.append(triplet) score -= (len(triplet_in_p) * 5) return score, pword def password_check(): # ---------- Variables ---------- # allowed_chars = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","0","1","2","3","4","5","6","7","8","9","!","$","%","^","&","*","(",")","_","-","+","="] rejected = [] pword = input("Please enter your password\n>>> ") # ---------- Checking length ---------- # while len(pword) < 8: pword = input("Password must be longer that 8 characters\n>>> ") while len(pword) > 24: pword = input("Password must be shorter that 24 characters\n>>> ") # ---------- Checking for unallowed characters ---------- # p_list = list(pword) for char in p_list: if char not in allowed_chars: rejected.append(char) while len(rejected) > 0: print("Your password contains unallowed chars\nThese are : ",rejected) pword = input(">>> ") p_list = pword.split() rejected = [] for char in p_list: if char not in allowed_chars: rejected.append(char) score, pword = score_addsub(pword,p_list) # ---------- Printing score ---------- # print("Your password : ", pword) if score >= 20: print("Your password score is : ", score, "\nSTRONG") elif score <= 0: print("Your password score is : ", score, "\nWEAK") else: print("Your password score is : ", score, "\nMEDIUM") end_of_task() def password_gen(): gen_p = "" p_length = random.randint(8,12) allowed_chars = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","0","1","2","3","4","5","6","7","8","9","!","$","%","^","&","*","(",")","_","-","+","="] for i in range(p_length): gen_p += random.choice(allowed_chars) p_split = list(gen_p) return p_split, gen_p def final_pass_gen(): p_split, gen_p = password_gen() score, pword = score_addsub(gen_p, p_split) while score < 20: p_split, gen_p = password_gen() score, pword = score_addsub(gen_p, p_split) print("Your password : ", pword,"\nYour password score is : ", score, "\nSTRONG") end_of_task() menu()
import gym from gym import spaces from gym.utils import seeding def cmp(a, b): return float(a > b) - float(a < b) # 1 = Ace, 2-10 = Number cards, Jack/Queen/King = 10 deck = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10] def draw_card(np_random): return int(np_random.choice(deck)) def draw_hand(np_random): return [draw_card(np_random), draw_card(np_random)] def usable_ace(hand): # Does this hand have a usable ace? return 1 in hand and sum(hand) + 10 <= 21 def sum_hand(hand): # Return current hand total if usable_ace(hand): return sum(hand) + 10 return sum(hand) def is_bust(hand): # Is this hand a bust? return sum_hand(hand) > 21 def score(hand): # What is the score of this hand (0 if bust)? return 0 if is_bust(hand) else sum_hand(hand) def is_natural(hand): # Is this hand a natural blackjack? return sorted(hand) == [1, 10] class BlackjackEnv1(gym.Env): """Simple blackjack environment Blackjack is a card game where the goal is to obtain cards that sum to as near as possible to 21 without going over. The player is playing against a dealer with a fixed strategy. Face cards (Jack, Queen, King) have point value 10. Aces can either count as 11 or 1, and it's called 'usable' at 11. This game is played with an infinite deck (or with replacement). The game starts with the player and dealer each receiving two cards. One of the dealer's cards is facedown and the other is visible. The player can request additional cards (action=1, hit) until they decide to stop (action=0, stick) or exceed 21 (bust). If double down is flagged (double_down=True), the player can double their bet (action=2, double) and then will receive exactly one additional card. If the player is dealt a 10 or face card and an Ace, this is called a natural blackjack and if natural is flagged (natural=True), the player immediately wins a payout of 1.5 (reward=1.5) unless the dealer also has a natural Blackjack. If the player busts, they immediately lose (reward=-1). After a stick or double down that does not result in a bust, the dealer draws until their sum is 17 or greater. If the dealer busts, the player wins (reward=1). Rewards are doubled in the double down case. If neither player nor dealer busts, the outcome (win, lose, draw) is decided by whose sum is closer to 21. The reward for winning is +1, drawing is 0, and losing is -1. These are again doubled in the double down case. The observation is a 3-tuple of: the player's current sum, the dealer's one showing card (1-10 where 1 is Ace), and whether or not the player holds a usable Ace (0 or 1). This environment corresponds to the version of the blackjack problem described in Example 5.1 in Reinforcement Learning: An Introduction by Sutton and Barto. http://incompleteideas.net/book/the-book-2nd.html """ def __init__(self, natural=False, double_down=False, dealer_expose=False): if double_down: self.action_space = spaces.Discrete(3) else: self.action_space = spaces.Discrete(2) self.observation_space = spaces.Tuple(( spaces.Discrete(32), spaces.Discrete(11), spaces.Discrete(2))) self.seed() self.natural = natural self.double_down = double_down self.dealer_expose = dealer_expose # Start the first game self.reset() def seed(self, seed=None): self.np_random, seed = seeding.np_random(seed) return [seed] def step(self, action): if self.natural and is_natural(self.player): if is_natural(self.dealer): reward = 0.0 #player and dealer natural Blackjack else: reward = 1.5 #player natural Blackjack done = True return self._get_obs(), reward, done, {} assert self.action_space.contains(action) if action == 2: # double down: bet double and get only 1 card, then compare self.player.append(draw_card(self.np_random)) done = True if is_bust(self.player): reward = -2.0 else: while sum_hand(self.dealer) < 17: self.dealer.append(draw_card(self.np_random)) reward = 2 * cmp(score(self.player), score(self.dealer)) elif action == 1: # hit: add a card to players hand and return self.player.append(draw_card(self.np_random)) if is_bust(self.player): done = True reward = -1.0 else: done = False reward = 0.0 elif action == 0: # stick: play out the dealer's hand, then compare done = True while sum_hand(self.dealer) < 17: self.dealer.append(draw_card(self.np_random)) reward = cmp(score(self.player), score(self.dealer)) return self._get_obs(), reward, done, {} def _get_obs(self): if self.dealer_expose: return (sum_hand(self.player), sum(self.dealer), usable_ace(self.player)) else: return (sum_hand(self.player), self.dealer[0], usable_ace(self.player)) def reset(self): self.dealer = draw_hand(self.np_random) self.player = draw_hand(self.np_random) return self._get_obs()
import tensorflow as tf import google.datalab.ml as ml """ Linear Regression: An analysis on the relationship between 2 variables where one variable is taken to be independent and the other a dependent. y = mx + c The linear regression could be thought as cause and effect, or a lock and key scenario This could be plotted in a form of graph taking X on the X-axis and Y on the Y-axis How is this done practically? We estimate initial values of m & c. Find the error with these values. Feedback error values to get better values of M & C Y = Wx + b """ # Model parameters W = tf.Variable([.3], dtype=tf.float32) b = tf.Variable([-.3], dtype=tf.float32) # Model input and output x = tf.placeholder(tf.float32) linear_model = W * x + b y = tf.placeholder(tf.float32) # loss loss = tf.reduce_sum(tf.square(linear_model - y)) # optimizer optimizer = tf.train.GradientDescentOptimizer(0.01) train = optimizer.minimize(loss) # training data x_train = [1, 2, 3, 4] y_train = [0, -1, -2, -3] # training loop init = tf.global_variables_initializer() with tf.Session() as sess: sess.run(init) for i in range(1000): sess.run(train, {x: x_train, y: y_train}) #Evaluate training accuracy curr_W, curr_b, curr_loss = sess.run([W, b, loss], {x: x_train, y: y_train}) print("W: %s b: %s loss: %s" % (curr_W, curr_b, curr_loss))
import tensorflow as tf import google.datalab.ml as ml """ Tensors: 1. Building a graph 2. Running a graph Tensor could be defined as a central unit of data in tensor flow. A Tensor consists of a set of primitive values shaped into an array of any number of dimensions. Ho do we represent data in tensors? If data is Scalar no bracket will be used. If it is a one dimensional vector one square bracket is used on each end.(ex: [11,2,3]) Case of 2-D vector (matrix), use two square brackets. (eg: [[1,2,3][1,11,123]] N-D vector would have N- brackets. Important characteristics of Tensor. Rank: The number of dimensions in a tensor, define it's Rank. Shape: The number of elements in each dimension defines the Shape. Data Type: The Data Type of tensor, depends on data type of tis elements. """ a = tf.constant(6.5, name='constant_a') b = tf.constant(3.4, name='constant_b') c = tf.constant(3.0, name='constant_c') d = tf.constant(100.2, name='constant_d') add = tf.add(a, b, name='add_ab') substract = tf.subtract(b, c, name="substract_bc") square = tf.square(d, name="square_d") final_sum = tf.add_n([add, substract, square], name="final_sum") with tf.Session() as session: print("a + b: ", session.run(add)) print("b -c: ", session.run(substract)) print("Suare of d: ", session.run(square)) print("Final of d :" + str(session.run(final_sum))) another_sum = tf.add_n([a, b, c, d, square], name="another_sum") print("Another sum ", str(session.run(another_sum))) writer = tf.summary.FileWriter("./SimpleMath", session.graph) writer.close() tensorboard_pid = ml.TensorBoard.start("./SimpleMath") ml.TensorBoard.stop(tensorboard_pid)
import numpy as np import matplotlib.pyplot as plt """ Covariance: Measures how two variables vary in tandem from their means. Measuring covariance: Think of the data sets for the two variables as high dimensional vectors Convert these to vectors of variances from the mean Take the dot product(consine of the angle between them) of the two vectors Divide by the sample size. We know a small covariance, close to 0, means there isn't much correlation between the two variables. And large covariances - that is, far from 0(could be negative for inverse relationships) mean there is a correlation But how large is "large"? That's where correlation comes in! Just divide covariance by the standard deviations of the both variables, and that normalizes things. So a correlation of -1 means a perfect inverse correlation correlation of 0: no correlation correlation of 1: perfect correlation Remember: correlation does not imply causation. Only a controlled, randomied experiment can give you insights on causation. Use correlation to decide what experiments to conduct """ def de_mean(x): xmean = np.mean(x) return [xi -xmean for xi in x] def covariance(x, y): n = len(x) return np.dot(de_mean(x), de_mean(y)) /(n - 1) def case1(): pageSpeeds = np.random.normal(3.0, 1.0, 1000) purchaseAmount = np.random.normal(50.0, 10.0, 1000) plt.scatter(pageSpeeds, purchaseAmount) plt.show() cov = covariance(pageSpeeds, purchaseAmount) print(cov) def case2(): pageSpeeds = np.random.normal(3.0, 1.0, 1000) purchaseAmount = np.random.normal(50.0, 10.0, 1000) /pageSpeeds plt.scatter(pageSpeeds, purchaseAmount) plt.show() cov = covariance(pageSpeeds, purchaseAmount) print(cov) def correlation(x, y): std_devx = x.std() std_devy = y.std() return covariance(x, y) / std_devx / std_devy def case3(): pageSpeeds = np.random.normal(3.0, 1.0, 1000) purchaseAmount = np.random.normal(50.0, 10.0, 1000) / pageSpeeds plt.scatter(pageSpeeds, purchaseAmount) plt.show() cov = correlation(pageSpeeds, purchaseAmount) print(cov) def case4(): pageSpeeds = np.random.normal(3.0, 1.0, 1000) purchaseAmount = np.random.normal(50.0, 10.0, 1000) / pageSpeeds cor = np.corrcoef(pageSpeeds, purchaseAmount) print(cor) def case5(): pageSpeeds = np.random.normal(3.0, 1.0, 1000) purchaseAmount = 100 - pageSpeeds * 3 plt.scatter(pageSpeeds, purchaseAmount) plt.show() cor = correlation(pageSpeeds, purchaseAmount) print(cor) if __name__ == '__main__': case1() case2() case3() case4() case5()
# def isPhoneNumber(text): # if len(text) != 12: # return False # for i in range(0, 3): # if not text[i].isdecimal(): # return False # if text[3] != '-': # return False # for i in range(4, 7): # if not text[i].isdecimal(): # return False # if text[7] != '-': # return False # for i in range(8, 12): # if not text[i].isdecimal(): # return False # return True # # # # print('Is 415-555-4242 a phone number?') # # print(isPhoneNumber('415-555-4242')) # # print('Is Moshi moshi a phone number?') # # print(isPhoneNumber('Moshi moshi')) # # message = '''Call me at 415-555-1011 tomorrow. 415-555-9999 is # my office.''' # for i in range(len(message)): # chunk = message[i:i+12] # if isPhoneNumber(chunk): # print('Phone number found: ' + chunk) # print('Done') # # import re # # phoneNumRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d') # mo = phoneNumRegex.search('My number is 415-555-4242') # # print('Phone number found: ' + mo.group()) # # import re # phoneNumRegex = re.compile(r'(\d\d\d)-(\d\d\d-\d\d\d\d)') # mo = phoneNumRegex.search('My number is 415-555-4242.') # # # # print(mo.group(1)) # # print(mo.group(2)) # # print(mo.group(0)) # # print(mo.group()) # # # print(mo.groups()) # # areaCode, mainNumber = mo.groups() # print(areaCode) # print(mainNumber) # # import re # # phoneNumRegex = re.compile(r'(\(\d\d\d\)) (\d\d\d-\d\d\d\d)') # mo = phoneNumRegex.search('My phone number is (415) 555-4242.') # print(mo.group(1)) # print(mo.group(2)) # # import re # # # # re.compile(r'(\(Parenthesis\)') # # # heroRegex = re.compile(r'Batman|Tina Fey') # mo1 = heroRegex.search('Batman and Tina Fey') # # print(mo1.group()) # # mo2 = heroRegex.search('Tina Fey and Batman') # print(mo2.group()) >>>phoneRegex = re.compile(r'(\d\d\d-)?\d\d\d-\d\d\d\d') >>>mo1 = phoneRegex.search('My number is 415-555-4242') mo1.group() '415-555-4242' >>> mo2 = phoneRegex.search('My number is 555-4242') >>> mo2.group() '555-4242'
#! /usr/bin/env python3 # -*- coding: utf-8 -*- '''Lecture 02, Exercise 08 Run dir(random). Find a function in random that you can use to return a random item from your grocery list. Remember you can use help() to find out what different functions do! ''' import random shopping_list = {'milk':9.42, 'eggs':5.67, 'bread':3.25, 'apples':13.40, 'tea':7.50} print(dir(random)) print(random.choice(list(shopping_list.keys())))
#! /usr/bin/env python3 # -*- coding: utf-8 -*- '''Lecture 03, Exercise 04 Write an in_grocery_list function that takes in a grocery_item print a message depending on whether grocery_item is in your grocery list. ''' def in_grocery_list(grocery_item): shopping_list = ['milk', 'eggs', 'bread', 'apples', 'tea'] if grocery_item in shopping_list: print('That item is in the shopping list') else: print('That item is not in the shopping list') in_grocery_list('milk') in_grocery_list('sugar')
#! /usr/bin/env python3 # -*- coding: utf-8 -*- ''' Lecture 02, Exercise 24 Write a function called 'Volume2' which calculates the box volume, assuming the height is 1, if not given. ''' def volume2(width, length, height=1): return(width * length * height) print(volume2(2, 5))
#! /usr/bin/env python3 # -*- coding: utf-8 -*- '''Lecture 03, Exercise 06 Challenge: Re-write the you_won function to randomly choose a number from your price list and print an appropriate messsage depending on whether you won (the number was greater than 10) or not. Also include the amount of change you will be receiving in your message. (Recall you are winning the amount change that you would have owed...) ''' import random def you_won(price_list): random_number = price_list[random.randint(0, len(price_list) - 1)] print(random_number) if random_number > 10: print('You have won $' + str(round(abs(10 - random_number),2))) else: print('You lost') price_list = [9.42, 5.67, 3.25, 13.40, 7.50] you_won(price_list)
#! /usr/bin/env python3 # -*- coding: utf-8 -*- ''' Lecture 02, Exercise 28 Make a function shout(word) that accepts a string and returns that string in capital letters with an exclaimation mark. ''' def shout(word): return(word.upper() + '!') print(shout('bananas'))
#! /usr/bin/env python3 # -*- coding: utf-8 -*- '''Lecture 02, Exercise 12 You may have noticed that your all_the_snacks function prints all your snacks squished together. Rewrite all_the_snacks so that it takes an additional argument spacer. Use + to combine your snack and spacer before multiplying. Test your function with different inputs. What happens if you use strings for both snack and spacer? Both numbers? A string and integer? Is it what you expected? ''' def all_the_snacks(snack, spacer): return ((snack + spacer) * 100) shopping_list = {'milk':9.42, 'eggs':5.67, 'bread':3.25, 'apples':13.40, 'tea':7.50} for item in shopping_list: print(all_the_snacks(item, ', ')) print(all_the_snacks('hello', ' ')) #print(all_the_snacks(5,3)) #print(all_the_snacks('hello', 5)) #print(all_the_snacks(5, 'hello'))
#! /usr/bin/env python3 # -*- coding: utf-8 -*- '''Lecture 02, Exercise 18 Try running all_the_snacks with your favourite snack and the spacer '! ' and no additional inputs. How would you run it while inputting your favourite snack and 42 for num while keeping the default spacer? Can you use this method to enter spacer and num in reverse order? ''' def all_the_snacks(snack, spacer=', ', num=100): return ((snack + spacer) * num) snack = 'coffee' print(all_the_snacks(snack, '! ')) print(all_the_snacks(snack, num=42)) print(all_the_snacks(snack, num=10, spacer='...'))
#! /usr/bin/env python3 # -*- coding: utf-8 -*- '''Lecture 05, Exercise 03 Copy the sonnet from https://urn.nsa.ic.gov/t/tx6qm and paste into sonnet.txt. Write the counts dictionary to a file, one key:value per line. ''' def word_count_file(input_filename, output_filename): input_file = open(input_filename, 'r') output_file = open(output_filename, 'w') count = {} for line in input_file: for word in line.split(): word = word.lower() if word in count: count[word] += 1 else: count[word] = 1 for key, value in count.items(): output_file.write(key + ':' + str(value) + '\n') input_file.close() output_file.close() word_count_file('sonnet.txt', 'sonnet_dict.txt')
import secrets options = ['paper', 'rock', 'scissors'] computer = secrets.choice(options) while True: player = input("player: pick rock, paper or scissors ") if player == "exit": print("Thanks for playing friend! see you later.") break if player == computer: print("it's a draw!") elif player == "paper" and computer == "rock": print("player1 winsss!") print("computer picked " + computer) print("If you want to quit, type 'exit' ") elif player == "rock" and computer == "scissors": print("player1 winsss!") print("computer picked " + computer) print("If you want to quit, type 'exit' ") elif player == "scissors" and computer == "paper": print("player1 winsss!") print("computer picked " + computer) print("If you want to quit, type 'exit' ") else: print("computer winsss!") print("computer picked " + computer) print("If you want to quit, type 'exit'") import random options = ['paper', 'rock', 'scissors'] computer = random.choice(options)
class GRAPH: """docstring for GRAPH""" def __init__(self, nodes): self.nodes=nodes self.graph=[[0]*nodes for i in range (nodes)] self.visited=[0]*nodes def show(self): print self.graph def add_edge(self, i, j): self.graph[i][j]=1 self.graph[j][i]=1 def bfs(self,s): queue=[s] self.visited[s]=1 while len(queue)!=0: x=queue.pop(0) print(x) for i in range(0,self.nodes): if self.graph[x][i]==1 and self.visited[i]==0: queue.append(i) self.visited[i]=1 n=int(input("Enter the number of Nodes : ")) g=GRAPH(n) e=int(input("Enter the no of edges : ")) print("Enter the edges (u v)") for i in range(0,e): u,v=map(int, raw_input().split()) g.add_edge(u,v) s=int(input("Enter the source node :")) g.bfs(s)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Aug 12 09:08:24 2018 @author: apb """ """ print all the operations were performed element wise. """ import numpy as np a=np.array([[2,4,6],[4,3,7]],dtype=np.float) b=np.array([[5,4,2],[3,5,9]],dtype=np.float) print(a) print(b) print('\nHere goes a-b') print(a-b) print(np.subtract(a,b)) """ its worth noting that the multiplication is not matrix one """ print('\nHere goes a*b') print(a) print(b) print(a*b) print(np.multiply(a,b)) """ print('matrices multiplication') b=b.transpose() print(a.dot(b)) """ print('\nHere goes a/b') print(a) print(b) print(a/b) print('\nHere goes a+b') print(a) print(b) print(a+b) print('\nlet see what it does') print(b) print(1+b) print('\n to see if multi also done element wise') print(b) print(b*.5) print(np.exp(b)) print(np.log(b)) print(np.sqrt(b)) """ element wise comparision """ print('-------------------element wise comparision------------------') c=np.array([[2,4,6],[4,3,7]],dtype=np.float) print(a) print(b) print(c) z=(a.any()==b.any()); print(z) z=(a.all()==b.all()); print(z) """ note any is function () else would retur wrong results""" if a.all==b.all: print('all equal') z=(a.any()==c.any()); print(z) z=(a.all()==c.all()); print(z) if a.all()==c.all(): print('all equal') print(a==b) print(a==c) """ array wise equality""" print(np.array_equal(a,b)) print(a) print('sum(a)') print(sum(a)) print('a.sum()') print(a.sum()) print('a.min()') print(a.min()) print('a.max()') print(a.max()) print(a.mean()) """ playing with array copy stuff""" h=a.view() print(h) print(h[0][1]) print(h[0,1]) print('np.copy(a)') i=np.copy(a) print(i) print('a.copy()') j=a.copy(); print(j) print('lets see some sorting stuff') j=a print(a) a.sort(axis=0) print('a.sort(axis=1)') print(a) a=j a.sort(axis=-1) print('a.sort(axis=0)') print(a) print('a.sort()') a=j a.sort() print(a) print(a)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Aug 10 11:01:02 2018 @author: apb """ books=[] books.append('c++') books.append('java') print(books) books.reverse() print(books) books.insert(2,'new one') print(books) # del any book by index del books[1] print(books) #remove books by name books.remove('new one') print(books) books.append('circus') books.append('alive') books.append('fiction') books.append('java') print(books) del books[-1] print('pop normal: '+books.pop()) # remember last one bigger index print('pop normal: '+books.pop(0)) # remember first one print(books) # lets see how sorting works books.append('circle') books.append('home alone') books.append('harry poter') books.append('win win') books.sort(); # sorted in ascending order print(books) books.sort(reverse=True); # sorted in descending order print(books) # finding the length of no of books print(len(books)) if ('circle' in books): print('still there') if ('cir' in books): print('still there') else: print('book not found')
# car_game.py using pygame and pymunk import random import math import numpy as np import pygame from pygame.color import THECOLORS import pymunk from pymunk.vec2d import Vec2d from pymunk.pygame_util import draw # initial variables to set up the pygame width = 1000 height = 700 # initialize the game and set the screen size pygame.init() screen = pygame.display.set_mode((width, height)) clock = pygame.time.Clock() # we'll use this for time keeping # alpha isn't used so it can be turned off screen.set_alpha(None) # if we show the sensors and redraw the screen, it will slow things down so we can better interpret the game show_sensors = True draw_screen = True # variables that define the action IDs LEFT = 0 RIGHT = 1 TURN_ANGLE = 0.2 # variables that affect the state of the environment STATIC_OBSTACLE_UPDATE = 100 # frame frequency with which the (more) static obstacles should be moved DYNAMIC_OBSTACLE_UPDATE = 5 # frame frequency with which the dynamic obstacles should be moved VELOCITY = 20 SENSOR_SPREAD = 10 # the distance from the start to the end of the sensors SENSOR_GAP = 20 # the gap before the first sensor DYNAMIC_OBSTACLE_RADIUS = 15 class GameState: def __init__(self): self.crashed = False # the flag that will switch on if we come within a unit of an obstacle, triggering recovery # initialize a space and zero out its gravity, we're treating this as a 2d problem self.space = pymunk.Space() self.space.gravity = pymunk.Vec2d(0., 0.) # make a car self.create_car(100, 100, 0.5) # we want to keep a running total of the number of actions we take in a game to evaluate the model self.num_steps = 0 # make walls to enclose the space static = [ pymunk.Segment( self.space.static_body, (0, 1), (0, height), 1), pymunk.Segment( self.space.static_body, (1, height), (width, height), 1), pymunk.Segment( self.space.static_body, (width-1, height), (width-1, 1), 1), pymunk.Segment( self.space.static_body, (1, 1), (width, 1), 1)] for s in static: s.friction = 1 s.group = 1 s.collision_type = 1 s.color = THECOLORS['red'] self.space.add(static) # create pseudo-random obstacles self.static_obstacles = [] self.static_obstacles.append(self.create_static_obstacle(200, 350, 75)) self.static_obstacles.append(self.create_static_obstacle(700, 200, 50)) self.static_obstacles.append(self.create_static_obstacle(600, 600, 35)) # create a dynamic object self.dynamic_obstacles = [] self.dynamic_obstacles.append(self.create_dynamic_obstacle()) self.dynamic_obstacles.append(self.create_dynamic_obstacle()) ####################################################################### ################ FUNCTIONS FOR DEFINING ############################### ################ THE GAME ENVIRONMENT ################################# ####################################################################### # create a car at the starting position xy in the xy plane and give it a starting angle of r for which to face def create_car(self, x, y, r): # give the car some constant power so that it is always in motion inertia = pymunk.moment_for_circle(1, 0, 14, (0, 0)) self.car_body = pymunk.Body(1, inertia) self.car_body.position = x,y self.car_shape = pymunk.Circle(self.car_body, 25) self.car_shape.color = THECOLORS["green"] self.car_shape.elasticity = 1. self.car_body.angle = r driving_direction = Vec2d(1,0).rotated(self.car_body.angle) # apply the driving direction to the car self.car_body.apply_impulse(driving_direction) self.space.add(self.car_body, self.car_shape) # create an object at x,y in the xy plane and give it a radius of r def create_static_obstacle(self, x, y, r): # set up the obstacle c_body = pymunk.Body(pymunk.inf, pymunk.inf) c_shape = pymunk.Circle(c_body, r) c_shape.elasticity = 1. c_body.position = x,y c_shape.color = THECOLORS["blue"] # add it to the environment self.space.add(c_body, c_shape) return c_body # create a dynamic object that will move in the environment and therefore help with overfitting - we'll just used a fixed location since if we make many, they'll move around quickly def create_dynamic_obstacle(self): # we need to give the object some intertia so that it will move inertia = pymunk.moment_for_circle(1, 0, 14, (0, 0)) dynamic_object_body = pymunk.Body(1, inertia) # give the object a starting position dynamic_object_body.position = 50, height - 100 # make the object the shape of a circle and make its color pink dynamic_object_shape = pymunk.Circle(dynamic_object_body, DYNAMIC_OBSTACLE_RADIUS) dynamic_object_shape.color = THECOLORS["pink"] dynamic_object_shape.elasticity = 1. dynamic_object_shape.angle = 0.5 # give the object a starting direction in which to move direction = Vec2d(1,0).rotated(dynamic_object_shape.angle) # add the object to the space self.space.add(dynamic_object_body, dynamic_object_shape) return dynamic_object_body def make_sonar_arm(self, x, y): arm_points = [] # make an arm for i in range(1, 40): arm_points.append((SENSOR_GAP + x + (SENSOR_SPREAD * i), y)) return arm_points ###################################################################### ################ FUNCTIONS FOR PLAYING ############################### ################ THE GAME ############################### ###################################################################### # this function applies a given action at the current frame of the game def frame_step(self, action): # APPLY THE ACTION if action == LEFT: self.car_body.angle -= TURN_ANGLE elif action == RIGHT: self.car_body.angle += TURN_ANGLE # move the obstacles every OBSTACLE_UPDATE number of frames if self.num_steps % STATIC_OBSTACLE_UPDATE == 0: self.move_static_obstacles() if self.num_steps % DYNAMIC_OBSTACLE_UPDATE == 0: self.move_dynamic_obstacles() # move the car in the direction of the action by appling some velocity in that direction driving_direction = Vec2d(1, 0).rotated(self.car_body.angle) self.car_body.velocity = VELOCITY * driving_direction # make the necessary updates to the screen screen.fill(THECOLORS["black"]) draw(screen, self.space) # update the screen self.space.step(1./10) if draw_screen: pygame.display.flip() clock.tick() # DETERMINE THE STATE collect the readings of the current location x,y = self.car_body.position sonar_readings = self.get_sonar_readings(x, y, self.car_body.angle) # normalize the readings so the numbers are cleaner to work with normalized_readings = [(x-20.)/20. for x in sonar_readings] # set the readings as the STATE of the game state = np.array([sonar_readings]) # DETERMINE THE REWARD - we consider the car in a crash state if any of the sonar readings are 1 i.e. the car is within one unit of an obstacle if self.car_is_crashed(sonar_readings): self.crashed = True reward = -500 self.recover_from_crash(driving_direction) else: # the higher the reading, the better the reward so we'll return the sum reward = -5 + int(self.sum_readings(sonar_readings) / 10) # increment the steps taken now that this frame has been fully processed self.num_steps += 1 return reward, state # function to randomly move the (more) static obstacles around the environment def move_static_obstacles(self): for static_obstacle in self.static_obstacles: # choose a random speed value between 1 and 5 to apply to the object speed = random.randint(1, 3) # choose a random direction to move the object in, between -2 and 2 direction = Vec2d(1, 0).rotated(self.car_body.angle + random.randint(-2, 2)) if random.randint(0, 1) >= 0.5: static_obstacle.velocity = speed * direction else: static_obstacle.velocity = speed * -direction def move_dynamic_obstacles(self): for dynamic_obstacle in self.dynamic_obstacles: speed = random.randint(10, 50) direction = Vec2d(1, 0).rotated(self.car_body.angle + random.randint(-1, 1)) if random.randint(0, 1) >= 0.5: dynamic_obstacle.velocity = speed * direction else: dynamic_obstacle.velocity = speed * -direction # given the current readings, determine if the car crashed def car_is_crashed(self, readings): if readings[0] == 1 or readings[1] == 1 or readings[2] == 1: return True else: return False # the car entered a crash state, so we want to back up at a slight angle until we're not in a crash state def recover_from_crash(self, driving_direction): while self.crashed: # back up at an angle self.car_body.velocity = -VELOCITY * driving_direction self.crashed = False for i in range(10): # turn slightly self.car_body.angle += TURN_ANGLE # update the screen to reflect the recovery changes screen.fill(THECOLORS["red"]) draw(screen, self.space) self.space.step(1./10) if draw_screen: pygame.display.flip() clock.tick() # take a sum of the readings to use as the reward def sum_readings(self, readings): total = 0 for reading in readings: total += reading return total # Return distance readings from each sensors. The distance is defined as a count of the first non-zero reading starting at the sensors def get_sonar_readings(self, x, y, angle): readings = [] # make 3 sonar arms arm_left = self.make_sonar_arm(x, y) arm_middle = arm_left arm_right = arm_left # rotate the arms so that they create a fan of readings in front of the car, and query their readings readings.append(self.get_arm_distance(arm_left, x, y, angle, 0.75)) # 45 degrees left readings.append(self.get_arm_distance(arm_middle, x, y, angle, 0)) # straight down the middle readings.append(self.get_arm_distance(arm_right, x, y, angle, -0.75)) # 45 degrees right if show_sensors: pygame.display.update() return readings def get_arm_distance(self, arm, x, y, angle, offset): distance_counter = 0 # check at each point on each iteration and see if we've hit something for point in arm: distance_counter += 1 # move the point to the right spot rotated_p = self.get_rotated_point(x, y, point[0], point[1], angle + offset) # check if we hit something (either an object or a wall) and return the current distance if we have if rotated_p[0] <= 0 or rotated_p[1] <= 0 or rotated_p[0] >= width or rotated_p[1] >= height: return distance_counter else: obstacle = screen.get_at(rotated_p) if self.get_track_or_not(obstacle) != 0: return distance_counter if show_sensors: pygame.draw.circle(screen, (255, 255, 255), (rotated_p), 2) return distance_counter def get_rotated_point(self, x_1, y_1, x_2, y_2, radians): # rotate x_2 and y_2 around x_1 and y_1 by the angle given by radians x_change = ((x_2 - x_1) * math.cos(radians)) + ((y_2 - y_1) * math.sin(radians)) y_change = ((y_1 - y_2) * math.cos(radians)) - ((x_1 - x_2) * math.sin(radians)) new_x = x_change + x_1 new_y = height - (y_change + y_1) return int(new_x), int(new_y) def get_track_or_not(self, readings): if readings == THECOLORS["black"]: return 0 else: return 1 if __name__ == "__main__": game_state = GameState() while True: game_state.frame_step((random.randint(0, 2)))
def gcd(a: int, b: int) -> int: """"Greatest Common Denominator. """ if a > b: r = a % b started = False while r != 0: started = True r = a % b a = b b = r if started: return a else: return b else: raise ValueError('a must be greater than b') def product_list(numbers: list) -> int: total = 1 for num in numbers: total *= num return total def prime_factor(n: int) -> list: """Prime factors. """ i = 2 factors = [] while i <= n: while n % i == 0: n /= i factors.append(i) i += 1 if n < i * i: if n > 1: factors.append(int(n)) break return factors def collatz(value): """TODO doc This collatz conjecture script shows the amount of steps needed, for a certain interval of integers to get to 1: (integer(i), steps(s)) It only works for positive integers {1, 2, 3, ...} """ steps = 0 i = value while i != 1: steps += 1 if i % 2 == 0: i /= 2 else: i = 3 * i + 1 return steps if __name__ == '__main__': print(prime_factor(int(input('input your integer value here: '))))
#!/bin/python3 """ A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers. """ def solLogic(): # Stores a list of all Palindrome found listofpali = [] # Checking and saving all the into the array for first_multiple in range(999, 100, -1): for second_multiple in range(999, 100, -1): number = first_multiple*second_multiple # Takes the number and reverses it to check if it is palindrome if int("".join([char for char in str(number)][::-1])) == number: # If number is palindrome, we save it in array listofpali.append(number) # Sort the array and return the last value listofpali.sort() return listofpali[-1] if __name__ == '__main__': print(solLogic())
''' Created on Mar 31, 2017 @author: ankur.sethi ''' mylist=[[300,101,200],['Paul',212,'dds'],[212,331,12]] for val in mylist: for v in val: print(v, end=" ")
# used with the csv files mentioned... # This program simply searches a database filled with names of cities # and their corresponding postal codes, then matches it with a file full # of postal codes and no city names. This was used because a exported # copy of a client list did not include which city the client was from import sys import os import csv from bs4 import BeautifulSoup import requests def main(postalCode): inputfile = csv.DictReader(open("file.csv")) postalfile = csv.DictReader(open("jcsv.csv")) lookuparray = [] postalarray = [] count = 0 for row in inputfile: lookuparray.append(row) for row in postalfile: for code in lookuparray: if row['CZIP'][:3]==code['Postal Code']: count+=1 print(row['CZIP'] + ": " + code["Place Name"]) break if __name__ == '__main__': main('k0l2h0')
import json import requests import sqlite3 api_key = 'YgZQoqt8gAna0G0koZRFZrCoUgDOA14QK3zMYEYfgEzwzbtLqXRuanUqQdtlnqjQtRRhpNx1E-KBnyQrAqtSsjaH1-GI-Bi0DdqApdgcUbuIz6cj4SwnAcXoSUXlXXYx' url = 'https://api.yelp.com/v3/businesses/search' #authorization from Yelp headers = {'Authorization': 'Bearer %s' % api_key,} #change the final 'term' each time you run the code to a cuisine of your choice #limited to 20 results each time #queries used: bars, asian, vegetarian, waffles, italian, american params = {'is_closed': 'false', 'location': 'Ann Arbor', 'limit': 20, 'term': 'restaurants', 'term': 'bars'} #request to the API req = requests.get(url, params=params, headers=headers) print(req.status_code) #turn data into json parsed = json.loads(req.text) #prints json # print(json.dumps(parsed, indent=4)) #prints list of restaurants with their ratings and addresses businesses = parsed["businesses"] # for restaurant in businesses: # print("Name:", restaurant["name"]) # print("Rating:", restaurant["rating"]) # print("Address:", " ".join(restaurant["location"]["display_address"])) #set up database conn = sqlite3.connect('new_yelp.sqlite') curr = conn.cursor() #creates table # curr.execute("""CREATE TABLE restaurants( # name text unique, # rating integer, # address text # )""") results = [] #parses through data to add to table i = 0 for restaurant in businesses: name = businesses[i]['name'] rating = businesses[i]['rating'] address = businesses[i]['location']['display_address'] tup = (str(name), str(rating), str(address)) results.append(tup) i += 1 #inserts data into table for tup in results: curr.execute("INSERT INTO restaurants VALUES (?,?,?)", tup) #creates table # curr.execute("""CREATE TABLE reviews( # name text unique, # review_count integer, # phone text # )""") results2 = [] #parses through data to add to table i = 0 for restaurant in businesses: name = businesses[i]['name'] review_count = businesses[i]['review_count'] phone = businesses[i]['phone'] tup2 = (str(name), str(review_count), str(phone)) results2.append(tup2) i += 1 #inserts data into table for tup2 in results2: curr.execute("INSERT INTO reviews VALUES (?,?,?)", tup2) conn.commit() conn.close
# -*- coding: utf-8 -*- """ Created on Mon Feb 15 10:42:43 2016 @author: raviteja """ import matplotlib.pyplot as plt import numpy as np # this function is used to find the mean square error def mse(Z,theta,Y): Yt =prediction(theta,Z) # this line takes to prediction function difference = (Yt.T-Y)**2 error = sum(difference)/len(Y) return error #this function is used to generate polynomial of higher degree and add it to the feature vector def polynomial(X,degree): z_train = np.ones((X.size,1), dtype=np.int) Z_train = np.append(z_train,X,axis =1) for i in range(degree-1): X =X*X Z_train =np.append(Z_train,X,axis=1) return Z_train # theta values are computated in this function def theta_computation(Z,Y): theta = np.dot(np.dot(np.linalg.inv(np.dot(Z.T,Z)),Z.T),Y) return theta #this function is for polynomial and cross_validation def polynomial_withCV(X,Y,degree,X_test): z_test = np.ones((X_test.size,1), dtype=np.int) Z_test = np.append(z_test,X_test,axis =1) z_train = np.ones((X.size,1), dtype=np.int) Z_train = np.append(z_train,X,axis =1) for i in range(degree-1): X =X*X X_test = X_test*X_test Z_train =np.append(Z_train,X,axis=1) Z_test =np.append(Z_test,X_test,axis=1) theta = theta_computation(Z_train,Y) return Z_train,theta,Z_test #this function to plot sample data def plot_sample_data(X,Y): plt.scatter(X,Y,color="red") plt.show() #this function to plot the model data def plot_model_data(X,Y,Yt): plt.scatter(X,Y,color="red") plt.scatter(X,Yt.T) plt.show() # this function is used to split the data and do cross validation def split_data(X,Y,degree): Testing_error =[] #all the testing errors of 10 fold cross validations Training_error = [] #all the training errors of 10 fold cross validations X_sets = np.split(X,10) Y_sets = np.split(Y,10) for i in range(len(X_sets)): X_test =np.vstack( X_sets[i]) Y_test = np.vstack(Y_sets[i]) if i<len(X_sets)-1: X_train = np.vstack(X_sets[i+1:]) Y_train =np.vstack(Y_sets[i+1:]) elif i==len(X_sets)-1 : X_train = np.vstack(X_sets[:i]) Y_train = np.vstack(Y_sets[:i]) while i>0: tempX = np.vstack(X_sets[i-1]) X_train = np.append(tempX,X_train) tempY = np.vstack(Y_sets[i-1]) Y_train = np.append(tempY,Y_train) i = i-1 X_train = np.vstack(X_train) Y_train = np.vstack(Y_train) Z_train,theta,Z_test = polynomial_withCV(X_train,Y_train,degree,X_test) Testing_error.append( mse(Z_test,theta,Y_test)) Training_error.append(mse(Z_train,theta,Y_train)) return sum(Testing_error),sum(Training_error) #this function to predict the Y def prediction(theta,Z): Yt =np.dot(theta.T,Z.T) return Yt def main(): #the program starts here #the line below has all the file name saved files =["svar-set1.dat.txt","svar-set2.dat.txt","svar-set3.dat.txt","svar-set4.dat.txt"] file_to_use = input("enter the file to be used:") # the line below is used to load the #particular file and distributes the data to X and Y X,Y = np.loadtxt(files[file_to_use-1],unpack =True,usecols=[0,1]) degree = input("enter the degree of the polynomial:") #reshaping the feature vector and label vector X = X.reshape(X.size,1) Y = Y.reshape(Y.size,1) #plotting the sample data to visualize the data beforing using it develop model plot_sample_data(X,Y) #the below line takes the program to split_data function which #splits the dat and sends data for cross_validation and return the MSE Testing_error, Training_error = split_data(X,Y,degree) # the average MSE of 10 fold cross validation is calculated Testing_error = Testing_error/10 Training_error = Training_error/10 print "Testing error for %s using the degree of polynomial of %d" %(files[file_to_use-1],degree) print Testing_error print "Training error for %s using the degree of polynomial of %d" %(files[file_to_use-1],degree) print Training_error # the part below this where the whole data is trained and predicted Z= polynomial(X,degree) theta = theta_computation(Z,Y) Yt = prediction(theta,Z) plot_model_data(X,Y,Yt) if __name__ == "__main__": main()
# Массив 10 строк на 10 столбцов служит игровым полем # Map - с большой буквы чтобы не путалось с внутренней функцией пайтона (map) Map = [[], [], [], [], [], [], [], [], [], []] # Заполнение игрового поля нулями row_number = 0 for row in Map: for column in range(10): row.append(0) # Добавляет в конце каждой строки ее номер - вертикальная разметка row.append(f'|{row_number}') row_number += 1 # Если эта переменная равна True - то сейчас ход первого игрока, если False - то второго first_player_turn = True # Главный игровой цикл running = True while running: # Перед выводом игрового поля, происходит вывод 15 пустых строк, чтобы предыдущее поле не мешалось с настоящим print('\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n') # Вывод каждого элемента каждой строки через разделитель ' | ' for row in Map: print((' | '.join(str(col) for col in row))) # Затем выводится горизонтальная разметка - номер каждого столбца print('_________________________________________') print(' | '.join(str(k) for k in range(len(Map)))) # Ввод будет происходить до тех пор, пока не будет введена свободная ячейка while True: # Если ход первого игрока, выводится просьба к ходу для первого, иначе - для второго if first_player_turn: print('\nПервый Игрок, вводите координаты точки') else: print('\nВторой Игрок, вводите координаты точки') # Затем вводятся координаты строки и столбца, в которую ставится отметка i, j = int(input('Строка: ')), int(input('Столбец: ')) # Для начала проверяется является ли ячейка пустой if Map[i][j] == 0: # Если ход первого игрока ставится отметка - 1, если второго то - 2 if first_player_turn: Map[i][j] = 1 else: Map[i][j] = 2 break else: print('\nЯчейка уже занята, попробуйте ввести другую!!! ==================================================') # Здесь проверка на выполнение условия окончания игры # P.S. я даже пытаться не буду объяснить этот кусок (говно)кода при помощи комментариев try: for r in range(len(Map)): for c in range(len(Map)): if Map[r][c] in [1, 2]: for r1 in [abs(r+1), abs(r), abs(r-1)]: # abs() предотвращает использование отрицательных индексов for c1 in [abs(c-1), abs(c), abs(c+1)]: # Отрицательные индексы будут выдавать элементы с конца if Map[r1][c1] in [1, 2] and not (r1 == r and c1 == c): for r2 in [r+1, r, r-1]: for c2 in [c-1, c, c+1]: if Map[r2][c2] in [1, 2] and not (r2 == r and c2 == c) and not (r2 == r1 and c2 == c1): running = False # Случаи с неправильным индексами будут просто игнорироваться except IndexError: pass # Затем происходит смена хода first_player_turn = not first_player_turn # После окончания игрового цикла, поле выводится еще один раз # ----------------------------------------------------------- # Перед выводом игрового поля, происходит вывод 15 пустых строк, чтобы предыдущее поле не мешалось с настоящим print('\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n') # Вывод каждого элемента каждой строки через разделитель ' | ' for row in Map: print((' | '.join(str(col) for col in row))) # Затем выводится горизонтальная разметка - номер каждого столбца print('_________________________________________') print(' | '.join(str(i) for i in range(10))) # По правилам игры если проигрышная комибинация попалась на ход первого игрока, то побеждает второй - и наоборот # Но так-как в конце игрового цикла ход сменяется, вывод инвертирован if first_player_turn: print('\nПервый Игрок победил!\nИгра завершена!') else: print('\nВторой Игрок победил!\nИгра завершена!')
#!/usr/local/bin/python # -*- coding: utf-8 -*- """ This module uses an wikipedia api and PyMongo to store information from wikipedia pages and save them into a database in order to perform queries upon them """ import wikipedia from threading import Thread, Semaphore import schedule import pymongo MONTH_NAMES = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] DAYS_IN_MONTH = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] SECTION_NO = 4 SECTION_NAMES = ['Events', 'Births', 'Deaths', 'Holidays and observances'] DB_NAMES = ['evs', 'brts', 'dths', 'holo'] MAX_THREADS = 8 SERVER_ADDR = "localhost" SERVER_PORT = 27017 def insert_entry(month, day, semaphore): """ Function that takes a month a day and performs an addition in the database with all the events in that day. @type month: String @param device_id: the name of the month @type day: Int @param day: the day in the month @type semaphore: Semaphore @param semaphore: makes sure no more than MAX_THREADS threads are running at the same time """ with semaphore: page_name = month + " " + str(day) page = wikipedia.page(page_name) # Connects to the mongo client = pymongo.MongoClient(SERVER_ADDR, SERVER_PORT) for i in xrange(SECTION_NO - 1): # Select the database database = client[DB_NAMES[i]] collection = database[month.lower() + '_' + str(day)] section = page.section(SECTION_NAMES[i]) entries = section.splitlines() # Go through each entry and insert it into the db # according to which category it belongs for entry in entries: entry_dict = entry.split(u'–', 1) if len(entry_dict) < 2: continue if entry_dict[1].strip() == "": continue post = {'year' : entry_dict[0].strip(), 'day' : page_name, 'category' : SECTION_NAMES[i].lower(), 'desc' : entry_dict[1].strip()} collection.insert(post) database = client[DB_NAMES[3]] collection = database[month.lower() + '_' + str(day)] section = page.section(SECTION_NAMES[3]) entries = section.splitlines() for entry in entries: post = {'day' : page_name, 'category' : SECTION_NAMES[3].lower(), 'desc' : entry} collection.insert(post) def job(): """ Does the job by instantiating threads and passing the necesary info for updating the database """ # Semaphore for limiting the number of threads SEM = Semaphore(MAX_THREADS) # Delete all the information if any client = pymongo.MongoClient("localhost", 27017) for db_name in DB_NAMES: client.drop_database(db_name) # For each month for mnth in xrange(12): threads = [] for dy in xrange(DAYS_IN_MONTH[mnth]): # Create thread t = Thread(target=insert_entry, \ args=(MONTH_NAMES[mnth], dy + 1, SEM)) t.start() threads.append(t) # Wait for threads to finish for t in threads: t.join() if __name__ == "__main__": """ Using schedule. For more info: https://github.com/dbader/schedule """ schedule.every(2).hours.do(job) job() while 1: schedule.run_pending()
""" push X: 정수 X를 큐에 넣는 연산이다. pop: 큐에서 가장 앞에 있는 정수를 빼고, 그 수를 출력한다. 만약 큐에 들어있는 정수가 없는 경우에는 -1을 출력한다. size: 큐에 들어있는 정수의 개수를 출력한다. empty: 큐가 비어있으면 1, 아니면 0을 출력한다. front: 큐의 가장 앞에 있는 정수를 출력한다. 만약 큐에 들어있는 정수가 없는 경우에는 -1을 출력한다. back: 큐의 가장 뒤에 있는 정수를 출력한다. 만약 큐에 들어있는 정수가 없는 경우에는 -1을 출력한다. """ # class 풀이 # Class 정의 class Queue: def __init__(self): self.list = [] # class에서 list를 초기화 def push(self, x): self.list.append(x) # push명령어로 입력받은 x를 list에 추가한다. def pop(self): try: print(self.list.pop(0)) # pop명령어로 맨앞의 정수를 빼낸다. except IndexError: print("-1") # pop명령어로 정수를 빼다가 list에 정수가 없으면 IndexError발생 def size(self): print(len(self.list)) # size 명령어로 list의 길이를 출력한다 = 리스트에 들어있는 정수 개수 def empty(self): if len(self.list) == 0: print("1") else: print("0") # empty명령어로 리스트의 길이가 0이면 1 그렇지 않으면 0을 출력 def front(self): try: print(self.list[0]) except IndexError: print("-1") # front 맨앞의 원소를 출력, 원소가 없는 경우 -1 출력 def back(self): try: print(self.list[-1]) except IndexError: print("-1") # 맨 뒤의 원소를 출력, 원소가 없는 경우 -1 출력 # 실행부 r = int(input()) # 실행 횟수 입력 q = Queue() for i in range(0, r): # 입력받는 반복 횟수만큼 반복 실행 cmd = input().split(" ") if cmd[0] == "push": q.push(int(cmd[1])) elif cmd[0] == "pop": q.pop() elif cmd[0] == "size": q.size() elif cmd[0] == "empty": q.empty() elif cmd[0] == "front": q.front() elif cmd[0] == "back": q.back()
from datetime import date def examples(): d0 = date(2014, 1, 1) d1 = date(2020, 8, 25) delta = d1 - d0 print(delta.days + 1) def calculate_days(idate): #print(date) # print( "{} - {} - {} ".format(idate[0:4], idate[4:6], idate[6:8]) ) f_date = date(2014, 1, 1) l_date1 = date(int(idate[0:4]), int(idate[4:6]), int(idate[6:8])) delta = l_date1 - f_date print(idate + " = " + str(delta.days + 1)) def print_timestamp(): timestamp = 1613520000 date_time = date.fromtimestamp(timestamp) # print("Date time object:", date_time.strftime("%d/%m/%Y")) # print(date_time) # print(date_time.strftime("%d/%m/%Y")) print(date_time.strftime("%Y%m%d")) def main(): print("Hello, World!") calculate_days("20140102") calculate_days("20200101") calculate_days("20210101") calculate_days("20210224") calculate_days(date.today().strftime('%Y%m%d')) if __name__== "__main__" : main()
#!/usr/bin/env python """ This is the python script describing the game rules for Tower's of Hanoi Game Puzzle. In this file exists 3 classes which are the game objects to create the game - TowerGame, Peg, Disk """ __author__ = "Adam Pucciano" __date__ = "4/15/2021" __version__ = "1.2" __email__ = "[email protected]" __status__ = "Production" import sys, json #Config settings #If in need of a config file to change the game settings (Peg/Disks) I could implement a config file read #from config import Config #config = Config() _disk_num = 4 _peg_num = 3 class Disk: """ This class defines the Disk game objects Each have a particular size associated with them """ def __init__(self, size): self.size = size #has a certain size def check_size(self): return self.size def _dump(self): return { "Disk" : { 'size' : self.size}} class Peg: """ This class defines a Peg game object Each Peg has a collection of disks that it keeps. Disks can only be removed through the contents stack. contents - The Disk object this Peg is currently holding in its stack position - The peg position in the tower game (usually 1 for starting peg and 3 for goal peg) """ def __init__(self, position): self.contents = [] self.position = position def _initContents(self, diskContents :[Disk]): if self.position == 1: for disk in diskContents: self.addDisk(disk) if (len(sys.argv) > 1): print("Disks initialized on Peg#{0}".format(self.position)) def _peek(self): """ Peek at the top disk of this peg Returns Disk """ if (len(self.contents) > 0): return self.contents[0] def _checkContents(self): """ Print out a log of the contents """ print(str(self._dump())) def _dump(self): """ Returns a dict representation of this Peg """ return { "Peg" : { 'Disks' : self.jsonify_contents(), 'Position' : self.position }} def jsonify_contents(self): """ Returns a string representation of the disks on this Peg """ disks = {} for i, disk in enumerate(self.contents): disks.update({ i : disk._dump() }) return disks def isEmpty(self): """ Checks if the contents of the peg is empty Returns True/False """ return self.contents == [] def peekTopSize(self): """ Peek at the top disk object Returns a size (int) """ if (len(self.contents) > 0): if self.contents[0] is not None: return self.contents[0].check_size() else: return 0 def addDisk(self, disk :Disk): """ Add disks to the top of the peg stack """ self.contents.insert(0, disk) def removeDisk(self): """ Remove a disk from the top of the peg stack """ return self.contents.pop(0) class TowerGame: """ This class holds an instance of a Tower of Hanoi game WINCONDITION - bool flag that holds the state of the current game GameDisks - list of the initial collection of Disk objects GamePegs - list of all pegs in the game """ def __init__(self, disks=4, pegs=3): self.WINCONDITION = False self.GameDisks = [] self.GamePegs = [] self.initGame(disks, pegs) #Global Game objects and fields def initGame(self, disks, pegs): for i in range(disks): self.GameDisks.append(Disk(i)) self.GameDisks.reverse() for i in range(1, pegs + 1): if (len(sys.argv) > 1): print("Peg #{0} created".format(i)) self.GamePegs.append(Peg(i)) self.GamePegs[0]._initContents(self.GameDisks) #Reports the content of Disks to the user def _inspectPeg(self, pegNumber : Peg): """ Invokes a print out of the contents (Disks) on a Peg to the caller """ return pegNumber._checkContents() def _reportGameState(self): """ Reports a formatted print out of the EACH Peg and disk contents in this current game object """ for i in self.GamePegs: print("Peg {0}".format(i.position)) print("{0}".format(self._inspectPeg(i))) print("\n") def jsonifyGameState(self): """ Creates a string representation of the TowerGame object Returns (String) """ state = "" for peg in self.GamePegs: state += json.dumps(peg._dump()) return state def getPeg(self, pegIndexNumber: int): """ Translates a Peg number to a Game Peg indexed in the Tower Game Returns a Peg Obj """ if (not isinstance(pegIndexNumber, int)): return None if (pegIndexNumber not in range(1, _peg_num + 1)): return None return self.GamePegs[pegIndexNumber - 1] def moveDisktoPeg(self, pegFrom :Peg, pegTo :Peg): """ Method describes the movement of a disk from the source peg to the destination peg Handles all the necessary sizing rules to accept or deny movements :param pegFrom: (Peg Obj) The source Peg we are taking a disk from :param pegTo: (Peg Obj) The destination Peg we are placing a disk to Returns True if the move was valid, False if there was an error """ if (pegFrom == None or pegTo == None): return False if (pegFrom.isEmpty()): print("No disks to move") return False if (len(pegTo.contents) != 0 and len(pegFrom.contents) != 0): if (pegTo.peekTopSize() < pegFrom.peekTopSize()): print("Cannot make this move, Destination Peg has a smaller disk size.") return False else: disk_to_add = pegFrom.peekTopSize() pegTo.addDisk(Disk(disk_to_add)) pegFrom.removeDisk() print("Moved disk from Peg #{0} to Peg#{1}".format(pegFrom.position, pegTo.position)) else: disk_to_add = pegFrom.peekTopSize() pegTo.addDisk(Disk(disk_to_add)) pegFrom.removeDisk() print("Moved disk from Peg #{0} to Peg#{1}".format(pegFrom.position, pegTo.position)) #Add check win condition here if (len(pegTo.contents) == _disk_num): self.check_win() return True def check_win(self): """ Checks if the win condition of the game has been met returns True/False """ if (len(self.GamePegs[_peg_num -1].contents) == _disk_num): nextBiggest = 0 for i, disk in enumerate(self.GamePegs[_peg_num -1].contents): if (disk.size <= nextBiggest): nextBiggest = disk.size self.WINCONDITION = True if (self.WINCONDITION == True): print("All disks in correct order") print("Congratulations You Win!") return True else: print("Disks have been stacked on the incorrect Goal Peg (#{0})".format(_peg_num)) return False ##Invoke Game as main entrypoint to interact with in CMD if __name__ == '__main__': if (len(sys.argv) > 1): if (sys.argv[1] == "-d"): temp = TowerGame(_disk_num, _peg_num) print("Welcome to Towers of Hanoi - There are {0} disks and {1} pegs in this version".format(_disk_num, _peg_num)) print("Move disks on pegs to by typing out the source peg # and destionation peg # when prompted") while(not temp.WINCONDITION): temp._reportGameState() txt = input("Source Peg# / Destination Peg#: ") source, dest = map(int, txt.split()) print ("Attempting to move a disk from {0} to {1}".format(source, dest)) if ((1 <= source and 1 <= dest) and (_peg_num >= source and _peg_num >= dest)): temp.moveDisktoPeg( temp.GamePegs[source - 1], temp.GamePegs[dest - 1]) else: print("Cannot execute move - Peg # not in range. There are a maximum of {0} pegs".format(_peg_num))
from pygame import Vector2 import pygame from graphics.drawing_surface import DrawingSurface class Screen: """A class for managing the application window. Attributes: `font`: A pygame.font.Font `surface`: A DrawingSurface Corresponds to the whole Screen area About dirty rects: Due to the performance limitations of pygame, the actual drawing to the display must be done only at those places which differ from the last update. """ def __init__(self, width, height, font_size): """Initializes Screen. Arguments: `width`: A positive integer The width of the window in pixels `height`: A positive integer The height of the window in pixels `font_size`: positive float Font size relative to `height`. Good values are something like 0.02. """ pygame.init() self._height = height font_pixels = int(self.get_height() * font_size) self.font = pygame.font.SysFont("monospace", font_pixels) self.surface = DrawingSurface( pygame.display.set_mode((width, height), vsync=1), self, Vector2(0)) self._previous_dirty_rects = [] self._current_dirty_rects = [] def update(self): """Updates screen. Only updates area that was either marked dirty for previous rendering (something that might no longer be rendered, i.e. should be cleared) or marked dirty for this rendering. """ pygame.display.update(self._previous_dirty_rects + self._current_dirty_rects) self._previous_dirty_rects = self._current_dirty_rects self._current_dirty_rects = [] def add_dirty_rect(self, rect): """Adds a pygame.Rect to the list of dirty rects""" self._current_dirty_rects.append(rect) def get_height(self): """Returns the height of the Screen drawing area in pixels""" return self._height
class FloatRect: """Similar class to pygame.Rect but with floats""" def __init__(self, x, y, width, height): """Initializes FloatRect Arguments: `x`: float x coordinate of the top left corner `y`: float y coordinate of the top left corner `width`: float `height`: float """ self._x = x self._y = y self._width = width self._height = height @property def height(self): return self._height @height.setter def height(self, value): self._height = value @property def width(self): return self._width @width.setter def width(self, value): self._width = value @property def top(self): return self._y @top.setter def top(self, value): self._y = value @property def bottom(self): return self._y + self._height @bottom.setter def bottom(self, value): self._y = value - self._height @property def left(self): return self._x @left.setter def left(self, value): self._x = value @property def right(self): return self._x + self.width @right.setter def right(self, value): self._x = value - self._width @property def center(self): return (self._x + self._width / 2, self._y + self._height / 2) @center.setter def center(self, value): self._x = value[0] - self._width / 2 self._y = value[1] - self._height / 2 @property def topleft(self): return (self._x, self._y) @topleft.setter def topleft(self, value): self._x = value[0] self._y = value[1] @property def size(self): return (self._width, self._height) @size.setter def size(self, value): self._width = value[0] self._height = value[1] @property def midtop(self): return (self._x + self._width / 2, self._y) @midtop.setter def midtop(self, value): self._x = value[0] - self._width / 2 self._y = value[1] @property def topright(self): return (self._x + self._width, self._y) @topright.setter def topright(self, value): self._x = value[0] - self._width self._y = value[1] @property def bottomleft(self): return (self._x, self._y + self._height) @topright.setter def topright(self, value): self._x = value[0] self._y = value[1] - self._height def copy(self): """Creates a copy of `self`""" return FloatRect(self._x, self._y, self._width, self._height) def __repr__(self): return f"FloatRect({self._x}, {self._y}, {self._width}, {self._height})"
import logging import sys import math from abc import ABC, abstractmethod from game.shapes import Rectangle from graphics.image import Image from utils.float_rect import FloatRect class Graphic(ABC): """A base class for movable and rotatable graphics. Attributes: `location`: A pygame.Vector2 The location of the Graphic `rotation`: Radians Positive rotation mean counter-clockwise (in coordinates where x grows right and y grows down) NOTE: See Shape class for more detailed descriptions. """ @abstractmethod def draw(self, camera): pass @property @abstractmethod def location(self): pass @location.setter @abstractmethod def location(self, value): pass @property @abstractmethod def rotation(self): pass @rotation.setter @abstractmethod def rotation(self, value): pass class PolylineGraphic(Graphic): """A class for drawing a polyline""" def __init__(self, polyline, color, width): """Initializes PolylineGraphic. Arguments: `polyline`: A Polyline The polyline to be drawn. `color`: A tuple of 3 The color of the polyline `width`: A positive float The width of the line in game world coordinates """ self._polyline = polyline self.color = color self.width = width def draw(self, camera): """Draws image on `camera`. Arguments: `camera`: Camera The target of drawing """ for line in self._polyline.lines: camera.draw_line(line.begin, line.end, self.color, self.width) @property def location(self): return self._polyline.location @location.setter def location(self, value): self._polyline.location = value @property def rotation(self): return self._polyline.rotation @rotation.setter def rotation(self, value): self._polyline.rotation = value class ImageGraphic(Graphic): """Class for movable and rotatable images.""" def __init__(self, rectangle, image): """Initializes ImageGraphic. Arguments: `rectangle`: A Rectangle Defines the area to which the image is drawn. NOTE: Should really be unrotated (i.e. topleft at topleft, etc) when the `rectangle.rotation` == 0. This is because `rectangle.rotation` is used to determine the rotation of the drawn `image`. `image`: An Image NOTE: The drawing of the image is done by setting its height to match that of the `rectangle`. Therefore `rectangle` and `image` should have (approximately) the same aspect ratio! """ rectangle_size = rectangle.size() rectangle_aspect_ratio = rectangle_size[0] / rectangle_size[1] image_aspect_ratio = image.get_width_pixels() / image.get_height_pixels() if abs(rectangle_aspect_ratio - image_aspect_ratio) > 0.1: raise ValueError("`rectangle` and `image` should have approximately \ the same aspect ratio!") self._rectangle = rectangle self._image = image @classmethod def from_image_path(cls, image_path, center_offset, size): """Creates ImageGraphic from an image file. Scales image to match the `size` aspect ratio. Arguments: `image_path`: pathlib.Path object Denotes the path to the image. `center_offset`: Vector2 The position of the center of the image relative to the `location` of the ImageGraphic `size`: Vector2 The dimensions of the image Returns: An ImageGraphic object """ helper_rect = FloatRect(0, 0, size[0], size[1]) helper_rect.center = (math.floor( center_offset[0]), math.floor(center_offset[1])) rectangle = Rectangle.from_rect(helper_rect) try: image = Image(image_path) except Exception: logging.critical(f"Failed loading image from {image_path}.") logging.critical(f"Are the configuration files OK?") sys.exit() image.set_aspect_ratio(helper_rect.width, helper_rect.height) return ImageGraphic(rectangle, image) def draw(self, camera): """Draws image on `camera`. Arguments: `camera`: A Camera """ camera.draw_image(self._image, self._rectangle.center(), self._rectangle.rotation, self._rectangle.size()[1]) @property def location(self): return self._rectangle.location @location.setter def location(self, value): self._rectangle.location = value @property def rotation(self): return self._rectangle.rotation @rotation.setter def rotation(self, value): self._rectangle.rotation = value
class Node(): def __init__(self,value): self.value = value self.left = None self.right = None def bst(arr): bst1(arr,0,len(arr)-1) def bst1(arr,start,end): if start > end: return mid = (start + end) // 2 node = Node(arr[mid]) node.left = bst1(arr,start,mid-1) node.right = bst1(arr,mid+1,end) print(node.value) return node if __name__ == "__main__": bst([1,2,3,4,5,6,7,8,9,10])
import unittest """ Expressions written in postfix expression are evaluated faster compared to infix notation as postfix does not require parenthesis. Write program to evaluate postfix expression. """ """ Approach: 1. Scan postfix expression from left to right. 2. If element is operand, we push it on the stack. 3. If element is operator, we pop the two most recent items from the stack, evaluate using them, and then push the result on stack. 4. Finally, the only value remaining in the stack is the output. """ def postfix_evaluate(postfix): stack = [] for i in range(len(postfix)): if is_operand(postfix[i]): stack.insert(0, postfix[i]) elif is_operator(postfix[i]): right_operand = stack.pop(0) left_operand = stack.pop(0) result = evaluate(left_operand, right_operand, postfix[i]) stack.insert(0, result) return int(stack.pop(0)) def is_operand(ch): return not is_operator(ch) and ch != '(' and ch != ')' def is_operator(ch): return ch == '+' or ch == '-' or ch == '*' or ch == '/' or ch == '^' def evaluate(lhs, rhs, op): lhs = int(lhs) rhs = int(rhs) if op == '+': return str(lhs + rhs) elif op == '-': return str(lhs - rhs) elif op == '*': return str(lhs * rhs) elif op == '/': return str(lhs / rhs) elif op == '^': return str(lhs ^ rhs) class TestPostfixEvaluate(unittest.TestCase): def test_postfix_evaluate(self): self.assertEqual(postfix_evaluate('231*+9-'), -4)
import unittest """ Given a string, find the longest substring which is a palindrome. Input: forgeeksskeegfor Output: geeksskeeg """ def longest_palindromic_substring(string): n = len(string) # table[i][j] is the length of palindromic substring starting at str[i] and ending at str[j]. # The max value in the table is the final result. table = [[0] * n for _ in range(n)] for i in range(n): table[i][i] = 1 for l in range(2, n+1): for i in range(n-l+1): j = i+l-1 if string[i] == string[j] and l == 2: table[i][j] = 2 elif string[i] == string[j]: table[i][j] = 2 + table[i+1][j-1] start = 0 max_length = 0 for i in range(n): for j in range(n): if max_length < table[i][j]: max_length = table[i][j] start = i return string[start:start+max_length] class TestLongestPalindromic(unittest.TestCase): def test_longest_palindromic(self): string = 'forgeeksskeegfor' self.assertEqual(longest_palindromic_substring(string), 'geeksskeeg')
import unittest """ Given a string, find the length of the longest substring without repeating characters. Input: ABDEFGABEF Output: 6 """ """ Approach: 1. Scan the given string from left to right. 2. For each character, maintain the most recent index where that character was last seen. 3. If a repeated character is found, if its last occurrence is not part of current longest substring, do nothing, else start a new longest unique substring one index after the last occurrence. 4. Update the max unique length as needed. """ def longest_substring_unique_chars(string): cur_len = 0 last_occurrence = {} max_len = -float('inf') start = 0 for i in range(len(string)): cur_char = string[i] if cur_char not in last_occurrence: cur_len += 1 else: lo = last_occurrence[cur_char] if start <= lo <= start + cur_len: max_len = max(max_len, cur_len) start = lo + 1 cur_len = i - start + 1 else: cur_len += 1 last_occurrence[cur_char] = i max_len = max(max_len, cur_len) return max_len class TestLongestUnique(unittest.TestCase): def test_longest_unique(self): string = 'ABDEFGABEF' self.assertEqual(longest_substring_unique_chars(string), 6) string = 'GEEKSFORGEEKS' self.assertEqual(longest_substring_unique_chars(string), 7) string = 'BBBB' self.assertEqual(longest_substring_unique_chars(string), 1)
import unittest """ Given n non negative integers representing an elevation map where width of each bar is 1, compute how much water it is able to trap after raining. Input: 2 0 2 Output: 2 Input: 3 0 0 2 0 4 Output: 10 """ """ Approach: 1. A bar can store water if there are taller bars to its left and right. 2. We can find the amount of water stored at each bar by finding the tallest bars to its left and right. 3. We then scan the bars from left to right and add the amount of water as min(left,right)-height(bar). """ def trapping_rain_water(list_of_bars): tallest_to_left = [0] * len(list_of_bars) tallest_to_right = [0] * len(list_of_bars) tallest_to_left[0] = list_of_bars[0] for i in range(1, len(list_of_bars)): tallest_to_left[i] = max(list_of_bars[i], tallest_to_left[i-1]) tallest_to_right[len(list_of_bars)-1] = list_of_bars[len(list_of_bars)-1] for i in range(len(list_of_bars)-2, -1, -1): tallest_to_right[i] = max(list_of_bars[i], tallest_to_right[i + 1]) water = 0 for i in range(len(list_of_bars)): water += min(tallest_to_left[i], tallest_to_right[i]) - list_of_bars[i] return water class TestTrappingRainWater(unittest.TestCase): def test_trapping_rain_water(self): list_of_bars = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1] self.assertEqual(trapping_rain_water(list_of_bars), 6)
import unittest """ Given an array with positive and negative numbers, find the maximum average subarray of given length. Input: 1 12 -5 -6 50 3, k = 4 Output: 1 (12-5-6+50)/4 """ def max_avg_subarray(list_of_numbers, k): assert len(list_of_numbers) >= k cur_max = sum(list_of_numbers[0:k]) cur_max_index = 0 j = 0 for i in range(k, len(list_of_numbers)): cur_sum = cur_max - list_of_numbers[j] + list_of_numbers[i] if cur_sum > cur_max: cur_max = cur_sum cur_max_index = j+1 j += 1 return cur_max_index class TestMaxAvgSubarray(unittest.TestCase): def test_max_avg_subarray(self): list_of_numbers = [1, 12, -5, -6, 50, 3] self.assertEqual(max_avg_subarray(list_of_numbers, 4), 1)
import unittest """ Given an array, print next greater element. The NGE for an element x is the first greater element on the right side of x in the array. Elements for which no greater element exist, print -1. Input: {4, 5, 2, 25} Output: {5, 25, 25, -1} """ def next_greater(arr): nge = [-1] * len(arr) stack = [arr[-1]] for i in range(len(arr) - 2, -1, -1): while len(stack) > 0 and stack[-1] <= arr[i]: stack.pop() if len(stack) > 0: nge[i] = stack[-1] stack.append(arr[i]) return nge class TestNGE(unittest.TestCase): def test_nge(self): arr = [4, 5, 2, 25] self.assertEqual(next_greater(arr), [5, 25, 25, -1]) arr = [13, 7, 6, 12] self.assertEqual(next_greater(arr), [-1, 12, 12, -1]) arr = [11, 13, 21, 3] self.assertEqual(next_greater(arr), [13, 21, -1, -1])
import unittest """ Given an array containing only 0s and 1s, find the largest subarray which contain equal number of 0s and 1s. Input: 1 0 1 1 1 0 0 Output: 1 to 6 Input: 1 1 1 1 Output: No subarray Input: 0 0 1 1 0 Output: 0 to 3 OR 1 to 4 """ """ Approach: 1. Scan the array from left to right. 2. For each index i, compute the difference between count of 1s and 0s to its left, inclusive. 3. A subarray with same number of 0s and 1s will have the same diff value before subarray and after subarray, (as net difference within the subarray is zero). 4. We have to find two diff values which are same and maximum distance apart. This can be done using a symbol table. 5. Return the max distance from symbol table. """ def find_max_subarray_equal_0_and_1(list_of_zeros_and_ones): difference_list = [0] * (len(list_of_zeros_and_ones) + 1) ones_count = 0 zeros_count = 0 difference_index = 1 for number in list_of_zeros_and_ones: if number == 1: ones_count += 1 else: zeros_count += 1 difference_list[difference_index] = ones_count - zeros_count difference_index += 1 difference_table = {} max_length = -float('inf') max_length_indices = None for i in range(len(difference_list)): difference_val = difference_list[i] if difference_val in difference_table: j = difference_table[difference_val] if max_length < i - j: max_length = i - j max_length_indices = [j, i-1] else: difference_table[difference_val] = i return max_length_indices class TestLargestSubarray(unittest.TestCase): def test_largest_subarray(self): list_of_zeros_and_ones = [1, 0, 1, 1, 1, 0, 0] self.assertEqual(find_max_subarray_equal_0_and_1(list_of_zeros_and_ones), [1, 6]) list_of_zeros_and_ones = [1, 0, 1, 0, 0, 0, 0] self.assertEqual(find_max_subarray_equal_0_and_1(list_of_zeros_and_ones), [0, 3]) list_of_zeros_and_ones = [1, 0, 1] self.assertEqual(find_max_subarray_equal_0_and_1(list_of_zeros_and_ones), [0, 1]) list_of_zeros_and_ones = [1, 1, 1, 1] self.assertIsNone(find_max_subarray_equal_0_and_1(list_of_zeros_and_ones))
import unittest """ There are n pairs and therefore 2n people. Everyone has a unique number ranging from 1 to 2n. All these 2n persons arranged in random fashion in an array of size 2n. We are also given who is partner of whom. Find the minimum number of swaps required to arrange these pairs such that all pairs become adjacent to each other. Input: n = 3 pairs = 1,3 2,6 4,5 arr = 3 5 6 4 1 2 Output: 2 We can get 3 1 5 4 6 2 by swapping 5 & 6 and 6 & 1 """ """ Approach: 1. Start scanning from left to right. 2. If first and second, already form a pair, then recur for the remaining list of numbers. 3. Else return the minimum of following two cases: a. Recur after swapping first with element that forms pair with second. b. Recur after swapping second with element that forms pair with first. """ def min_swaps_required(list_of_numbers, list_of_pairs): return min_swaps_required_helper(list_of_numbers, list_of_pairs, 0) def forms_pair(ele1, ele2, list_of_pairs): for pair in list_of_pairs: if pair[0] == ele1 and pair[1] == ele2 or pair[0] == ele1 and pair[1] == ele2: return True return False def swap_in_list(list_of_numbers, start_index, one_from_pair, dest_index, list_of_pairs): second_from_pair = 0 for pair in list_of_pairs: if pair[0] == one_from_pair: second_from_pair = pair[1] elif pair[1] == one_from_pair: second_from_pair = pair[0] found = -1 for i in range(start_index, len(list_of_numbers)): if list_of_numbers[i] == second_from_pair: found = i break list_of_numbers[found], list_of_numbers[dest_index] = list_of_numbers[dest_index], list_of_numbers[found] return list_of_numbers def min_swaps_required_helper(list_of_numbers, list_of_pairs, index): if index >= len(list_of_numbers): return 0 cur = list_of_numbers[index] next = list_of_numbers[index + 1] if forms_pair(cur, next, list_of_pairs): return min_swaps_required_helper(list_of_numbers, list_of_pairs, index + 2) else: list1 = swap_in_list(list_of_numbers[:], index+2, list_of_numbers[index], index+1, list_of_pairs) list2 = swap_in_list(list_of_numbers[:], index+2, list_of_numbers[index+1], index, list_of_pairs) return 1 + min(min_swaps_required_helper(list1, list_of_pairs, index + 2), min_swaps_required_helper(list2, list_of_pairs, index + 2)) class TestMinSwaps(unittest.TestCase): def test_min_swaps(self): list_of_numbers = [3, 5, 6, 4, 1, 2] list_of_pairs = [(1, 3), (2, 6), (4, 5)] self.assertEqual(min_swaps_required(list_of_numbers, list_of_pairs), 2)
""" Given a singly linked list, swap kth node from beginning with kth node from end. Swapping of data is not allowed, only pointers should be changed. """ def swap_kth_nodes(head, k): n = count_nodes(head) if k > n: return head # kth from beginning == kth from end if n == 2*k-1: return head # find kth node from beginning prev_x = None x = head for i in range(1, k): prev_x = x x = x.next # find kth node from end: (n-k+1)st from beginning prev_y = None y = head for i in range(1, n-k+1): prev_y = y y = y.next # Update prev pointers if prev_x: prev_x.next = y if prev_y: prev_y.next = x # Update next pointers temp = x.next x.next = y.next y.next = temp # Update head pointer if k == 1: head = y if k == n: head = x return head def count_nodes(head): cur = head count = 0 while cur: count += 1 cur = cur.next return count class Node: def __init__(self, data): self.data = data self.next = None def print_ll(head): cur = head result = [] while cur: result.append(cur.data) cur = cur.next print result if __name__ == '__main__': head = Node(1) head.next = Node(2) head.next.next = Node(3) head.next.next.next = Node(4) head.next.next.next.next = Node(5) head.next.next.next.next.next = Node(6) head.next.next.next.next.next.next = Node(7) print_ll(head) print_ll(swap_kth_nodes(head, 5))
import unittest """ You are given n pairs of numbers. In every pair first number is always smaller than second number. A pair (c,d) can follow another pair (a,b) if b < c. Chain of pairs can be formed in this fashion. Find the longest chain which can be formed from a given set of pairs. Input: (5,24),(39,60),(15,28),(27,40),(50,90) Output: 3, chain is (5,24),(27,40),(50,90) """ def chain_of_pairs(pairs): pairs = sorted(pairs, cmp=pair_comparator) # This is similar to finding LIS where sequence is given pairs. n = len(pairs) # table[i] denotes length of LIS ending in pairs[i]. table = [1] * n for i in range(1, n): for j in range(i): if pairs[i][0] > pairs[j][1] and table[i] < table[j] + 1: table[i] = table[j] + 1 return max(table) def pair_comparator(pair1, pair2): return pair1[0] - pair2[0] class TestChainOfPairs(unittest.TestCase): def test_chain_of_pairs(self): pairs = [[5, 24], [39, 60], [15, 28], [27, 40], [50, 90]] self.assertEqual(chain_of_pairs(pairs), 3)
""" Find whether a given undirected graph has a cycle. NOTE: Another way to do this is using Union-Find algorithm. """ """ Approach: 1. The idea is to perform a DFS starting from every vertex. 2. Along with standard DFS stuff, we also pass the parent node which started the DFS. Example, If we are doing DFS at u, and we start exploring an unvisited neighbor of u say v, then we pass parent as u for DFS from v. 3. During DFS, if we find a visited node, then we compare it with parent. If the visited node and parent are same, it means we just came from parent (in above example, that would be the case when u is parent, and since graph is undirected, u will again appear as neighbour of v during DFS from v), so we just skip the node. 4. However, if we find visited node, not equal to current parent, it means we will be exploring an already visited node using the current edge. Hence, there is a cycle. """ def has_cycle_helper(G, v, parent, visited): visited[v] = True V = len(G) for u in range(V): if G[v][u] == 1: if not visited[u]: return has_cycle_helper(G, u, v, visited) elif parent != u: return True return False def has_cycle(G): V = len(G) visited = [False] * V for v in range(V): if has_cycle_helper(G, v, v, visited): return True return False
import unittest """ Diameter of a binary tree is number of nodes on longest path between any two leaves in the tree. Recursive definition of diameter = max(diameter of left subtree, diameter of right subtree, 1 + height of left subtree + height of right subtree). The first two cases are when diameter path does not include current node and third case is when diameter path includes current node. """ class Node: def __init__(self, data, left=None, right=None): self.data = data self.left = left self.right = right class BinaryTree: def __init__(self, root): self.root = root def diameter(self): return self.diameter_of_subtree(self.root)[0] def diameter_of_subtree(self, node): if node is None: return -float('inf'), 0 left_diameter, left_height = self.diameter_of_subtree(node.left) right_diameter, right_height = self.diameter_of_subtree(node.right) height = 1 + max(left_height, right_height) return max(left_diameter, right_diameter, 1 + left_height + right_height), height class TestBinaryTree(unittest.TestCase): def test_diameter(self): root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) binary_tree = BinaryTree(root) self.assertEqual(binary_tree.diameter(), 4)
import unittest """ Given an array A, find the size of longest bitonic subarray A[i...j] such that A[i] <= A[i+1] <= ... <= A[k] >= A[k+1] >= ... >= A[j-1] >= A[j] Input: 12 4 78 90 45 23 Output: 5 (4 78 90 45 23) """ """ Approach: 1. This is similar to finding max j-i such that a[j]>a[i] 2. Compute two auxiliary arrays: longest_increasing_ending_at_me and longest_decreasing_starting_from_me 3. Names should be self-explanatory. 4. Once we have these arrays, return the max among (longest_inc[i] + longest_dec[i] - 1) for all i. """ def find_longest_bitonic_array(list_of_numbers): longest_increasing_ending_at_me = [1] * len(list_of_numbers) longest_decreasing_starting_at_me = [1] * len(list_of_numbers) for i in range(1, len(list_of_numbers)): if list_of_numbers[i] >= list_of_numbers[i-1]: longest_increasing_ending_at_me[i] = longest_increasing_ending_at_me[i-1] + 1 for i in reversed(range(len(list_of_numbers) - 1)): if list_of_numbers[i] >= list_of_numbers[i+1]: longest_decreasing_starting_at_me[i] = longest_decreasing_starting_at_me[i+1] + 1 max_bitonic_size = 0 for i in range(len(list_of_numbers)): max_bitonic_size = max(max_bitonic_size, longest_increasing_ending_at_me[i] + longest_decreasing_starting_at_me[i]) return max_bitonic_size - 1 # since k gets counted twice class TestLongestBitonic(unittest.TestCase): def test_longest_bitonic(self): list_of_numbers = [12, 4, 78, 90, 45, 23] self.assertEqual(find_longest_bitonic_array(list_of_numbers), 5) list_of_numbers = [20, 4, 1, 2, 3, 4, 2, 10] self.assertEqual(find_longest_bitonic_array(list_of_numbers), 5) list_of_numbers = [10, 20, 30, 40] self.assertEqual(find_longest_bitonic_array(list_of_numbers), 4) reversed(list_of_numbers) self.assertEqual(find_longest_bitonic_array(list_of_numbers), 4) list_of_numbers = [10] self.assertEqual(find_longest_bitonic_array(list_of_numbers), 1)
import unittest """ Given an array of distinct integers, find the length of the longest subarray which contains numbers that can be arranged in a contiguous sequence. Input: 10 12 11 Output: 3 Input: 14 12 11 20 Output: 2 Input: 1 56 58 57 90 92 94 93 91 45 Output: 5 """ """ Approach: 1. Since all elements are distinct, the largest subarray with contiguous elements will have the following property: Difference between min and max in the subarray will be equal to last index - first index in subarray. 2. We scan from left to right, consider all subarrays starting at current index. 3. Time complexity is O(n^2). """ def longest_subarray_length_with_contiguous_numbers(list_of_numbers): max_subarray_len = -float('inf') end = len(list_of_numbers) for i in range(end-1): cur_min = list_of_numbers[i] cur_max = list_of_numbers[i] for j in range(i+1, end): cur_min = min([cur_min, list_of_numbers[j]]) cur_max = max([cur_max, list_of_numbers[j]]) if cur_max-cur_min == j-i: max_subarray_len = max([max_subarray_len, j-i+1]) return max_subarray_len class TestLongestSubarrayWithContiguousElements(unittest.TestCase): def test_longest_subarray(self): list_of_numbers = [1, 56, 58, 57, 90, 92, 94, 93, 91, 45] self.assertEqual(longest_subarray_length_with_contiguous_numbers(list_of_numbers), 5) list_of_numbers = [10, 12, 11] self.assertEqual(longest_subarray_length_with_contiguous_numbers(list_of_numbers), 3) list_of_numbers = [14, 12, 11, 20] self.assertEqual(longest_subarray_length_with_contiguous_numbers(list_of_numbers), 2)
import unittest """ Given two lists, generate all possible weaving of the lists such that the relative order is maintained. Input: [1, 2] and [3, 4] Output: [1, 2, 3, 4] [3, 4, 1, 2] [1, 3, 2, 4] [3, 1, 2, 4] [1, 3, 4, 2] [3, 1, 4, 2] """ def weaving(list1, list2): if len(list1) == 0: return [list2] if len(list2) == 0: return [list1] result = [] for l in weaving(list1[1:], list2): result.append([list1[0]] + l) for l in weaving(list1, list2[1:]): result.append([list2[0]] + l) return result class TestWeaving(unittest.TestCase): def test_weaving(self): list1 = [1, 2] list2 = [3] self.assertEqual(weaving(list1, list2), [[1, 2, 3], [1, 3, 2], [3, 1, 2]])
""" Given an array of length n, return the majority element - An element that occurs more than n/2 times. Input : 3 3 4 2 4 4 2 4 4 Output : 4 Input : 3 3 4 2 4 4 2 4 Output : None """ import unittest """ Approach 1: 1. Initialize a dictionary 2. If item not present, insert it with count = 1 3. If item already present, increment count by 1 4. If count > n/2 return item """ """ Approach 2: Moore's voting algorithm: 1. FindCandidate: 1.1 Initialize majority element as first element, set its count = 1 1.2 For each element equal to majority element, increment count by 1, else decrement count by 1 1.3 If count becomes zero, reinitialize majority element NOTE: For an element to be majority, it MUST occur consecutively in the array at least once!. This runs in linear time. 2. CheckMajority 2.1 Find the actual count of majority element and see if its > n/2 """ def moore_voting_find_candidate(list_of_numbers): majority_index = 0 count = 1 for i in range(1, len(list_of_numbers)): if list_of_numbers[i] == list_of_numbers[majority_index]: count += 1 else: count -= 1 if count == 0: majority_index = i count = 1 return list_of_numbers[majority_index] def moore_voting_check_majority(list_of_numbers, candidate): count = 0 threshold = len(list_of_numbers) / 2 for num in list_of_numbers: if num == candidate: count += 1 if count > threshold: return True return False def moore_voting_majority_element(list_of_numbers): candidate = moore_voting_find_candidate(list_of_numbers) if moore_voting_check_majority(list_of_numbers, candidate): return candidate else: return None class TestMajorityElement(unittest.TestCase): def test_moore_voting_majority_preset(self): list_of_numbers = [3, 3, 4, 2, 4, 4, 2, 4, 4] candidate = moore_voting_majority_element(list_of_numbers) self.assertEqual(candidate, 4) def test_moore_voting_majority_absent(self): list_of_numbers = [3, 3, 4, 2, 4, 4, 2, 4] candidate = moore_voting_majority_element(list_of_numbers) self.assertIsNone(candidate) if __name__ == '__main__': unittest.main()
import unittest """ Given a value N, if we want to make change for N cents, and we have an infinite supply of each S = {S1, S2, ..., Sm} valued coins, how many ways can we make the change? Input: N = 4, S = {1, 2, 3} Output: {1,1,1,1}, {1,1,2}, {2,2}, {1,3} so total 4 ways. """ def coin_change_2(N, S): num_denoms = len(S) # table[i][j] denotes number of ways to represent sum i using denominations S[0]...S[j] # table[N][num_denoms-1] stores the final result. table = [[0] * num_denoms for _ in range(N+1)] for j in range(num_denoms): table[0][j] = 1 for i in range(1, N+1): for j in range(num_denoms): # Number of ways to represent i = Number of ways to represent i including S[j] + # Number of ways to represent i excluding S[j] if i - S[j] >= 0: table[i][j] += table[i-S[j]][j] if j > 0: table[i][j] += table[i][j-1] return table[N][num_denoms-1] def coin_change(N, S): ways = [0]*(N+1) ways[0] = 1 for i in range(len(S)): for j in range(S[i], N+1): ways[j] += ways[j - S[i]] return ways[N] class TestCoinChange(unittest.TestCase): def test_coin_change(self): S = [3, 2, 1] N = 4 self.assertEqual(coin_change(N, S), 4)
""" Print the left view of binary tree. These are the nodes which are visible if binary tree is viewed from left direction. """ class Node: def __init__(self, data, left=None, right=None): self.data = data self.left = left self.right = right class BinaryTree: def __init__(self, root): self.root = root self.result = [] self.max_level = -1 def left_view(self): self.left_view_recursive(self.root, 0) return self.result def left_view_recursive(self, node, level): if not node: return if self.max_level < level: self.result.append(node.data) self.max_level = level self.left_view_recursive(node.left, level+1) self.left_view_recursive(node.right, level+1)
import unittest """ Given two strings, str and pat, find smallest substring in str containing all characters from pat. NOTE: Assume str and pat only contain ASCII characters. Input: str = "geeksforgeeks", pat = "ork" Output: "ksfor" """ """ Approach: 1. Use a sliding window. 2. Keep a count of each character in pat. 3. Now, scan str from left to right and increment count of current char in str. 4. If that char is present in pat too, then increment number of matches by 1. 5. If number of matches becomes equal to length of pat, we have found a window. 6. Try reducing size of window by removing extra characters from left. 7. Return best possible window size. """ def smallest_window(str, pat): if len(pat) == 0: return "" if len(pat) > len(str): return None pat_count = [0] * 256 str_count = [0] * 256 pat_length = len(pat) for i in range(pat_length): pat_count[ord(pat[i])] += 1 matches = 0 w_left = 0 start = -1 min_size = float('inf') for i in range(len(str)): str_count[ord(str[i])] += 1 if pat_count[ord(str[i])] >= str_count[ord(str[i])]: matches += 1 if matches == pat_length: while pat_count[ord(str[w_left])] == 0 or str_count[ord(str[w_left])] > pat_count[ord(str[w_left])]: str_count[ord(str[w_left])] -= 1 w_left += 1 cur_size = i - w_left + 1 if min_size > cur_size: min_size = cur_size start = w_left if start == -1: return None return str[start: start + min_size] class TestSmallestWindow(unittest.TestCase): def test_smallest_window(self): self.assertEqual(smallest_window("aaaacba", "ab"), "ba") self.assertEqual(smallest_window("geeksforgeeks", "ork"), "ksfor") self.assertEqual(smallest_window("xyz", "yxz"), "xyz") self.assertEqual(smallest_window("xyz", "xyz"), "xyz") self.assertEqual(smallest_window("xyz", ""), "") self.assertIsNone(smallest_window("xyz", "xyzzzzz")) self.assertIsNone(smallest_window("dbaac", "xyz")) self.assertEqual(smallest_window("this is a test string", "tist"), "t stri")
import unittest """ Given an array of positive and negative numbers in random order, rearrange the array elements so that positive and negative numbers are placed alternatively. If one type of numbers is more than half, the extra ones appear at end of array. Input: -1 2 -3 4 5 6 -7 8 9 Output: 9 -7 8 -3 5 -1 2 4 6 """ """ Approach: 1. Get all the positive numbers on one side. 2. Get all the negative numbers on other side. 3. Now swap every alternate negative number with next positive number. """ def rearrage_positive_and_negative(list_of_numbers): # Get all negative numbers before all positive numbers i = -1 for j in range(len(list_of_numbers)): if list_of_numbers[j] < 0: i += 1 list_of_numbers[i], list_of_numbers[j] = list_of_numbers[j], list_of_numbers[i] pos_index = i + 1 neg_index = 0 while neg_index < pos_index < len(list_of_numbers) and list_of_numbers[neg_index] < 0: list_of_numbers[pos_index], list_of_numbers[neg_index] = list_of_numbers[neg_index],\ list_of_numbers[pos_index] pos_index += 1 neg_index += 2 return list_of_numbers class TestRearrangement(unittest.TestCase): def test_rearrangement(self): result = [4, -3, 5, -1, 6, -7, 2, 8, 9] self.assertEqual(rearrage_positive_and_negative([-1, 2, -3, 4, 5, 6, -7, 8, 9]), result)
""" This Graph implementation maintains a vertex-indexed array of lists of integers. Every edge appears twice: if the edge connects v and w, then w appears in v's list and v appears in w's list. The second constructor reads a graph from an input stream, in the format V followed by E followed by a list of pairs of int values between 0 and V-1. """ class Graph: def __init__(self): self.V = 0 self.E = 0 self.adj = None def read_from_file(self, filename): with open(filename) as f: self.V = int(f.readline()) self.adj = [[] for x in xrange(self.V)] E = int(f.readline()) for i in xrange(E): next_edge = f.readline().split() v = next_edge[0] w = next_edge[1] self.add_edge(int(v), int(w)) def V(self): return self.V def E(self): return self.E def adj(self, v): return self.adj[v] def add_edge(self, v, w): self.adj[v].append(w) self.adj[w].append(v) self.E += 1 def degree(self, v): return len(self.adj[v]) def max_degree(self): return max([len(v) for v in xrange(self.V)]) def avg_degree(self): return 2 * self.E / self.V def __repr__(self): s = str(self.V) + ' vertices, ' + str(self.E) + ' edges\n' for v in xrange(self.V): s += str(v) + ': ' for w in self.adj[v]: s += str(w) + ' ' s += '\n' return s if __name__ == '__main__': graph = Graph() graph.read_from_file('tinyG.txt') print graph
import unittest """ Given a sorted array of positive numbers, find the smallest positive integer value that cannot be represented as sum of any subset of given array. Input: 1 3 6 10 11 15 Output: 2 Input: 1 1 1 1 Output: 5 Input: 1 1 3 4 Output: 10 Input: 1 2 5 10 20 40 Output: 4 Input: 1 2 3 4 5 6 Output: 22 """ """ Approach: 1. Scan the array from left to right. 2. Keep a running sum starting at 1 => the least possible outcome. 3. Let 'res' be the minimum sum that can be represented from arr[0...i-1] 4. At arr[i], we have two choice to make: NOTE: If c = a + b and a > 0 and b > 0, then it follows that c > a and c > b. That is, in order to represent a value as a sum of other values, the other values must be smaller than sum. (a) res is the final result: This is the case when arr[i] is bigger than res, we know res cannot be represented by numbers following arr[i] as they are all bigger than arr[i] (b) res is incremented by arr[i]: This happens when arr[i] <= res. If arr[0...i-1] can represent res-1, then arr[0...i] can represent arr[i] + res - 1. """ def find_smallest_integer_with_no_equivalent_sum(list_of_numbers): res = 1 end = len(list_of_numbers) for i in range(end): if list_of_numbers[i] <= res: res += list_of_numbers[i] else: return res return res class TestSmallestInteger(unittest.TestCase): def test_smallest_integer(self): list_of_numbers = [1, 3, 4, 5] self.assertEqual(find_smallest_integer_with_no_equivalent_sum(list_of_numbers), 2) list_of_numbers = [1, 2, 6, 10, 11, 15] self.assertEqual(find_smallest_integer_with_no_equivalent_sum(list_of_numbers), 4) list_of_numbers = [1, 1, 3, 4] self.assertEqual(find_smallest_integer_with_no_equivalent_sum(list_of_numbers), 10)
import unittest """ You are given a binary tree in which each node contains an integer value (which might be positive or negative) Design an algorithm to count the number of paths that sum to a given value. The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes). """ """ Approach: 1. The idea is to keep a running sum: sum of all nodes from root to current node. 2. Maintain a hashtable of running sum values, and increment the hashtable if running sum is already present. 3. Now, say we are looking for target_sum. Now, if running_sum - target_sum is present in hashtable, it means there is a path ending in current node, with sum = target_sum. Number of such paths = value in hashtable. 4. We recursively do this for left and right subtrees of current node. 5. Once, we have done exploring a node, we decrement running_sum value by 1 in the hashtable, since this node cannot be reached from any other node in the tree now, hence no need of keeping the path ending at it. """ class Node: def __init__(self, key, left=None, right=None): self.key = key self.left = left self.right = right def paths_with_sum_helper(node, running_sum, target_sum, table): if node is None: return 0 total_paths = 0 running_sum += node.key if running_sum in table: table[running_sum] += 1 else: table[running_sum] = 1 if running_sum - target_sum in table: total_paths = table[running_sum - target_sum] total_paths += paths_with_sum_helper(node.left, running_sum, target_sum, table) total_paths += paths_with_sum_helper(node.right, running_sum, target_sum, table) table[running_sum] -= 1 if table[running_sum] == 0: del table[running_sum] return total_paths def paths_with_sum(node, target_sum): table = dict() # needed if target_sum starts at root table[0] = 1 return paths_with_sum_helper(node, 0, target_sum, table) class TestPathsWithSum(unittest.TestCase): def test_paths_with_sum(self): root = Node(10) root.left = Node(5) root.left.left = Node(3) root.left.left.left = Node(3) root.left.left.right = Node(-2) root.left.right = Node(1) root.left.right.right = Node(2) root.right = Node(-3) root.right.right = Node(11) self.assertEqual(paths_with_sum(root, 8), 3)
import unittest """ Given a set of non-negative integers, and a value sum, determine if there is a subset of the given set with sum equal to given sum. Input: set: 3 34 4 12 5 2, sum: 9 Output: True (3,4,2) or (4,5) """ """ Approach: 1. Let isSubsetSum(set, n, sum) denote if there is a subset within set of n elements with sum = sum. 2. We can either include the last element in the subset or exclude it from the the subset. 3. This leads to below recursion: isSubsetSum(set, n, sum) = isSubsetSum(set, n-1, sum-set[n]) || isSubsetSum(set, n-1, sum) 4. This naive implementation has exponential runtime. 5. Let table[i][j] denote whether there is a subset with sum = i in set[0...j]. The final result is stored in table[sum][n]. """ def subset_sum(arr, sum): n = len(arr) table = [[False] * (n+1) for _ in range(sum+1)] for i in range(n+1): table[0][i] = True for i in range(1, sum+1): for j in range(1, n+1): table[i][j] = table[i][j-1] if i-arr[j-1] >= 0: table[i][j] = table[i-arr[j-1]][j-1] or table[i][j] return table[sum][n] def subset_sum2(arr, sum): n = len(arr) table = [False] * (sum + 1) table[0] = True for i in range(n): for j in range(sum, -1, -1): if table[j] and j + arr[i] <= sum: table[j + arr[i]] = True return table[sum] class TestSubsetSum(unittest.TestCase): def test_subset_sum(self): arr = [3, 34, 4, 12, 5, 2] sum = 9 self.assertTrue(subset_sum2(arr, sum)) sum = 10000 self.assertFalse(subset_sum2(arr, sum))
import unittest """ Given an input string and a dictionary of words, find out if the input string can be segmented into a space-separated sequence of dictionary words. Consider the following dictionary { i, like, sam, sung, samsung, mobile, ice, cream, icecream, man, go, mango} Input: ilike Output: Yes The string can be segmented as "i like". Input: ilikesamsung Output: Yes The string can be segmented as "i like samsung" or "i like sam sung". """ """ Approach: 1. The problem has the following optimal substructure: word_break(string, valid_words): n = len(string) for i in range(n): if string[:i] in valid_words and word_break(string[i+1:], valid_words): return True return False """ def word_break(string, valid_words): n = len(string) # table[i] is True if string[0...i] can be broken into sequence of dictionary words. # table[n-1] will store the final result. table = [False] * n for i in range(n): if not table[i] and string[:i+1] in valid_words: table[i] = True if table[i]: for j in range(i+1, n): if string[i+1:j+1] in valid_words: table[j] = True return table[n-1] class TestWordBreak(unittest.TestCase): def test_word_break(self): valid_words = ["mobile", "samsung", "sam", "sung", "man", "mango", "icecream", "and", "go", "i", "like", "ice", "cream"] string = 'samsungandmangok' self.assertFalse(word_break(string, valid_words)) string = 'ilikesamsung' self.assertTrue(word_break(string, valid_words)) string = 'iiiiiiii' self.assertTrue(word_break(string, valid_words)) string = 'ilikelikeimangoiii' self.assertTrue(word_break(string, valid_words)) string = 'samsungandmango' self.assertTrue(word_break(string, valid_words))
import random count1=0 count2=0 n = random.randint(1,100) print('''Welcome to the Banana Guessing Game Dave hid some bananas. Your task is to find out the number of bananas he hid. Players have to compete bewteen each other to see who can guess the number of bananas first!.''') while n>0: y=int(input("Player 1 input your guess:")) if y!=n: if (n-y)<10 and (y-n)<10: print("You are quite close. Try again!") count1=count1+1 elif (y-n)>10: print("Your guess is too high. Try again!") count1=count1+1 elif (n-y)>10: print("Your guess is too low. Try again!") count=count1+1 x=int(input("Player 2 input your guess:")) if x != n: if (n-y)<20 or (y-n)<20: print("You are quite close. Try again!") count2=count2+1 elif (x-n)>10: print("Your guess is too high. Try again!") count2=count2+1 elif (n-x)>10: print("Your guess is too low. Try again!") count2=count2+1 if y==n: print("Player 1 wins! You tried %d times!"%count1) break if x==n: print("Player 2 wins! You tried %d times!"%count2) break continue
a=[] y=0 while y<10: L=input("Please enter a word.\n") if L[0]=="A" or L[0]=="E" or L[0]=="I" or L[0]=="O" or L[0]=="U" or L[0]=="a" or L[0]=="e" or L[0]=="i" or L[0]=="o" or L[0]=="u": a.append(L) y=y+1 else: y=y+1 while y==10: print(a) break
#122. Best Time to Buy and Sell Stock II #Medium #5241 #2172 #Add to List #Share #You are given an integer array prices where prices[i] is the price of a given stock on the ith day. #On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day. #Find and return the maximum profit you can achieve. #Example 1: #Input: prices = [7,1,5,3,6,4] #Output: 7 #Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4. #Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3. #Total profit is 4 + 3 = 7. #Example 2: #Input: prices = [1,2,3,4,5] #Output: 4 #Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. #Total profit is 4. #Example 3: #Input: prices = [7,6,4,3,1] #Output: 0 #Explanation: There is no way to make a positive profit, so we never buy the stock to achieve the maximum profit of 0. #Constraints: #1 <= prices.length <= 3 * 104 #0 <= prices[i] <= 104 from typing import List def maxProfit(prices: List[int]) -> int: def maximumOfTwo(a: int, b: int): if(a>b): return a return b def maximumProfitInList(prices: List[int], startIndex: int, maxPrice: int, minPrice: int): if(maxPrice < prices[startIndex]): maxPrice = prices[startIndex] elif (minPrice > prices[startIndex]): if(startIndex + 1 < len(prices)): return maximumOfTwo((maxPrice - minPrice), (maxPrice - minPrice) + maximumProfitInList(prices, startIndex + 1, prices[startIndex], prices[startIndex])) else: if(startIndex + 1 < len(prices)): return maximumOfTwo((maxPrice - minPrice), (maxPrice - minPrice) + maximumProfitInList(prices, startIndex + 1, prices[startIndex], prices[startIndex])) if(startIndex+1 >= len(prices)): return maxPrice - minPrice return maximumOfTwo((maxPrice - minPrice), maximumProfitInList(prices, startIndex + 1, maxPrice, minPrice)) if(len(prices) == 0 or len(prices) == 1): return 0 return maximumProfitInList(prices, 1, prices[0], prices[0]) print(maxProfit([1,2,3,4,5])) print(maxProfit([7,6,4,3,1])) print(maxProfit([1, 7, 2, 3, 6, 7, 6, 7])) def maxProfitOptimal(prices: List[int]) -> int: def maximumOfTwo(a: int, b: int): if(a>b): return a return b def maximumProfitOptimal(prices: List[int]): minPrice = prices[0] profit = 0 for i in range(1,len(prices)): if(minPrice>prices[i]): minPrice = prices[i] else: profit = profit + (prices[i]-minPrice) minPrice = prices[i] return profit if(len(prices) == 0 or len(prices) == 1): return 0 return maximumProfitOptimal(prices) print(maxProfitOptimal([1,2,3,4,5])) print(maxProfitOptimal([7,6,4,3,1])) print(maxProfitOptimal([1, 7, 2, 3, 6, 7, 6, 7]))
x = 2 y = 3 x = y print(x) print(x==y) print(x>y) print(x<y) soma = x + y print(soma == x) print(soma == y) print(soma < y) print(soma > x)
from collections import deque def score(player): result = 0 i = 1 while player: x = player.pop() result += x * i i += 1 return result def play(p1, p2): while p1 and p2: a = p1.popleft() b = p2.popleft() if a > b: p1.append(a) p1.append(b) else: p2.append(b) p2.append(a) winner = p1 if p1 else p2 return score(winner) def play_recursive(p1, p2): played_rounds = set() while p1 and p2: config = f'{p1},{p2}' if config in played_rounds: return 1 played_rounds.add(config) a = p1.popleft() b = p2.popleft() if len(p1) >= a and len(p2) >= b: p1_copy = deque(list(p1)[:a]) p2_copy = deque(list(p2)[:b]) winner = play_recursive(p1_copy, p2_copy) if winner == 1: p1.append(a) p1.append(b) elif winner == 2: p2.append(b) p2.append(a) else: if a > b: p1.append(a) p1.append(b) else: p2.append(b) p2.append(a) return 1 if p1 else 2 def part1(deck1, deck2): player1 = deque(deck1) player2 = deque(deck2) print(play(player1, player2)) def part2(deck1, deck2): player1 = deque(deck1) player2 = deque(deck2) winner_num = play_recursive(player1, player2) if winner_num == 1: print(score(player1)) elif winner_num == 2: print(score(player2)) with open('../input/22.txt') as stream: decks = [] for deck in stream.read().split('\n\n'): cards = [int(x) for x in deck.split('\n')[1:]] decks.append(cards) part1(*decks) part2(*decks)
# The football.csv file contains the results from the English Premier League. # The columns labeled ‘Goals’ and ‘Goals Allowed’ contain the total number of # goals scored for and against each team in that season (so Arsenal scored 79 goals # against opponents, and had 36 goals scored against them). Write a program to read the file, # then print the name of the team with the smallest difference in ‘for’ and ‘against’ goals. import urllib2 import pandas as pd football_url = urllib2.urlopen('https://raw.githubusercontent.com/K-Du/dsp/master/python/football.csv') football_csv = pd.read_csv(football_url) # Find difference between Goals and Goals Allowed football_csv['Goals - Goals Allowed'] = abs(football_csv['Goals'] - football_csv['Goals Allowed']) # Sort the dataframe by "Goals - Goals Allowed" football_csv.sort_values(by = 'Goals - Goals Allowed', inplace = True) # Get the team name with smallest difference print football_csv.head(1)['Team'].iloc[0] # Answer is Aston Villa with a difference of 1 goal
import sys for query in sys.stdin: # Take query and process it query = query.strip().upper().split() # If length of query is 1 (so 1 search term) if len(query) == 1: genre_first = query[0] # genre1 is genre to search for with open('part3/movieInformation', 'r') as f: for line in f: line = line.strip() genre, movies = line.split('\t') if genre_first == genre: movies = movies.split('|') print(movies) # Otherwise ... else: genre_first, operator, genre_second = query first_set = second_set = None with open('part3/movieInformation', 'r') as f: for line in f: line = line.strip() genre, movies = line.split('\t') if genre_first == genre: movies = movies.split('|') first_set = set(movies) if genre_second == genre: movies = movies.split('|') second_set = set(movies) # Output set that fits the operator if operator == 'AND': # AND is the intersection of the sets print(first_set.intersection(second_set)) if operator == 'OR': # OR is the union of the sets print(first_set.union(second_set))
#O(n^2) time #O(1) space def bubblesort(lst): swapped=True size = len(lst) while swapped: swapped=False for i in xrange(size): if i+1<size and lst[i] and lst[i+1] and lst[i]>lst[i+1]: lst[i],lst[i+1]=lst[i+1],lst[i] swapped=True return lst if __name__ == '__main__': print bubblesort([4,2,1,3])
import unittest from typing import List from utility.tree_node import TreeNode class Solution: # Recursive solution def postorderTraversal_recursion(self, root: TreeNode) -> List[int]: result = [] if root is not None: if root.left is not None: left = self.postorderTraversal_recursion(root.left) result = result + left if root.right is not None: right = self.postorderTraversal_recursion(root.right) result = result + right result.append(root.val) return result # Recursive solution def postorderTraversal_iterative(self, root: TreeNode) -> List[int]: result: List[int] = [] if root is not None: iteration: List[(TreeNode, int)] = [] iteration.append((root, 0)) while(len(iteration) != 0): current_tuple: (TreeNode, int) = iteration.pop() if current_tuple[1] == 0: iteration.append((current_tuple[0], 1)) if current_tuple[0].left is not None: iteration.append((current_tuple[0].left, 0)) elif current_tuple[1] == 1: iteration.append((current_tuple[0], 2)) if current_tuple[0].right is not None: iteration.append((current_tuple[0].right, 0)) else: result.append(current_tuple[0].val) return result class SimpleTest(unittest.TestCase): # Returns True or False. def test(self): root = TreeNode(1, None, TreeNode( 2, TreeNode( 3, None, None ), None )) s = Solution() self.assertTrue([3, 2, 1] == s.postorderTraversal_recursion(root)) self.assertTrue([3, 2, 1] == s.postorderTraversal_iterative(root)) if __name__ == '__main__': unittest.main()
import random name = input("enter your name : ").title() print("Hello {} Welcome to Hangman Game".format(name)) print("Disclaimer: You need to guess the word within n+2 number of tries else you will lose the game where n is the length of the word") print("lets start playing!!!") words = ["apple","mango","orange","pomogranate","watermelon"] word = random.choice(words) attempt = len(word)+2 print("choosen word is having {} number of characters and its a fruit.".format(len(word))) guesses = "" while attempt > 0: guess = input("\nenter the alphabet:") guesses += guess set_g = set(guesses) set_w = set(word) if set_g.intersection(set_w) == set_w: yes = input("you left with {} attempts ,do you want to exit,press y:".format(attempt)) print("you won!!") exit() elif guess in word: for char in word: if char in guesses: print(char, end="") else: print("_", end="") attempt -= 1 elif guess not in word: print("Try again!! incorrect") continue attempt -= 1 elif attempt == 0: print("out of attempts")
''' Created on 2014. 4. 13. @author: Alice ''' def file_into_problem(file_name): problem = {} with open(file_name, 'r+') as f: case_number = int(f.readline()) problem['case_number'] = case_number problem['cases'] = [] for i in xrange(case_number): problem_text = f.readline() problem_float = [int(n) for n in problem_text.split()] problem['cases'].append(problem_float) return problem def solve_problem(problem): case_number = problem['case_number'] case_counter = 1 for case in problem['cases']: row = case[0] column = case[1] mines = case[2] field_size = row * column safty_zone = field_size - mines if field_size > 9 and safty_zone < 9: result_message = "Impossible" print "Case #%d:\n%s" % (case_counter, result_message) case_counter += 1 if __name__ == '__main__': p = file_into_problem('test c') print p solve_problem(p)
class Coffee: def __init__(self, hot_water, hot_milk, ginger_syrup, sugar_syrup, tea_leaves_syrup): self.hot_water = hot_water self.hot_milk = hot_milk self.ginger_syrup = ginger_syrup self.sugar_syrup = sugar_syrup self.tea_leaves_syrup = tea_leaves_syrup class HotTea: def __init__(self, hot_water, hot_milk, ginger_syrup, sugar_syrup, tea_leaves_syrup): self.hot_water = hot_water self.hot_milk = hot_milk self.ginger_syrup = ginger_syrup self.sugar_syrup = sugar_syrup self.tea_leaves_syrup = tea_leaves_syrup class Blacktea: def __init__(self, hot_water, ginger_syrup, sugar_syrup, tea_leaves_syrup): self.hot_water = hot_water self.ginger_syrup = ginger_syrup self.sugar_syrup = sugar_syrup self. tea_leaves_syrup = tea_leaves_syrup class Greentea: def __init__(self, hot_water, ginger_syrup, sugar_syrup, green_mixture): self.hot_water = hot_water self.ginger_syrup = ginger_syrup self.sugar_syrup = sugar_syrup self.green_mixture = green_mixture class Beverage: hot_coffee = Coffee(100, 400, 30, 50, 30) tea1 = HotTea(200, 100, 10, 10, 30) black_tea1 = Blacktea(300, 30, 50, 30) green_tea1 = Greentea(100, 30, 50, 30) # noinspection SpellCheckingInspection class Resources: def __init__(self): self.hot_water = 400 self.hot_milk = 540 self.ginger_syrup = 100 self.sugar_syrup = 100 self.tea_leaves_syrup = 100 self.green_mixture = 0 def prepare_coffee(self, coffee): """Checks enough resources for making coffee, if there are enough resources, it makes coffee""" hot_water = self.hot_water - coffee.hot_water hot_milk = self.hot_milk - coffee.hot_milk ginger_syrup = self.ginger_syrup - coffee.ginger_syrup sugar_syrup = self.sugar_syrup - coffee.sugar_syrup tea_leaves_syrup = self.tea_leaves_syrup - coffee.tea_leaves_syrup if hot_water < 0: print('Sorry, coffee cannot be prepared because not enough water!') elif hot_milk < 0: print('Sorry, coffee cannot be prepared because not enough milk!') elif ginger_syrup < 0: print('Sorry,coffee cannot be prepared because not enough ginger syrup!') elif sugar_syrup < 0: print('Sorry, coffee cannot be prepared because not enough sugar syrup!') elif tea_leaves_syrup < 0: print('Sorry, coffee cannot be prepared because not enough tea leaves syrup!') else: print('Coffee Prepared!') self.hot_water = hot_water self.hot_milk = hot_milk self.ginger_syrup = ginger_syrup self.sugar_syrup = sugar_syrup self.tea_leaves_syrup = tea_leaves_syrup def prepare_hot_tea(self, tea): """Checks enough resources for making coffee, if there are enough resources, it makes tea""" hot_water = self.hot_water - tea.hot_water hot_milk = self.hot_milk - tea.hot_milk ginger_syrup = self.ginger_syrup - tea.ginger_syrup sugar_syrup = self.sugar_syrup - tea.sugar_syrup tea_leaves_syrup = self.tea_leaves_syrup - tea.tea_leaves_syrup if hot_water < 0: print('Sorry, hot tea cannot be prepared beacause not enough water!') elif hot_milk < 0: print('Sorry, hot tea cannot be prepared beacause not enough milk!') elif ginger_syrup < 0: print('Sorry, hot tea cannot be prepared beacause not enough ginger syrup!') elif sugar_syrup < 0: print('Sorry, hot tea cannot be prepared beacause not enough sugar syrup!') elif tea_leaves_syrup < 0: print('Sorry, hot tea cannot be prepared beacause not enough tea leaves syrup!') else: print('Hot tea Prepared!') self.hot_water = hot_water self.hot_milk = hot_milk self.ginger_syrup = ginger_syrup self.sugar_syrup = sugar_syrup self.tea_leaves_syrup = tea_leaves_syrup def prepare_black_tea(self, black_tea): """Checks enough resources for making coffee, if there are enough resources, it makes black tea""" hot_water = self.hot_water - black_tea.hot_water ginger_syrup = self.ginger_syrup - black_tea.ginger_syrup sugar_syrup = self.sugar_syrup - black_tea.sugar_syrup tea_leaves_syrup = self.tea_leaves_syrup - black_tea.tea_leaves_syrup if hot_water < 0: print('Sorry, black tea cannot be prepared beacause not enough water!') elif ginger_syrup < 0: print('Sorry, black tea cannot be prepared beacause not enough ginger syrup!') elif sugar_syrup < 0: print('Sorry, black tea cannot be prepared beacause not enough sugar syrup!') elif tea_leaves_syrup < 0: print('Sorry, black tea cannot be prepared beacause not enough tea leaves syrup!') else: print('Black tea Prepared!') self.hot_water = hot_water self.ginger_syrup = ginger_syrup self.sugar_syrup = sugar_syrup self.tea_leaves_syrup = tea_leaves_syrup def prepare_greem_tea(self, green_tea): """Checks enough resources for making coffee, if there are enough resources, it makes green tea""" hot_water = self.hot_water - green_tea.hot_water ginger_syrup = self.ginger_syrup - green_tea.ginger_syrup sugar_syrup = self.sugar_syrup - green_tea.sugar_syrup green_mixture = self.green_mixture - green_tea.green_mixture if hot_water < 0: print('Sorry, Green tea cannot be prepared beacause not enough water!') elif ginger_syrup < 0: print('Sorry, Green tea cannot be prepared beacause not enough ginger syrup!') elif sugar_syrup < 0: print('Sorry, Green tea cannot be prepared beacause not enough sugar syrup!') elif green_mixture < 0: print('Sorry, Green tea cannot be prepared beacause not enough green tea mixture!') else: print('green tea prepared!') self.hot_water = hot_water self.ginger_syrup = ginger_syrup self.sugar_syrup = sugar_syrup self.green_mixture = green_mixture def make_coffee(self): """Asks the user what kind of coffee he wants and makes it""" choice = input('What do you want to buy? 1 - coffee, 2 - Hot tea, 3 - Black tea, 4- Green Tea, back - to main menu: ') if choice == '1': self.prepare_coffee(Beverage.hot_coffee) if choice == '2': self.prepare_hot_tea(Beverage.tea1) if choice == '3': self.prepare_black_tea(Beverage.black_tea1) if choice == '4': self.prepare_greem_tea(Beverage.green_tea1) def remaining(self): """Output current amount of resources""" print(f'The coffee machine has:') print(f'{self.hot_water} of water') print(f'{self.hot_milk} of milk') print(f'{self.ginger_syrup} of ginger syrup') print(f'{self.sugar_syrup} of sugar syrup') print(f'{self.tea_leaves_syrup} of tea leaves') print(f'{self.green_mixture} of green mixture') class CoffeeMachine: def __init__(self): self.cup_of_coffee = Beverage() self.resources = Resources() self.run_machine() def run_machine(self): """Basic program loop and processing user commands""" while True: action = input('Write action (buy, remaining, exit): ') print() if action == 'buy': self.resources.make_coffee() print() elif action == 'remaining': self.resources.remaining() print() elif action == 'exit': break machine = CoffeeMachine()
#!/usr/bin/python3 import sys import csv import twitter import time import random import configparser def parse_file(file_name): print(file_name) people = list() with open(file_name, 'r') as csvfile: reader = csv.reader(csvfile, delimiter=';') for line in reader: people.append(line) return people def wait(config): wait_time = random.randint(int(config['INFO']['min_time']), int(config['INFO']['max_time'])) #print("Choosing time between %d and %d - waiting %d seconds before next action" % (config['INFO']['min_time'], config['INFO']['max_time'], wait_time)) time.sleep(wait_time) def follow_people(api, people, config): #print(people) count_followed = 0 total_people = len(people) print('Going to follow %d people (this is going to take between %d and %d seconds to complete)' % (total_people, int(config['INFO']['min_time']) * total_people, int(config['INFO']['max_time']) * total_people)) for i in range(total_people): account_name = people[i] try: person = api.CreateFriendship(screen_name=people[i]) print(account_name, 'has been followed') count_followed += 1 except twitter.error.TwitterError as e: print('error for ', account_name, e) pass #Just to be safe and avoid receiving 40X from twitter's API wait(config) print(count_followed, 'people out of ', total_people, 'have been followed') def main(): try: config = configparser.ConfigParser() config.read(['config.cfg', 'config.local.cfg']) api = twitter.Api(consumer_key=config['TWITTER']['consumer_key'], consumer_secret=config['TWITTER']['consumer_secret'], access_token_key=config['TWITTER']['access_token_key'], access_token_secret=config['TWITTER']['access_token_secret']) if len(sys.argv) > 1: people = parse_file(sys.argv[1]) follow_people(api, people, config) else: print('Usage: python follow_people_on_twitter.py people_to_follow.csv') except Exception as e: print('error', e) if __name__ == "__main__": main()
# 나이순 정렬 [ 티어 : 실버 5 ] # https://www.acmicpc.net/problem/10814 from sys import stdin N = int(stdin.readline()) member_list = [] for _ in range(N): age, name = map(str, stdin.readline().split()) member_list.append((int(age), name)) member_list.sort(key = lambda member: (member[0])) for member in member_list: print(member[0], member[1])
# age = 18 # name = 'bxl' # print('{0} was {1} yeas old'.format(name,age)) # print('string must in "" by {0}'.format(name)) # printStr=name+'is'+str(age)+'yeas old' # print(printStr) # print('{0:.5f}'.format(1/6),end='this is end') # print('{0:-^18}'.format('9')) # i = 5 # print('{0}'.format(i)) # i = i+1 # print(i) s = '''abcd efg''' for x in s: print(x,end='') print('<hr>') s = '''abcd efg ''' for x in s: print(x,end='')
import numpy def survival_curve_from_lifespans(lifespans, uncertainty_interval=0): """Produce a survival curve from a set of lifespans with optional uncertainty. If no uncertainty interval is provided, produce a standard, stair-step survival curve (which indicates infinite precision in when the time of death is known). Alternately, if an uncertainty interval is provided, it is assumed that the provided lifespan is actually +/- half of the interval. (e.g. If lifespans were assayed every 5 hours, provide 5 as the uncertainty interval and give the single lifespan as the midpoint of the interval.) In this case a non-stair- step plot is produced to reflect a uniform distribution of possible death times in that interval. This latter mode is generally preferable. Parameters: lifespans: list of point estimates of the lifespans of individuals in a population. This should be the middle of the interval between lifespan measurements. uncertainty_interval: Length of time between lifespan measurements. Returns: t, f t: timepoints f: fraction alive at each timepoint (1 to 0) """ if uncertainty_interval > 0: lifespans = numpy.asarray(lifespans) half_interval = uncertainty_interval / 2 return survival_curve_from_intervals(lifespans - half_interval, lifespans + half_interval) else: timepoints = [0] fraction_alive = [1] step = 1/len(lifespans) for lifespan in sorted(lifespans): last_frac = fraction_alive[-1] timepoints.extend([lifespan, lifespan]) fraction_alive.extend([last_frac, last_frac-step]) return timepoints, fraction_alive def survival_curve_from_intervals(last_alives, first_deads): """Produce a survival curve from a set of (last_alive, first_dead) timepoints. This function produces a survival curve for a population of individuals, using two timepoints per individual: the last known time the individual was alive, and the first known time it was dead. Curves plotted in this fashion do not have the stairstep shape of curves with point estimates of lifespans; moreover these curves more accurately represent the uncertainty of death times. Parameters: last_alives, first_deads: lists containing the last-known-alive timepoint and first-know-dead timepoint for each individual in the population. Returns: t, f t: timepoints f: fraction alive at each timepoint (1 to 0) """ last_alives = list(last_alives) first_deads = list(first_deads) assert len(first_deads) == len(last_alives) timepoints = sorted([0] + last_alives + first_deads) number_alive = numpy.zeros(len(timepoints), float) # for each individual, construct a curve that is 1 before last_alive, # 0 after first_dead, and linear in between, and get the value of that # curve at every timepoint that will be in the final curve. # We then sum up all of these curves to get the total survival curve for last_alive, first_dead in zip(last_alives, first_deads): number_alive += numpy.interp(timepoints, [last_alive, first_dead], [1, 0]) fraction_alive = number_alive / len(last_alives) return timepoints, fraction_alive
import numpy def weighted_mean_and_std(x, w): """Return the mean and standard deviation of the data points x, weighted by the weights in w (which do not need to sum to 1).""" w = numpy.array(w, dtype=float) w /= w.sum() x = numpy.asarray(x) weighted_mean = (w*x).sum() squared_diff = (x - weighted_mean)**2 weighted_var = (w * squared_diff).sum() return weighted_mean, numpy.sqrt(weighted_var) def weighted_mean(x, w): """Return the mean of the data points x, weighted by the weights in w (which do not need to sum to 1).""" w = numpy.array(w, dtype=float) w /= w.sum() x = numpy.asarray(x) return (w*x).sum() def _gaussian(x, mu=0, sigma=1): return (1/numpy.sqrt(2 * numpy.pi * sigma**2) * numpy.exp(-0.5 * ((numpy.asarray(x)-mu)/sigma)**2)) def gaussian_mean(x, y, p, std=1): """Given a set of positions x where values y were observed, calculate the gaussian-weighted mean of those values at a set of new positions p, where the gaussian has a specied standard deviation. """ return numpy.array([weighted_mean(y, _gaussian(x, mu=pp, sigma=std)) for pp in p]) def savitzky_golay(data, kernel=11, order=4): """Apply Savitzky-Golay smoothing to the input data. http://en.wikipedia.org/wiki/Savitzky-Golay_filter """ kernel = abs(int(kernel)) order = abs(int(order)) if kernel % 2 != 1 or kernel < 1: raise TypeError("kernel size must be a positive odd number, was: %d" % kernel) if kernel < order + 2: raise TypeError("kernel is to small for the polynomals\nshould be > order + 2") order_range = range(order+1) half_window = (kernel-1) // 2 m = numpy.linalg.pinv([[k**i for i in order_range] for k in range(-half_window, half_window+1)])[0] window_size = len(m) half_window = (window_size-1) // 2 offsets = range(-half_window, half_window+1) offset_data = list(zip(offsets, m)) smooth_data = list() data = numpy.concatenate((numpy.ones(half_window)*data[0], data, numpy.ones(half_window)*data[-1])) for i in range(half_window, len(data) - half_window): value = 0.0 for offset, weight in offset_data: value += weight * data[i + offset] smooth_data.append(value) return numpy.array(smooth_data) def lowess(x, y, f=2/3., iters=3, outlier_threshold=6, weights=None, degree=1): """Apply LOWESS to fit a nonparametric regression curve to a scatterplot. http://en.wikipedia.org/wiki/Local_regression Parameters: x, y: 1-d arrays containing data points in x and y. f: smoothing parameter in range [0, 1]. Lower values = less smoothing. iter: number of robustifying iterations (after each of which outliers are detected and excluded). Larger numbers = more robustness, but slower run-time. outlier_threshold: data points that are further from the lowess estimate than outlier_threshold * numpy.median(numpy.abs(residuals)) are declared outliers. degree: degree of locally weighted fit. Generally 1 is fine, though for data with local minima/maxima, degree=2 may fit better. Returns: array of smoothed y-values for the input x-values. """ x = numpy.asarray(x) y = numpy.asarray(y) r = max(4, int(numpy.ceil(f*(len(x)-1)))) # below hogs RAM for large input, without much speed gain. # h = [numpy.sort(numpy.abs(x - xv))[r] for xv in x] # w = numpy.clip(numpy.abs(numpy.subtract.outer(x, x) / h), 0, 1) # w = (1 - w**3)**3 delta = 1 max_dists = numpy.empty_like(x) if weights is None: weights = 1 for it in range(iters): y_est = [] for i, xv in enumerate(x): # for xv, wv in zip(x, w.T): x_dists = numpy.abs(x - xv) if it == 0: max_dist = numpy.partition(x_dists, r)[r] max_dists[i] = max_dist else: max_dist = max_dists[i] wv = numpy.clip(x_dists/max_dist, 0, 1) wv = (1 - wv**3)**3 final_weights = delta * wv * weights if degree > 1: poly = numpy.poly1d(numpy.polyfit(x, y, degree, w=final_weights)) y_est.append(poly(xv)) else: # faster to hard-code weighted linear regression formula weighted_x = final_weights * x b1 = numpy.dot(final_weights, y) b2 = numpy.dot(weighted_x, y) A11 = numpy.sum(final_weights) A12 = A21 = numpy.sum(weighted_x) A22 = numpy.dot(weighted_x, x) # solve linear system A*beta = b where A = [[A11, A12], [A21, A22]] and b = [b1, b2] determinant = A11 * A22 - A12 * A21 beta1 = (A22*b1 - A12*b2) / determinant beta2 = (A11*b2 - A21*b1) / determinant y_est.append(beta1 + beta2 * xv) y_est = numpy.array(y_est) residuals = y - y_est s = numpy.median(numpy.abs(residuals)) if s > 0: delta = numpy.clip(residuals / (outlier_threshold * s), -1, 1) delta = (1 - delta**2)**2 return numpy.array(y_est) def robust_polyfit(x, y, degree=2, iters=3): """Fit a polynomial to scattered data, robust to outliers. Parameters: x, y: 1-d arrays containing data points in x and y. degree: degree of the polynomial to fit. iter: number of robustifying iterations (after each of which outliers are detected and excluded). Larger numbers = more robustness, but slower run-time. Returns: polynomial coefficients, array of smoothed y-values for the input x-values. """ x, y = numpy.asarray(x), numpy.asarray(y) weights = numpy.ones(len(x), float) # delta in original formulation for _ in range(iters): cs = numpy.polynomial.polynomial.polyfit(x, y, degree, w=weights) y_est = numpy.polynomial.polynomial.polyval(x, cs) residuals = y - y_est s = numpy.median(numpy.abs(residuals)) if s > 0: weights = (residuals / (6 * s)).clip(-1, 1) weights = (1 - weights**2)**2 return cs, y_est
import numpy import itertools def fit_polynomial(image, mask=None, degree=2, poly_args=None): """Return an array containing the values of a polynomial fit to the input. Parameters: image: 2D array. mask: if specified, use only the values in the image at points where the mask is true degree: degree of the fit polynomial in x and y poly_args: if not None, must have been generated by get_poly_args(). Useful when multiple images of the same shape are to be fit to a polynomial so the poly_args array does not need to be recalculated. """ image = numpy.asarray(image) shape = image.shape if poly_args is None: poly_args = get_poly_args(shape, degree) if mask is not None: mask = numpy.asarray(mask, dtype=bool) if not numpy.any(mask): return numpy.zeros_like(image) a = poly_args[mask, :] b = image[mask] else: a = poly_args.reshape((shape[0]*shape[1], poly_args.shape[-1])) b = image.ravel() # solve ax = b, where a contains the polynomial expansion of the spatial positions # of the image samples, and b contains the image samples coefficients, residues, rank, singval = numpy.linalg.lstsq(a, b) output = (poly_args * coefficients).sum(axis=-1) return output def subtract_background(image, mask=None, degree=2): """Fit the input to a low-order polynomial to approximate the background and then subtract that from the image. See fit_polynomial() for further details. Note: effectively a high-pass filter. """ background = fit_polynomial(image, mask, degree) sub = (image - background).clip(0, numpy.inf) return sub.astype(image.dtype) def get_poly_args(shape, degree): """Return an array containing the arguments for a polynomial in x and y defined over an array of the given shape. Let 'binomial(degree)' refer to the number of parameters of a polynomial function of the given degree. Then the output shape = (shape[0], shape[1], binomial(degree)) Example: let degree = 2, and let x, y = numpy.indices(shape) result = get_poly_args(shape, degree) result[:,:,0] == 1 result[:,:,1] == x result[:,:,2] == y result[:,:,3] == x*x result[:,:,4] == x*y result[:,:,5] == y*y """ x, y = numpy.indices(shape) poly_args = [numpy.ones(shape)] for i in range(1, degree+1): for v in itertools.combinations_with_replacement([x, y], i): poly_args.append(numpy.prod(v, axis=0)) poly_args = numpy.array(poly_args) # shape = binomial(degree), shape[0], shape[1] poly_args = poly_args.transpose((1,2,0)) # shape = shape[0], shape[1], binomial(degree) return poly_args
import collections import numpy from scipy.stats import kde from skimage import measure def density_at_points(data): """Use KDE to calculate the probability density at each point in a dataset. Useful for coloring points in scatterplot by the density, to better help visualize crowded regions of the plot. Parameter: data: array of shape (n_data_points, n_dimensions) Returns: densities: array of shape (n_data_points) Example: import numpy import matplotlib.pyplot as plt # prepare some data mode1 = numpy.random.multivariate_normal(mean=[0, 0], cov=[[4, 1], [1, 7]], size=300) mode2 = numpy.random.multivariate_normal(mean=[8, 8], cov=[[2, 1], [1, 1]], size=300) data = numpy.concatenate([mode1, mode2], axis=0) # calculate the contours density = density_at_points(data) # plot the data plt.scatter(data[:,0], data[:,1], s=12, c=density, cmap='inferno') """ data = numpy.asarray(data) kd = kde.gaussian_kde(data.T) return kd(data.T) ContourResult = collections.namedtuple('ContourResult', ('density', 'extent', 'c_level', 'contours')) def contour(data, fraction, fraction_of='density', samples_x=100, samples_y=100): """Calculate contours that enclose a given fraction of the input data. Use KDE to estimate the density of a scattered 2D dataset, and calculate from that the contours of the density function which enclose a given fraction of the total density, or a given fraction of the input data points. By design, KDE places density beyond the data points. Thus a contour containing a specified fraction of the density will be larger than a contour containing the same fraction of the data points. Indeed, the former contour may well contain rather more of the data points. One or more input fractions may be provided. As the density function may be multimodal, more than one contour may be returned for each input fraction. Parameters: data: 2D dataset, of shape (n_points, 2) fraction: a single value in the range (0, 1), or an array of the same. fraction_of: either 'density' or 'points' (see above). samples_x, samples_x: resolution of the x, y grid along which to estimate the data density. Returns: density: array of shape (samples_x, samples_y) containing density estimates. (Will not sum to one, as these are point estimates at the centers of each pixel, not the integral over each pixel's area.) extent: tuple (xmin, xmax, ymin, ymax) that represents the spatial extent of the density array. c_level: level or a list of levels if multiple fractions were provided. If fraction_of='density', the following approximates each fraction: density[density >= c_level].sum() / density.sum() If fraction_of='points', the following approximates each fraction: (data_density >= c_level).sum() / len(data_density) Where data_density is the KDE estimate of the density at each data point. (The function density_at_points can calculate this.) contours: a list of contours (if a single value is provided for fraction) or a list of lists of contours (one list for each fraction). Each contour is an array of shape (n_points, 2). Examples: import numpy import matplotlib.pyplot as plt # prepare some data mode1 = numpy.random.multivariate_normal(mean=[0, 0], cov=[[4, 1], [1, 7]], size=300) mode2 = numpy.random.multivariate_normal(mean=[8, 8], cov=[[2, 1], [1, 1]], size=300) data = numpy.concatenate([mode1, mode2], axis=0) # calculate the contours density, extent, c_level, contours = contour(data, [0.25, 0.5]) # plot the data plt.scatter(data[:,0], data[:,1], s=12, color='blue') # plot the density (note imshow expects images to have shape (y, x)...) plt.imshow(density.T, extent=extent, origin='lower') # plot the contours for the fractions 0.25 and 0.5 for level_contours, color in zip(contours, ['red', 'orange']): # there may be several contours for each level for c in level_contours: plt.plot(c[:,0], c[:,1], color=color) """ data = numpy.asarray(data) assert data.ndim == 2 and data.shape[1] == 2 fraction = numpy.asarray(fraction) orig_dim = fraction.ndim if orig_dim == 0: fraction = fraction.reshape(1) assert numpy.all((fraction > 0) & (fraction < 1)) assert fraction_of in ('density', 'points') # now calculate the spatial extent over which to get the KDE estimates of # the density function. # We must extend the mins and maxes a bit because KDE puts weight all around # each data point. So to get close to the full density function, we need to # evaluate the function a little ways away from the extremal data points. maxes = data.max(axis=0) mins = data.min(axis=0) extra = 0.2 * (maxes - mins) maxes += extra mins -= extra xmax, ymax = maxes xmin, ymin = mins # make a grid of points from the min to max positions in two dimensions indices = numpy.mgrid[xmin:xmax:samples_x*1j, ymin:ymax:samples_y*1j] kd = kde.gaussian_kde(data.T) # now flatten the grid to a list of (x, y) points, evaluate the density, # and expand back to a grid. density = kd(indices.reshape(2, samples_x * samples_y)).reshape(samples_x, samples_y) if fraction_of == 'density': # find density levels where a given fraction of the total density is above # the level. density_values = numpy.sort(density.flat) density_below_value = density_values.cumsum() total_density = density_below_value[-1] # we now have a mapping between density values and the total amount of density # below that value. To find the desired density levels (where a given fraction # of the total density is above that level), just use that mapping: c_levels = numpy.interp((1-fraction)*total_density, density_below_value, density_values) else: # find density levels where a given fraction of the input data points are # above the level data_density = kd(data.T) c_levels = numpy.percentile(data_density, (1-fraction)*100) # now find the contours in the density array at the desired levels contours = [] for c_level in c_levels: level_contours = measure.find_contours(density, c_level) # The contours are in units of the indices into the density array. # Scale these to the the spatial extent of the data for rc in level_contours: rc /= [samples_x, samples_y] # first scale to [0, 1] in each dim rc *= (maxes - mins) # then scale out to the desired min and max rc += mins contours.append(level_contours) if orig_dim == 0: contours = contours[0] c_levels = c_levels[0] extent = [xmin, xmax, ymin, ymax] return ContourResult(density, extent, c_levels, contours)
# Create a function that will take all your coins and convert it to the cash amount. # The function should look at each key (pennies, nickels, dimes and quarters) and perform the appropriate math on the integer value to determine how much money you have in dollars. Store that value in a variable named `dollarAmount` and print it. def calc_dollars(**coins): cash_total = 0 for key, value in coins.items(): if key == "pennies": cash_total += value*.01 if key == "nickels": cash_total += value*.05 if key == "dimes": cash_total += value*.10 if key == "quarters": cash_total += value*.25 print(cash_total) calc_dollars(pennies= 342, nickels=9, dimes=32, quarters=4)
from turtle import Turtle, goto import turtle class Scoreboard(Turtle): def __init__(self): super().__init__() self.points = 0 self.pu() self.color("white") self.speed("fastest") self.goto(0, 280) self.ht() self.write(f"Score = {self.points}", align = "center", font = ("Arial", 15, "normal")) def score(self): self.clear() self.points += 1 self.write(f"Score = {self.points}", align = "center", font = ("Arial", 15, "normal")) def game_over(self): self.goto(0,0) self.write(f"GAME OVER", align = "center", font = ("Arial", 15, "normal"))
#-*- coding: utf-8 -*- # 2016-2017 Programacao 1 (LTI) # Grupo 60 # 43558 Nuno Amaral Soares # 50021 Bruno Miguel da Silva Machado from dateTime import * from constants import * def createHeader (day, time, type): """ Creates a header for an output file, according to the project's specification Requires: day is a string in the DD:MM:YY format with the update date time is a string in the HH:MM format with the update hour type refers if the header is for a Schedule or Translators file Ensures: a string equal to the pretended header, according to the project's specification and respective to the given day and time """ header = "Company:\nReBaBel\nDay:\n" header += day #adds the day header += "\nTime:\n" header += time #adds the time if type == "schedule": header += "\nSchedule:" elif type == "translators": header += "\nTranslators:" return header def writeScheduleFile(tasksAssigned, file_name, header): """Writes a collection of services into a file. Requires: tasksAssigned is a list with the structure as in the output of scheduling.scheduleTasks representing the translation tasks assigned; file_name is a str with the name of a .txt file; header is a string with a header, as in the examples provided in the general specification (omitted here for the sake of readability). Ensures: writing of file named file_name representing the list of translation tasks in tasksAssigned prefixed by header and organized as in the examples provided in the general specification (omitted here for the sake of readability); the listing in this file keeps the ordering top to bottom of the translations tasks as ordered head to tail in tasksAssigned. """ outfile = open(file_name, 'w') headerlist = header.split('\n') for line in headerlist: outfile.writelines(line + '\n') for task in tasksAssigned: for i in range(0,len(task)): task[i] = str(task[i]) for task in tasksAssigned: string = ', '.join(task) + '\n' outfile.writelines(string) outfile.close() def writeTranslatorsFile(translatorsUpdated, file_name, header): """ Writes the translators information from the translators dictionary into a file. Requires: translatorsUpdated is the updated translator dictionary. file_name is a str with the name of a .txt file; header is a string with a header, as in the examples provided in the general specification (omitted here for the sake of readability). Ensures: writing of file named file_name representing the updated information about each translator from the updated translators dictionary (translatorsUpdated) prefixed by header and organized as in the examples provided in the general specification (omitted here for the sake of readability); """ outfile = open(file_name, 'w') headerlist = header.split('\n') for line in headerlist: outfile.writelines(line + '\n') names = sorted(translatorsUpdated) for name in translatorsUpdated: for i in range(0, len(translatorsUpdated[name])): translatorsUpdated[name][i] = str(translatorsUpdated[name][i]) for name in names: string = name + ', ' + ', '.join(translatorsUpdated[name]) + '\n' outfile.writelines(string) outfile.close()
import time # Code by Matthew Freeman # Use python 3 to run class lfsr: # Class implementing linear feedback shift register. # This class helps produce psedo random numbers. # algorithim was found here: https://www.maximintegrated.com/en/design/technical-documents/app-notes/4/4400.html def __init__(self, taps): # Receives a list of taps. Taps are the bit positions that are XOR-ed # together and provided to the input of lfsr self.taps = taps # initial state of lfsr self.register = '1111111111111111' # following methods converts integers to binary strings and vice-versa #-------------------------------------------------------- def int_to_bin(self, i): o = '{0:b}'.format(i) return o def bin_to_int(self, b): return int(b, 2) #-------------------------------------------------------- def clock(self, bit): # Receives input bit and simulates one clock cycle # This xors bits then shifts and returns output bit # input bit are XOR-ed with the taps res = int(self.register[self.taps[0]]) for m in range(1, len(self.taps)): tap = self.taps[m] res = res ^ int(self.register[tap]) res = str(res ^ int(bit)) o = self.register[len(self.register) - 1] self.register = res + self.register[:-1] return o # returns output bit def seed(self, s): # This function seeds the lfsr by feeding all bits from s into clock s = self.int_to_bin(s) for i in s: self.clock(i) def get_output(self, n, skip=0): # This function clocks lfsr 'skip' number of cycles, # then clocks 'n' cycles more and records the output. Then returns # the output as an int. for x in range(skip): self.clock("0") out = '' for x in range(n): out += self.clock("0") out = self.bin_to_int(out) return out def get_random_int(self, min, max): # This function returns a psedo random integer using the lfsr # It takes a min integer and a max integer, and uses 1000 skips, then 1000 bits out = self.get_output(1000, 1000) out = out % (max - min + 1) out += min return out if __name__ == "__main__": l = lfsr([2, 4, 5, 7, 11, 14]) l.seed(int(time.time())) # seeds to time to make output appear more random print(l.get_random_int(-1000, 1000)) # prints a random integer between -1000 and 1000
# PROBLEM 1: PAYING THE MINIMUM def interest_rate(balance, annualInterestRate, monthlyPaymentRate): """ balance = balance of the payment annualInterestRate = self-explaining monthlyPaymentRate = self-explaining """ monthlyInterestRate = (annualInterestRate/12.0) totalPaid = 0 totalBalance = 0 unpaidBalance = balance for i in range(1, 13): minMonthlyPayment = monthlyPaymentRate*unpaidBalance monthlyUnpaidBalance = unpaidBalance - minMonthlyPayment updatedBalanceEachMonth = monthlyUnpaidBalance + (monthlyUnpaidBalance * monthlyInterestRate) unpaidBalance = updatedBalanceEachMonth totalPaid += minMonthlyPayment totalBalance += updatedBalanceEachMonth minMonthlyPayment = round(minMonthlyPayment, 2) updatedBalanceEachMonth = round(updatedBalanceEachMonth, 2) monthlyUnpaidBalance = round(monthlyUnpaidBalance, 2) print ("Month: " + str(i)) print ("Minimum monthly payment: " + str(minMonthlyPayment)) print ("Remaining balance: " + str(updatedBalanceEachMonth)) totalPaid = round(totalPaid, 2) print ("Total paid: " + str(totalPaid)) print ("Remaining balance: " + str(updatedBalanceEachMonth)) # PROBLEM 2: PAYING DEBT OFF IN A YEAR minPayment = 0 unpaidBalance = 1 while unpaidBalance > 0: minPayment += 10 unpaidBalance = balance for month in range (1, 13): unpaidBalance = (unpaidBalance - minPayment) *(1+annualInterestRate/12.0) print "Lowest payment:", minPayment # PROBLEM 3: USING BISECTION SEARCH TO MAKE THE PROGRAM FASTER low = balance / 12.0 high = (balance * (1 + annualInterestRate / 12.0)**12) / 12.0 epsilon = 0.01 minPayment = (high + low) / 2.0 unpaidBalance = balance for month in range(1, 13): unpaidBalance = (unpaidBalance - minPayment) * (1 + annualInterestRate / 12.0) while abs(unpaidBalance) > epsilon: if unpaidBalance < 0: high = minPayment else: low = minPayment minPayment = (high + low) / 2.0 unpaidBalance = balance for month in range(1, 13): unpaidBalance = (unpaidBalance - minPayment) * (1 + annualInterestRate / 12.0) print "Lowest Payment:", round(minPayment, 2)