Code

The Stack of Scrolls

A data structure is a way of organizing data so that certain operations are fast and easy. The first one is the stack.

Last in, first out

Picture the Guild archivist piling scrolls on a desk. New scrolls go on top, and the archivist always takes from the top. That's LIFO: last in, first out.

A Python list makes a perfect stack. Adding and removing at the end is fast (O(1)):

stack = []
stack.append("map")      # push
stack.append("recipe")   # push
print(stack[-1])         # peek -> recipe
print(stack.pop())       # pop  -> recipe
print(stack)             # ['map']

Where stacks shine

Stacks are great whenever the most recent thing must be handled first: undo history, the call stack, and matching brackets. When you see an opening bracket, push it. When you see a closing bracket, the top of the stack must be its partner.

Pip tip: Check for an empty stack before you pop(), popping an empty list raises IndexError.

Assignment

Complete is_balanced(text):

  1. Loop over every character. Ignore anything that isn't a bracket.
  2. Push opening brackets (, [, { onto stack.
  3. For a closing bracket, return False if the stack is empty or its top isn't the matching opener (use PAIRS); otherwise pop.
  4. At the end, the text is balanced only if the stack is empty.