def test_error_is_empty(self): queue = Queue(size=3) self.assertEqual(queue.is_empty(), True) queue.put(5) self.assertEqual(queue.is_empty(), False) queue.get() self.assertEqual(queue.is_empty(), True)
class TestQueue(unittest.TestCase): def setUp(self): self.our_queue = Queue() def test_is_empty(self): self.assertTrue(self.our_queue.is_empty()) def test_enqueue(self): self.our_queue.enqueue(5) self.assertEqual(5, self.our_queue.peek()) def test_is_not_empty(self): self.our_queue.enqueue(5) self.assertFalse(self.our_queue.is_empty()) def test_dequeue(self): self.our_queue.enqueue(5) self.our_queue.enqueue(8) self.our_queue.enqueue(5) self.assertEqual(5, self.our_queue.peek()) self.assertEqual(5, self.our_queue.dequeue()) self.assertEqual(8, self.our_queue.peek()) def test_get_size(self): self.our_queue.enqueue(5) self.our_queue.enqueue(8) self.our_queue.enqueue(5) self.assertEqual(3, self.our_queue.size_of())
def test_is_empty(self): q = Queue() q.enqueue(1) q.enqueue(2) q.enqueue(3) q.dequeue() q.dequeue() self.assertFalse(q.is_empty()) q.dequeue() self.assertTrue(q.is_empty())
def test_dequeue(self): mock_item1 = MagicMock() mock_item2 = MagicMock() queue = Queue() queue.enqueue(mock_item1) queue.enqueue(mock_item2) assert queue.is_empty() == False assert queue.dequeue() == mock_item1 assert queue.dequeue() == mock_item2 assert queue.is_empty() == True
def queue_first(): q = Queue() q.print() print("Is empty?", q.is_empty()) for i in range(1, 9, 2): print("Enq ", str(i) + ": ", end="") q.enq(i) q.print() print("Front:", q.front()) for i in range(4): print("Deq: ", q.deq(), "- ", end="") q.print() print("Front:", q.front()) print("Is empty?", q.is_empty())
def topological_sort(graph): all_in_degrees = graph.compute_indegree_every_vertex() sort_result = [] q = Queue() for i in range(len(all_in_degrees)): if all_in_degrees[i] == 0: q.enqueue(i) while not q.is_empty(): u = q.dequeue() sort_result.append(u) for adj_vertex in graph.get_vertices_reachable_from(u): all_in_degrees[adj_vertex] -= 1 if all_in_degrees[adj_vertex] == 0: q.enqueue(adj_vertex) if len(sort_result) != graph.get_num_vertices(): return None return sort_result
def __str__(self): queue = Queue() graph_string = "" print("Searching WUG") for node in self.nodes: self.set_all_nodes_unvisited() queue.empty() queue.add(node) node_string = "" while not queue.is_empty(): current_node = queue.poll() if current_node.is_visited(): continue current_node.set_visited(True) node_string += str(current_node) + "\n\t" for edge in current_node.get_edges(): if not edge.get_node().is_visited(): node_string += str(edge.get_weight()) + " -> " + str( edge.get_node()) + "\n\t" if node_string != "": graph_string += node_string + "\n" return graph_string
class TestGraph(unittest.TestCase): def setUp(self): self.queue = Queue() def test_is_empty_true(self): self.assertTrue(self.queue.is_empty()) def test_is_empty_false(self): self.queue.push('a') self.assertFalse(self.queue.is_empty()) def test_pop(self): self.queue.push('a') self.queue.push('b') self.assertEqual(self.queue.pop(), 'a') self.assertEqual(self.queue.pop(), 'b')
def tree_info(node): """ Returns the number of nodes and the height of the sub-tree starting at <node>. """ # Initialize the queue queue = Queue() # Add the root node and its level to the queue queue.enqueue((node, 0)) # Loop until the queue is empty size = 0 height = 0 while (not queue.is_empty()): # Get the last node from the queue node, level = queue.dequeue() size += 1 # If it has a left child put it in the queue with its level left_child = node.get_left() if (left_child is not None): queue.enqueue((left_child, level + 1)) height = max(height, level + 1) # If it has a right child put it in the queue with its level right_child = node.get_right() if (right_child is not None): queue.enqueue((right_child, level + 1)) height = max(height, level + 1) return size, height
def search_queue(self, value, node): """ Searches the binary tree for the specified value using a queue (FIFO order) and returns the corresponding node object. Returns <None> if not found. """ # Initialize the queue queue = Queue() # Add the root node queue.enqueue(node) # Loop until the queue is empty while (not queue.is_empty()): # Get the last node from the queue node = queue.dequeue() # Check the node if (node.get_value() == value): return node # If it has a left child put it in the queue left_child = node.get_left() if (left_child is not None): queue.enqueue(left_child) # If it has a right child put it in the queue right_child = node.get_right() if (right_child is not None): queue.enqueue(right_child) return None
def tree_nodes(node): """ Returns in a list of lists the node information in the tree/sub-tree starting at <node>. """ node_list = [] # Initialize the queue queue = Queue() # Add the root node and its level to the queue queue.enqueue(node) # Loop until the queue is empty while (not queue.is_empty()): # Get the last node from the queue and append its info node = queue.dequeue() node_list.append(node_info(node)) # If it has a left child put it in the queue left_child = node.get_left() if (left_child is not None): queue.enqueue(left_child) # If it has a right child put it in the queue right_child = node.get_right() if (right_child is not None): queue.enqueue(right_child) return node_list
def simulateManyServer(num_secs, file_per_min, in_file, num_servers): request_list = [Server(file_per_min) for i in range(num_servers)] print_queue = Queue() waiting_times = [] with open(in_file) as lines: for line in lines: data = line.split(',') request = Request(int(data[0].strip()), data[1], int(data[2].strip())) print_queue.enqueue(request) current_server = 0 for current_second in range(num_secs): if (not request_list[current_server].busy()) and ( not print_queue.is_empty()): next_task = print_queue.dequeue() waiting_times.append(next_task.wait_time()) request_list[current_server].start_next(next_task) current_server = (current_server + 1) % len(request_list) for server in request_list: if server.busy: server.tick() average_wait = sum(waiting_times) / len(waiting_times) print("Average Wait %6.2f secs %3d tasks remaining." % (average_wait, print_queue.size()))
class Book: """ A book in a library === Attributes === name: the name of this book author: the author(s) of this book publication date: the publication date of this book wait_list: a queue of members waiting to rent the book due_date: the date that this book must be returned is_rented: the status of the book regarding renting it owned_by: the library that owns the book * Note that the member at the front of the queue represents the user who is currently holding the book * === Representation Invariants === is_rented = False => Book.rent_list.is_empty() = True """ name: str author: str publication_date: date rent_list: Queue due_date: date is_rented: bool owned_by: Any def __init__(self, name: str, author: str, publication_date: List[int]): """ Creates a new Book object :param name: the name of the book :param author: the author of the book :param publication_date: a list containing the year, month, and date of publication """ self.name = name self.author = author self.publication_date = date(int(publication_date[0]), int(publication_date[1]), int(publication_date[2])) self.rent_list = Queue() self.due_date = date.today() self.is_rented = False self.owned_by = None # Book is initially owned by nobody def __str__(self): return "{0}, by {1}".format(self.name, self.author) def __repr__(self): return "({0})".format(str(self)) def __eq__(self, other: Book): return self.name == other.name and self.author == other.author def is_available(self) -> bool: """ Returns true iff this book is available to rent. False otherwise """ return self.rent_list.is_empty()
def __str__(self): queue = Queue() graph_string = "" for node in self.nodes: self.set_all_nodes_unvisited() queue.empty() queue.add(node) node_string = "" while not queue.is_empty(): current_node = queue.poll() if current_node.is_visited(): continue current_node.set_visited(True) node_string += str(current_node) + " -> " for adjacent_node in current_node.get_adjacent_nodes(): if not adjacent_node.is_visited(): queue.add(adjacent_node) if node_string != "": graph_string += node_string[:-4] + "\n" return graph_string
def BFS(self): # keep a queue for BFS queue = Queue() # enqueue the start state to the queue as a tuple (state, parent_state) self.start_state.set_parent(State(None)) queue.enqueue(self.start_state) self.expanded.append((self.start_state.get_state(), None)) # keep looping whilst there's still states in the queue while queue.is_empty() != True and len(self.visited) <= 1000: # dequeue next state and add it to visited current_state = queue.front() parent_state = queue.dequeue().get_parent() children_states = self.get_children_states(current_state, parent_state) self.visited.append(current_state.get_state()) # add current states children states to the queue for child_state in children_states: queue.enqueue(child_state) self.expanded.append((child_state.get_state(), self.last_update(child_state, current_state))) # check if end state is found if current_state.get_state() == self.goal_state.get_state(): # end state found self.path(current_state) break
def breadth_first_tree_search(self, problem): queue = Queue() node = Node(problem.initial, None, None, 0) queue.enqueue(node) explored = [] #print("problem initial = ", problem.initial) while not queue.is_empty(): node = queue.dequeue() #print(node.state) if (problem.goal_test(node.state)): #print("goal reached: ", node.state) return node explored.append(node.state) problem.visited = len(explored) frontier_nodes = node.expand_frontier(problem) problem.time += len(frontier_nodes) #print("frontier: ", frontier_nodes.state) for fnode in frontier_nodes: #print(fnode) if (fnode != None and fnode.state not in explored): queue.enqueue(fnode) if (queue.size() > problem.frontier): problem.frontier = queue.size() return None
def _test_queue(self): queue = Queue() assert queue.is_empty() for item in self._test_items: queue.push(item) assert queue.size() == 4, "expected queue to be of size 4" assert ( queue.peek() == "firstItem" ), "expected first item in queue to be firstItem" popped = queue.pop() assert queue.size() == 3 assert queue.peek() == "secondItem" assert popped == "firstItem" while not queue.is_empty(): queue.pop() assert queue.is_empty()
def simulation(numSeconds, ppm1, ppm2,minTask,maxTask): p1 = Printer(ppm1) p2 = Printer(ppm2) pQueue = Queue() wTimes = [] avgList = [] for currentSecond in range(numSeconds): if newpTask(): task = Task(currentSecond,minTask,maxTask) pQueue.enqueue(task) if (p1.getPageRate() >= p2.getPageRate() or p2.getPageRate() is 0): p1fastest = True else: p1fastest = False if (not p1.busy() and not p2.busy() and p2.getPageRate() is not 0 and not pQueue.is_empty()): if (p1fastest): nexttask = pQueue.dequeue() wTimes.append(nexttask.waitTime(currentSecond)) p1.startNext(nexttask) elif (not pr1fastest): nexttask = pQueue.dequeue() wTimes.append(nexttask.waitTime(currentSecond)) p2.startNext(nexttask) if (not p1.busy()): if (not pQueue.is_empty()): nexttask = pQueue.dequeue() wTimes.append(nexttask.waitTime(currentSecond)) p1.startNext(nexttask) if (p2.getPageRate() is not 0 and not pr2.busy()): if (not pQueue.is_empty()): nexttask = pQueue.dequeue() wTimes.append(nexttask.waitTime(currentSecond)) p2.startNext(nexttask) p1.tick() p2.tick() avgWait = sum(wTimes)/len(wTimes) print("Average Wait %6.2f secs %3d tasks remaining." \ %(avgWait,pQueue.size())) output = ("Average Wait %6.2f secs %3d tasks remaining." \ %(avgWait,pQueue.size())) return(avgWait)
def leverorder(self, root): q = Queue() q.enqueue(root) while not q.is_empty(): node = q.dequeue print(str(node.get_key()), ' ', end='') if node.get_left(): q.enqueue(node.get_left()) if node.qet_right(): q.enqueue(node.get_right())
def radixSort(nums): """ we are taking the input as list of numbers (in string format) reason being - it will ease in indexing and getting the individual digits with the help of string utilities. Return - we return a list of numbers which are sorted in increasing order""" if nums is None or len(nums) < 1: return nums mainQ = Queue() binQs = [] # Add all the numbers in the main Queue for n in nums: mainQ.enqueue(n) # create an array of Queues and initialize them - bin 0 to 9 for i in range(10): binQs.append(Queue()) # get the max length of digits in any input number - this will decide the # outer iteration we need to do in our radix sort implementation maxLen = len(nums[0]) for i in range(1, len(nums)): if len(nums[i]) > maxLen: maxLen = len(nums[i]) # we need to iterate maxLen times ie length of the biggest number (in # digits) for i in range(1, maxLen + 1): visited = [] # below iteration includes only numbers of digit length i while not mainQ.is_empty(): val = mainQ.dequeue() if i > len(val): visited.append(val) continue r = val[-i] #get the ith index from last r = int(r) binQs[r].enqueue(val) for v in visited: mainQ.enqueue(v) for i in range(10): while not binQs[i].is_empty(): mainQ.enqueue(binQs[i].dequeue()) result = [] while not mainQ.is_empty(): result.append(mainQ.dequeue()) return result
def breadth_first(a): result_list = [] queue = Queue() queue.enqueue(a) while not queue.is_empty(): treenode = queue.dequeue() if treenode is not None: queue.enqueue(treenode.get_left()) queue.enqueue(treenode.get_right()) result_list.append(treenode.get_data()) return (result_list)
def test_empty_queue(self): queue = Queue() self.assertEqual(queue.head, None) self.assertEqual(queue.tail, None) self.assertTrue(queue.is_empty()) with self.assertRaises(Queue.Empty): queue.peek() with self.assertRaises(Queue.Empty): queue.dequeue()
def ac_3(node, graph, available_colors, neighbours_assigned_colors): test_available_colors = {} need_to_backtrack = False for color in available_colors[node]: test_available_colors = {} for k, v in available_colors.items(): test_available_colors[k] = v test_available_colors[node] = color arc_already_queued = {} queue = Queue() for neighbour in graph.get(node): arc = (neighbour, node) queue.enque(arc) arc_already_queued[arc] = True print arc_already_queued while not queue.is_empty(): arc = queue.deque() arc_already_queued[arc] = False state = remove_inconsistent_values(arc, test_available_colors) removed = state[0] need_to_backtrack = state[1] if removed: for neighbour in graph.get(arc[0]): adj_arc = (neighbour, arc[0]) if not arc_already_queued.get(adj_arc): queue.enque(adj_arc) arc_already_queued[adj_arc] = True if need_to_backtrack: break print 'need to backtrack: ', need_to_backtrack print 'test available colors: ', test_available_colors if not need_to_backtrack: break available_colors = {} for k, v in test_available_colors.items(): available_colors[k] = v neighbours_assigned_colors[node] = True for neighbour in graph.get(node): if not neighbours_assigned_colors.get(neighbour): node = neighbour break counter = 0 for k, v in test_available_colors.items(): if len(test_available_colors.get(k)) == 1: counter += 1 print 'next node ', node print 'available colors: ', available_colors if counter == len(available_colors): return True print 'counter: ', counter ac_3(node, graph, available_colors, neighbours_assigned_colors)
def levelorder(self): result = [] queue = Queue() queue.enqueue(self.get_root()) while not queue.is_empty(): current = queue.dequeue() result.append(current) if current.get_left() is not None: queue.enqueue(current.get_left()) if current.get_right() is not None: queue.enqueue(current.get_right()) return result
def bfs_search(self, root): queue = Queue() root.visited = True queue.enqueue(root) while not queue.is_empty(): r = queue.dequeue() print(r) for node in r.links: if node.visited is False: node.visited = True queue.enqueue(node)
class TestQueueADT(unittest.TestCase): def setUp(self): self.my_queue = Queue() def test_exceptions(self): self.assertRaises(IndexError, self.my_queue.dequeue) def test_queue_operations(self): self.assertEquals(self.my_queue.is_empty(), True) queue_elements = ["First", "Second", "Third", "Fourth"] counter = 0 while counter < len(queue_elements): self.my_queue.enqueue(queue_elements[counter]) self.assertEquals(self.my_queue.is_empty(), False) counter += 1 counter = 0 while counter < len(queue_elements): self.assertEquals(self.my_queue.dequeue(), queue_elements[counter]) counter += 1 self.assertEquals(self.my_queue.is_empty(), True)
def bfs(self, element): result = [] queue = Queue() queue.enqueue(self.get_root()) while not queue.is_empty(): current = queue.dequeue() if current.get_data() == element: return element if current.get_left() is not None: queue.enqueue(current.get_left()) if current.get_right() is not None: queue.enqueue(current.get_right()) return None
def display_bfs(vertex): visited = set() q = Queue() q.push(vertex) while not q.is_empty(): current = q.pop() if current in visited: continue visited.add(current) print(current.get_key()) for dest in current.get_neighbours(): if dest not in visited: q.push(dest)
def bfs(self): """ Returns the path from the start position to the goal position using breath first search (BFS). Returns <None> if no solution is found. """ # Initialize the queue queue = Queue() # Add the start point to the queue queue.enqueue(self.start) previous = {self.start: None} self.added = 1 # Loop until the queue is empty self.visited = 0 while (not queue.is_empty()): # Get the last item from the queue current = queue.dequeue() self.visited += 1 # Stop if it is the goal and return the path if (current == self.goal): path = self.get_path(previous) return path # Define the order in the directions idx = self.order_dir() # Add to the queue the neighbours of the current position for direction in idx: # Offset values row_offset, col_offset = self.offset[direction] # Neighbour position row_neigh = current[0] + row_offset col_neigh = current[1] + col_offset neighbour = (row_neigh, col_neigh) # If neighbour position is valid and not in the dictionary if (self.layout[row_neigh][col_neigh] != '#' and self.layout[row_neigh][col_neigh] != '*' and neighbour not in previous): # Add it to the queue queue.enqueue(neighbour) previous[neighbour] = current self.added += 1 return None
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()