0(1[2]3{4}5)stack1PAIR = {")": "(", "]": "[", "}": "{"}2def balanced(text):3 stack = []4 for ch in text:5 if ch in "([{":6 stack.append(ch)7 elif ch in PAIR:8 if not stack or stack.pop() != PAIR[ch]:9 return False10 return not stackresult
Stack: item blocks on a plinth, the newest on topInput tape: the tokens, read left to rightA hopping token: one push or one popEach token hops from the input tape to the stack: a push lands on top, a pop takes the top item off. balanced() pushes every opener and lets every closer pop its partner; an editor pushes every edit and undo pops the newest; a postfix calculator pushes numbers and lets each operator pop two and push the result.

Matching brackets

  1. In ([]{}) every closing bracket must match the most recent bracket still open. Most recent first is last in, first out: the rule of a stack. A Python list works as one: append() pushes on top, pop() takes the top off.

Undo

Evaluating expressions

What happens

;; step 1/10 · why-stack
input: "([]{})"
rule: a closer must match the newest opener still open
stack = []          # a Python list
stack.append(x)     # push x on top
stack.pop()         # remove and return the top

The not stack test on line 8 matters: a closer with nothing open, as in ")(", would make pop() on an empty list raise IndexError. Python checks not stack first and stops there, so pop() never runs on an empty list. Python list append() and pop() from the end take amortized O(1) time (MIT 6.006, lecture 2), so balanced() and eval_postfix() run in O(n) time for n characters or tokens. In the worst case, such as "((((", the stack grows to n items.