0

Given an array a = [1,2,3,[4,5]] using Python 3, how can I add all the elements in the array?

sum(a[0])
sun(a[0][1])

The above code did not work. Also in the case, if you're given an array with an unknown amount of arrays inside arrays, How can those numbers be calculated?

4
  • You can use len(array) to find the number of elements inside. Commented Jul 26, 2018 at 13:41
  • 1
    What output do you expect? 15? Commented Jul 26, 2018 at 13:41
  • 1
    Flatten it, then sum it. Commented Jul 26, 2018 at 13:41
  • 1
    Terminology nitpick: arrays and lists are different things. arrays can only contain certain types of objects, and they can't contain other arrays. Commented Jul 26, 2018 at 13:43

4 Answers 4

3
def xsum(x):
    if not x:
        return 0

    head, *tail = x

    if isinstance(head, list):
        return xsum(head) + xsum(tail)
    elif tail:
        return head + xsum(tail)
    else:
        return head
Sign up to request clarification or add additional context in comments.

Comments

2

You need a flatten function. Here is one:

def flatten(a):
    """generator of flattened n-deep iterable (excluding str) a."""
    for elem in a:
        if not isinstance(elem, str):
            try:
                yield from flatten(elem)
            except TypeError:
                yield elem
        else:
            yield elem

which you can then use in sum, for example:

a = [1, 2, 3, [4, [5, 6]]
print(list(flatten(a)))  # --> [1, 2, 3, 4, 5, 6]
print(sum(flatten(a)))  # --> 21

Comments

0

You can use functools.reduce to sum this nested list

>>> from functools import reduce
>>> a = [1,2,3,[4,5]] 
>>> reduce(lambda x,y: x + (sum(y) if type(y)==list else y), [0]+a)
15

If the list can be more than one level nested, you have to use a recursive approach

>>> f = lambda x,y: x + (reduce(f, y) if type(y)==list else y)
>>> reduce(f, [0]+a)
15

Comments

0

You can use the closure property for finding sum of infinite nested list.

def nested_list_sum(x):
c = []

def l_sum(x):
    for i in x:
        if isinstance(i, list):
            l_sum(i)
        else:
            c.append(i)
l_sum(x)
return sum(c)

like a = [1,2,3,[4,5]] ----> 15

a = [1,2,3,[4,5, [6,7, [8, 9]]], [10, 11, 12, [13, 14, 5]]] -- > 110

Comments

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.