Trying to get this top_sort with Kahns algorithm right. But my problem is how to create the list where I am adding the indegree to the nodes. I think I might not need to create the graph... or?
We know this:
self.edges = defaultdict(lambda: [])
self.variables = {}
Nodes can be accessed through self.variables['variable_name'].
Edges are stored in a dictionary. A node's children can be accessed by self.edges[variable].
def top_sort(self):
indegree = defaultdict(int)
graph = defaultdict(list)
for key, values in self.edges.items(): #This part is clearly wrong
graph[v].append(u)
indegree[u] += 1
Q = [u for u in graph if indegree[u]==0]
L = []
while Q:
start = Q.pop()
L.append(start)
for i in self.edges[start]:
indegree[i] -= 1
if indegree[i] == 0:
Q.append(i)
for k in indegree:
if indegree[k]:
return False
return L
question from:
https://stackoverflow.com/questions/65951164/add-nodes-to-indegree-list 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…