Predict the output
Both loops scan 6 items. What does this print?
a = [1, 2, 3, 4, 5, 6]
lo, hi, moves = 0, len(a) - 1, 0
while lo < hi:
lo += 1
moves += 1
slow = 0
for fast in range(len(a)):
if a[fast] % 2 == 0:
slow += 1
print(moves, slow)Choose an answer, then open Show answer below to check it.
Show answer
Answer: A 5 3
Right: the opposite pointers meet after 5 moves, and 3 even values move the slow pointer.
Neither pointer ever goes back, so the total moves stay within a small multiple of n.
Why not the others?
- B 6 6. The slow pointer only moves on even values.
- C 3 3. Only lo moves here, so it takes 5 steps to meet hi.