def TestFactory(): # Create a list of colors to compare with user input, if the color is not in # the list, cancel the order color_choice = ["red", "white", "blue"] customer_orders = MyQueue() # Intitalize a boolean b = True while b : print("Welcome to the Waskelly Wabbit Wiget Works automated odering system!") print("") name = input("\t Please input customer name (or exit): ") # If the User enters exit, break out of the loop if name == "exit": break color = input("\t Please select desired widget color (red, white, blue): ") # If the color isnt one of the choices given, continue if color_choice.count(color) == 0: print("Sorry, that's not a color we offer. Order cancelled. \n") continue quantity = input("\t Excellent choice. How many %s widgets do you want? "%(color)) # If the number given is not a valid positive integer, continue if not quantity.isdigit(): print("Bad quantity. Order cancelled \n") continue print("Order confirmed! Please shop with us again. \n") customer_orders.enqueue(Order(name, color, quantity)) print("") print ("Now processing orders:") # While the Queue is full while not customer_orders.isEmpty(): # Use the getter or accessors from the Order class processed_Order = customer_orders.dequeue() order_Num = processed_Order.getOrderNum() order_Name = processed_Order.getCustomerName() order_Color = processed_Order.getCustomerColor() order_Quantity = processed_Order.getCustomerQuantity() # Print the orders and their values out print (" Order Shipped: \t Order %d: customer %s requests %s %s widgets." \ % (order_Num, order_Name, order_Quantity,order_Color)) # Since the while loop broke, the Queue is empty print("Queue empty.")
def findMovieTransRelation(self, movA, movB): # finds path between 2 movies using BFS. file = open('outputPS2.txt', 'a+') file.write("\n--------Function findMovieTransRelation --------\n") file.write("Movie A: %s\n" % movA) file.write("Movie B: %s\n" % movB) for i in self.ActMov: if i.getName() == movA: i.visited = True else: i.visited = False q = MyQueue.MyQueue() temp_path = [movA] q.enqueue(temp_path) while q.IsEmpty() == False: tmp_path = q.dequeue() last_node = tmp_path[len(tmp_path) - 1] if last_node == movB: file.write("Related: Yes, %s" % tmp_path.pop(0)) file.writelines([" > %s" % item for item in tmp_path]) file.write("\n----------------------------------------") file.close() return for link_node in self.getNeighbours(last_node): if not link_node.getVisited(): link_node.visited = True new_path = tmp_path + [link_node.getName()] q.enqueue(new_path) file.write("Related: No") file.write("\n-----------------------------------------") file.close()
def breadth_first_order(tnode): explore = MyQueue.create() MyQueue.enqueue(explore, tnode) while MyQueue.size(explore) > 0: current = MyQueue.dequeue(explore) print(tn.get_data(current), end=" ") left = tn.get_left(current) if left is not None: MyQueue.enqueue(explore, left) right = tn.get_right(current) if right is not None: MyQueue.enqueue(explore, right)
def main(): maxFrames = 72 colorQueue = MyQueue() grayQueue = MyQueue() videoCapture = cv2.VideoCapture("clip.mp4") threadList = [ Thread(target=extractFrames, args=["clip.mp4", colorQueue, maxFrames]), Thread(target=convertToGray, args=[colorQueue, grayQueue]), Thread(target=displayFrames, args=[grayQueue]) ] for i in threadList: i.start() for i in threadList: i.join()
def astar(G, startN, endN): c = it.count() pq = MyQueue.PriorityQ() #! Format is (Unique ID, Source, Distance, Parent) #! next(c) is to create a uniqueness for each obj in the Priority Q #! Source is the starting node #! Distance for starting will be zero #! Parent, starting does not have any parent thus None is placed pq.push(0, next(c), startN, 0.0, None) #! Used nodes or nodes that have been stepped thru used = {} #! Starting of A* Algo while pq.getSize() > 0: #! Get the Priority obj within the priority Q. Priority by Distance _, __, curN, dis, p = pq.pop() #! When path is found. Below is static, if dynamic can put curN == endN if curN == endN: #! Building the path, end node will be appended first, then slowly search for the parent from the used dict - #! and the parent node will be appended until the start node. Then reverse the array it will show the path from start to end. #! Lastly it will be break out of this while loop finalpath = [] finalpath.append(curN) n = p while n is not None: finalpath.append(n) n = used[n] finalpath = finalpath[::-1] return finalpath #! to make it efficient and prevent endless loop, if the current Node is found within used nodes, - #! it will just skip to the next Queue object if curN in used: continue #! Adding current node into the used dict and linked it with the parent node. used[curN] = p #! Searching for the paths #? nei (NODE ID) e.g #? 5103941180 ################### #? etc (dict) e.g #? {'osmid': 35091912, 'oneway': True, 'lanes': '2', 'name': 'Punggol Place', 'highway': 'residential', 'maxspeed': '40', 'length': 25.879} 1 #! ndis is new distance for nei, etc in G[curN].items(): if nei in used: continue #! 'length' can be any numeric data in etc ndis = dis + etc[0].get("length") f = heuristic(G, nei,endN) + ndis pq.push(f,next(c), nei, ndis, curN) return -1
def loadToQueueAndDisplay(self): self.queue_list = MyQueue.Queue() while True: try: f = open(input('Please enter the find path: ')) print('The file is load successfully!') break except: print('File-path is not correct') board = f.readline() for line in f: self.queue_list.enQueue(line.strip('\n')) f.close() while not self.queue_list.isEmpty(): self.queue_list.deQueue()
def BreadthFirstSearch(graph, startingNodeData): searchQueue: MyQueue = MyQueue() seen: set = set([]) searchQueue.add(startingNodeData) while searchQueue.isEmpty() == False: currentNodeData = searchQueue.remove() if currentNodeData not in seen: seen.add(currentNodeData) print(currentNodeData) for neighbor in graph[currentNodeData]: if neighbor not in seen: searchQueue.add(neighbor)
def breadth_first_search(b1, bn, U): n = U.shape[0] if b1 == bn: return True previous = [None] * n # previous = [] bfs = [] # Mark all buildings as not visited visited = [False] * n # visited = [False] * 8 # Relations to building B1 rels_b1 = U[:, b1] # Set relationship between building and itself to False rels_b1[b1] = False adjs_b1 = adjacent(rels_b1) # Create a queue for BFS q = MyQueue.MyQueue() # Mark current building as visited and enqueue it visited[b1] = True # Put first in array of adjacent in queue q.enqueue(b1) while not q.isEmpty(): # Deque a building from the top of the queue and print it b = q.dequeue() bfs.append(b) # Get all adjacent buildings of the dequeued building b rels_b = U[:, b] rels_b[b] = False adjs = adjacent(rels_b) for i in range(len(adjs)): # If found destination building, stop curr = adjs[i] # current node if visited[curr] == False: # print "previous["+str(curr)+"]="+str(b) previous[curr] = b visited[curr] = True q.enqueue(curr) path = unique(previous, bn, b1) return path, bfs
def squreAllHouse(squre): if queuesDict.has_key(squre): queue = queuesDict[squre] else: queue = MyQueue(40) for house in get_houselist(squre): print house houseObj = getHouse(house, squreDict[squre]) print houseObj.title if houseObj.url not in queue: queue.enqueue(houseObj.url) save(houseObj) if (queue.isfull()): queue.dequeue() queuesDict[squre] = queue
def aStar(dicCity,cityA,cityB,h): """ A* search between two city from dicCity with a definned heuristic """ frontier = MyQueue() frontier.put(0,cityA) sumWeight = {cityA: 0} steps = 0 while frontier: current = frontier.get() steps+=1 if current==cityB: return current, steps for coLeaf in current.getcoLeafs(dicCity): tempWeight = sumWeight[current] + current.getWeightOf(coLeaf) if coLeaf not in sumWeight or tempWeight < sumWeight[coLeaf]: sumWeight[coLeaf] = tempWeight coLeaf.parent = current priority = h(coLeaf, cityB) + tempWeight frontier.put(priority,coLeaf) raise Exception("no solution")
def main(): testArr = ['a', 'b', 'c', 'd'] print("NODE") package1: Node = Node(1) print(str(package1)) package2: Node = Node(2) package1.next = package2 print(str(package1)) print(repr(package2)) package2.next = Node(3) print(str(package2)) print() print("LINKED LIST") linkedList :LinkedList = LinkedList('A') linkedList.printLinkedList() linkedList.append('B') linkedList.append('C') linkedList.printLinkedList() linkedList.prepend('Alpha') linkedList.printLinkedList() linkedList.remove('B') linkedList.printLinkedList() linkedList.remove('C') linkedList.printLinkedList() linkedList.remove('Alpha') linkedList.printLinkedList() linkedList.remove('A') linkedList.printLinkedList() linkedList.remove('A') testArr = ['a', 'b', 'c', 'd'] for i in testArr: linkedList.append(i) linkedList.printLinkedList() print() print("STACK") stackOfEmails: Stack = Stack('A') #stackOfEmails.pop() #print(stackOfEmails.isEmpty()) #stackOfEmails.printStack() for i in testArr: stackOfEmails.push(i) stackOfEmails.printStack() #print(stackOfEmails.isEmpty()) while(stackOfEmails.isEmpty() == False): print("The Node with the data '{}' will be deleted".format(stackOfEmails.peek())) stackOfEmails.pop() stackOfEmails.printStack() print(stackOfEmails.isEmpty()) stackOfEmails.push('Z') stackOfEmails.printStack() print() print("QUEUE") myQueue : MyQueue = MyQueue() print(myQueue.isEmpty()) for i in testArr: myQueue.add(i) myQueue.printQueue() while(myQueue.isEmpty()==False): print("The node with the data '{}' will be removed".format(myQueue.remove())) myQueue.printQueue() print(myQueue.isEmpty()) myQueue.remove() print() print("HEAP") testArr2 = [17, 10, 20, 15, 25] myHeap : Heap = Heap() for i in testArr2: myHeap.add(i) myHeap.printHeap() myHeap.poll() myHeap.printHeap() print() print("BINARY SEARCH TREE") testArr3 = [8, 15, 5] binaryTree : BinarySearch = BinarySearch(10) #binaryTree.printInOrder() for i in testArr3: binaryTree.insert(i) binaryTree.printInOrder() print(binaryTree.find(10)) for i in testArr3: print(binaryTree.find(i)) print(binaryTree.find(100)) print() print("TEST") test1 = Test() test2 = Test() print(Test.__dict__) print(test1.__dict__) test1.classVar = 34 print(Test.__dict__) print(test1.__dict__) print(test2.__dict__) print(test2.classVar) print()
def main(): i = 0 y= MyQueue() x = Order() while True: end = False print ("Welcome to the Waskelly Wabbit Widget Works automated ordering system!") print ('') name = input ("Please input customer name (or exit) ") if (name == "exit"): print ('') print ("Now processing orders: ") break else: x.name=name color = input ("Please select desired widget color (red, white, blue) ") ## Ask the user for a color color=color.lower() if (color == "red"): x.color=color elif (color == "white"): x.color=color elif (color == "blue"): x.color=color else: end = True if end == True: ##If the color is invalid, start the ordering process over print ("Sorry, that's not a color we offer. Order cancelled.") print ('') continue quan = input (("Excellent choice, how many %s widgets do you want? ") % (x.color)) if (quan.isdigit()): #Ask for the quantity and make sure that the input is valid x.quantity=quan print ("Order confirmed! Please shop with us again.") print ('') else: end = True if end == True: ## If the input is invalid, restart the ordering process print ("Bad quantity. Order cancelled") print ('') continue i = i + 1 ##Keep track of the number of orders x.number= i ## Add the successful order to the queue toenq=(("Order %s: customer %s requests %s %s widgets") % (x.number, x.name, x.quantity, x.color)) y.enqueue(toenq) while not (y.isEmpty()): print (("Order shipped: %s") % (y.dequeue())) else: print ("Queue empty")
import My2_3Tree as T23 import MyAVLTree as TAVL import MyBinaryTree as BST import MyHeap as HP import MyLinkedList as LST import MyQueue as Q import MyStack as S InitDictionary = { '0': None, '1': S.MyStack(), '2': Q.MyQueue(), '3': LST.LinkList(), '4': BST.BST(), '5': TAVL.AVLTree(), '6': HP.Heap(), '7': T23.Tree23() } def InitDict(key): return InitDictionary[str(key)] class ClassObject(object): obj = None name = '' def __init__(self, key): if key == 0: print "No object created.\n"
def testQueue(): q = MyQueue(1) # Initalisierungs Checks assert q.max == 1, "Maximale Größe passt nicht" assert q.size == 0, "Aktuelle Größe passt nicht" is_empty = q.empty() assert is_empty, "Nach Initalisierung sollte die Schlange noch leer sein" is_full = q.full() assert is_full == False, "Schlange ist nach Initalisierung nicht voll" assert q.size == 0, "Größe passt nicht" succeeded = q.enqueue(1) assert succeeded, "Erfolgreich eingefügt" check(q) is_full = q.full() assert is_full, "Schlange ist voll" value = q.dequeue() assert value == 1, "Wert sollte 1 sein" check(q) is_empty = q.empty() assert q.empty(), "Schlange ist wieder leer" check(q) succeeded = q.enqueue(-42) assert succeeded, "Erfolgreich eingefügt" check(q) value = q.dequeue() assert value == -42, "Wert sollte 1 sein" check(q) value = q.dequeue() assert value == None, "Schlange war schon leer" check(q) is_empty = q.empty() assert q.empty(), "Schlange ist wieder leer" check(q) succeeded = q.enqueue(1) assert succeeded, "Erfolgreich eingefügt" succeeded = q.enqueue(2) assert succeeded == False, "Konnte Elelement nicht einfügen" check(q) value = q.dequeue() assert value == 1, "Hätte nicht überschreiben dürfen" check(q) is_empty = q.empty() assert is_empty, "Sollte wieder leer sein" succeeded = q.enqueue(2**31 - 1) assert succeeded, "Einfügen geklappt" value = q.dequeue() assert value == (2**31 - 1), "Zu große Zahl" q = MyQueue(3000) for x in range(2000): #print(x) value = x succeeded = q.enqueue(value) assert succeeded, "Einfügen muss klappen" assert not q.empty(), "Darf nicht leer sein" assert not q.full(), "Darf nicht voll sein" check(q) #print() for x in range(2000): value = q.dequeue() #print(value) iter = x assert (iter == value), "Wert passt nicht" assert not q.full(), "Darf nicht voll sein" check(q) for x in range(2000): #print(x) value = x * -1 succeeded = q.enqueue(value) assert succeeded, "Einfügen muss klappen" assert not q.empty(), "Darf nicht leer sein" assert not q.full(), "Darf nicht voll sein" check(q) #print() for x in range(2000): value = q.dequeue() #print(value) iter = x * -1 assert (iter == value), "Wert passt nicht" assert not q.full(), "Darf nicht voll sein" check(q)
def TestFactory(): """An interactive widget ordering system to handle orders of widgets containing data about customer name, widget color and quantity.""" #Order Variable Reset name = "" color = "" num = "" #Order queue queue = MyQueue() #Keep program running until exit while True: #welcome message print("\nWelcome to the Waskelly Wabbit Widget Works automated ordering system!") #user inputs name (or type 'exit') name = input("\n\tPlease input customer name (or exit): ") #check for actual input, if none, re-ask if name == "": continue #check lower case name for the word 'exit' if name.lower() == "exit": break #user inputs order color color = input("\tPlease select desired widget color (red, white, blue): ").lower() #if not defined color, cancel order if not color in ["red", "white", "blue"]: print("\t\tSorry, %s not a color we offer. Order cancelled." %color) continue #iser inputs order quantity num = input("\tExcellent choice. How many %s widgets do you want? " %color) #if value not a positive whole number, cancel order if not num.isnumeric(): print("\t\tBad quantity. Order cancelled.") continue #if made this far, all values are valid, create order newOrder = Order(name, color, num) #add new order to the order queue queue.enqueue(newOrder) #order confimation message #on exit process orders print("\nNow processing orders:\n") #iterate over order queue, dequeue orders for order in range(len(queue)): print(" Order shipped:\t", queue.dequeue()) #all orders processed message print("\nQueue empty")