Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the sum of a nested list of ints

import math
lists =  [1,[2,3],4]
total = 0
for i in range(len(lists)):
    total += sum(i)
print(total)

I want it to print,

>>>10

But throws an error.

I would like it to get it to add all numbers, including the ones within the nested if.

like image 460
Jack Avatar asked Dec 12 '22 16:12

Jack


2 Answers

In your program, for i in range(len(lists)) - evaluates to 3 as the lists object has 3 element. and in the loop total += sum(i) it would try to do a int + list operation, which results in an error. Hence you need to check for the type and then add the individual elements.

def list_sum(L):
    total = 0  
    for i in L:
        if isinstance(i, list): 
            total += list_sum(i)
        else:
            total += i
    return total

This is @pavelanossov 's comment - does the same thing, in a more elegant way

sum(sum(i) if isinstance(i, list) else i for i in L)
like image 196
karthikr Avatar answered Dec 30 '22 05:12

karthikr


You can use flatten function in the compiler.ast module to flatten the list. Then simply sum up all the elements.

>>> lists =  [1,[2,3],4]
>>> from compiler.ast import flatten
>>> sum(flatten(lists))
10

EDIT: Only works with Python 2.x

like image 34
Faruk Sahin Avatar answered Dec 30 '22 04:12

Faruk Sahin