【问题标题】:How to find distance of shortest route on graph using dictionary如何使用字典在图形上查找最短路线的距离
【发布时间】:2019-07-09 15:44:44
【问题描述】:

我需要使用边的权重找到从一个给定节点到另一个节点的最短距离。我已将以下图表存储为字典: A visual representation of the graph

我尝试过使用递归方法,但到目前为止我似乎失败了。 这是我正在使用的字典:

towns = {'kendal':     [['penrith', 28],  ['milnthorpe', 8],  ['barrow', 35]],
         'penrith':    [['kendal', 28]],
         'barrow':     [['kendal', 35],   ['milnthorpe', 31]],
         'milnthorpe': [['kendal', 8],    ['barrow', 31],     ['lancaster', 14]],
         'lancaster':  [['milnthorpe', 14]]
        }

用户输入开始和结束节点:

places = ['kendal', 'penrith', 'barrow', 'milnthorpe', 'lancaster']

from_town = ''
while from_town not in places:
    from_town = input('Where are you going from?').lower()

to_town = ''
while to_town not in places:
    to_town   = input('Where are you going to?').lower()

然后运行下面的代码,它很容易与直接连接到起始节点的节点一起工作,否则,递归继续并且不会停止。

routes = []

def get_route(start, finish):
    others = []

    for x in range(len(towns[start])):

        if towns[start][x][0] == finish:
            routes.append(towns[start][x][1])
        else:
            if towns[start][x][0] not in others:
                others.append(towns[start][x][0])

    for y in range(len(others)):
        get_route(others[y], to_town)

get_route(from_town, to_town)
routes.sort()
print(routes[0], 'miles')

我知道我还没有停止递归的方法,但我需要让程序列出所有可能的路线。

【问题讨论】:

  • 你为什么不使用networkx库?
  • @CorentinLimier 抱歉,我不知道这个库,我教给我的伙伴也不知道,所以我需要这个尽可能简单,但感谢您的回复.
  • 不相关 - 但是:为什么 for x in range(len(towns[start])): 而不是 for town,distance in towns[start]: 等等。
  • @PatrickArtner 谢谢,我会用它来代替
  • @PatrickArtner for town,distance in towns[start]:实际上在做什么?

标签: python graph


【解决方案1】:

你有几个问题;我建议您备份并使用增量编程,这样您一次只能处理一个。从几行代码开始;在添加更多之前调试它们。例如,编写一个检查直接路由的例程,否则返回失败。在进行任何递归之前让其充分发挥作用。

目前,您的主要问题在这里:

for y in range(len(others)):
    get_route(others[y], to_town)

由于您的递归不涉及您去过的地方的“记忆”,因此您的递归执行无限回溯和循环。摆脱这种情况的唯一方法是,如果others 对于所有 个活动呼叫为空。

我建议您查找 Dijkstra's algorithm 以获取有关跟踪您去过的地方的帮助。

还请注意,您的函数不返回任何内容。你有一个未初始化的局部变量routes;这与主程序中的变量相同。

【讨论】:

  • 感谢您的指点 - 我不会发现这一点。非常感谢!
猜你喜欢
  • 1970-01-01
  • 2011-04-30
  • 1970-01-01
  • 2017-08-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-08
  • 2013-07-03
相关资源
最近更新 更多