Overview
Check that every bracket in a line of code is closed in the right order with a stack, where counting brackets is not enough.
- append to push, pop to take the last item
- each closer matches the latest opener
- counting misses ([)]
Short Course
A stack is a list used from one end: append pushes, pop takes the last
item back, both O(1). It fits anything nested: each closing bracket must
match the most recent opening one. Trap: counting brackets accepts ([)].
history = []
history.append("home")
history.append("cart")
history.pop() # 'cart': the back button
history[-1] # 'home': the current page
Task
Write is_balanced(text): True if every (, [ and { in text is
closed by the matching bracket in the right order; other characters don't
matter. Example: is_balanced('f(a[0]) {}') → True,
is_balanced('([)]') → False.
Test Suites
Pending
Next
Output