Predict the output
What does this print?
balance, out = 3, []
for day, change in enumerate([-1, -1, 4, -7, 2]):
balance += change
out.append((day, balance))
print(out)Choose an answer, then open Show answer below to check it.
Show answer
Answer: A [(0, 2), (1, 1), (2, 5), (3, -2), (4, 0)]
Right: the balance first goes below zero on day 3.
Writing the running value after each step is exactly the dry-run table, and it shows the answer for the shown solution is day 3.
Why not the others?
- B [(0, 2), (1, 1), (2, 5), (3, -2)]. This loop records every day; it does not stop at the first negative.
- C [(1, 2), (2, 1), (3, 5), (4, -2), (5, 0)]. enumerate starts at 0.
Traced by running the Python solution.
Text version
Start at 3 (args [[-1, -1, 4, -7, 2], 3]):
| Line | day | change | balance |
|---|---|---|---|
| 2 | |||
| 3 | 3 (changed) | ||
| 4 | 0 (changed) | -1 (changed) | 3 |
| 5 | 0 | -1 | 2 (changed) |
| 3 | 0 | -1 | 2 |
| 4 | 1 (changed) | -1 | 2 |
| 5 | 1 | -1 | 1 (changed) |
| 3 | 1 | -1 | 1 |
| 4 | 2 (changed) | 4 (changed) | 1 |
| 5 | 2 | 4 | 5 (changed) |
| 3 | 2 | 4 | 5 |
| 4 | 3 (changed) | -7 (changed) | 5 |
| 5 | 3 | -7 | -2 (changed) |
| 6 | 3 | -7 | -2 |
14 rows, result 3.
Start at 1, never negative (args [[1, -1, 2], 1]):
| Line | day | change | balance |
|---|---|---|---|
| 2 | |||
| 3 | 1 (changed) | ||
| 4 | 0 (changed) | 1 (changed) | 1 |
| 5 | 0 | 1 | 2 (changed) |
| 3 | 0 | 1 | 2 |
| 4 | 1 (changed) | -1 (changed) | 2 |
| 5 | 1 | -1 | 1 (changed) |
| 3 | 1 | -1 | 1 |
| 4 | 2 (changed) | 2 (changed) | 1 |
| 5 | 2 | 2 | 3 (changed) |
| 3 | 2 | 2 | 3 |
| 7 | 2 | 2 | 3 |
12 rows, result -1.