user99889 user99889 - 2 months ago 14
Python Question

Python recursion attempt is not returning any value

I am wondering why it's not returning anything--I would expect it to return sum. I am fairly new to recursion, am I doing this all wrong?

def inc(sum,vec):
if vec==[]:
print "returning sum",sum
return sum
sum= sum+vec.pop(0)

In [78]: s=inc(0,[6,7])
returning sum 13

In [79]: s


The else block should have a return inc(sum,vec).

Why? Take a look at this:

  • inc(0, [6, 7]) called
    • in else -> calling inc(6, [7])
      • in else -> calling inc(13, [])
        • in if vec == [] -> returning 13 to previous caller
      • now inc(13, []) == 13 and that's all, this value is not passed anywhere
    • inc(6, [7]) doesn't return anything
  • inc(0, [6, 7]) doesn't return anything

BTW, if vec == [] can be safely replaced with if not vec and sum = sum + vec.pop(0) - with sum += vec.pop(0) for more clarity (although this line might me altogether omitted, see below).

All in all, the code could look like this:

def inc(sum, vec):
    if not vec:
        return sum
    return inc(sum + vec.pop(0), vec)

What's more, you could've used a default value with the sum argument:

def inc(vec, sum = 0): # << right here
    if not vec:
        return sum
    return inc(vec, sum + vec.pop(0)) # change the argument position

With that the call to this function will be clearer:

inc(0, [6, 7]) # before
inc([6, 7])    # after

If you want a one-liner (might be a bit less readable, though):

def inc(vec, sum = 0):
    # return sum if vec is empty or the _result_ of a recursive call otherwise
    return sum if not vec else inc(vec, sum + vec.pop(0))