Predict the output
What does this print?
from collections import Counter
seen = Counter({0: 1})
total = hits = 0
for x in [1, 2, 1, 2]:
total += x
hits += seen[total - 3]
seen[total] += 1
print(hits)Choose an answer, then open Show answer below to check it.
Show answer
Answer: A 3
Right: [1, 2], [2, 1] and [1, 2] at the end each add up to 3.
Prefix totals run 1, 3, 4, 6; the hits come at totals 3, 4 and 6, because 0, 1 and 3 appeared before them.
Why not the others?
- B 2. That misses one of the three stretches; the last [1, 2] counts too.
- C 1. Only the first stretch would count if the map were never updated.