0

UPDATE

I did not use nested function in the following code,but the answer is wrong: {'s': 4, 't': 4, 'w': 4, 'v': 4}

I think the problem is in the recursive call,where n does not decrease when the functions call back,but I don't know how to revise it.

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()    

1 Answer 1

1
def dfs(graph,start)

Function declaration creates local scope for variables. To access any variable from outside you'll need to pass it as an argument to this function.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.