def test_balance(): for string, res in zip( ('(()()(()', '(()((())()))', '())(', '))((', '((())', '(hjy()(()', '(()(pdd()))', '(a)(', '))f(d)((', '(()t', ')))'), (False, True, False, False, False, False, True, False, False, False, False)): print(string, res) assert Stack.is_balanced(string) == res
def test_pop(): for vals, (cor_res, popped) in zip( ([1, 2, 3, 4], [], [0], [None, 0, 17]), (([1, 2, 3], 4), ([], None), ([], 0), ([None, 0], 17))): stack = Stack.create(vals) p = stack.pop() print(vals, 'pop:', cor_res, popped) assert stack.to_list() == cor_res and p == popped
def test_peek(): for vals, (cor_res, corr_p) in zip( ([1, 2, 3, 4], [], [0], [None, 0, 17]), (([1, 2, 3, 4], 4), ([], None), ([0], 0), ([None, 0, 17], 17))): stack = Stack.create(vals) p = stack.peek() print(vals, 'peek:', cor_res, corr_p) assert stack.to_list() == cor_res and p == corr_p
def test_push(): for (vals, adds), res in zip( (([1, 2], [3, 4]), ([], []), ([], [0]), ([], [None]), (list(range(5)), list(range(5, 0, -1)))), ([1, 2, 3, 4], [], [0], [None], [0, 1, 2, 3, 4, 5, 4, 3, 2, 1])): stack = Stack.create(vals) for a in adds: stack.push(a) print(vals, '+', adds, res) assert stack.to_list() == res
def test_size(): for vals, res in zip(( list('(()()(()'), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], ), ( 8, 10, )): print(vals, res) assert Stack.create(vals).size() == res
def __init__(self): self.inputs = Stack() self.outputs = Stack()
class StackedQueue: def __init__(self): self.inputs = Stack() self.outputs = Stack() def enqueue(self, item): self.inputs.push(item) def dequeue(self): if not self.outputs.size(): while self.inputs.size(): self.outputs.push(self.inputs.pop()) return self.outputs.pop() def size(self): return self.inputs.size() + self.outputs.size() def to_list(self): return self.inputs.to_list()[::-1] + self.outputs.to_list() @classmethod def create(cls, vals: list): new_queue = cls() for v in vals: new_queue.enqueue(v) return new_queue
def test_postfix_calc(): for string, res in zip( ('1 2 + 3 * =', '8 2 + 5 * 9 + =', '1 2 + 3 + 4 + =', '1 2 + 5 * 3 * 0 =', '4 1 2 + * ='), (9, 59, 10, 0, 12)): print(string, res) assert Stack.postfix_calc(string) == res