
A snail climbs a pole, “H” meters in height. It climbs up “A” meters during the day, and slides down “B” meters during the night. It is known that A > B, and B is greater than or equal to 0. On which day, will the snail reach the top of the pole? My solution to this problem is displayed below.
h = int(input())
a = int(input())
b = int(input())
rate = a - b
h2 = h - a
day_night = h2 // rate
extra_day = 1 - 0**(h2 % rate)
print(day_night + extra_day + 1)
To begin, I define the variables as directed in the problem. To make things easier, I store the meters that the snail climbs in 24 hours in the “rate” variable, and the updated height in the “h2” variable. The day_night variable represents how many days and nights it would take to climb the pole.
In order to solve this problem, I basically need to round up the quotient to the nearest whole number, while not counting the last slide IF the snail already made it to the top during the day. You can see this reasoning in the extra_day variable, which becomes zero if the remainder is zero as well. The variable becomes 1, if the quotient is a float.
Finally, I add up the variables day_night (the amount of days and nights it takes), and the extra day. I also add 1, to balance out the amount of days it takes for the snail to climb.
This is not the only way to solve this problem, however. The first method I used was mathematical, here is my solution using an algorithm .
#snail challenge - algorithm solution
height = 10
up = 3
down = 0
pos = 0
day = 0
while pos < height:
pos += up
day += 1
if pos < height: #if the snail hasn't gone to the top yet, it slides down
pos -= down
print(day, pos)
Here, I start by also defining the variables. The pos variable indicates the current position of the snail, and the day variable indicates what day it is.
The code is wrapped in a while condition, which will repeat the code until the snail climbs all the way to the top. On every iteration, we add one to the day and position variables. If the snail hasn’t reached the end of the pole by the end of the day, it slides down. The cycle breaks when the snail reached the top. The last output indicates the height of the pole, and on what day the snail reached it.