Tammara Brown
Tammara Brown

Reputation: 17

How to add an array with using Python

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?

Upvotes: 0

Views: 77

Answers (4)

user3278460
user3278460

Reputation:

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

Upvotes: 3

utks009
utks009

Reputation: 573

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

Upvotes: 0

FHTMitchell
FHTMitchell

Reputation: 12147

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

Upvotes: 2

Sunitha
Sunitha

Reputation: 12005

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

Upvotes: 0

Related Questions