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 :)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With