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

时间:2018-05-02 16:09:41

标签: python algorithm dictionary

尝试从此伪代码编写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

我写的代码是:

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

它给我KeyError = 0,我假设这与线L [v] = L [u] +权重有关。除此之外,我认为代码是正确的。 如果有人发现问题,请告诉我,欢呼。

1 个答案:

答案 0 :(得分:2)

在您的代码中,我看到u = inf or u = L[...],但原始伪代码u是图形顶点,而不是重量。换句话说,您将距离与顶点混淆。也许使用字符串来命名顶点?

提供图表格式的示例。 G [1]是一个带过渡键的字典吗?具有权重的转换对的列表?在不同的地方看起来有不同的解释。

{u,v} or {v,u} == i[0]显然是错误,您可能意味着{u,v} == i[0] or {v,u} == i[0]