Skip to content
Advertisement

Calculating min, max without using a list

I am trying to solve a problem from a python textbook:

Write a program that asks the user to enter the number of times that they have run around a racetrack, and then uses a loop to prompt them to enter the lap time for each of their laps. When the loop finishes, the program should display the time of their fastest lap, the time of their slowest lap, and their average lap time.

So far the concept of lists haven’t been introduced but I can’t think of a way to calculate the min, max lap time without using min(),max() on a list.

Here is my code:

num_laps = int(input('Enter number of laps you ran: '))


total_time = 0.0
lap_time_list = []

for lap in range(1,num_laps+1):
    lap_time = float(input('nEnter the lap time in minutes for each lap from first to last: '))
    total_time += lap_time
    lap_time_list.append(lap_time)


avg_time = total_time / num_laps
fast_lap = min(lap_time_list)
slowest_lap = max(lap_time_list)

# Display the time of fastest lap, slowest lap and average lap time

print('nAverage lap time:',avg_time,'mins')
print('nFastest lap time:',fast_lap,'mins')
print('nSlowest lap time:',slowest_lap,'mins')

Advertisement

Answer

well i think you can actually do this fairly simply, without a list. just keep track of the largest and smallest numbers seen so far.. right? not sure if this works but a simple example is something along the lines of:

num_laps = int(input('Enter number of laps you ran: '))

slowest, fastest, avg = 0, 1000, 0 # fastest just needs to be a very large number usually like a int.big

for lap in range(num_laps):
    lap_time = int(input('nEnter the lap time in minutes for each lap from first to last: ')) # assumes round numbers
    if lap_time > slowest:
        slowest = lap_time
    if lap_time < fastest:
        fastest = lap_time
    avg += lap_time

avg /= num_laps

there’s probably a bug in there somewhere, and edge cases to handle but the idea remains and you should be able to make it work correctly using the concept.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement