Predict the output
What does this print?
cand, n = 0, 0
for v in [2, 2, 1, 1, 2]:
if n == 0:
cand = v
n += 1 if v == cand else -1
print(cand, n)Choose an answer, then open Show answer below to check it.
Show answer
Answer: A 2 1
Right: 2 leads, 1 and 1 cancel it to zero, and the last 2 restarts it at 1.
The counter ends as a leftover margin, not a tally, which is why a confirmation pass is needed without the guarantee.
Why not the others?
- B 1 0. After the two 1s the counter is 0, but the final 2 becomes the candidate.
- C 2 3. The counter is a margin, not the number of 2s.