【发布时间】:2017-02-13 10:47:50
【问题描述】:
我无法在嵌套的 for 循环中环绕我的代码。我在 wiki 上关注卡恩算法:Kahn's。我不明白如何测试 outboundEdge 是否有每个 endArray 元素 (m) 的传入边。
这是我目前所拥有的:
def topOrdering(self, graph):
retList = []
candidates = set()
left = []
right = []
for key in graph:
left.append(key)
right.append(graph[key])
flattenedRight = [val for sublist in right for val in sublist]
for element in left:
if element not in flattenedRight:
#set of all nodes with no incoming edges
candidates.add(element)
candidates = sorted(candidates)
while len(candidates) != 0:
a = candidates.pop(0)
retList.append(a)
endArray = graph[a]
for outGoingEdge in endArray:
if outGoingEdge not in flattenedRight:
candidates.append(outGoingEdge)
#flattenedRight.remove(outGoingEdge)
del outGoingEdge
if not graph:
return "the input graph is not a DAG"
else:
return retList
【问题讨论】:
标签: python algorithm topological-sort