tags:

views:

34

answers:

2

I have a simple code that finds paths using a graph stored in a dictionary. The code is exactly:

def find_path(dct, init, depth, path=[]):
   if depth == 0:
      return path
   next_ = dct[init]
   depth-=1
   find_path(dct, next_, depth)

If I print the path right before return path it prints to screen the correct path (after an initial depth of 5). However, the value returned is None. I don't know what's going on!

Why would the value of path right above the return is correct, yet the returned path is not what I want?

+3  A: 

Shouldn't this

find_path(dct, next_, depth)

be

return find_path(dct, next_, depth)
# ^^^^
# Return

In Python (unlike in say, Ruby) you have to explicitly return a value. Otherwise None is returned.

Manoj Govindan
Yes, but I wonder why is the `path` argument right above path correct, but it is not returned. BTW. Your fix DID solve the problem. Many thanks!
Arrieta
Because it returns it to the next level up... but then that level never keeps passing it up the chain. `return` doesn't automatically pass a value all the way up a recursive call stack; just one level at a time.
Amber
+1  A: 

Because you're calling it with depth greater than 0, which is causing it to fall off the end and return None.

Ignacio Vazquez-Abrams
Thanks, @Ignacio. As usual a very good answer.
Arrieta