The subway map is below. It consist of 3 different list, each representing a different subway line. However, there are 2 connecting stations that can connect to another line. The stations are Newton and Little India.
subway_map = [ ['Botanic Gardens', 'Stevens', 'Newton', 'Little India', 'Rochor'], ['Newton', 'Novena', 'Toa Payoh', 'Braddell', 'Bishan'], ['Dhoby Ghaut', 'Little India', 'Farrer Park', 'Boon Keng']]
So I want to implement a function that finds all the stations within the given distance. For example:
eg_1 = find_station_within_distance(subway_map, origin = 'Botanic Gardens', dist = 3)
eg_2 = find_station_within_distance(subway_map, origin = 'Little India', dist = 1)
eg_3 = find_station_within_distance(subway_map, origin = 'Dhoby Ghaut', dist = 3)
#function should return either list below
print(eg_1)
['Stevens', 'Newton']
#or
['Newton', 'Stevens']
print(eg_2)
['Farrer Park', 'Newton', 'Rochor', 'Dhoby Ghaut']
print(eg_3)
['Little India', 'Farrer Park', 'Boon Keng', 'Rochor', 'Newton', 'Stevens', 'Novena']
So far, I can only get the stations within the given distance on the line that the origin is from.
def find_stations_within_distance(subway_map, orig, dist):
result = []
for lines in subway_map:
if orig in lines:
orig_idx = lines.index(orig)
max_idx = dist + orig_idx
if max_idx >= len(lines):
result += lines[orig_idx+1:]
elif max_idx < len(lines):
result += lines[orig_idx+1:max_idx+1]
return result