Stacks: Balanced Brackets

Push every opening bracket, and pop when a closing one arrives. A stack checks nesting perfectly.

Python · intermediate · 7 min · 40 steps · free

What you'll learn

stack_brackets.py

def is_balanced(text):
    pairs = {')': '(', ']': '[', '}': '{'}
    stack = []
    for ch in text:
        if ch in '([{':
            stack.append(ch)
        elif ch in pairs:
            if not stack or stack.pop() != pairs[ch]:
                return False
    return len(stack) == 0

print(is_balanced('{[()]}'))
print(is_balanced('(]'))

Step by step

  1. Python defines the function is_balanced(). Its body does not run yet: it runs each time the function is called.
  2. Python calls is_balanced(), with text = '{[()]}'. It gets its own names.
  3. pairs is created and points to a new dict: {): '(', ]: '[', }: '{'}.
  4. stack is created and points to a new list: [].
  5. ch is created with the value '{'.
  6. ch in '([{' is true, so the block under it runs.
  7. { goes on top of the stack.
  8. ch changes from '{' to '['.
  9. ch in '([{' is true, so the block under it runs.
  10. '[' is added to the end of the list that stack points to.
  11. ch changes from '[' to '('.
  12. ch in '([{' is true, so the block under it runs.
  13. Three openers stacked: {, [, (.
  14. ch changes from '(' to ')'.
  15. ch in '([{' is false, so the block under it is skipped.
  16. ch in pairs is true, so the block under it runs.
  17. ) arrives: pop the top, (. It matches.
  18. ch changes from ')' to ']'.
  19. ch in '([{' is false, so the block under it is skipped.
  20. ch in pairs is true, so the block under it runs.
  21. '[' is removed from the end of the list that stack points to.
  22. ch changes from ']' to '}'.
  23. ch in '([{' is false, so the block under it is skipped.
  24. ch in pairs is true, so the block under it runs.
  25. '{' is removed from the end of the list that stack points to.
  26. Python moves to the next item of the loop: for ch in text.
  27. The stack is empty at the end: every bracket was closed. Balanced.
  28. is_balanced() has finished, so its names are gone. It prints True.
  29. Python calls is_balanced(), with text = '(]'. It gets its own names.
  30. pairs is created and points to a new dict: {): '(', ]: '[', }: '{'}.
  31. stack is created and points to a new list: [].
  32. ch is created with the value '('.
  33. ch in '([{' is true, so the block under it runs.
  34. '(' is added to the end of the list that stack points to.
  35. ch changes from '(' to ']'.
  36. ch in '([{' is false, so the block under it is skipped.
  37. ch in pairs is true, so the block under it runs.
  38. ] arrives but the top is (: they do not match.
  39. The function returns False.
  40. is_balanced() has finished, so its names are gone. It prints False.

Common mistakes

Best practices

Key takeaways

Check yourself

Push 1, 2, 3, then pop: you get?

Answer: 3

"((" is balanced?

Answer: No, the stack is not empty at the end

·

More in Lists, Stacks, Queues and Hashing