A nested list is given. The task is to print the sum of this list using recursion. A nested list is a list whose elements can also be a list.
Input: [1,2,] Output: 6 Input: [[4,5],[7,8,],100] Output: 144 Input: [[1,2,3],[4,[5,6]],7] Output: 28
Recursion: In recursion, a function calls itself repeatedly. This technique is generally used when a problem can be divided into smaller subproblems of the same form.
Iterate through the list and whenever we find that an element of the list is also a list that means we have to do the same task of finding sum with this element list (which can be nested) as well. So we have found a subproblem and, we can call the same function to perform this task and just changing the argument to this sublist. And when the element is not a list, then simply add its value to the global total variable.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course