class AnimalQueue(object): def __init__(self): self.cat_queue = Queue() self.dog_queue = Queue() self.time = 0 def enqueue(self, animal): if type(animal) is Dog: self.dog_queue.add(animal) elif type(animal) is Cat: self.cat_queue.add(animal) else: raise ValueError("invalid type") animal.order = self.time self.time += 1 def dequeueDog(self): return self.dog_queue.remove() def dequeueCat(self): return self.cat_queue.remove() def dequeueAny(self): if self.dog_queue.isEmpty(): return self.dequeueCat() elif self.cat_queue.isEmpty(): return self.dequeueDog() topDog = self.dog_queue.peek() topCat = self.cat_queue.peek() if topDog.order < topCat.order: return self.dequeueDog() else: return self.dequeueCat()
def find_path(self, s, e): """finds the path from s to e and updates the grid with the found path and returns if it was able to reach the end""" #initializing the queues rq = Queue() cq = Queue() #initially marking reached end as false (used to know if the end is reachable) reached_end = False #initializing the visited array to keep track of visited nodes and a prev array to keep track of the path visited = np.zeros((self.grid_size[0], self.grid_size[1]), dtype = np.bool) prev = self.create_list((self.grid_size[0], self.grid_size[1], 2), None) #added the starting row position to the row queue and starting column position to the column queue rq.add(s[0]) cq.add(s[1]) #marked the first positions as true visited[s[0]][s[1]] = True #running while the queues is not empty (only put one because the queue will always be the same size) while len(cq.queue) > 0: #removes the nodes coordinates from the queues and puts them into the variables r, c r = rq.remove() c = cq.remove() #checks if the node location is the same as the end location (checks if it reached the end) if r == e[0] and c == e[1]: reached_end = True break #adding to it the appropriate neighbors to the queues and the visited and prev arrays if c + 2 < self.grid_size[1] and np.all(self.grid[r][c + 1] == [10, 206, 245]) and visited[r][c + 2] == False: rq.add(r) cq.add(c + 2) visited[r][c + 2] = True prev[r][c + 1] = [r, c] prev[r][c + 2] = [r, c + 1] if c - 2 >= 0 and np.all(self.grid[r][c - 1] == [10, 206, 245]) and visited[r][c - 2] == False: rq.add(r) cq.add(c - 2) visited[r][c - 2] = True prev[r][c - 1] = [r, c] prev[r][c - 2] = [r, c - 1] if r - 2 >= 0 and np.all(self.grid[r - 1][c] == [10, 206, 245]) and visited[r - 2][c] == False: rq.add(r - 2) cq.add(c) visited[r - 2][c] = True prev[r - 1][c] = [r, c] prev[r - 2][c] = [r - 1, c] if r + 2 < self.grid_size[0] and np.all(self.grid[r + 1][c] == [10, 206, 245]) and visited[r + 2][c] == False: rq.add(r + 2) cq.add(c) visited[r + 2][c] = True prev[r + 1][c] = [r, c] prev[r + 2][c] = [r + 1, c] self.create_path(prev, e, reached_end) return(reached_end)
def test_removing_item_from_the_queue(): q = Queue() q.add("hello") q.add("blob") assert q.remove().value == "hello" assert q.remove().value == "blob" with pytest.raises(AttributeError) as e: q.remove() assert str(e.value) == "EmptyQueueError"
def testQueue(): a = Queue() #Testing isEmpty() print(a.isEmpty()) #Testing adding for i in range(10): a.add(i) a.displayQueue() #Testing removing a.remove() a.displayQueue()
def breadthFirst(tree): queue = Queue() queue.add(tree) while not (queue.isEmpty()): node = queue.remove() print(node.data) children = node.getChildren() for child in children: queue.add(child)
class AnimalShelter(): def __init__(self): self.cats = Queue() self.dogs = Queue() def enqueue(self, animal): if animal.__class__ == Cat: self.cats.add(animal.name) else: self.dogs.add(animal.name) def dequeueAny(self): if not self.dogs.isEmpty(): return self.dequeueDog() else: self.dequeueCat() def dequeueCat(self): if self.cats.isEmpty(): return None else: cat = self.cats.peek() self.cats.remove() return cat def dequeueDog(self): if self.dogs.isEmpty(): return None else: dog = self.dogs.peek() self.dogs.remove() return dog def print_shelter(self): print() print('Our Cats : ') for i in self.cats.my_queue: print(i) print() print('Our Dogs : ') for i in self.dogs.my_queue: print(i) print()
class TestQueueClasses(TestCase): def setUp(self): self.queue = Queue() def test_is_empty(self): self.assertTrue(self.queue.is_empty()) def test_insert(self): self.queue.insert(1) self.assertEqual(1, self.queue.head.cargo) def test_remove(self): self.queue.insert(1) self.assertEqual(1, self.queue.remove()) def test_insert_remove_multi(self): self.queue.insert(1) self.queue.insert(2) self.queue.insert(3) self.assertEqual(1, self.queue.remove()) self.assertEqual(2, self.queue.remove()) self.assertEqual(3, self.queue.remove())
class QueueTest(TestCase): def setUp(self): self.queue = Queue() def test_add(self): """tests the add function of the Queue class""" self.queue.add(1) self.assertEqual([1], self.queue.queue) def test_remove(self): """tests the remove function of the Queue class""" a = self.queue.queue[0] self.assertEqual(a, self.queue.remove())
def bfs(self, index): root = self.__nodes[index] queue = Queue() queue.add(root) root.marked = True while not queue.is_empty(): remove_node = queue.remove() for n in remove_node.adjacent: if not n.marked: n.marked = True queue.add(n) visit(remove_node) print()
def BreathFistSearch(root): if root is None: return from Queue import Queue queue = Queue() root.state = State.VISITING queue.add(root) while queue.isEmpty() is False: node = queue.remove() for child in node.adj: if child.state is State.UNVISITED: child.state = State.VISITING queue.add(child) visit(node) node.state = State.VISITED
def BFS(self): if len(self.nodes) == 0: return [] root = self.nodes[0] visited = set([root]) Q = Queue() Q.add(root) BfsResult = [] while Q.size() > 0: QueueHead = Q.remove() BfsResult.append(QueueHead) for neighbour in QueueHead.neighbours: if neighbour not in visited: Q.add(neighbour) visited.add(neighbour) return BfsResult
def RouteBetweenNodes(G, A, B): from Queue import Queue if A == B: return True queue = Queue() for u in G.nodes: u.state = State.UNVISITED A.state = State.VISITING queue.add(A) while queue.isEmpty() is False: node = queue.remove() for v in node.adj: if v == B: return True elif v.state == State.UNVISITED: v.state = State.VISITING queue.add(v) node.state = State.VISITED return False
queue = Queue() option = 0 while option != 'exit': printQueue(head) option = optionQueue() if option == '1': [name, titles ] = input('Enter team and their titles e.g. (name, titles): ' ).split(', ') data = footballTeam(name, titles) head = queue.add(head, data) os.system('clear') elif option == '2': head = queue.remove(head) os.system('clear') elif option == '3': os.system('clear') print(f'\nIs the Queue empty? {queue.isEmpty(head)}') elif option == '4': os.system('clear') print(f'\nSize of the current Queue is {queue.size(head)}') elif option == '5': os.system('clear') print(f'\nThe current top of the Queue is {queue.top(head)}') else: break
from Queue import Queue import os, sys currentdir = os.path.dirname(os.path.realpath(__file__)) parentdir = os.path.dirname(currentdir) sys.path.append(parentdir) from helpers import readData from env import env if __name__ == "__main__": airbnbList = readData(env['path_airbnb']) myQueue = Queue() for i in range(myQueue.limit): myQueue.insert(airbnbList[i]) myQueue.show() #myQueue.remove() print( "##############################################################################################################################" ) myQueue.tam() myQueue.remove() print( "##############################################################################################################################" ) myQueue.insert(airbnbList[0]) myQueue.show()
from Queue import Queue queue = Queue() queue.insert(5) queue.insert(6) print queue.remove() queue.insert(7) print queue.remove() print queue.remove() print queue.remove()
class Operation: def __init__(self): self.IBSTree = BSTree(None) self.IQueue = Queue() # Load file to data set def loadFile(self,file): try: fh = open(file,"r") fh.readline() for line in fh: arr = list(line.rstrip().split(',')) # New person person = Person(arr[0],arr[1],arr[2],arr[3]) # Add person to Tree self.IBSTree.insert(person) print("The file is loaded successfully!") except: print("File path is correct!") # Add person to dataset def addNewPerson(self): IDExist = True ID = None while IDExist: ID = input("Please insert the new ID:") # Check ID is existed person = self.IBSTree.findPerson(ID) if person is None: IDExist = False else: print("This ID has been chosen, please choose anothor ID!") name = input("Please insert the Name:") birthplace = input("Please insert the Birthplace:") birthofDate = input("Please insert the Birth of Date:") person = Person(ID,name,birthofDate,birthplace) # Add to Tree self.IBSTree.insert(person) print("New ID:", person.ID) print("Name:", person.Name) print("Birthplace:",person.Birthplace) print("Date of birth:",person.DayofBirth) input("Please tyoe anything to come back to the main memu") # Inorder : Left to Right def InorderTraverse(self): lists = self.IBSTree.Inorder(self.IBSTree) print("ID | Name | Day of Birth | Birthplace") for person in lists: person.printDetail() input("Please tyoe anything to come back to the main memu") # Queue def Bfs(self): print("ID | Name | Day of Birth | Birthplace") if self.IBSTree is None: return self.IQueue.add(self.IBSTree) # Loop Queue and Print while self.IQueue.peek() is not None: current_node = self.IQueue.remove() current_node.person.printDetail() if (current_node.left is not None): self.IQueue.add(current_node.left) if (current_node.right is not None): self.IQueue.add(current_node.right) input("Please tyoe anything to come back to the main memu") # Search Person def SearchbyID(self,ID): print("Search for ID = ",ID) person = self.IBSTree.findPerson(ID) if person is not None: print("ID | Name | Day of Birth | Birthplace") person.printDetail() else: print("The searched ID is not valid") input("Please tyoe anything to come back to the main memu") # Delete by ID def DeleteByID(self,ID): #Search Person personFound = self.IBSTree.findPerson(ID) if personFound is not None: # Delete Person self.IBSTree.delete(self.IBSTree,ID) print("ID | Name | Day of Birth | Birthplace") personFound.printDetail() else: print("The searched ID is not valid") input("Please tyoe anything to come back to the main memu")
print("Conveyor Belt Generated") print("Input your commands") print(" 0XXXX \n" "Retrieve a product with ID XXXX \n" "1XXXX \n" "Store a product with ID XXXX \n" "2XY00 \n" "Sort warehouse X at row Y \n" "30000 \n" "Retrieve a product from the conveyor belt \n" "40000 \n" "Output information on all of the warehouses \n" "5XXXX \n" "Search for a product ID XXXX \n" "9XXXXYYYY \n" "Manually put a product ID XXXX at position YYYY \n") newcom = True while newcom: comm = input("Please enter command\n") commandQue.add(Node(comm)) yesno = '' while yesno != 'y' and yesno != 'n': yesno = input("Would you like to enter another command? y/n\n") yesno = yesno.lower() if yesno == 'n': newcom = False #Execution for i in range(commandQue.size): executeCommand(commandQue.remove())
from Stack import Stack from Queue import Queue s = Stack() s.push(1) s.push(2) s.push(3) q = Queue() q.add(1) q.add(2) q.add(3) print("Stack 'contains' tests: %r, %r, %r, %r" % (s.contains(0), s.contains(1), s.contains(2), s.contains(3))) print("Queue 'contains' tests: %r, %r, %r, %r" % (q.contains(0), q.contains(1), q.contains(2), q.contains(3))) s.pop() s.pop() s.pop() print("Empty stack 'contains' test: %r" % s.contains(4)) q.remove() q.remove() q.remove() print("Empty queue 'contains' test: %r" % q.contains(4))