1

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)
2
  • 1
    what are x and y suppose to mean to this function?
    – cmd
    Commented Nov 7, 2013 at 21:18
  • I want to sum up the elements in the array such that they are bounded by x and y
    – goodcow
    Commented Nov 8, 2013 at 0:34

2 Answers 2

6

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. )

2
  • it will never even get to the if before that. he probably wanted a return sum at the end of the function
    – cmd
    Commented Nov 7, 2013 at 21:16
  • The tests agains y are entirely redundant, as sum is either going to be smaller, or equal or larger than x. The third branch is never going to be touched upon, it doesn't matter what value y has, ever. Commented Nov 7, 2013 at 21:17
5

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.

2
  • So generally, recursion does not happen with global variables?
    – goodcow
    Commented Nov 8, 2013 at 0:29
  • No, mixing globals and return values is not a good idea; recursion just makes it worse. Commented Nov 8, 2013 at 8:43

Not the answer you're looking for? Browse other questions tagged or ask your own question.