class Queue: def __init__(self): self.push_queue = Stack() self.pop_queue = Stack() def is_empty(self): return self.pop_queue.is_empty() and self.push_queue.is_empty() def enqueue(self, data): self.push_queue.push(data) def dequeue(self): if self.is_empty(): raise Exception('Can\'t dequeue. Queue is empty') if self.pop_queue.is_empty(): while (not self.push_queue.is_empty()): self.push_queue.push(self.push_queue.pop()) return self.pop_queue.pop() def size(self): return self.push_queue.size() + self.pop_queue.size()
def check_balanced(expr): opening = '([{' closing = ')]}' opening_d = {opening[i] : closing[i] for i in range(len(opening))} closing_d = {closing[i] : opening[i] for i in range(len(opening))} s = Stack() for i, c in enumerate(expr): if c in opening_d: s.push(c) if c in closing_d: if not s.is_empty() and opening_d[s.peek()] == c: s.pop() else: print('parenthèse fermante en trop au caractère', i+1) return False return s.size() == 0
class StackTest(unittest.TestCase): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.test_stack = Stack() def test_to_array(self): self.test_stack.push('4') self.test_stack.push('5') self.assertEqual(self.test_stack.to_array(), ['5', '4']) def test_push(self): self.test_stack.push(4) self.test_stack.push(5) self.assertEqual(self.test_stack.to_array(), [5, 4]) def test_pop(self): self.test_stack.push(4) self.test_stack.push(5) self.assertEqual(self.test_stack.pop(), 5) self.assertEqual(self.test_stack.to_array(), [4]) def test_length(self): self.test_stack.push(4) self.test_stack.push(5) self.test_stack.push(4) self.test_stack.pop() self.assertEqual(len(self.test_stack), 2) def test_peek(self): self.test_stack.push(4) self.test_stack.push(5) self.test_stack.push(3) self.assertEqual(self.test_stack.peek(), 3) def test_is_empty(self): self.assertEqual(self.test_stack.is_empty(), True)