繁体   English   中英

如何制作一个 Python 代码来确定从特定来源(基于字典值)到达目的地的分钟数?

[英]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)?

我如何编写一个函数,该函数将根据存储在路由字典中的数据返回从源到达目的地所需的估计分钟数。 这条路线是单向的,可以从任何来源到达任何目的地。

编辑:来源和目的地是实际地点的名称。

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
     }
}

请帮忙。

以下应该工作,(假设只能从源到达一次目的地,根据您拥有的示例数据),您可以做的是,获取源是元组对的当前源的字典键,您将获得当前源的键,您将拥有下一个目标,然后获取此源、目标对所需的时间,并在循环内再次执行,如果找到目标则停止并打印总时间,或者如果元组对则停止找不到这意味着无法从给定源到达目的地:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM