Paul's Python CoursePPC

Stacks

Not met yet

A stack is a pile used only from the top: push puts something on, pop takes the top thing off, so the last in is the first out. A list is a good stack if you only use its end: append pushes and pop() pops, both O(1). Stacks fit anything that has to be undone or closed newest first: undo buttons, brackets, and the calls waiting in a recursion.

Try it

main.py
PARTNERS = {")": "(", "]": "[", "}": "{"}


def balanced(text):
    still_open = []
    for character in text:
        if character in "([{":
            still_open.append(character)
        elif character in PARTNERS:
            if not still_open or still_open.pop() != PARTNERS[character]:
                return False
    return not still_open


print(balanced("lift(hook[2]) swing{left}"))

Output

Press Run and what your program prints shows up here.

Easy to get wrong

  • Thinks pop() with no index takes the first item.
  • Thinks pop() reads the top item without taking it off the stack.
  • Thinks counting open brackets is enough to check them, without keeping which kinds were opened and in what order.
  • Thinks undo takes back the first change made rather than the latest.

Where it comes up