【问题标题】:Getting KeyError : 3获取 KeyError:3
【发布时间】:2016-10-17 22:19:33
【问题描述】:

Getting KeyError: 3 when trying to do following to find the topological sort:

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。为什么呢?怎么解决?

【问题讨论】:

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


    【解决方案1】:

    似乎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: [] } 会得到您可能期望的输出。

    希望对你有帮助。

    【讨论】:

    • 但是当我按照你的建议做时,dfs_topsort 返回 null。我正在做的是为其他示例工作,但不是这个。如何解决这个问题??
    • 我认为您需要在dfs_topsort函数中更改相同的逻辑:将for u in graph:更改为for u in graph.iterkeys():。另外,它返回None而不是null,并且根据您的代码cmets,“如果有循环,则返回一个空列表”,所以这不应该是True,它返回None吗?跨度>
    • 不,如果我使用这个例子:graph = { 1: [2, 3], 2: [4, 5, 6], 3: [4,6], 4: [5, 6], 5: [6], 6: [] },我正在做的事情给出了正确的输出。即使在 dfs_topsort 中将其更改为 graph.iterkey() 后,它也不会返回任何内容。
    • 抱歉,我不确定您要解决的问题,我以为您只是想修复 KeyError..
    • 看起来您正在搜索整数图并寻找匹配的字符串?这当然行不通。您是否尝试修改 this code tutorial 以使用整数列表?
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-18
      • 2018-12-19
      • 2018-10-24
      • 2022-11-20
      • 2021-11-10
      • 2020-09-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多