简体   繁体   中英

list index out of range (Python 3)

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([]))

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM