簡體   English   中英

使用python進行拓撲排序的工具中的錯誤

[英]errors in my implement of topological sort using python

更新

我沒有在以下代碼中使用嵌套函數,但是答案是錯誤的: {'s': 4, 't': 4, 'w': 4, 'v': 4}

我認為問題出在遞歸調用中,當函數回調時n不會減少,但我不知道如何修改它。

import unittest
#dfs
def dfs(graph,start,visited,n,topo_order):
        visited.add(start)
        for w in graph[start]:
            if w not in visited:
                dfs(graph,w,visited,n,topo_order)
        topo_order[start]=n
        n-=1
def topological_sort(graph):
    visited=set()
    n=len(graph)
    topo_order={}
    for v in graph:
        if v not in visited:
            dfs(graph,v,visited,n,topo_order)
    print(topo_order)
class topological_sort_test(unittest.TestCase):
    def test(self):
        file=[]
        with open('topological_test.txt') as f:
            data=f.read()
        data=data.split('\n')
        data=[i.split() for i in data]        
        G={}
        for lst in data:
            G[lst[0]]=lst[1:]
        topological_sort(G)
if __name__=='__main__':
    unittest.main()    
def dfs(graph,start)

函數聲明為變量創建局部作用域。 要從外部訪問任何變量,您需要將其作為該函數的參數傳遞。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM