An example using filter and map and recursion:
def islist[x]:
return isinstance[x, list]
def notlist[x]:
return not isinstance[x, list]
def nested_sum[seq]:
return sum[filter[notlist, seq]] + map[nested_sum, filter[islist, seq]]
And here is an example using reduce and recursion
from functools import reduce
def nested_sum[seq]:
return reduce[lambda a,b: a+[nested_sum[b] if isinstance[b, list] else b], seq]
An example using plain old recursion:
def nested_sum[seq]:
if isinstance[seq[0], list]:
head = nested_sum[seq[0]]
else:
head = seq[0]
return head + nested_sum[seq[1:]]
An example using simulated recursion:
def nested_sum[seq]:
stack = []
stack.append[seq]
result = 0
while stack:
item = stack.pop[]
if isinstance[item, list]:
for e in item:
stack.append[e]
else:
result += item
return result
Adjustment for handling self-referential lists is left as an exercise for the reader.
View Discussion
Improve Article
Save Article
View Discussion
Improve Article
Save Article
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.
Examples :
Input: [1,2,[3]] Output: 6 Input: [[4,5],[7,8,[20]],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.
Implementation:
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 the 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 change the argument to this sublist. And when the element is not a list, then simply add its value to the global total variable.
Python3
def
sum_nestedlist[ l ]:
total
=
0
for
j
in
range
[
len
[l]]:
if
type
[l[j]]
=
=
list
:
total
+
=
sum_nestedlist[l[j]]
else
:
total
+
=
l[j]
return
total
print
[sum_nestedlist[[[
1
,
2
,
3
],[
4
,[
5
,
6
]],
7
]]]
Time Complexity: O[N], Where N is the total number of elements in the list.
Auxiliary Space: O[1]
This is a Python Program to find the total sum of a nested list using recursion. Problem Description The program takes a nested list and finds the total sum of the nested list using recursion. Problem Solution 1. Initialize a variable to a nested list. Program/Source Code Here is source code of the Python Program to find the sum of a nested list using recursion. The program output is also shown below.
2. Pass the list as an argument to a recursive function to find the sum of elements
of the list.
3. In the function, use a for loop and recursion to obtain the elements inside the sublists and store the summed up elements in a variable.
4. Return the total sum of the elements.
5. Print the sum of the nested list.
6. Exit.
def sum1[lst]: total = 0 for element in lst: if [type[element] == type[[]]]: total = total + sum1[element] else: total = total + element return total print[ "Sum is:",sum1[[[1,2],[3,4]]]]
Program Explanation
1. A variable is initialized
to a nested list.
2. The list is passed as an argument to a recursive function to find the sum of elements of the list.
3. In the function, A for loop and repeated recursion to obtain the elements inside the sublists.
4. The total sum of the elements is found out and is returned.
5. The sum of the elements in the nested list is printed.
Runtime Test Cases
Sanfoundry Global Education & Learning Series – Python Programs.
To practice all Python programs, here is complete set of 150+ Python Problems and Solutions.
Next Steps:
- Get Free Certificate of Merit in Python Programming
- Participate in Python Programming Certification Contest
- Become a Top Ranker in Python Programming
- Take Python Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.
Subscribe to his free Masterclasses at Youtube & technical discussions at Telegram SanfoundryClasses.