Given 2 lists of tuples limits
and speeds
, both have the format of [(speed1, time1), (speed2, time2)]. My goal is to write a function to check whether the there is a period of time that the speed exceeds the limit (Return True if exceeds).
For example, Given limits = [(50,100), (30, 20)], speeds = [(30, 80), (10, 30), (40, 10)], return True.
The example inputs imply that during the first 100 miles, the speed limit is 50. In the 101-120 mile, speed limit is 30. Since in the speeds list, the last 10 miles have speed 40 > 30, so we return True.
We can assume the inputs are valid, so the limits and speeds list always start and end at the same time.
Can I have some pointers on the correctness and how the code can be refactored?
def speed_check(limits, speeds):
i, j = 0, 0
prev_limit_range, prev_speed_range = 0, 0
while j < len(speeds) and i < len(limits):
if limits[i][0] < speeds[j][0]:
return True
if limits[i][1] + prev_limit_range < speeds[j][1] + prev_speed_range:
prev_limit_range += limits[i][1]
i += 1
elif limits[i][1] + prev_limit_range > speeds[j][1] + prev_speed_range:
prev_speed_range += speeds[j][1]
j += 1
else:
prev_limit_range += limits[i][1]
prev_speed_range += speeds[j][1]
i += 1
j += 1
return False
assert speed([(30, 15), (55, 20)], [(30, 15), (55, 20)]) == False
assert speed([(30, 15), (55, 20)], [(30, 14), (65, 20)]) == True