Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Recursion – summing a nested list

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading