: 3 위상 종류를 찾기 위해 다음을 수행 할 때 : 위의 예를 들어 3 : 나는 KeyError를 얻고얻기 KeyError를 : 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)
. 왜 이렇게이다? 어떻게 고칠 수 있습니까?
하지만 제안 할 때 dfs_topsort는 null을 반환합니다. 내가 뭘하는지는 다른 예제를 위해 노력하고 있지만,이 예제가 아닙니다. 이 문제를 해결하는 방법 ?? – Angad
'dfs_topsort' 함수에서 같은 논리를 변경해야한다고 생각합니다 : graph.iterkeys() :'에서'for u for graph :'를'for'로 변경하십시오. 또한,'None'이 아닌'null'을 반환하고 코드 주석에 따라 "주기가 있으면 빈 목록을 반환합니다."따라서 이것이 참이 아니어야하고 None을 반환합니까? – davedwards
아니요,이 예를 사용하는 경우 그래프 = { 1 : [2, 3], 2 : [4,5,6], 3 : [4,6], 4 : [5,6] 5 : [6], 6 : [] }, 내가 한 것은 정확한 결과를 제공합니다. dfs_topsort에서 graph.iterkey()로 변경 한 후에도 아무 것도 반환하지 않습니다. – Angad