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().
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