获取KeyError:3

时间:2016-10-17 22:19:34

标签: python graph depth-first-search topological-sort

获取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。为什么会这样?如何解决?

2 个答案:

答案 0 :(得分:0)

对于图表中存在的每个BrowserModuledfs_topsort算法似乎需要key

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

此外,您在评论中提供的另一个示例有效,因为每个值(右侧)(13)也在Key值(左侧)[[2,3], [4, 5, 6], [4, 6], [5, 6], [6], []]中。

因此,使用1, 2, 3, 4, 5, 6会给出您可能期望的输出。

我希望这会对你有所帮助。

答案 1 :(得分:0)

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

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