[英]How to make a Python code that will determine the number of minutes to get to a destination from a specific source (based on dictionary values)?
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.请帮忙。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.