Predict the output
What does this print?
fuel = [4, 1, 2, 6, 3]
cost = [2, 5, 4, 1, 3]
start = tank = 0
for i in range(len(fuel)):
tank += fuel[i] - cost[i]
if tank < 0:
start, tank = i + 1, 0
print(start, sum(fuel) >= sum(cost))Choose an answer, then open Show answer below to check it.
Show answer
Answer: A 3 True
Right: the tank goes negative after stops 1 and 2, so the loop starts at stop 3, and the totals allow a full loop.
Each restart discards a stretch that could never contain a valid start, so one pass is enough.
Why not the others?
- B 4 True. From stop 3 the tank stays non-negative, so there is no restart at 4.
- C 0 True. Stop 0 has spare fuel, but the van runs dry leaving stop 1.