LighOfDarkness
LighOfDarkness

Reputation: 39

How to fix "'int' object is not subscriptable" in this case?

I'm just trying to write recursive code, but I've got this error. Where is my mistake?

I've tried to identify all the variables but it isn't working.

def sum(arr):
    if len(arr) > 1:
        answer = int(arr.pop()[0] + sum(arr))
        return answer
    else:
        return arr[0]

print(str(sum([1, 45])))

I expect recursion work properly but it doesn't. It has to give sum of the array.

Upvotes: 0

Views: 46

Answers (1)

Dean Coakley
Dean Coakley

Reputation: 1877

arr.pop returns and removes the last element of the list. So it returns an int, not a list of ints.

https://docs.python.org/2/library/array.html#array.array.pop

Here is how I would fix your code. I just remove the [0] from arr.pop() which fixes the code and also remove some unnecessary casting

def sum(arr):
    if len(arr) > 1:
        answer = arr.pop() + sum(arr)
        return answer
    else:
        return arr[0]

print(sum([1, 45]))

Upvotes: 1

Related Questions