Python - Skew Nested Tuple Summation
Last Updated :
16 May, 2023
Given a Tuple, nesting at 2nd position, return summation of 1st elements.
Input : test_tup = (5, (6, (1, (9, None))))
Output : 21
Explanation : 9 + 6 + 5 + 1 = 21.
Input : test_tup = (5, (6, (1, None)))
Output : 12
Explanation : 1 + 6 + 5 = 12.
Method #1: Using infinite loop
In this, we perform get into skew structure while summation using infinite loop and break when we reach None value.
Python3
# Python3 code to demonstrate working of
# Skew Nested Tuple Summation
# Using infinite loop
# initializing tuple
test_tup = (5, (6, (1, (9, (10, None)))))
# printing original tuple
print("The original tuple is : " + str(test_tup))
res = 0
while test_tup:
res += test_tup[0]
# assigning inner tuple as original
test_tup = test_tup[1]
# printing result
print("Summation of 1st positions : " + str(res))
OutputThe original tuple is : (5, (6, (1, (9, (10, None)))))
Summation of 1st positions : 31
Time complexity: O(n), where n is the number of elements in the input tuple.
Auxiliary space: O(1), as only a constant amount of additional memory is used to store the variables test_tup and res, regardless of the size of the input tuple.
Method #2: Using recursion
In this, we perform summation and recur for the 2nd element of tuple, return on None.
Python3
# Python3 code to demonstrate working of
# Skew Nested Tuple Summation
# Using recursion
# helper function to perform task
def tup_sum(test_tup):
# return on None
if not test_tup:
return 0
else:
return test_tup[0] + tup_sum(test_tup[1])
# initializing tuple
test_tup = (5, (6, (1, (9, (10, None)))))
# printing original tuple
print("The original tuple is : " + str(test_tup))
# calling fnc.
res = tup_sum(test_tup)
# printing result
print("Summation of 1st positions : " + str(res))
OutputThe original tuple is : (5, (6, (1, (9, (10, None)))))
Summation of 1st positions : 31
The time complexity of the given code is O(n), where n is the number of elements in the input nested tuple.
The auxiliary space used by the given code is O(n), where n is the number of elements in the input nested tuple.
Method 3: Using isinstance() + recursion
Recursively traverses the nested tuple and adds up the first element of each tuple it encounters.
- The tup_sum() function takes in a tuple test_tup as input.
- The base case for the recursion is when test_tup is an empty tuple or a tuple with no integer elements. In this case, the function returns 0 to stop the recursion.
- If the base case is not met, the function assumes that the first element of test_tup is an integer and adds it to the result. Then, the function recursively calls itself with the remaining elements of test_tup (i.e., test_tup[1:]), which may themselves be tuples.
- The recursion continues until the base case is met, at which point the function returns the total sum of the first elements of all the tuples encountered during the traversal.
Python3
def tup_sum(test_tup):
# Base case: return 0 for empty tuple or tuple with no integer elements
if not test_tup or not isinstance(test_tup[0], int):
return 0
else:
# Recursively compute sum of first element of current tuple and remaining tuples
return test_tup[0] + tup_sum(test_tup[1:])
# Example tuple
test_tup = (5, (6, (1, (9, (10, None)))))
# Print original tuple
print("The original tuple is:", test_tup)
# Compute sum of first elements
res = tup_sum(test_tup)
# Print result
print("Sum of first elements:", res)
OutputThe original tuple is: (5, (6, (1, (9, (10, None)))))
Sum of first elements: 5
Time complexity: O(n), where n is the total number of elements in the nested tuple.
Auxiliary space: O(m), where m is the maximum depth of the nested tuple.
Method #4: Using a stack data structure
In this implementation, we use a stack to traverse the nested tuple. We start by adding the entire tuple to the stack. In each iteration, we pop an element from the stack and check if it's an integer or a tuple. If it's an integer, we add it to the result. If it's a tuple, we push its first and second elements onto the stack (in that order). We continue this process until the stack is empty, and then return the result.
Python3
# Python3 code to demonstrate working of
# Skew Nested Tuple Summation
# Using stack
# initializing tuple
test_tup = (5, (6, (1, (9, (10, None)))))
# function to compute sum of first elements using stack
def sum_first_elements(test_tup):
stack = []
res = 0
stack.append(test_tup)
while stack:
curr = stack.pop()
if isinstance(curr, int):
res += curr
elif curr:
stack.append(curr[1])
stack.append(curr[0])
return res
# printing original tuple
print("The original tuple is : " + str(test_tup))
# printing result
print("Summation of 1st positions : " + str(sum_first_elements(test_tup)))
OutputThe original tuple is : (5, (6, (1, (9, (10, None)))))
Summation of 1st positions : 31
Time complexity: O(n), where n is the total number of elements in the nested tuple.
Auxiliary space: O(h), where h is the maximum depth of the nested tuple.
Method 5; using a generator function and the built-in sum function
- The program defines a generator function called get_first_element that takes a tuple as an argument.
- Inside the generator function, the program checks if the argument passed is a tuple. If it is, then it yields the first element of the tuple using the index tup[0].
- The program then recursively calls the get_first_element function with the second element of the tuple using tup[1].
- If the argument passed to the function is not a tuple, then the function does not yield anything and the recursion stops.
- The program initializes a nested tuple called test_tup that contains integers and nested tuples.
- The program prints the original tuple using the print function.
- The program calculates the sum of the first elements of the nested tuples in test_tup by calling the get_first_element generator function using the sum function. The result is stored in the res variable.
- The program prints the result using the print function.
Python3
# Python3 code to demonstrate working of
# Skew Nested Tuple Summation
# Using a generator function and sum
# define generator function to yield first element of each nested tuple
def get_first_element(tup):
if isinstance(tup, tuple):
yield tup[0]
yield from get_first_element(tup[1])
# initializing tuple
test_tup = (5, (6, (1, (9, (10, None)))))
# printing original tuple
print("The original tuple is : " + str(test_tup))
# calculate sum of first elements using generator and sum
res = sum(get_first_element(test_tup))
# printing result
print("Summation of 1st positions : " + str(res))
OutputThe original tuple is : (5, (6, (1, (9, (10, None)))))
Summation of 1st positions : 31
Time complexity for this method is O(n) where n is the number of elements in the nested tuple.
Auxiliary space is O(1) because the generator function yields each first element one at a time, without storing them all in memory at once.
Similar Reads
Python | Nested Tuples Subtraction
Sometimes, while working with records, we can have a problem in which we require to perform index-wise subtraction of tuple elements. This can get complicated with tuple elements being tuples and inner elements again being tuple. Letâs discuss certain ways in which this problem can be solved. Metho
7 min read
Python - Absolute Tuple Summation
Sometimes, while working with Python tuples, we can have a problem in which we need to perform the summation of absolute values of intermediate tuple elements. This kind of problem can have application in many domains such as web development. Let's discuss certain ways in which this task can be perf
6 min read
Python - Nested record values summation
Sometimes, while working with records, we can have problems in which we need to perform summation of nested keys of a key and record the sum as key's value. This can have possible applications in domains such as Data Science and web development. Let us discuss certain ways in which this task can be
7 min read
Python | Summation of tuples in list
Sometimes, while working with records, we can have a problem in which we need to find the cumulative sum of all the values that are present in tuples. This can have applications in cases in which we deal with a lot of record data. Let's discuss certain ways in which this problem can be solved. Metho
7 min read
Python - Dual Tuple Alternate summation
Given dual tuple, perform summation of alternate elements, i.e of indices alternatively. Input : test_list = [(4, 1), (5, 6), (3, 5), (7, 5)] Output : 18 Explanation : 4 + 6 + 3 + 5 = 18, Alternatively are added to sum. Input : test_list = [(4, 1), (5, 6), (3, 5)] Output : 13 Explanation : 4 + 6 + 3
8 min read
Python - Tuple Matrix Columns Summation
Sometimes, while working with Tuple Matrix, we can have a problem in which we need to perform summation of each column of tuple matrix, at the element level. This kind of problem can have application in Data Science domains. Let's discuss certain ways in which this task can be performed. Input : tes
8 min read
Python | Column summation of tuples
Sometimes, we encounter a problem where we deal with a complex type of matrix column summation in which we are given a tuple and we need to perform the summation of its like elements. This has a good application in Machine Learning domain. Let's discuss certain ways in which this can be done. Method
7 min read
Python | Grouped summation of tuple list
Many times, we are given a list of tuples and we need to group its keys and perform certain operations while grouping. The most common operation is addition. Let's discuss certain ways in which this task can be performed. Apart from addition, other operations can also be performed by doing small cha
10 min read
Python - Index Value Summation List
To access the elements of lists, there are various methods. But sometimes we may require to access the element along with the index on which it is found and compute its summation, and for that, we may need to employ different strategies. This article discusses some of those strategies. Method 1: Nai
4 min read
Python | Matrix True Summation
Checking a number/element by a condition is a common problem one faces and is done in almost every program. Sometimes we also require to get the totals that match the particular condition to have a distinguish which to not match for further utilization like in data Science. Let's discuss certain way
8 min read