Open In App

Python | Nested Tuples Subtraction

Improve
Improve
Like Article
Like
Save
Share
Report

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. 

Method #1: Using zip() + nested generator expression

The combination of the above functions can be used to perform the task. In this, we combine the elements across tuples using zip(). The iterations and difference logic are provided by the generator expression. 

Python3




# Python3 code to demonstrate working of
# Nested Tuples Subtraction
# using zip() + nested generator expression
 
# initialize tuples
test_tup1 = ((1, 3), (4, 5), (2, 9), (1, 10))
test_tup2 = ((6, 7), (3, 9), (1, 1), (7, 3))
 
# printing original tuples
print("The original tuple 1 : " + str(test_tup1))
print("The original tuple 2 : " + str(test_tup2))
 
# Nested Tuples Subtraction
# using zip() + nested generator expression
res = tuple(tuple(a - b for a, b in zip(tup1, tup2))
            for tup1, tup2 in zip(test_tup1, test_tup2))
 
# printing result
print("The resultant tuple after subtraction : " + str(res))


Output : 

The original tuple 1 : ((1, 3), (4, 5), (2, 9), (1, 10))
The original tuple 2 : ((6, 7), (3, 9), (1, 1), (7, 3))
The resultant tuple after subtraction : ((-5, -4), (1, -4), (1, 8), (-6, 7))

Method #2: Using isinstance() + zip() + loop + list comprehension

The combination of above functions can be used to perform this particular task. In this, we check for the nesting type and perform recursion. This method can give flexibility of more than 1 level nesting. 

Python3




# Python3 code to demonstrate working of
# Nested Tuples Subtraction
# using isinstance() + zip() + loop + list comprehension
 
# function to perform task
 
 
def tup_diff(tup1, tup2):
    if isinstance(tup1, (list, tuple)) and isinstance(tup2, (list, tuple)):
        return tuple(tup_diff(x, y) for x, y in zip(tup1, tup2))
    return tup1 - tup2
 
 
# initialize tuples
test_tup1 = ((1, 3), (4, 5), (2, 9), (1, 10))
test_tup2 = ((6, 7), (3, 9), (1, 1), (7, 3))
 
# printing original tuples
print("The original tuple 1 : " + str(test_tup1))
print("The original tuple 2 : " + str(test_tup2))
 
# Nested Tuples Subtraction
# using isinstance() + zip() + loop + list comprehension
res = tuple(tup_diff(x, y) for x, y in zip(test_tup1, test_tup2))
 
# printing result
print("The resultant tuple after subtraction : " + str(res))


Output : 

The original tuple 1 : ((1, 3), (4, 5), (2, 9), (1, 10))
The original tuple 2 : ((6, 7), (3, 9), (1, 1), (7, 3))
The resultant tuple after subtraction : ((-5, -4), (1, -4), (1, 8), (-6, 7))

Time complexity: O(n), where n is the number of elements in the tuples.
Auxiliary space: O(n), as the code creates a new tuple to store the result of the subtraction. 

Approach 3: Using NumPy

Note: Install numpy module using command “pip install numpy”

Python3




# Approach 1 : Using numpy
 
import numpy as np
 
test_tup1 = ((1, 3), (4, 5), (2, 9), (1, 10))
test_tup2 = ((6, 7), (3, 9), (1, 1), (7, 3))
 
# convert the tuples to numpy arrays
arr1 = np.array(test_tup1)
arr2 = np.array(test_tup2)
 
# perform the subtraction
result = arr1 - arr2
 
# convert back to tuple
result = tuple(map(tuple, result))
 
# print the result
print(result)
 
# This code is contributed by Edula Vinay Kumar Reddy


Output:

((-5, -4), (1, -4), (1, 8), (-6, 7))
 

Time complexity: O(n)
Auxiliary Space: O(n)

Explanation: Here, we are using numpy to perform the subtraction of nested tuples. The NumPy library provides the numpy array which can perform the subtraction of elements between arrays. We convert the input tuples to numpy arrays and then perform a subtraction between the two arrays. Finally, we convert the result back to the tuple.

Approach #4: Using map() and lambda function

We can use the map() function along with lambda function to subtract the corresponding values of tuples from both the input tuples. We can then use the tuple() function to convert the resulting map object into a tuple.

  1. Initialize two tuples test_tup1 and test_tup2 with the given values.
  2. Print the original tuples test_tup1 and test_tup2.
  3. Use the zip() function to create an iterator that aggregates the elements from the two tuples test_tup1 and test_tup2.
  4. Use map() to apply a lambda function to each element of the iterator created by the zip() function. The lambda function subtracts the corresponding values of the tuples from both the input tuples.
  5. Convert the resulting map object into a tuple using the tuple() function.
  6. Assign the resulting tuple to a variable res.
  7. Print the resulting tuple res.

Python3




# Python3 code to demonstrate working of
# Nested Tuples Subtraction
# using map() and lambda function
 
# initialize tuples
test_tup1 = ((1, 3), (4, 5), (2, 9), (1, 10))
test_tup2 = ((6, 7), (3, 9), (1, 1), (7, 3))
 
# printing original tuples
print("The original tuple 1 : " + str(test_tup1))
print("The original tuple 2 : " + str(test_tup2))
 
# Nested Tuples Subtraction
# using map() and lambda function
res = tuple(map(lambda x: tuple(x[0] - x[1]
                                for x in zip(*x)), zip(test_tup1, test_tup2)))
 
# printing result
print("The resultant tuple after subtraction : " + str(res))


Output

The original tuple 1 : ((1, 3), (4, 5), (2, 9), (1, 10))
The original tuple 2 : ((6, 7), (3, 9), (1, 1), (7, 3))
The resultant tuple after subtraction : ((-5, -4), (1, -4), (1, 8), (-6, 7))

Time complexity: O(n), where n is the number of elements in the input tuples.
Auxiliary space: O(n), where n is the number of elements in the input tuples.

Approach #5: Using a loop and append function

In this approach, we can use a for loop to iterate through both tuples and subtract each element from the corresponding element in the other tuple. We can store the result in a new tuple using the append() function.

  1. Initialize two tuples test_tup1 and test_tup2 with nested tuples as their elements.
  2. Print the original tuples using the print() function and string concatenation.
  3. Create an empty list res to store the result of subtraction.
  4. Use a for loop with the range() function to iterate over the length of the tuples.
  5. Inside the for loop, create an empty list temp to store the result of each subtraction.
  6. Use another for loop to iterate over the length of the nested tuples.
  7. Inside the nested for loop, subtract each corresponding element of the nested tuples and append the result to the temp list.
  8. Convert the temp list to a tuple using the tuple() function and append it to the res list.
  9. Print the final result by converting the res list to a tuple using the tuple() function and using the print() function with string concatenation.

Python3




# initialize tuples
test_tup1 = ((1, 3), (4, 5), (2, 9), (1, 10))
test_tup2 = ((6, 7), (3, 9), (1, 1), (7, 3))
 
# printing original tuples
print("The original tuple 1 : " + str(test_tup1))
print("The original tuple 2 : " + str(test_tup2))
 
# using a loop and append function
res = []
for i in range(len(test_tup1)):
    temp = []
    for j in range(len(test_tup1[i])):
        temp.append(test_tup1[i][j] - test_tup2[i][j])
    res.append(tuple(temp))
 
# printing result
print("The resultant tuple after subtraction : " + str(tuple(res)))


Output

The original tuple 1 : ((1, 3), (4, 5), (2, 9), (1, 10))
The original tuple 2 : ((6, 7), (3, 9), (1, 1), (7, 3))
The resultant tuple after subtraction : ((-5, -4), (1, -4), (1, 8), (-6, 7))

Time complexity: O(n^2) where n is the length of the tuples since we have nested loops.
Auxiliary space: O(n) since we are storing the result in a new tuple.



Last Updated : 06 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads