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"?

Cupitor
  • 11,007
  • 19
  • 65
  • 91

1 Answers1

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.

Knut
  • 1,792
  • 13
  • 9
  • 2
    Except `L` is not a global, it is a `nonlocal`. – roippi May 25 '14 at 13:48
  • 1
    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? – Knut May 25 '14 at 13:53
  • Well, it will make a *global* L, which will shadow the enclosing scope's `L`. – roippi May 25 '14 at 13:57
  • 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… :/ – Knut May 25 '14 at 14:00
  • 2
    It's very simple, don't use assignment. `L+= [node]` or `L.append(node)` both work on python 2. – roippi May 25 '14 at 14:01