Home > Mobile >  Recursion - summing a nested list
Recursion - summing a nested list

Time:03-29

I'm trying to sum all the numbers in a nested list as a practice for recursion. However, the output gives 1 instead of the total of all numbers. Where did i go wrong?

I tried looping through the nested list and if its a list, then it calls the same function again. If its not a list, it adds the number to the total.

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

def sumL(input): 
    total = 0 
    for i in input: 
        if type(i) is list:
            total  = sumL(i)
        else: 
            total  = i
        return total 
    
sumL(L)

CodePudding user response:

You are exiting on the first iteration of the for loop. As i equals 1, then you type check it, then you = total and immediately return. You should return after you have exited the for loop.

def sumL(ls):
    total = 0
    for i in ls:
        if isinstance(i, list):
            total  = sumL(i)
        else:
            total  = i
    return total

Note* don't use input as an argument, as it is the name of a function

  • Related