3

Write a recursive function addElements that returns the sum of the elements in a list. For example, addElements([2,1,3]) gives 6.

def addElements(s):
    if s == []:
        return 0
    else:
        s[0] + addElements(s[1:])
        return s

Error:

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

getting this error, Any help would be good thanks :)

1
  • Heh, you could just cheat and do sum(s). Commented Mar 26, 2014 at 15:52

3 Answers 3

3

The problem is in these lines.

s[0] + addElements(s[1:])
return s

You are finding the sum of two elements, ignoring them and returning the list. When you simply return s, previous addElements(s[1:]) call will get the s[1:] and you will be trying to

s[0] + s[1:]

where s[0] would be the first element in the list, and s[1:] would be rest of the list. That is why you are getting that error.

What you should have done is

return s[0] + addElements(s[1:])

So, your recursion will become like this

addElements([2, 1, 3])
       ||
2 + (addElements([1, 3]))
       ||
2 + (1 + (addElements([3])))
       ||
2 + (1 + (3 + (addElements([]))))
       ||
2 + (1 + (3 + (0)))
       ||
2 + (1 + (3))
       ||
2 + (4)
       ||
6 # Your answer
Sign up to request clarification or add additional context in comments.

1 Comment

@user3464959 Glad to have been of help! Feel free to accept my answer if you feel it was useful to you. :-)
1

This has nothing to do with recursion. The first element of s is obviously an integer and you are trying to add a list to an int as the error stated.

Maybe you meant:

def addElements(s):
    if not s: return 0
    return s[0] + addElements(s[1:])

Comments

0

You should see the different exit points of the function and see what types are the values you return.

If you see this alternative code:

def addElements(s):
    return 0 if s == [] else s[0] + addElements(s[1:])

you can see the two alternatives being 0 or s[0] (which should yield an integer in your flat list) + addElements(s[1:]) (which should yield another call to itself (having the cut condition an integer as return value), or an integer).

Also I'd suggest you use sum(s) instead of your custom function, since sum() is native and compiled, and will be quicker.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.