Reputation: 21
Trying to experiment around with calculating the sum of a list of integers or floating-points using recursion. However, I am getting a 'list index out of range' error. Forgive me if this is silly but I am very new to this and still just playing around.
def sum(listOfNumbers):
listOfNumbers == int or float
if len(listOfNumbers) == 1:
return listOfNumbers[0]
else:
return listOfNumbers[0] + sum(listOfNumbers[1:])
for (input, output) in [ ([1.0], 1), ([1,2], 3), ([1,2.0,3], 6) ]:
result = 'PASSED' if sum(input) == output else 'FAILED'
print('Test', input, result)
print(sum([]))
Upvotes: 2
Views: 88
Reputation: 23
You are passing an empty list as a parameter to the print(sum())
call you are making. Perhaps try passing input
to see the result of your sum()
function printed.
Upvotes: 1
Reputation: 76194
Your sum
function does not work properly when the list has no elements in it. len(listOfNumbers)
would equal zero, so the else
clause executes, and tries to access listOfNumbers[0]
. But a list with no elements doesn't have a zeroth element, so listOfNumbers[0]
crashes with a "list index out of range" error.
Change your function so it handles lists of length zero. The simplest way to implement this change would be:
def sum(listOfNumbers):
if len(listOfNumbers) == 0:
return 0
if len(listOfNumbers) == 1:
return listOfNumbers[0]
else:
return listOfNumbers[0] + sum(listOfNumbers[1:])
... But you really only need one base case, so you can remove the middle clause:
def sum(listOfNumbers):
if len(listOfNumbers) == 0:
return 0
else:
return listOfNumbers[0] + sum(listOfNumbers[1:])
Upvotes: 0