def test_push(): my_stack = Stack() my_stack.push(0) my_stack.push(1) assert my_stack.items == [0, 1] assert my_stack.size() == 2 assert my_stack.is_empty() is False
def parens_matched(x): # Read a string from left to right and decide whether left and right parentheses are balanced. stack = Stack() matched = True for char in x: if char == '(': stack.push(0) elif char == ')': popped = stack.pop() if popped == []: matched = False break return matched and stack.size() == 0
def convert_infix_to_postfix(infix_expr): op = Stack() postfix = [] infix = list(infix_expr) for index in range(len(infix)): if infix[index] in ops: while (not op.is_empty()) and precedence[op.peek()] >= precedence[infix[index]]: if op.peek() == '(': op.pop() else: postfix.append(op.pop()) if infix[index] != ')': op.push(infix[index]) elif infix[index] != ' ': postfix.append(infix[index]) while op.size() > 0: postfix.append(op.pop()) print(''.join(postfix))
def test_initialization(): my_stack = Stack() assert my_stack.items == [] assert my_stack.size() == 0 assert my_stack.is_empty()