Python Program to Find the Total Sum of a Nested List Using Recursion
Last Updated :
06 Apr, 2023
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
# Python Program to find sum
# of nested list using Recursion
def sum_nestedlist( l ):
# specify that global variable is
# referred to here in this function
total = 0
for j in range(len(l)):
if type(l[j]) == list :
# call the same function if
# the element is a list
total+= sum_nestedlist(l[j])
else:
# if it's a single element
# and not a list, add it to total
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)
Method 2: Using recursion
This program defines a function sum_nestedlist that takes a nested list as input and returns the sum of all its elements. It does this by using a stack to iterate through each element of the list, adding each non-list element to a running total and extending the stack with any list elements.
Python3
def sum_nestedlist(l):
stack = l
total = 0
while stack:
elem = stack.pop()
if type(elem) == list:
stack.extend(elem)
else:
total += elem
return total
# example usage
my_list = [[1,2,3],[4,[5,6]],7]
print(sum_nestedlist(my_list)) # Output: 28
Time complexity: O(n), where n is the total number of elements in the nested list.
Auxiliary space: O(d), where d is the maximum depth of nesting in the input list.
Method 3: Using Iteration
This function uses a stack to keep track of nested lists. It pops the last element from the stack, and if it's a list, it pushes its elements to the stack. If it's a number, it adds it to the total.
Follow the below steps to implement the above idea:
- Define a function sum_nestedlist_iterative(lst) that takes a nested list lst as input.
- Initialize a variable total to 0 and a list stack containing the input last.
- Enter a while loop that continues until the stack list is empty.
- Pop the last element from the stack list and assign it to current.
- For each element in current, check if it is a list. If it is a list, append it to the stack list. If it is not a list, add the element to the total variable.
- Repeat steps 4-5 until all elements in lst have been checked.
- Return the final value of total.
Below is the implementation of the above approach:
Python3
def sum_nestedlist_iterative(lst):
total = 0
stack = [lst]
while stack:
current = stack.pop()
for element in current:
if type(element) == list:
stack.append(element)
else:
total += element
return total
print(sum_nestedlist_iterative([[1,2,3],[4,[5,6]],7]))
Time complexity: O(n), where n is the total number of elements in the nested list.
Auxiliary space: O(m), where m is the maximum depth of the nested list.
Method 4: Using a Stack
Step-by-step approach:
- Initialize an empty stack and push the input list onto it.
- Initialize the sum variable to 0.
- While the stack is not empty:
a. Pop the top element from the stack.
b. If the element is a list, push all its elements onto the stack.
c. If the element is an integer, add it to the sum variable. - Return the sum variable.
Python3
def sum_nestedlist(l):
stack = []
stack.append(l)
total = 0
while stack:
curr = stack.pop()
if type(curr) == list:
for elem in curr:
stack.append(elem)
else:
total += curr
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 input list.
Auxiliary Space: O(M), where M is the maximum size of the stack during the execution of the program.
Method 5: Using Queue
step-by-step approach:
- Define a function named sum_nestedlist_queue that takes in a nested list lst as input.
- Initialize a variable named total to 0 to keep track of the sum of all the elements in the nested list.
- Create a queue using the deque function from the collections module. The queue should be initialized with the input nested list lst.
- Start a loop that continues as long as the queue is not empty. The loop will pop the first element in the queue (using the popleft method), and assign it to a variable named current.
- For each element in current, check if it is a list by using the type function. If the element is a list, append it to the end of the queue using the append method.
- If the element is not a list, add it to the total variable.
- Repeat steps 4-6 until the queue is empty.
- Return the final value of total.
- Call the sum_nestedlist_queue function with an example nested list, and print the result.
Python3
from collections import deque
def sum_nestedlist_queue(lst):
total = 0
queue = deque([lst])
while queue:
current = queue.popleft()
for element in current:
if type(element) == list:
queue.append(element)
else:
total += element
return total
print(sum_nestedlist_queue([[1,2,3],[4,[5,6]],7]))
Time complexity: O(n), where n is the total number of elements in the nested list.
Auxiliary space: O(max_depth), where max_depth is the maximum depth of the nested list.
Similar Reads
Python Program to Flatten a Nested List using Recursion
Given a nested list, the task is to write a python program to flatten a nested list using recursion. Examples: Input: [[8, 9], [10, 11, 'geeks'], [13]] Output: [8, 9, 10, 11, 'geeks', 13] Input: [['A', 'B', 'C'], ['D', 'E', 'F']] Output: ['A', 'B', 'C', 'D', 'E', 'F'] Step-by-step Approach: Firstly,
3 min read
Python program to find the sum of Characters ascii values in String List
Given the string list, the task is to write a Python program to compute the summation value of each character's ASCII value. Examples: Input : test_list = ["geeksforgeeks", "teaches", "discipline"] Output : [133, 61, 100] Explanation : Positional character summed to get required values. Input : test
4 min read
Python Program to Flatten a List without using Recursion
The task is to convert a nested list into a single list in Python i.e no matter how many levels of nesting are there in the Python list, all the nested have to be removed in order to convert it to a single containing all the values of all the lists inside the outermost brackets but without any brack
7 min read
Python Program to Find the Sum of Natural Numbers Using While Loop
Calculating the Sum of N numbers in Python using while loops is very easy. In this article, we will understand how we can calculate the sum of N numbers in Python using while loop.Calculate Sum of Natural Numbers in Python Using While LoopBelow are some of the examples by which we can see how we can
2 min read
Python Program to Display Fibonacci Sequence Using Recursion
We are given a task to write the Fibonacci sequence using recursion. we will take the range as input of integer and then print the Fibonacci Sequence. In this article, we will see the method of Python Program to Display Fibonacci Sequence Using Recursion. Example: Input: n = 9Output: 0 1 1 2 3 5 8 1
2 min read
Python Program To Add Two Numbers Represented By Linked Lists- Set 1
Given two numbers represented by two lists, write a function that returns the sum list. The sum list is a list representation of the addition of two input numbers. Example: Input:Â List1: 5->6->3 // represents number 563Â List2: 8->4->2 // represents number 842Â Output:Â Resultant list: 1->4->0->5 // re
4 min read
Python3 Program to Find if there is a subarray with 0 sum
Given an array of positive and negative numbers, find if there is a subarray (of size at-least one) with 0 sum.Examples : Input: {4, 2, -3, 1, 6}Output: true Explanation:There is a subarray with zero sum from index 1 to 3.Input: {4, 2, 0, 1, 6}Output: true Explanation:There is a subarray with zero s
3 min read
Python Program To Find The Sum Of Last N Nodes Of The Given Linked List
Given a linked list and a number n. Find the sum of the last n nodes of the linked list.Constraints: 0 <= n <= number of nodes in the linked list. Examples: Input: 10->6->8->4->12, n = 2 Output: 16 Sum of last two nodes: 12 + 4 = 16 Input: 15->7->9->5->16->14, n = 4
10 min read
Python3 Program to Find a triplet that sum to a given value
Given an array and a value, find if there is a triplet in array whose sum is equal to the given value. If there is such a triplet present in array, then print the triplet and return true. Else return false.Examples: Input: array = {12, 3, 4, 1, 6, 9}, sum = 24; Output: 12, 3, 9 Explanation: There is
6 min read
Python - Ways to sum list of lists and return sum list
When working with nested lists (lists of lists), we may need to compute the sum of corresponding elements across all inner lists. In this article, we will see how Python provides multiple methods to perform this task. The most common and efficient way to sum up a list of lists is by using zip() comb
2 min read