0

I changed the DFS pseudocode for Topological Sort on Wiki for python and got the following:

def topological_sort(nodes):
    """Topological sort for DAGs. Written based on pseudocode on Wiki.
    DFS-based sort by Tarjan 1976"""        
    L=[]
    def visit(node):
        if node.dfs_tmark:
            print ("Error: Graph is not a DAG")
        if not node.dfs_pmark:
            node.dfs_tmark=True
            for m in node.parents:
                visit(m)
            node.dfs_pmark=True
            L=[node]+L
    for node in nodes:
        if not (node.dfs_pmark and node.dfs_tmark):
            visit(node)

However I am getting the error: UnboundLocalError: local variable 'L' referenced before assignment. As far as I remember python looks for variables backwards in scopes and I wonder why it cannot reach "L"?

10
  • 1
    Why not just make L an argument and not rely on scope at all? Commented May 25, 2014 at 13:39
  • You have to define L beforehand in order to concatenate here(L=[node]+L). Commented May 25, 2014 at 13:40
  • @iamsudip, well I already did. Just before visit. Commented May 25, 2014 at 13:45
  • 2
    stackoverflow.com/a/18002922/650884 Commented May 25, 2014 at 13:46
  • @jonrsharpe, still the same error. Commented May 25, 2014 at 13:46

1 Answer 1

1

You can read from variables which are defined in outer scope but you can't write into it without specifying the global statement. In your example it should work as soon as you specify global L in the first line of your visit method.

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

5 Comments

Except L is not a global, it is a nonlocal.
But the nonlocal-statement is available from Python3 and not for Python2… And as far as I remember the global statement should do the work right?
Well, it will make a global L, which will shadow the enclosing scope's L.
Yeah thats right… I only don't see a better solution (except avoiding globals / nonlocals completely) as long we don't all (or at least the threadstarter) use Python3… :/
It's very simple, don't use assignment. L+= [node] or L.append(node) both work on python 2.

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.