Getting KeyError : 3

Getting KeyError : 3

尝试执行以下操作以查找拓扑排序时出现 KeyError: 3:

def dfs_topsort(graph):         # recursive dfs with 
    L = []                      # additional list for order of nodes
    color = { u : "white" for u in graph }
    found_cycle = [False]
    for u in graph:
        if color[u] == "white":
            dfs_visited(graph, u, color, L, found_cycle)
        if found_cycle[0]:
            break

    if found_cycle[0]:           # if there is a cycle, 
        L = []                   # then return an empty list  

    L.reverse()                  # reverse the list
    return L                     # L contains the topological sort


def dfs_visited(graph, u, color, L, found_cycle):
    if found_cycle[0]:
        return
    color[u] = "gray"
    for v in graph[u]:
        if color[v] == "gray":
            found_cycle[0] = True
            return
        if color[v] == "white":
            dfs_visited(graph, v, color, L, found_cycle)
    color[u] = "black"      # when we're done with u,
    L.append(u)

graph_tasks = {1: [2,11],
    2: [3],
    11: [12],
    12: [13]
    }
order = dfs_topsort(graph_tasks)

for task in order:
    print(task)

在上面的示例中,我收到 KeyError: 3。为什么?如何修复?

似乎 dfs_topsort 算法需要对图中存在的每个 value 一个 key

所以我们需要为每个值包含键。第一个缺失的是 3,它导致了 KeyError: 3,还有 13。如果我们包含这些键并给它们空值(因为它们没有连接到任何其他节点),那么它会修复错误。

此外,您在评论中给出的另一个示例有效,因为每个值(右侧)( [2,3], [4, 5, 6], [4, 6], [5, 6], [6], [] ) 也在关键值(左侧)[1, 2, 3, 4, 5, 6 中].

所以使用 graph_tasks = { 1: [2, 11], 2: [3], 3: [], 11: [12], 12: [13], 13: [] } 会给出您可能期望的输出。

希望对您有所帮助。

我遇到了和你一样的问题,我发现它没有从我的数据集中搜索 3 的值。我所做的是为我的 3 个值添加一个列表。您可能想要添加如下内容:

graph_tasks = {...,
...,
3: [n,n],
...,
...,
}