How can I write a function that will return the estimated number of minutes it will take to reach a destination from the source based on the data stored in the route dictionary. The route is one-way only and any destination can be reached from any source.
EDIT: The sources and destinations are names of actual places.
route = { ("San Mateo","Cabatuan"):{ "travel_time_mins":10 }, ("Cabatuan","Cauayan"):{ "travel_time_mins":35 }, ("Cauayan","Ilagan"):{ "travel_time_mins":55 }, ("Ilagan","Cordon"):{ "travel_time_mins":30 }, ("Cordon","Santiago"):{ "travel_time_mins":25 }, ("Santiago","Roxas"):{ "travel_time_mins":15 }, ("Roxas","Aurora"):{ "travel_time_mins":30 }, ("Aurora","Magat"):{ "travel_time_mins":35 }, ("Magat","Ramon"):{ "travel_time_mins":40 }, ("Ramon","San Mateo"):{ "travel_time_mins":20 } }
Please help.
Advertisement
Answer
Following should work, (assuming only once destination can be reached from a source, based on the sample data you have), what you can do is, get the dictionary key for which source is the current source for the tuple pair, you will get the key for current source, and you will have next destination, then get the time requried for this source, destination pair, and do it again inside the loop, stop if destination is found and print the total time, or stop if the tuple pair couldn’t be found that means the destination can not be reached from given source:
def calcEstTime(route, source, destination): prev = source total = 0 while True: next = [k[1] for k in route if k[0] == prev] if next: next = next[0] # Assumes only one destination from a source total += route[(prev, next)]['travel_time_mins'] if next == destination: print(f'Estimated time from source{source} to destination {destination} is: {total}') break prev = next else: print(f'source {source} can not be reached from destination {destination}') break >>> calcEstTime(route, 'A', 'B') source A can not be reached from destination B >>> calcEstTime(route, 'Santiago', 'Magat') Estimated time from sourceSantiago to destination Magat is: 80