2

我不断收到这个关键错误,我不明白怎么做。我正在使用 for-in 语句,因此密钥肯定存在:

def floydWarshall(inFile):
    graph = readGraph(inFile)
    print(graph) # = {'0': {'1': 28, '3': 33}, '2': {'3': 50}, '1': {'4': 44, '2': 10}, '3': {'4': 30}, '4': 999999999}
    nodes = graph.keys()
    print(nodes) # = dict_keys(['0', '2', '1', '3', '4'])

    distance = {}

    for n in nodes:
        distance[n] = {}

        for k in nodes:
        distance[n][k] = graph[n][k]

    for k in nodes:
        for i in nodes:
            for j in nodes:
                distance[i][j] = min (distance[i][j], distance[i][k] + distance[k][j])
    printSolution(distance)

错误:

Traceback (most recent call last):
File "C:/Users/.../prob1.py", line 58, in floydWarshall
    distance[n][k] = graph[n][k]
KeyError: '2' 

关键错误只是在节点中首先出现的任何键上,每次都会更改

4

2 回答 2

2

并非所有图节点都与所有其他图节点有边,因此遍历k整个图上的所有节点graph[n][k]会导致 KeyError。

也许你想要类似的东西:

for n in nodes:
    distance[n] = {}

    for k in graph[n]: 
        distance[n][k] = graph[n][k]

或者,如果您想在边不存在的情况下将 distance[n][k] 设置为某个默认值:

for n in nodes:
    distance[n] = {}

    for k in nodes: 
        distance[n][k] = graph[n].get(k, default_value)

default_value节点之间的距离通常设置为无穷大

于 2015-03-04T00:43:48.907 回答
0

这对我来说似乎是预期的行为。您的图形字典不是一个完整的矩阵。例如,graph[1] 不包含键 3。

当 graph[n][m] 不包含从 n 到 m 的边时,您似乎想要一个默认的无穷大值。您可以通过进行显式检查或使用defaultdict来做到这一点。

于 2015-03-04T00:51:51.827 回答