First solution in Clear category for Fast Train by colinmcnicholl
"""Input: Same as function fast_train().
Output: A list of integers representing the speed limit for each
unit distance of track over the total distance between stations.
speed_limits = 
for distance, speed_limit in sections:
speed_limits += [speed_limit] * distance
speed_limits[-1] = 1
"""Input: Speed, 'new_speed', of train as an integer.
The first 'new_speed' selected in the function fast_train is the
current speed + 1, the highest of the available choices, as the goal is
the minimum time. Given that the train runs by the same amount (distance)
as the speed value, the 'new_speed' is repeated 'new_speed' times,
reduced by 1 then 'new_speed - 1' is repeated 'new_speed - 1' times
down to 1. So we have a list of speeds over each unit diatnce of track.
Output: A list of train speeds.
return [speed for sp in range(new_speed, 0, -1) for speed in [sp] * sp]
def speed_violations(speeds, speed_limits, cur_dist):
"""Input: A list of train speeds (integers), a list of speed limits
(integers) and current distance (integer).
Output: True if train speed is greater than speed limit in any unit
distance section of track bewteen current distance and destination station,
else False (bool).
return any(speed > speed_limit
for speed, speed_limit
in zip(speeds, speed_limits[cur_dist:]))
"""Input: List of the section of the rail. Each section is tuple of
distance (as an integer) and speed limit (as an integer).
The function computes the minimum time between stations, subject to
specified speed limits over specified distances in given track sections.
Output: The minimum time (minutes) as an integer.
trip_dist = sum([distance for distance, _ in sections])
speed_limits = speed_limits_each_unit_distance(sections)
cur_dist, cur_speed, minutes = 0, 0, 0
while cur_dist < trip_dist:
minutes += 1
for new_speed in [cur_speed + 1, cur_speed, cur_speed - 1]:
speeds = speeds_descending_each_unit_distance(new_speed)
if not speed_violations(speeds, speed_limits, cur_dist):
cur_dist += new_speed
cur_speed = new_speed
if __name__ == '__main__':
assert fast_train([(4, 3)]) == 3, 'basic'
assert fast_train([(9, 10)]) == 5, '1 section'
assert fast_train([(5, 5), (4, 2)]) == 6, '2 section'
print("Coding complete? Click 'Check' to earn cool rewards!")
March 29, 2019