Open In App

Python – Skew Nested Tuple Summation

Last Updated : 16 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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))


Output

The 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))


Output

The 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)


Output

The 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)))


Output

The 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))


Output

The 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 Dictionary values summation
Sometimes, while working with Python dictionaries, we can have problem in which we have nested records and we need cumulative summation of it's keys values. This can have possible application in domains such as web development and competitive programming. Lets discuss certain ways in which this task can be performed. Method #1 : Using loop + items(
8 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 performed. Method #1: Using loop This is a brute f
7 min read
Python - Summation of Custom nested keys in Dictionary
Given a dictionary with keys as nested dictionaries, find the sum of values of certain custom keys inside the nested dictionary. Input : test_dict = {'Gfg' : {1 : 6, 5: 9, 9: 12}, 'is' : {1 : 9, 5: 7, 9: 2}, 'best' : {1 : 3, 5: 4, 9: 14}}, sum_key = [1] Output : 18 Explanation : 6 + 9 + 3 = 18, only values with key 1 are summed. Input : test_dict =
10 min read
Python | Summation of list as tuple attribute
Many times, while dealing with containers in any language we come across lists of tuples in different forms, tuples in themselves can have sometimes more than native datatypes and can have list as their attributes. This article talks about the summation of list as tuple attribute. Let's discuss certain ways in which this task can be performed. Meth
9 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 changes. Method 1: Using Counter() + "+" operator Thi
10 min read
Python | Summation of Kth Column of Tuple List
Sometimes, while working with Python list, we can have a task in which we need to work with tuple list and get the possible accumulation of its Kth index. This problem has applications in the web development domain while working with data information. Let's discuss certain ways in which this task can be performed. Method #1: Using list comprehensio
7 min read
Python | Accumulative index summation in tuple list
Sometimes, while working with data, we can have a problem in which we need to find accumulative summation of each index in tuples. This problem can have applications in web development and competitive programming domain. Let's discuss certain way in which this problem can be solved. Method 1: Using accumulate() + sum() + lambda + map() + tuple() +
8 min read
Python - Summation of tuple dictionary values
Sometimes, while working with data, we can have a problem in which we need to find the summation of tuple elements that are received as values of dictionary. We may have a problem to get index wise summation. Let’s discuss certain ways in which this particular problem can be solved. Method #1: Using tuple() + sum() + zip() + values() The combinatio
4 min read
Python - Tuple to Dictionary Summation conversion
Sometimes, while working with Python tuples, we can have a problem in which we can have data points in tuples, and we need to convert them to dictionary after performing summation of similar keys. This kind of operation can also be extended to max, min or product. This can occur in data domains. Let's discuss certain ways in which this task can be
5 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 performed. Input : test_list = [(-7, -8), (-5, -6)] Ou
6 min read
Practice Tags :