goodcow
goodcow

Reputation: 4795

Recursive functions in python

I just started learning python after scheme. Is recursion like sum+=alist[0]+sumup(alist[1:]) not allowed? I get the error

TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'

The code:

m=int(input())
c=list(map(int,input().split()))
x,y=map(int,input().split())
sum=0

def sumup(alist):
    global sum
    if alist==[]:
        return 0
    else:
        if sum<x:
            sum+=alist[0]+sumup(alist[1:])
        elif sum>=x:
            return sum
        elif sum>y:
            return 0

sumup(c)

Upvotes: 1

Views: 332

Answers (2)

karthikr
karthikr

Reputation: 99620

You forgot a return statement in the if sum <x: clause:

        if sum<x:
            sum+=alist[0]+sumup(alist[1:])

should be

        if sum<x:
            sum+=alist[0]+sumup(alist[1:])
            return sum

and also, another case - if sum <= y you are not returning anything. (You might want to get rid of elif sum>y clause, as that would never happen. )

Upvotes: 6

Martijn Pieters
Martijn Pieters

Reputation: 1121366

Your recursive function returns None for the case where alist is not empty and sum < x is True.

You'll need to get rid of the global sum here however, as you are going to end up adding to that value whatever you return from recursive calls. That'll only lead to doubling the value.

At most, make sum a parameter to the function to pass along the value to recursive calls. You didn't provide us with sample input and output, so it is very hard to determine what you are trying to achieve with the function.

Last, but not least, the elif sum > y: branch will never be executed, as one of sum < x and sum >= x will always be True.

Upvotes: 5

Related Questions