1

I was trying to make a definition that would add all numbers within each sublist in a list of lists.

def MassAddition(_list):
    output = []
    total = 0
    for i in _list:
        if isinstance(i, list):
            output.append(MassAddition(i))
        else:
            total = total + i
    output.append(total)
    return output

Problem is that it returns an extra item in a list at the end. I think its because I made total = 0 and then appended it to output list outside of for loop. Can someone help me clean this up? Ps. This definition should be able to handle any level of nested lists.

example: input = [[0,1,2], [2,1,5],[2,2,2],2,2,1] desiredoutput = [[3],[8],[6],5]

Thank you,

konrad
  • 3,544
  • 4
  • 36
  • 75

1 Answers1

0

You can check the additional numbers for type too. If they can only be int:

def mass_addition(lst):
    output = []
    total = 0
    extra_flag = False
    for i in lst:
        if isinstance(i, list):
            output.append(mass_addition(i))
        elif isinstance(i, int):
            extra_flag = True
            total += i
    if extra_flag:
        output.append(total)
    return output
Paulo Almeida
  • 7,803
  • 28
  • 36
  • if the list is nested as so: [[1,2], [[1], [2], [3,4]]]. The output still contains nested lists - [[3], [[1], [2], [7]]]. is this what the OP wants? – Tom May 12 '15 at 21:59
  • @EpsilonX, I'm not sure, but if it isn't, the problem must be defined more clearly. That would mean the problem with the original function wasn't just returning an extra item in the end of the list, as konrad said. – Paulo Almeida May 12 '15 at 22:06
  • I think the main problem is that, indeed, we don't know what the OP wants. – TigerhawkT3 May 12 '15 at 22:08
  • True. @PauloAlmeida Perhaps both are the problem?? – Tom May 12 '15 at 22:10