简体   繁体   中英

Unable to debug sum of a list using recursion in Python

def sumList(arr):
    items = len(arr)
    if(items == 0):
        return 0
    elif(items == 1):
        return arr[0]
    else:
        return(arr[0] + sumList(arr[1:]))

print(sumList([2, 4, 6, 10, 123]))

This code will still run if the "else if" part is commented out. But, shouldn't the last else give an error for the last case when only one item is present as it's returning the list starting from index 1, which does not exist?

Slices will never give an index out-of-range error. For example:

mylist = [1, 2, 3]
print(mylist[10000:])
# []

Let's clarify the question: you seem to be asking why this code:

def sumList(array):
    items = len(array)

    if items == 0:
        return 0

    if items == 1:
        return array[0]

    return array[0] + sumList(array[1:])

still works if/when we remove the second conditional expression:

def sumList(array):
    items = len(array)

    if items == 0:
        return 0

    #if items == 1:
    #   return array[0]

    return array[0] + sumList(array[1:])

And the answer that @Tomothy32 provides tells us that the last line will eventually become:

return array[0] + sumList([])

Which due to your first conditional expression, becomes:

return array[0] + 0

In Python 3 we can express this as simply:

def sumList(array):
    if not array:  # empty containers are false in boolean context
        return 0

    head, *tail = array  # Python 2: head, tail = array[0], array[1:]

    return head + sumList(tail)

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