def path_to(self, v): if not self.has_path_to(v): return None path = Stack() e = self.edge_to[v] while e is not None: path.push(e) e = self.edge_to[e.fr] return path
def topological_sort(graph): visited = [False] * graph.num_vertices stack = Stack() for v in range(graph.num_vertices): if visited[v]: continue depth_first_search(graph, v, visited, stack) return stack
def path_to(self, v): if not self.has_path_to(v): return None path = Stack() while v != self.source: path.push(v) v = self.edge_to[v] path.push(self.source) return path
def is_balanced(seq): stack = Stack() brackets = {"(": ")", "[": "]", "{": "}"} for idx, char in enumerate(seq): if char in brackets.keys(): stack.push((char, idx + 1)) elif char in brackets.values(): if stack.empty(): return (False, idx + 1) top, _ = stack.pop() if brackets[top] != char: return (False, idx + 1) else: continue return (stack.empty(), len(seq) - 1 if not stack.top() else stack.pop()[1])
def test_peek_empty_stack(self): newStack = Stack() self.assertEqual(newStack.peek(), None)
def test_clear(self): newStack = Stack([1,2,3,4,5]) newStack.clear() self.assertEqual(newStack.size(), 0)
def test_pop_from_empty_stack(self): newStack = Stack() popped = newStack.pop() self.assertEqual(popped, None)
def test_peek(self): newStack = Stack([1,2,3,4]) self.assertEqual(newStack.peek(), 4)
def test_pop(self): newStack = Stack([1,2,3,4]) popped = newStack.pop() self.assertEqual(popped, 4) self.assertEqual(newStack.size(), 3)
def test_push(self): newStack = Stack() newStack.push(1) self.assertEqual(newStack.size(), 1)
def test_is_empty(self): newStack = Stack() self.assertTrue(newStack.is_empty())
def test_size(self): newStack = Stack() self.assertFalse(newStack.size())
def test_initialize_empty_stack(self): try: newStack = Stack() print("test_initialize_empty_stack: PASS") except: print("test_initialize_empty_stack: FAIL")