def record(conString,curs): end=False while end==False: ticket_no =input("Enter ticket number :") vehicle_id = input("Enter vehicle ID :") exist2 =P1.searchSerial(vehicle_id, curs) if not exist2: print("The vehicle is not registered. Please register first") P1.regV(conString) violator_no = input("Enter violator :") exist1 = P1.searchSin(violator_no, curs) if not exist1: print("The person is not registered. Please register first") P3.regPerson(conString,curs,violator_no) office_no = input("Enter officer ID :") vtype = input("Enter violation type:") vdate = input("Enter violation date (DD-Month-YY):") place = input("Enter place :") description = input("Enter description :") print("Ticket number: "+ticket_no+" Violator: "+violator_no+" Vehicle ID: "+vehicle_id+" Officer number: "+office_no+" Violation type: "+vtype+"Date: "+vdate+" Place: "+place+" Description: "+description) answer = input("If these information are correct, please enter y. If you want to re-enter, please enter n:") if answer=='y' or answer=='Y': end=True statement = "insert into ticket values ('"+ticket_no+"','"+violator_no+"','"+vehicle_id+"','"+office_no+"','"+vtype+"','"+vdate+"','"+place+"','"+description+"')" return statement
def __init__( self, num_boids, ff, center=P3.P3(0, 0, 0), radius=20 ): #possibly also orientation, maybe something about obstacles? Flock.flock_count += 1 self.boids = [] self.distance_matrix = [[0 for _ in range(num_boids)] for _ in range(num_boids)] self.ff = ff # randomly distributes boids in circle on xy plane using center and radius for i in range(num_boids): r = radius * math.sqrt(random.random()) theta = 2 * math.pi * random.random() x = r * math.cos(theta) y = r * math.sin(theta) # eventually velocity is taken from config file v = P3.P3(1 * random.random() * random.randrange(-1, 2, 2) + 5, 1 * random.random() * random.randrange(-1, 2, 2) + 5, 0) self.boids.append( Boid.Boid( self, i, P3.P3(x, y, 0) + center + P3.P3(0, 0, 2 * random.randrange(-5, 6, 10)), v, Behavior.behavior)) self.update_dist_matrix()
def record(conString, curs): end = False while end == False: ticket_no = input("Enter ticket number :") vehicle_id = input("Enter vehicle ID :") exist2 = P1.searchSerial(vehicle_id, curs) if not exist2: print("The vehicle is not registered. Please register first") P1.regV(conString) violator_no = input("Enter violator :") exist1 = P1.searchSin(violator_no, curs) if not exist1: print("The person is not registered. Please register first") P3.regPerson(conString, curs, violator_no) office_no = input("Enter officer ID :") vtype = input("Enter violation type:") vdate = input("Enter violation date (DD-Month-YY):") place = input("Enter place :") description = input("Enter description :") print("Ticket number: " + ticket_no + " Violator: " + violator_no + " Vehicle ID: " + vehicle_id + " Officer number: " + office_no + " Violation type: " + vtype + "Date: " + vdate + " Place: " + place + " Description: " + description) answer = input( "If these information are correct, please enter y. If you want to re-enter, please enter n:" ) if answer == 'y' or answer == 'Y': end = True statement = "insert into ticket values ('" + ticket_no + "','" + violator_no + "','" + vehicle_id + "','" + office_no + "','" + vtype + "','" + vdate + "','" + place + "','" + description + "')" return statement
def __init__(self, flock, id, position, vel, acc=P3.P3(0, 0, 0)): self.id = id # holding a unique identifying int self.position = position # P3 holding the position or (x, y, z) of the boid self.vel = vel # P3 holding the velosities of the boid self.acc = acc # Float holding the acceleration self.flock = flock # Current flock holding boid object
def make_force_field(buildings): buildingList = [] # holds touple of center and radius for building in buildings: c = P3.P3(building.x + (building.width / 2), building.y + (building.height / 2), building.z + (building.depth / 2)) # Center of the building buildingList.append( (c, math.sqrt((building.width / 2)**2 + (building.width / 2)**2))) def force_field(boidPosition): nonlocal buildingList sum = P3.P3(0, 0, 0) for buildingPosition in buildingList: c, rb = buildingPosition # Unpacking r = boidPosition - c # Vector between the building center and the boidPosition d = r.magnitude( ) # The magnitude of the vector between building center and boidPosition fdir = 1 / d * r # The direction of the force from building to boid fmag = 1 / (d - rb) # Magnitude of the force force = fdir * fmag # Create final force to be returned from its vector sum += force # Return the final force on the given boid position (P3) return sum return force_field
def __init__( self, num_boids, center, radius ): #possibly also orientation, maybe something about obstacles? self.num_boids = num_boids self.boids = [] Flock.flock_count += 1 self.distance_matrix = [[0 for _ in range(num_boids)] for _ in range(num_boids)] # defaults boid to grid row = -1 for i in range(num_boids): if i % 10 == 0: row += 1 self.boids.append( Boid(i, P3(200 + 10 * row, -20 + 4 * i, 50), P3(-15, 0, 0), P3(0, 0, 0), self))
def behavior(boid): max_acc = .1 max_vel = 25 r = 200 nby = [other for other in boid.flock.boids if boid.id > other.id and boid.flock.distance_matrix[boid.id][other.id] < r or other.id > boid.id and boid.flock.distance_matrix[other.id][boid.id] < r] # collision avoidance r2 = 50 avoid = [other for other in nby if boid.id > other.id and boid.flock.distance_matrix[boid.id][other.id] < r2 or other.id > boid.id and boid.flock.distance_matrix[other.id][boid.id] < r2] v1 = P3.P3(0, 0, 0) for other in avoid: v1 += other.position - boid.position * (1 / boid.position.distance(other.position)**2) # velocity matching v2 = P3.P3(0, 0, 0) for b in nby: v2 += b.velocity if len(nby) > 1: v2 *= 1/len(nby) v2 -= boid.velocity # flock centering v3 = P3.P3(0, 0, 0) for b in nby: v3 += b.position if len(nby) > 1: v3 *= 1 / len(nby) v3 -= boid.position # Robin: Cod = .35, mass = 0.0182kg, density = 1.09kg/m^3, body frontal area = 4.6cm^2 # c = coefficient of drag * density * perpendicular area * 1/2 c = .0088 * 1 drag = c * boid.velocity.distance()**2 drag_vector = -1 * boid.velocity * drag delta_vel = 50*v1 + 800*v2 + 5000*v3 # - drag_vector acc = P3.P3.normalize(delta_vel) * max_acc return acc if acc.distance() < delta_vel.distance() else delta_vel
class main: rows = 8 columns = 7 planeloc = [[0 for x in range(columns)] for y in range(rows)] planeloc[0][0] = 'X' planeloc[0][2] = 'Y' planeloc[3][6] = 'Z' bufferA = [[0 for x in range(columns)] for y in range(rows)] bufferA[0][0] = 'X' bufferA[0][2] = 'Y' bufferA[3][6] = 'Z' bufferB = [[0 for x in range(columns)] for y in range(rows)] bufferC = [[0 for x in range(3)] for y in range(3)] bufferD = [[0 for x in range(3)] for y in range(3)] bufferC[0][0] = 'X' bufferC[0][1] = 'Y' bufferC[0][2] = 'Z' bufferD[0][0] = 'X' bufferD[0][1] = 'Y' bufferD[0][2] = 'Z' # print (bufferA) plane_X = planeX.planeX(0, 0) plane_Y = planeY.planeY(0, 2) plane_Z = planeZ.planeZ(3, 6) p1 = P1.P1(0, plane_X, plane_Y, plane_Z, bufferA, bufferB) p2 = P2.P2(0, bufferC, bufferD) p3 = P3.P3(bufferC, bufferD) for i in range(0, 20): print("") # print("") # print("") # print("TIME ", i+1) # print("") time.sleep(1) #Process 1 work p1.proc1(i, plane_X, plane_Y, plane_Z, bufferA, bufferB) #Process 2 Work if i % 2 is 0: p2.proc2AC(i, bufferA, bufferC) else: p2.proc2BD(i, bufferB, bufferD) #Process 3 Work if i % 2 is 0: p3.checkC(i, bufferC) else: p3.checkD(i, bufferD)
def force_field(boidPosition): nonlocal buildingList sum = P3.P3(0, 0, 0) for buildingPosition in buildingList: c, rb = buildingPosition # Unpacking r = boidPosition - c # Vector between the building center and the boidPosition d = r.magnitude( ) # The magnitude of the vector between building center and boidPosition fdir = 1 / d * r # The direction of the force from building to boid fmag = 1 / (d - rb) # Magnitude of the force force = fdir * fmag # Create final force to be returned from its vector sum += force # Return the final force on the given boid position (P3) return sum
def __init__(self, id, boids=None, count=20, behavior_id=0, center=P3.P3(-100, -100, 10), radius=15): self.id = id self.boids = boids self.count = count self.behavior_id = behavior_id self.center = center self.radius = radius
def main(): polinomios = [] while True: print("a. Agregar términos a un polinomio") print("b. Imprimir el polinomio generado hasta el momento") print("c. Imprimir la integral del polinomio generado hasta el momento") print("d. Evaluar la expresión para un valor específico de x") print("e. Salir del menú") opcion = input("Digite opcion: ").lower().strip() if opcion == 'a': a = float(input("Digite a: ")) n = float(input("Digite n: ")) t = (a, n) polinomios.append(t) elif opcion == 'b': print(P3.conv_str(polinomios)) elif opcion == 'c': print(P3.conv_str(P2.integra_polinomio(polinomios))) elif opcion == 'd': x = float(input("Digite x: ")) print(evalua_pol(polinomios, x)) elif opcion == 'e': break
def __init__(self, settings, gui): if isinstance(settings, Config.Config_World): self.settings = settings self.gui = gui if isinstance(settings.screen, Config.Config_Screen): render.start(self.settings.screen.x_pos, self.settings.screen.y_pos, self.settings.screen.x_size, self.settings.screen.y_size, 1000) # creating city grid for b in range(2): self.x_location += 100 self.y_location = 90 for z in range(3): self.y_location -= 20 # self.x_location += 20 for i in range(2): self.y_location -= 10 self.x_location -= 20 self.c = random.randint(0, 1) for t in range(2): self.c2 = random.randint(0, 1) b_location = P3.P3(self.x_location, self.y_location, 0) # print(b_location) buildings.extend([ Building.Building(b_location, 10, random.randrange(20, 65), 10, (self.c, 0, self.c2)) ]) self.x_location += 10 if isinstance(settings, Config.Config_World): flock = settings.flocks[0] if isinstance(flock, Config.Config_Flock): self.F1 = Flock.Flock(flock.count, World.make_force_field(buildings), flock.center, flock.radius) self.render = render.Render(self.F1) gui.set_tick_method(self.tick)
class main: rows = 8 columns = 7 bufferA = [[0 for x in range(7)] for y in range(8)] # Coordinates for X Y Z randomly generated x_xCoor = random.randint(0, rows - 1) x_yCoor = random.randint(0, columns - 1) y_xCoor = random.randint(0, rows - 1) y_yCoor = random.randint(0, columns - 1) z_xCoor = random.randint(0, rows - 1) z_yCoor = random.randint(0, columns - 1) # generate coordinates again if same coordinates if ((x_xCoor == y_xCoor or x_xCoor == z_xCoor or y_xCoor == z_xCoor) and (x_yCoor == y_yCoor or x_yCoor == z_yCoor or y_xCoor == z_xCoor)): x_xCoor = random.randint(0, rows - 1) x_yCoor = random.randint(0, columns - 1) y_xCoor = random.randint(0, rows - 1) y_yCoor = random.randint(0, columns - 1) z_xCoor = random.randint(0, rows - 1) z_yCoor = random.randint(0, columns - 1) bufferA[x_xCoor][x_yCoor] = 'X' bufferA[y_xCoor][y_yCoor] = 'Y' bufferA[z_xCoor][z_yCoor] = 'Z' bufferB = [[0 for x in range(7)] for y in range(8)] bufferC = [[0 for x in range(3)] for y in range(3)] bufferD = [[0 for x in range(3)] for y in range(3)] bufferC[0][0] = 'X' bufferC[0][1] = 'Y' bufferC[0][2] = 'Z' bufferD[0][0] = 'X' bufferD[0][1] = 'Y' bufferD[0][2] = 'Z' time_interval = 1 iterations = 20 semA = threading.Semaphore() semB = threading.Semaphore() semC = threading.Semaphore() semD = threading.Semaphore() plane_X = planeX.planeX(x_xCoor, x_yCoor) plane_Y = planeY.planeY(y_xCoor, y_yCoor) plane_Z = planeZ.planeZ(z_xCoor, z_yCoor) p1 = P1.P1(0, plane_X, plane_Y, plane_Z, bufferA, bufferB, semA, semB) p2 = P2.P2(0, bufferC, bufferD, semA, semB, semC, semD) p3 = P3.P3(bufferC, bufferD, plane_X, plane_Y, plane_Z, z_xCoor, y_yCoor) #thread class declarations i = 0 t1 = threading.Thread(target=p1.proc1, args=(i, plane_X, plane_Y, plane_Z, bufferA, bufferB, semA, semB, semC, semD, time_interval, iterations)) t2 = threading.Thread(target=p2.proc, args=(i, bufferA, bufferB, bufferC, bufferD, semA, semB, semC, semD, time_interval, iterations)) t3 = threading.Thread(target=p3.check, args=(i, bufferC, bufferD, semC, semD, plane_X, plane_Y, plane_Z, semA, semB, time_interval, iterations)) t1.start() t2.start() t3.start()
while (run): print("\n1. New Vehicle Registration") print("2. Auto Transaction") print("3. Driver License Registration") print("4. Violation Record") print("5. Search Engine") selection = input("Please select your program number or 'exit':\n") try: digit = int(selection) if digit == 1: P1.regV(conString) elif digit == 2: P2.AutoTransaction(conString) elif digit == 3: P3.DriverLiRegis(conString) elif digit == 4: P4.violation(conString) elif digit == 5: P5.search_engine(conString) else: print("Must be between 1 and 5") except ValueError: if selection == 'exit': run = False else: print("Please enter a digit or 'exit'")
import P3 as mypq import matplotlib.pyplot as plt ns=(10, 20, 50, 100, 200, 500) tNaive=mypq.timeit(ns, mypq.NaivePriorityQueue) tmyHeap=mypq.timeit(ns, mypq.HeapPriorityQueue) tPython=mypq.timeit(ns, mypq.PythonHeapPriorityQueue) plt.plot(ns,tNaive,label='NaivePQ') plt.plot(ns,tmyHeap,label='MyHeapPQ') plt.plot(ns,tPython,label='PythonHeapPQ') plt.xlabel('Number of Lists Merged') plt.ylabel('Elapsed time in seconds') plt.legend() plt.title('The running time of `mergesortedlists` with different heap implementations') plt.show()
ground(10) for building in World.buildings: Building.Building.draw_building(building) for b in self.flock.boids: v = make_bird_vertices(b) draw_bird(v) pygame.display.flip() def dispose(self): pygame.quit() if __name__ == "__main__": flock = Flock.Flock(100, P3.P3(-75, -75, 0), 10) f = Render(flock) start(0, 0, 800, 600, 1000) while 1: f.draw() for b in flock.boids: b.move_Boid(.1)
#/usr/bin/env python3 import P3 import matplotlib.pyplot as plt import matplotlib matplotlib.rcParams.update({'font.size': 14}) elapsed_NaivePriorityQueue = P3.timeit(pqclass=P3.NaivePriorityQueue) elapsed_HeapPriorityQueue = P3.timeit(pqclass=P3.HeapPriorityQueue) elapsed_PythonHeapPriorityQueue = P3.timeit(pqclass=P3.PythonHeapPriorityQueue) elapsed_times = [ elapsed_NaivePriorityQueue, elapsed_HeapPriorityQueue, elapsed_PythonHeapPriorityQueue ] names = ['Naive', 'Heap', 'Python Heap'] ns = [10, 20, 50, 100, 200, 500] plt.figure(figsize=[7, 7]) for elapsed_time, name in zip(elapsed_times, names): plt.plot(ns, elapsed_time, label=name) plt.legend() plt.xlabel('Number of Lists') plt.ylabel('Elapsed Time (seconds)') plt.title('Efficiency of Heap Implementations') plt.savefig('P3-C.png') plt.show()
import P2 from P2 import Heap, MaxHeap, MinHeap import P3 from P3 import PriorityQueue, NaivePriorityQueue, HeapPriorityQueue, PythonPriorityQueue from random import sample from time import time import heapq import numpy as np import matplotlib.pyplot as plt ns = (10, 20, 50, 100, 200, 500) naive_queue = P3.timeit(pqclass=NaivePriorityQueue, n_average=5) heap_queue = P3.timeit(pqclass=HeapPriorityQueue, n_average=5) python_queue = P3.timeit(pqclass=PythonPriorityQueue, n_average=5) plt.plot(ns, naive_queue) plt.plot(ns, heap_queue) plt.plot(ns, python_queue) plt.title("Runtime for mergesortedlists Method") plt.ylabel("Runtime") plt.xlabel("Merged Lists") plt.legend(["NaivePriorityQueue", "HeapPriorityQueue", "PythonPriorityQueue"]) plt.show()
#RunCode start1 = time.time() a = P1.ParseSeqFile('sequencefile.txt') end1 = time.time() print('*******************\nParseSeqFile: \n*******************\n\n', a, '\n\n') labels = [] for tuples in a: labels.append(tuples[0]) start2 = time.time() b = P2.AlignByDP(a) end2 = time.time() print('*******************\nAlignByDP: \n*******************\n\n') print(b, '\n\n') start3 = time.time() c = P3.ComputeDistMatrix(b) end3 = time.time() print('*******************\nComputeDistMatrix: \n*******************\n\n') for line in c: lines = [] for element in line: lines.append('%010.8f' % element) print(lines) start4 = time.time() d = P4.Cluster(c, labels) end4 = time.time() print('\n*******************\nCluster: \n*******************\n\n', d) print('\n') print('|+++++++++++++++|\n| Test Analysis |\n|+++++++++++++++|\n')
Boid.Boid( self, i, P3.P3(x, y, 0) + center + P3.P3(0, 0, 2 * random.randrange(-5, 6, 10)), v, Behavior.behavior)) self.update_dist_matrix() def update(self, tick): for b in self.boids: b.move_Boid(tick) self.update_dist_matrix() def update_dist_matrix(self): for i in range(len(self.boids)): for j in range(len(self.boids) - i - 1): self.distance_matrix[i][j] = self.boids[i].position.distance( self.boids[j].position) def get_distance(self, i, j): if i > j: return self.distance_matrix[i][j] else: return self.distance_matrix[j][i] if __name__ == '__main__': flock = Flock(20, P3.P3(-200, -100, 50), 20) for i in range(20): flock.update(1) print()
def AutoTransaction(conString): """ This component is used to complete an auto transaction. Your program shall allow the officer to enter all necessary information to complete this task, including the details about the seller, the buyer, the date, and the price. The component shall also remove the relevant information of the previous ownership. auto_sale (transaction_id,seller_id,buyer_id,vehicle_id,s_date,price); """ # for testing------------------------------------------- #user = input("Username {} ".format(getpass.getuser())) #if not user: # user = getpass.getuser() #pw = getpass.getpass() #conString = ''+user+'/'+pw+'@gwynne.cs.ualberta.ca:1521/CRS' # testing ends------------------------------------------ ongoing = True while(ongoing): print("===========================================================") print("Make a new auto transaction, enter 'N'.\n ") if input() == 'N': # connecting to database con = cx_Oracle.connect(conString); curs=con.cursor(); # check if the vehicle exists checking = True while(checking): checking = False vehicle_id = input("\nPlease enter vehicle id:") try: val = str(vehicle_id) except ValueError: print("Invalid Input Type. Try Again.") curs.execute("SELECT serial_no FROM vehicle WHERE lower(serial_no) = '{}'".format(str.lower(vehicle_id))) if not curs.fetchone(): print("Vehicle Not Registered") checking = True checking = True while(checking): checking = False seller_id = input("Seller_id:") # check if the seller exists curs.execute("SELECT sin FROM people WHERE lower(sin) = '{}'".format(str.lower(seller_id)) ) if not curs.fetchone(): print("Seller not registered.") # check if the seller owns the vehicle curs.execute("SELECT vehicle_id FROM owner WHERE lower(owner_id) = '{}'".format(str.lower(seller_id))) vehicles = [] row = curs.fetchone() while row: vehicles.append(row[0].strip()) row = curs.fetchone() #print(vehicles) if not vehicle_id in vehicles: print("This seller does not own car '{}'\n".format(vehicle_id)) checking = True checking = True all_owners = [] while(checking): checking = False buyer_id = [] # in case there are more buyers buyer_id.append(input("Buyer_id:") ) # check if the buyer_id exists curs.execute("SELECT sin FROM people WHERE lower(sin) = '{}'".format(str.lower(buyer_id[0]))) if not curs.fetchone(): print("Buyer not registered.") ch = input("Would you like to register a new buyer? y/n \n") if ch == 'y': # register a new person into people database P3.regPerson(conString, curs,buyer_id[0]) if ch == 'n': print("See you next time!") return # check if the buyer is an owner curs.execute("SELECT owner_id FROM owner WHERE lower(vehicle_id) = '{}'".format(str.lower(vehicle_id))) owners = [] row = curs.fetchone() while row: owners.append(row[0].strip()) row = curs.fetchone() if buyer_id[0] in owners: print("Buyer owns car {}, enter buyer ID again.".format(vehicle_id)) checking = True else: all_owners = owners # check if this buyer is the primary owner is_primary = input("Are there any secondary owners? y/n\n") if is_primary == 'y': num = input("How many other owners? Enter the number:") for i in range(int(num)): checking = True while(checking): checking = False bid = input("Buyer_id:") if bid in all_owners: print("Buyer owns car {}, enter buyer ID again.".format(vehicle_id)) checking = True if bid == buyer_id[0]: print("Invalid secondary buyer ID. Enter again.") checking = True curs.execute("SELECT sin FROM people WHERE lower(sin) = '{}'".format(str.lower(bid))) if not curs.fetchone(): print("Buyer not registered.") checking = True else: buyer_id.append(bid) # obtain date and price s_date = "'"+input("Sale Date:(YYYY-MM-DD )")+"'" checking = True while(checking): checking = False try: price = float(input("Price:")) except ValueError: print("Invalid input!") checking = True # obtain the largest transaction_id ` curs.execute("SELECT MAX(transaction_id) FROM auto_sale") largest = curs.fetchone() transaction_id = int(largest[0]) + 1 # add informatio to table auto_sale #curs.bindarraysize = 1 #curs.setinputsizes(int, 15, 15, 15, date, float) statement = "INSERT INTO auto_sale VALUES ('{}', '{}', '{}', '{}', TO_DATE({},'YYYY-MM-DD'), {})"\ .format(transaction_id, seller_id, buyer_id[0], vehicle_id, s_date, price) curs.execute(statement) # add information to the new owner # I assumed that the first buyer id entered to be primary owner for i in range(len(buyer_id)): if i == 0: add = "INSERT INTO owner VALUES ('{}', '{}', '{}')"\ .format(buyer_id[i], vehicle_id, 'y') else: add = "INSERT INTO owner VALUES ('{}', '{}', '{}')"\ .format(buyer_id[i], vehicle_id, 'n') curs.execute(add) # remove from old one curs.execute("DELETE FROM owner WHERE lower(owner_id) = '{}'".format(str.lower(seller_id)) ) c = input("Would you like another transaction? y/n\n") if c == 'n': # close database connection con.commit() curs.close() ongoing = False else: ongoing = True
def regV(conString): verify = False while (not verify): serialNo = input("Enter serial number: ").lower() maker = input("Enter Maker: ").lower() typeId = input("Type ID#: ").lower() model = input("Enter Model: ").lower() year = input("Enter Year: ").lower() color = input("Enter color: ").lower() pOwner = None secondaryOwner = [] primaryOwner = [] verify = serialNo.isalnum() and maker.isalpha() and typeId.isdigit( ) and model.isalnum() and year.isdigit() and color.isalpha() if (not verify): print("\nError in entry, please ensure all data is correct") print("Serial: " + serialNo + " " + str(serialNo.isalnum())) print("Maker: " + maker + " " + str(maker.isalpha())) print("Type ID#: " + typeId + " " + str(typeId.isdigit())) print(" Model: " + model + " " + str(model.isalnum())) print(" Year: " + year + " " + str(year.isdigit())) print("Color: " + color + " " + str(color.isalpha()) + "\n") con = cx_Oracle.connect(conString) curs = con.cursor() if (searchSerial(serialNo, curs)): print("Vehicle already registered. Returning to main menu") else: count = int(input("How many drivers?")) x = 0 while (x < count): ownerId = input("Enter owner SIN: ").lower() primary = input("Is primary owner? (y/n): ").lower() if (not (searchSin(ownerId, curs))): print("Person not found") P3.regPerson(conString, curs, ownerId) if (primary == "y"): primaryOwner.append(ownerId) else: secondaryOwner.append(ownerId) x += 1 statement = " insert into vehicle values('" + serialNo + "','" + maker + "','" + model + "'," + year + ",'" + color + "'," + typeId + ")" try: curs.execute(statement) except: print("Sql error, try again.") return for x in primaryOwner: print("PRIMARY: ") print(x) statement2 = " insert into owner values('" + x + "','" + serialNo + "','y')" try: curs.execute(statement2) except: print("Sql error, try again.") return for x in secondaryOwner: print("SECONDARY: ") print(x) statement3 = " insert into owner values('" + x + "','" + serialNo + "','n' )" try: curs.execute(statement3) except: print("Sql error, try again.") break return con.commit() curs.close() con.close()
def test_a(self): polinomio = [(2, 2), (8, 4), (8.8, 3)] resultado = "2x2+8x4+8.8x3" self.assertEqual(resultado, P3.conv_str(polinomio).replace(" ", ""))
def test1(self): self.assertEqual(P3.bash_check(2, 1, 4, [[2, 3], [2, 4], [1, 2]]), "1100")
import P3 import matplotlib.pyplot as plt import numpy as np naive_queue =P3.timeit(pqclass=P3.NaivePriorityQueue) my_queue=P3.timeit(pqclass=P3.HeapPriorityQueue) python_queue=P3.timeit(pqclass=P3.PythonHeapPriorityQueue) ns= (10, 20, 50, 100, 200, 500) plt.figure() plt.plot(ns,naive_queue,label='Naive Queue', c = 'r') plt.plot(ns,my_queue,label='My Heap Queue', c= 'g') plt.plot(ns,python_queue,label='Python Heap Queue',c = 'b') plt.title('Comparing Elapsed time for Different Priority Queue implementations') plt.xlabel('Number of Lists Merged') plt.ylabel(' Elapsed time in seconds') plt.legend(loc = 'upper center') plt.show()
def test3(self): self.assertEqual( P3.solve_problem(4, [(7, 1, 2), (5, 2, 3), (6, 2, 4)], "0010"), "1 0 0")
import P3 import matplotlib.pyplot as plt npq=P3.timeit(pqclass=P3.NaivePriorityQueue) hpq=P3.timeit(pqclass=P3.HeapPriorityQueue) ppq=P3.timeit(pqclass=P3.PythonHeapPriorityQueue) ns=[10, 20, 50, 100, 200, 500] plt.figure() L=5 plt.plot(ns,npq,label='Naive PQ',lw=L) plt.plot(ns,hpq,label='Heap PQ',lw=L) plt.plot(ns,ppq,label='Python Heap PQ',lw=L) plt.legend() plt.title('Figure Showing Performace of Different PQ Implementations') plt.xlabel('Number of Lists Merged [-]') plt.ylabel('Elapsed Average Time [s]') plt.savefig('P3-C.png',format='png',dpi=300) plt.show()
def test6(self): self.assertEqual( P3.solve_problem(4, [(7, 1, 2), (5, 2, 3), (6, 2, 4)], "0110"), "1 1 1")
import P1 import P2 import P3 import P4 labelSequenceList = P1.ParseSeqFile("P1_sequences.txt") print(labelSequenceList) alignedSequencesDict = P2.AlignByDP(labelSequenceList) print(alignedSequencesDict) distMatrix = P3.ComputeDistMatrix(alignedSequencesDict) print(distMatrix) labelList = [ "Mouse", "Bovine", "Gibbon", "Orangutan", "Gorilla", "Chimp", "Human" ] binaryTreeString = P4.Cluster(distMatrix, labelList) print(binaryTreeString)
def test2(self): self.assertEqual( P3.solve_problem(4, [(7, 1, 2), (5, 2, 3), (6, 2, 4)], "1100"), "1 1 Infinity")
def main(): print( "1. View total votes in the U.S. for every election year from 2000 to 2016." ) print( "2. Compares the number of votes and percentages for Republicans and Democrats for any state from 2000-2016" ) print( "3. View the top 5 Republican states in either the 2012 or 2016 elections" ) print( "4. View the top 5 Democrat states in either the 2012 or 2016 elections" ) print("5. View Florida's Republican votes from 1976-2016") print("6. View Florida's Democrat votes from 1976-2016") print( "7. View a color-coded map of the 2016 U.S. Presidential Election results" ) print("8. View third party votes in the U.S. from 1976-2016") choice = int(input("Choose one option (ex: 1) ")) if choice == 1: print(P1.total_votes()) P1.total_votes_map() elif choice == 2: state_input = input("Type in a state (ex: District of Columbia) ") print(P2.compare_votes(state_input)) P2.compare_votes_map(state_input) elif choice == 3: year = int( input("Choose an election year. Type in either 2012 or 2016: ")) if year == 2012: print(P3.rep_states2012()) P3.rep_states_2012_plot() elif year == 2016: print(P3.rep_states2016()) P3.rep_states_2016_plot() elif choice == 4: year = int( input("Choose an election year. Type in either 2012 or 2016: ")) if year == 2012: print(P3.dem_states2012()) P3.dem_states_2012_plot() elif year == 2016: print(P3.dem_states2016()) P3.dem_states_2016_plot() elif choice == 5: print(P4.fl_repvotes()) P4.florida_rep_votes_plot() elif choice == 6: print(P4.fl_demvotes()) P4.florida_dem_votes_plot() elif choice == 7: print(P6.us_map_2016()) elif choice == 8: print(P7.total_non_rd()) P7.total_non_rd_map() else: main()
def test_b(self): polinomio = [(3, 3)] resultado = "3x3" self.assertEqual(resultado, P3.conv_str(polinomio).replace(" ", ""))
def regV(conString): verify = False while(not verify): serialNo = input("Enter serial number: ").lower() maker = input("Enter Maker: ").lower() typeId = input("Type ID#: ").lower() model = input("Enter Model: ").lower() year = input("Enter Year: ").lower() color = input("Enter color: ").lower() pOwner = None secondaryOwner = [] primaryOwner = [] verify = serialNo.isalnum() and maker.isalpha() and typeId.isdigit() and model.isalnum() and year.isdigit() and color.isalpha() if(not verify): print("\nError in entry, please ensure all data is correct") print("Serial: "+serialNo+" "+ str(serialNo.isalnum())) print("Maker: "+maker + " " + str(maker.isalpha())) print("Type ID#: "+ typeId + " " + str(typeId.isdigit())) print(" Model: " + model+ " " + str(model.isalnum())) print(" Year: " + year + " "+ str(year.isdigit())) print("Color: " + color+" " + str(color.isalpha()) +"\n") con = cx_Oracle.connect(conString); curs = con.cursor(); if(searchSerial(serialNo, curs)): print("Vehicle already registered. Returning to main menu") else: count = int(input("How many drivers?")) x = 0 while(x<count): ownerId = input("Enter owner SIN: ").lower() primary = input("Is primary owner? (y/n): ").lower() if(not(searchSin(ownerId, curs))): print("Person not found") P3.regPerson(conString, curs, ownerId) if(primary=="y"): primaryOwner.append(ownerId) else: secondaryOwner.append(ownerId) x+=1 statement = " insert into vehicle values('" + serialNo + "','" + maker +"','" + model + "'," + year + ",'" + color + "'," + typeId + ")" try: curs.execute(statement) except: print("Sql error, try again.") return for x in primaryOwner: print("PRIMARY: ") print(x) statement2 =" insert into owner values('" + x +"','" + serialNo +"','y')" try: curs.execute(statement2) except: print("Sql error, try again.") return for x in secondaryOwner: print("SECONDARY: ") print(x) statement3 =" insert into owner values('" + x +"','" + serialNo +"','n' )" try: curs.execute(statement3) except: print("Sql error, try again.") break return con.commit() curs.close() con.close()