Stopping early
Leave a loop the moment you have your answer. About 9 minutes.
A snail on a wall
A snail climbs a wall. Each day it climbs 4 cm, and each night it slips back 1 cm. The wall is 10 cm tall. On which day does it reach the top?
Notice a trick. On the third day the snail climbs from 6 up to 10 and reaches the top. It doesn't wait for night to slip back. So the check "have I arrived?" has to happen right after the climb, before the slip.
- day
- 1
- position
- 4
Day 1: the snail climbs 4 and reaches height 4. That's not the top yet.
Break out of the loop
The word break leaves the loop on the spot. Any lines after it in that pass are skipped, and the computer carries on after the loop.
That's just what the snail needs. Make a loop that goes on until you say stop. Each pass is one day: count the day, climb, and then if you've reached the top, break. If not, slip back and carry on. The loop is written as while true, which means keep going until a break happens.
while True:
days = days + 1
position = position + up
if position >= height:
break
position = position - downA wall is 5 cm tall. A snail climbs 3 cm each day and slips 2 cm each night. On which day does it reach the top?
- ADay 3
- BDay 5
- CDay 2
Show the answer
Day 3. Day 1 ends at 1, day 2 ends at 2, and on day 3 it climbs from 2 up to 5 and reaches the top.
Days to climb
A snail climbs a wall. Each day it climbs up cm. If it has reached the top, it stops. Otherwise, each night it slips back down cm. Return the day on which it reaches the top.
height = 10, up = 4, down = 1 → 3
1 ≤ height ≤ 100,000 · 1 ≤ down < up ≤ 1,000