简体   繁体   中英

Summing the elements of a list recursively

def sum(L):
    if len(L) == 1:
        return L[0]
    i = sum (len (L) // 2)
    if  len(L) > 1:
        return i + i

L=[2,4]

print (sum(L))

when i try to run it there is a TypeError: object of type 'int' has no len().

In sum (len (L) // 2) , you're passing an integer (the result of len(L) // 2 ) as the L argument to your sum() function. (Please don't give functions the same name as built-in functions.) The recursively-called sum() then tries to evaluate len(L) == 1 on this integer, but integers don't support len() , and so you get the error message in question. What exactly are you actually trying to do?

  1. Don't name your function sum , it shadows the builtin function
  2. Implement your function so as to clearly define a base case and a recursive case.

    For the base case, when the length is 1, return that element. You've got this right.
    For the recursive case, split your list into half and recursively compute the sum for each half.

def sum_recursive(L):
    if len(L) == 1:
        return L[0]

    idx = len(L) // 2
    return sum_recursive(L[:idx]) + sum_recursive(L[idx:])

sum_recursive must always receive a list and return an integer.

Some dry runs:

In [5]: sum_recursive([1, 2, 4, 8])
Out[5]: 15

In [6]: sum_recursive([2, 4])
Out[6]: 6

Keep in mind that this won't be able to handle empty lists as input. If you want to account for that as well, change your base case to:

def sum_recursive(L):
    if len(L) <= 1:
        return sum(L)
    ...

We're making use of the builtin sum function here which handles empty lists gracefully by returning 0. For single-element lists, the first element is returned (this is also why it is important you don't shadow these utility functions).

If you don't want to use sum there, you'll need to split your base case into two parts:

def sum_recursive(L):
    if len(L) == 0:
        return 0
    elif len(L) == 1:
        return L[0]
    ...

I think what you were aiming for was to write a recursive sum function that continuously splits the list into smaller chunks. So basically what you need to do is compute the index of the midpoint, then use list slicing to pass the first sublist and second sublist recursively back into the function, until hitting your base case(s) of 0 or 1 elements remaining.

def add(values):
    if len(values) == 0:
        return 0
    elif len(values) == 1:
        return values[0]
    mid = len(values)//2
    return add(values[:mid]) + add(values[mid:])

>>> add([1,2,3,4,5])
15

In your code

i = sum (len (L) // 2)

line is throwing an error because in recursion after the first call of sum() you are passing an integer not list

def sum(L):
    if len(L) == 0:
        return 0
    elif len(L) == 1:
        return L[0]
    else:
        index = len(L)-1
        return L[index] + sum(L[0:index])

L=[2,4]

print (sum(L))

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