20 — Practice solutions

← Questions

These are independently written explanations, not an official marking scheme.

20A

Pop returns 7. Final contents [4, 2, 9], top 2. Another push is disallowed because capacity is 3 and all positions are live.

20B

def balanced(text):
    stack = []
    for character in text:
        if character == "(":
            stack.append(character)
        elif character == ")":
            if len(stack) == 0:  # A closing bracket has no matching opener.
                return False
            stack.pop()  # Match this closer with the latest unmatched opener.
    return len(stack) == 0  # Leftover opening brackets also make it invalid.

Empty input leaves no unmatched brackets and returns True. ")(" fails at its first character because no earlier opening bracket exists.

20C

Stacks: [10], [10,4], [10,4,2], [10,8], [2]. Result 2. Infix converts to 10 4 2 * -. At subtraction, pop right=8 first, then left=10, and compute 10−8.