Python 3D Academyবাংলা

Matching brackets and evaluating expressions

🌍 In real life. You pack a gift for Eid: the bangles go in a small box, the small box goes in a bigger box, and the big box goes in a shopping bag. To unpack, you open the bag first, then the big box, then the small box: whatever was closed last is opened first. You can't open the small box while the big one is still shut around it.

Code nests the same way. In print(len(a[0])) every bracket that opens must close, and the inner ones must close before the outer ones.

The idea in one sentence: brackets are balanced when every closer matches the most recent opener that is still open, and nothing is left open at the end; a stack of the open brackets checks exactly that.

Its words:

  • opener: (, [ or {; closer: ), ] or }
  • balanced: every opener is closed by its own kind of closer, inner ones first

How it works, step by step:

  1. read the text one character at a time
  2. an opener: push it
  3. a closer: if the stack is empty, or the top is not its partner, it is not balanced; otherwise pop the top
  4. at the end: balanced only if the stack is empty

Watch ([]{()}) close every box in the right order:

Now ([)]. It has one of each bracket, so counting says it is fine. The stack sees the problem: when ) arrives, the most recent open bracket is [, not (:

Why it is correct. A closer can only close the innermost box that is still open, and the innermost open box is always the last opener pushed: the top. If the top is the wrong kind, the boxes cross, as in ([)]. If the stack is empty, there is no box to close. And whatever is still on the stack at the end was never closed.

What it costs. One push or one pop per character, each O(1): O(n) time for n characters. The stack holds at most every opener at once, so O(n) memory in the worst case (((((…).

def is_balanced(text):
    pairs = {")": "(", "]": "[", "}": "{"}
    stack = []
    for ch in text:
        if ch in "([{":
            stack.append(ch)
        elif ch in pairs:                    # other characters are ignored
            if not stack or stack[-1] != pairs[ch]:
                return False
            stack.pop()
    return not stack                         # nothing may be left open

for code in ["print(len(a[0]))", "([)]", "((", ")("]:
    print(code, is_balanced(code))

Evaluating expressions. A calculator has the same problem: in (3 + 4) × 2 the bracket must be worked out first. Written in postfix (each operator after its two numbers), the same sum is 3 4 + 2 *, with no brackets at all, and a stack works it out:

  1. a number: push it
  2. an operator: pop the right number, then the left number, and push the result
  3. at the end the one number left is the answer

So 3 4 + pushes 3 and 4, then pops them and pushes 7; 2 * pushes 2, then pops 2 and 7 and pushes 14. Python itself runs your code like this: its bytecode is a stack machine, pushing values and letting each operation pop its inputs.

def eval_postfix(expr):
    stack = []
    for token in expr.split():
        if token in ("+", "-", "*"):
            right = stack.pop()       # the top is the second number
            left = stack.pop()
            if token == "+":
                stack.append(left + right)
            elif token == "-":
                stack.append(left - right)
            else:
                stack.append(left * right)
        else:
            stack.append(int(token))
        print(token.rjust(2), stack)
    return stack.pop()

print(eval_postfix("3 4 + 2 *"))

Mistakes and edge cases.

  • returning True at the end without checking the stack is empty: (( would pass
  • popping on a closer without checking the stack first: ) crashes with IndexError instead of answering False
  • counting brackets instead of using a stack: ([)] has the right counts but crosses
  • in postfix, popping the numbers in the wrong order: 10 4 - is 10 − 4 = 6, and the top of the stack is the 4
  • an empty text is balanced: nothing opened, nothing to close

Quiz

  1. Which one is balanced?

    • ([)]
    • (()
    • {[()]}
  2. What does this print?

    stack = []
    for token in "4 2 - 3 *".split():
        if token == "-":
            right, left = stack.pop(), stack.pop()
            stack.append(left - right)
        elif token == "*":
            right, left = stack.pop(), stack.pop()
            stack.append(left * right)
        else:
            stack.append(int(token))
    print(stack)
  3. is_balanced("((") gives True. Which line is wrong?

    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 True
  4. Why isn't counting each kind of bracket enough?

    • The counts can match while brackets close in the wrong order, as in ([)]
    • Counting is too slow: O(n²)
    • Counting can't handle an empty text
  5. For a text of n characters, what does the stack check cost?

    • O(n) time, and up to O(n) memory
    • O(n²) time, O(1) memory
    • O(1) time

Coding tasks

  1. Write is_balanced(text) with a stack: True if every (, [ and { in text is closed by its own kind of bracket, inner ones first. Other characters don't matter.

  2. Fix eval_postfix(expr): expr is a postfix sum of whole numbers and +, -, *, separated by spaces, like "3 4 + 2 *". Give back its value.