简体   繁体   English

Python中自定义的Dijkstra算法

[英]Self-defined Dijkstra's algorithm in Python

I can successfully ran the codes that are not in a function format.我可以成功运行非函数格式的代码。 However, once I packaged everything into a function.然而,一旦我将所有东西都打包成一个函数。 I will receive an error.我会收到一个错误。 The data is as following:数据如下:

# A
graph_a = {}
graph_a['s'] = {}
graph_a['a'] = {}
graph_a['b'] = {}
graph_a['c'] = {}
graph_a['d'] = {}
graph_a['f'] = {}
graph_a['s']['a'] = 2
graph_a['s']['b'] = 5
graph_a['a']['b'] = 8
graph_a['a']['d'] = 7
graph_a['b']['d'] = 2
graph_a['b']['c'] = 4
graph_a['c']['d'] = 6
graph_a['c']['f'] = 3
graph_a['d']['f'] = 1

cost_a = {}
cost_a['a'] = 2
cost_a['b'] = 5
cost_a['f'] = float('inf')
cost_a['c'] = float('inf')
cost_a['d'] = float('inf')

parent_a = {}
parent_a['a'] = 's'
parent_a['b'] = 's'
parent_a['c'] = None
parent_a['d'] = None
parent_a['f'] = None

I also defined the lowest cost node function to find the lowest cost node in the cost in each iteration.我还定义了最低成本节点函数,以在每次迭代的成本中找到成本最低的节点。

searched = []

def lowestcostnode(x):
    lowestnode = None
    lowestcost = float('inf')
    for node in x:
        if x[node] < lowestcost and node not in searched:
            lowestcost = x[node]
            lowestnode = node
    return lowestnode

I can get the results successfully via:我可以通过以下方式成功获得结果:

searched = []
node = lowestcostnode(cost_a)
while node is not None:
    currentcost = cost_a[node]
    neighbors = graph_a[node]
    for n in neighbors:
        if cost_a[n] > currentcost + neighbors[n]:
            cost_a[n] = currentcost + neighbors[n]
            parent_a[n] = node
    searched.append(node)
    node = lowestcostnode(cost_a)

The result is as:结果如下:

cost_a
{'a': 2, 'b': 5, 'f': 8, 'c': 9, 'd': 7}

But once I tried to packed the codes into a function, I got error message:但是一旦我尝试将代码打包到一个函数中,我就会收到错误消息:

  1. The function will generate error message as following if I create the searched list within the function:如果我在函数中创建搜索列表,该函数将生成如下错误消息:
def dijkstra(graph, parent, cost):
    searched = []
    node = lowestcostnode(cost)
    while node is not None:
        currentcost = cost[node]
        neighbors = graph[node]
        for n in neighbors:
            if cost[n] > currentcost + neighbors[n]:
                cost[n] = currentcost + neighbors[n]
                parent[n] = node
        searched.append(node)
        node = lowestcostnode(cost)
    print('parent as:', parent)
    print('cost as:', cost)
    return parent, cost

The error will be:错误将是:

dijkstra(graph_a, cost_a, parent_a)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-57-00f1df255994> in <module>
----> 1 dijkstra(graph, parent, cost)

<ipython-input-56-517377fe9acb> in dijkstra(graph, parent, cost)
     12 def dijkstra(graph, parent, cost):
     13     searched = []
---> 14     node = lowestcostnode(cost)
     15     while node is not None:
     16         currentcost = cost[node]

<ipython-input-56-517377fe9acb> in lowestcostnode(x)
      5     lowestcost = float('inf')
      6     for node in x:
----> 7         if x[node] < lowestcost and node not in searched:
      8             lowestcost = x[node]
      9             lowestnode = node

NameError: name 'searched' is not defined

However, I already defined the searched one line before calling the lowestcostnode function.但是,在调用最低成本节点函数之前,我已经定义了搜索到的一行。

Thank you in advance for your help.预先感谢您的帮助。

You are calling: dijkstra(graph_a, cost_a, parent_a) but based on your function definition I would expect: dijkstra(graph_a, parent_a, cost_a)您正在调用:dijkstra(graph_a, cost_a, parent_a) 但根据您的函数定义,我期望:dijkstra(graph_a, parent_a, cost_a)

Does this fix your problem?这能解决您的问题吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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