def test_peek_checks_first_entry(self): q = Queue() q.enqueue(1) q.enqueue(2) self.assertEqual(1, q.peek())
def test_pop_empty_queue(self): q = Queue() try: q.dequeue() self.fail("Should not be able to dequeue empty queue") except IndexError as e: self.assertEqual("Queue is empty", str(e))
def test_push_pop_changes_size(self): q = Queue() self.assertEqual(0, len(q)) q.enqueue(1) self.assertEqual(1, len(q)) q.enqueue(2) self.assertEqual(2, len(q)) q.dequeue() self.assertEqual(1, len(q)) q.dequeue() self.assertEqual(0, len(q))
def visit_nodes(): work_list = Queue() work_list.enqueue(from_vertice) visited = set() while work_list: current_vertice = work_list.dequeue() if current_vertice == to_vertice: break visited.add(current_vertice) for neighbor in graph.neighbors(current_vertice): if neighbor not in visited: work_list.enqueue(neighbor) parent[neighbor] = current_vertice
def nodes_at_level(graph, root, depth): """Returns the name of all vertices that are at the specified level. If no such nodes exist, return an empty list. Args: graph(Graph): the graph to extract nodes from root(str): the name of the root node to start from depth(int): the depth away from the root node Returns: list(str): a list of the names of all vertices reachable at depth Raises: ValueError: if the depth is negative ValueError: if root does not exist in the graph""" if not graph.contains_vertice(root): raise ValueError("Root not found in graph") if depth < 0: raise ValueError("Given invalid depth") result = [] work_list = Queue() work_list.enqueue((root, 0)) discovered = set() while work_list: current_vertice, current_level = work_list.dequeue() if current_vertice in discovered: continue discovered.add(current_vertice) if current_level < depth: for neighbor in graph.neighbors(current_vertice): work_list.enqueue((neighbor, current_level + 1)) elif current_level == depth: result.append(current_vertice) # neighbors at this point are discarded if level >= depth return result
def test_empty_queue_length_and_bool(self): q = Queue() self.assertEqual(0, len(q)) self.assertFalse(q)
def test_push_peek(self): q = Queue() q.enqueue(10) self.assertEqual(1, len(q)) self.assertEqual(10, q.peek())
def test_push_peek_pop_ordering(self): q = Queue() q.enqueue(1) q.enqueue(2) q.enqueue(3) self.assertEqual(1, q.peek()) self.assertEqual(1, q.dequeue()) self.assertEqual(2, q.peek()) self.assertEqual(2, q.dequeue()) self.assertEqual(3, q.peek()) self.assertEqual(3, q.dequeue())