简体   繁体   English

Dijkstra的算法问题和python中的关键错误

[英]Dijkstra’s Algorithm issue and key error in python

Trying to code Dijkstras algorithm from this psuedocode: 尝试从此伪代码编码Dijkstras算法:

1: procedure ShortestPath
2:   for 0 ≤ i ≤ n do
3:     L(vi) = ∞
4:   end for
5:   L(a) = 0
6:   S = ∅
7:   while z /∈ S do
8:     u = vertex not in S with L(u) minimal
9:     S = S ∪ {u}
10:    for v /∈ S do
11:      if L(u) + µ(uv) < L(v) then
12:        L(v) = L(u) + µ(uv)
13:      end if
14:    end for
15:  end while
16:  return L(z)
17: end procedure

The code I have written is this: 我写的代码是这样的:

from math import inf
def dijkstras(G,start,stop):
    L = {}
    for i in G[0]:
        L[i] = inf
    L[start] = 0
    visited = []
    print(L)
    while stop not in  visited:
        u = inf
        for i in L:
            if L[i] < u and L[i] not in visited:
                u = L[i]
                break
        visited.append(u)
        for v in G[0]:
            if v in visited:
                continue

            if {u,v} or {v,u} in G[1]:
                for i in G[1]:
                    if {u,v} or {v,u} == i[0]:
                        weight = i[1]
                        break
                    else:
                        weight = inf
                if L[u] + weight < L[v]:
                    L[v] = L[u] + weight
    return stop

It gives me KeyError = 0, I Presume this is to do with line L[v] = L[u] + weight. 它给我KeyError = 0,我认为这与线L [v] = L [u] +权重有关。 Other than that I think the code is correct. 除此之外,我认为代码是正确的。 If anyone spots the issue please let me know, cheers. 如果有人发现问题,请让我知道。

In your code I see u = inf or u = L[...] , yet in original pseudocode u is a graph vertice, not weight. 在您的代码中,我看到u = inf or u = L[...] ,但是在原始伪代码中, u是图形顶点,而不是权重。 In other words you confused distances with vertices. 换句话说,您将距离与顶点混淆了。 Perhaps use strings to name vertices? 也许使用字符串来命名顶点?

Provide example of your graph format. 提供图形格式的示例。 Is G[1] a dictionary with transition keys? G [1]是带有过渡键的字典吗? list of pairs of a transition with its weight? 权重的转换对列表? Looks like in different place it is interpreted differently. 看起来好像在不同的地方有不同的解释。

{u,v} or {v,u} == i[0] is obviously error, you likely meant {u,v} == i[0] or {v,u} == i[0] {u,v} or {v,u} == i[0]显然是错误,您可能表示{u,v} == i[0] or {v,u} == i[0]

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

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