1

I want to sum numbers in multidimentional array using recursion in Python:

tab = [7, 5, [3, 6, [2]], 7, [1, [2, 3, [4]], 9, 2], 4]

I have tried few things, for example this:

sum(map(sum, tab))

It works for simple arrays, e.g. [[1, 2], [3, 4]], but it doesn't work for the one on top. I get this error:

TypeError: 'int' object is not iterable

Any ideas please?

0

2 Answers 2

4

One way to do it:

tab = [7, 5, [3, 6, [2]], 7, [1, [2, 3, [4]], 9, 2], 4]

def r_sum(tab):
    return sum(r_sum(item) if isinstance(item, list) else item for item in tab)

r_sum(tab)
# 55
Sign up to request clarification or add additional context in comments.

Comments

3

You can use the following recursive algorithm:

tab = [7, 5, [3, 6, [2]], 7, [1, [2, 3, [4]], 9, 2], 4]

def sumLst(l):
    sum = 0
    for ele in l:
        if type(ele) in [float, int]:
            sum += ele
        else:
            sum += sumLst(ele)
    return sum
print(sumLst(tab))

2 Comments

I think if isinstance(ele, (float, int)) is neater here. Also I think you just need to check if ele is a list in this case, then you recurse if it is.
@RoadRunner Personally I find type(ele) in [float, int] more readable, since with isinstance(ele, (float, int)) I always assume on first sight that you want to check against a tuple. However in case you prefer feel free to use your statement. There is no real argument against it ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.