【发布时间】: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