def test_stack(self): stack = Stack() for i in [23, 4, 2, 56]: stack.push(i) self.assertEqual(stack.size(), 4) self.assertEqual(stack.peek(), 56) self.assertEqual(stack.pop(), 56) stack.pop() stack.pop() stack.pop() self.assertEqual(stack.size(), 0) self.assertRaises(RuntimeError, stack.pop)
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