Predict the output
What does this print?
stack: list[tuple[int, int]] = []
for v in [5, 3, 7, 2]:
low = min(v, stack[-1][1]) if stack else v
stack.append((v, low))
stack.pop()
print(stack[-1], stack[-1][1])Choose an answer, then open Show answer below to check it.
Show answer
Answer: A (7, 3) 3
Right: after popping 2, the top pair remembers the minimum 3.
Each pair records the minimum at the time it was pushed, so popping restores the earlier minimum for free.
Why not the others?
- B (7, 2) 2. The pair for 7 was pushed before 2 existed, so its minimum is 3.
- C (2, 2) 2. The pop removed the pair for 2.