My task is to write a function planning a track run. I have to add a while loop to see if the input parameter a_distance was covered and count the number of laps within this distance. I have the following (yet uncompleted) function defined:
import math # ceil
LAP_DISTANCE = 400
def plan_track_run(a_distance):
count = 0
total = 0
r_output = ""
while total < a_distance:
count = count + (1/(LAP_DISTANCE)*a_distance)
total = total + count * LAP_DISTANCE
r_output += f"lap #{math.ceil(count)} time ____ s in {count:.2f} x {LAP_DISTANCE}m ={total:.2f}m\n"
The output is a template to write down times for particular distances. The output when the a_distance is smaller than a lap distance (400 meters) can be seen here:
lap #1 time ____ s in 0.50 x 400m = 200.00m
Unfortunately, I do not achieve the desired output in the case when the a_distance is larger than a lap distance, e.g. 1500 meters. There should be a multiline output for each laps, counting upwards until the total number of laps and the total distance is displayed in the last line:
lap #1 time ____ s in 1.00 x 400m = 400.00m
lap #2 time ____ s in 2.00 x 400m = 800.00m
lap #3 time ____ s in 3.00 x 400m = 1200.00m
lap #4 time ____ s in 3.75 x 400m = 1500.00m
My current and wrong output for a_distance = 1500 is:
lap #4 time ____ s in 3.75 x 400m = 1500.00m
Please help me modify this code so that I achieve the desired output also for distances larger than 400 meters. Thank you in advance.
Your second formula fully cancels out the first one, leaving you with
total == a_distance
which will terminate the loop.Why do you need to calculate the count from the distance? Just
count = count + 1
should be enough, no? And honestly, I would rename that tolap
to give it proper context.The next total would be
total = total + LAP_DISTANCE
ortotal = count * LAP_DISTANCE
. You should either build the cumulative sum or multiply to get the total, but not both at the same time. To avoid overshooting the distance, a simple conditional ormath.min
can be used.Alternatively, compute the number of laps first (
laps = math.ceil(a_distance/LAP_DISTANCE)
) and then execute the loop laps times:for lap in range(laps): ...