Stacks in practice
Implement bracket matching and reverse Polish notation evaluation using a Python list as a stack.
- Implement is_balanced(s) for bracket matching using a stack
- Implement evaluate_rpn(tokens) for reverse Polish notation evaluation
- Trace through both algorithms step by step
Two problems that have clean stack solutions. Read through the code, then modify and re-run to build intuition.
Bracket matching and RPN evaluation
is_balanced checks that every opening bracket has a matching closer in the
right order. evaluate_rpn evaluates a postfix expression. Both follow the same
pattern: scan the input left to right, push to or pop from a stack at each step.
Tracing is_balanced on {[()]}
Walk through {[()]} character by character:
| Step | Character | Action | Stack |
|---|---|---|---|
| 1 | { | push opener | [{] |
| 2 | [ | push opener | [{, [] |
| 3 | ( | push opener | [{, [, (] |
| 4 | ) | pop (, matches | [{, [] |
| 5 | ] | pop [, matches | [{] |
| 6 | } | pop {, matches | [] |
Stack is empty at the end — balanced.
Now try {[(]): at step 4 you hit ], pop (, but ( does not match ] —
return False immediately.
Tracing evaluate_rpn on 3 4 + 2 *
| Step | Token | Action | Stack |
|---|---|---|---|
| 1 | 3 | push number | [3] |
| 2 | 4 | push number | [3,4] |
| 3 | + | pop 4 and 3, push 7 | [7] |
| 4 | 2 | push number | [7,2] |
| 5 | * | pop 2 and 7, push 14 | [14] |
Result: 14. The order of pops matters: the second pop is the left operand.
RPN eliminates the need for parentheses and operator precedence rules entirely. Calculators from the 1970s used RPN because it was simpler to implement in hardware. Postscript (the language behind PDFs) is RPN-based.
Where to go next
Next: queues — the FIFO counterpart to the stack, and why collections.deque
matters for efficient queue operations.