Learn Programming and technology with ease @ developerpublish.com

HomePythonPython Program to Find the Total Sum of a Nested List Using Recursion

Python Program to Find the Total Sum of a Nested List Using Recursion

Pythonâ€™s recursion allows us to solve complex problems by breaking them down into simpler subproblems. In this illustration, weâ€™ll delve into a Python program that employs recursion to determine the total sum of a nested list.

Problem Statement

Develop a Python program that calculates and presents the total sum of a given nested list. The program should use recursion to navigate through the nested structure, adding up all the individual elements, regardless of the depth of nesting.

Python Program to Find the Total Sum of a Nested List Using Recursion

```def nested_list_sum(nested_list):
total_sum = 0

for element in nested_list:
if isinstance(element, list):
total_sum += nested_list_sum(element)
else:
total_sum += element

# Input and Output
sample_nested_list = [1, [2, 3, [4, 5]], [6, [7]]]
total = nested_list_sum(sample_nested_list)
print("Nested List:", sample_nested_list)
print("Total Sum:", total)
```

You May Also Like

Python Program to Remove Duplicates from a Linked List

In this Python program, we will create a singly linked list and remove duplicate elements from it. A linked list...

Python Program to Solve the Celebrity Problem

This Python program solves the Celebrity Problem by finding a person who is known by everyone but does not know...

Python Program to Solve n-Queen Problem with Recursion

This Python program uses a recursive approach to solve the n-Queens problem. It explores all possible combinations of queen placements...