Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
67 views
in Technique[技术] by (71.8m points)

python - Add nodes to indegree-list

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...