简体   繁体   中英

Intermediate results in a recursive DFS function - Python

I am basically trying to understand recursion better with this example. Lets look at the following DFS algorithm that returns all the nodes connected to the base root node. The "graph" in this case is defined as a list of tuples of edges between vertices.

def dfs(graph,node,dfs_visited):
    if node not in dfs_visited:
        dfs_visited.append(node)

        #find next node to go
        potential_paths = [i for i in graph if node in i]
        new_nodes = [node_ for path in potential_paths for node_ in 
                     path if node_ !=node]   
        for n in new_nodes:
            dfs(graph,n,dfs_visited)
    return dfs_visited

For example, if graph was

 graph = [(0, 1),(0, 2),(1, 2),(3, 4),(4,5)]

the result of starting at node 0 would be

 dfs(graph,0,[])
 [0,1,2]

What I am curious about in this case is that this is the result of the "return" from only one of the recursive calls. Obviously the code works the way I intended to and I am fine with the result, but I am just curious where the intermediate "returns" go. For example when we run the same function with an added print statement right before the return statement, we get the following output:

dfs(graph,0,[])
returning [0, 1]
returning [0, 1, 2]
returning [0, 1, 2]
returning [0, 1, 2]
returning [0, 1, 2]
returning [0, 1, 2]
returning [0, 1, 2]

So how does Python know which one of these is the actual output of the function? Is it just the last one?

In this line where you recursively call the function:

for n in new_nodes:
    dfs(graph,n,dfs_visited)

is where the return value of the nested call ends up. You don't assign this value to any variable, so python just forgets about it as soon as it goes on to the next iteration. You should get (almost) the same output as what you have printed above by using the following print statement:

for n in new_nodes:
    ret = dfs(graph,n,dfs_visited)
    print(ret)

(The exception is the value returned by your initial call, which won't be printed. So you should have one less line of [0, 1, 2] than above.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM