pythonpython-3.xrecursionarraylisttypeerror

TypeError: object of type 'int' has no len(), then i pass list to func


I wanted to write a recursive function that calculates the sum of the elements in an array, but when I pass the array to the function, it thinks that I passed an integer and writes that there is no len() function for it

arr1 = [1, 2, 3, 4, 5, 6]

def rec_sum(arr):
    if len(arr) == 0:
        return 0
    else:
        return(arr[len(arr) - 1] + rec_sum(arr.pop(len(arr) - 1)))

print(rec_sum(arr1))

Solution

  • Python's list.pop() method returns the element that is popped, so you are passing an integer to the recursive function call and not another list. Try using list slicing:

    arr1 = [1, 2, 3, 4, 5, 6]
    
    def rec_sum(arr):
        if len(arr) == 0:
            return 0
        else:
            return(arr[len(arr) - 1] + rec_sum(arr[:len(arr)-1]))
    
    print(rec_sum(arr1))
    

    Output:

    21