1

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
    else:
       sum= sum+vec.pop(0)
       inc(sum,vec)

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

In [79]: s
Sam Weisenthal
  • 2,791
  • 9
  • 28
  • 66

2 Answers2

1

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))
ForceBru
  • 43,482
  • 10
  • 63
  • 98
1

Python does not have an implicit return. Many people seem to assume that languages that do not otherwise have an implicit return, have an implicit return while using recursion. This is not true. Avoid this common pitfall and fix your code like this

def inc(sum,vec):
    if vec==[]:
        print "returning sum",sum
        return sum
    else:
       sum = sum+vec.pop(0)
       return inc(sum,vec)
Eli Sadoff
  • 7,173
  • 6
  • 33
  • 61