python中确定旅行目的地的代码怎么写
发布网友
发布时间:2023-05-25 17:15
我来回答
共1个回答
热心网友
时间:2024-12-15 02:32
下面应该是可行的,(假设一个源只能到达一次目的地,基于你拥有的样本数据),你能做的是,获取源是元组对的当前源的字典键,你将获得当前源的键,你将有下一个目的地,然后获得该源,目的地对所需的时间,并在循环中再次执行,如果找到目的地,则停止并打印总时间,或者如果找不到元组对,则停止,这意味着无法从给定源到达目的地:
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