Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error doing recursion in python using lists

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

like image 329
badman123 Avatar asked Dec 03 '25 05:12

badman123


1 Answers

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
like image 65
thefourtheye Avatar answered Dec 05 '25 19:12

thefourtheye