Python | Cumulative Nested Tuple Column Product

Sometimes, while working with records, we can have a problem in which we require to perform index wise multiplication of tuple elements. This can get complicated with tuple elements to be tuple and inner elements again be tuple. Let’s discuss certain ways in which this problem can be solved.

Method #1 : Using zip() + nested generator expression
The combination of above functions can be used to perform the task. In this, we combine the elements across tuples using zip(). The iterations and product logic is provided by generator expression.

Python3

 `# Python3 code to demonstrate working of` `# Cumulative Nested Tuple Column Product` `# 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))`   `# Cumulative Nested Tuple Column Product` `# 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 product : "` `+` `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 product : ((6, 21), (12, 45), (2, 9), (7, 30))```

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` `# Cumulative Nested Tuple Column Product` `# using isinstance() + zip() + loop + list comprehension`   `# function to perform task ` `def` `tup_prod(tup1, tup2):` `    ``if` `isinstance``(tup1, (``list``, ``tuple``)) ``and` `isinstance``(tup2, (``list``, ``tuple``)):` `        ``return` `tuple``(tup_prod(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))`   `# Cumulative Nested Tuple Column Product` `# using isinstance() + zip() + loop + list comprehension` `res ``=` `tuple``(tup_prod(x, y) ``for` `x, y ``in` `zip``(test_tup1, test_tup2))`   `# printing result` `print``(``"The resultant tuple after product : "` `+` `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 product : ((6, 21), (12, 45), (2, 9), (7, 30))```

Method #3: Using numpy.multiply()

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

This approach uses the numpy library’s multiply() function to perform the element-wise multiplication of the corresponding elements of the two nested tuples. This method can handle any level of nesting and is more concise and efficient than the previous methods.

Python3

 `import` `numpy as np`   `# 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))`   `# Cumulative Nested Tuple Column Product` `# using numpy.multiply()` `res ``=``tuple``(``tuple``(i) ``for` `i ``in`  `np.multiply(test_tup1, test_tup2))`   `# printing result` `print``(``"The resultant tuple after product : "` `+` `str``(res))` `#This code is contributed by Edula Vinay Kumar Reddy`

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 product : ((6, 21), (12, 45), (2, 9), (7, 30))

Time complexity: O(n)

Auxiliary Space: O(n)

Method #4: Using recursion

Steps:

1. Define a recursive function tup_prod() that takes two tuples as input and returns a new tuple as output.
2. Check if the input tuples are lists or tuples using isinstance() function. If not, return the product of the two tuples.
3. If the input tuples are lists or tuples, create an empty list res to store the product of each element of the two tuples.
4. Use a for loop and the zip() function to iterate over the elements of the two tuples.
5. Recursively call the tup_prod() function with the corresponding elements of the two tuples as input and append the result to the list res.
6. Convert the list res to a tuple and return it.
7. Initialize the input tuples test_tup1 and test_tup2.
8. Call the tup_prod() function with the input tuples as arguments to obtain the product of corresponding elements of the tuples.
9. Print the original input tuples and the resultant tuple after product.

Python3

 `# function to perform task ` `def` `tup_prod(tup1, tup2):` `    ``if` `isinstance``(tup1, (``list``, ``tuple``)) ``and` `isinstance``(tup2, (``list``, ``tuple``)):` `        ``res ``=` `[]` `        ``for` `x, y ``in` `zip``(tup1, tup2):` `            ``res.append(tup_prod(x, y))` `        ``return` `tuple``(res)` `    ``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))`   `# Cumulative Nested Tuple Column Product` `# using recursion` `res ``=` `tup_prod(test_tup1, test_tup2)`   `# printing result` `print``(``"The resultant tuple after product : "` `+` `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 product : ((6, 21), (12, 45), (2, 9), (7, 30))```

The time complexity of the given Python code is O(n), where n is the total number of elements in the input tuples ‘test_tup1’ and ‘test_tup2’.

The auxiliary space required by the code is O(n), where n is the total number of elements in the input tuples ‘test_tup1’ and ‘test_tup2’.

Method #5: Using  itertools:

Algorithm :

1. Initialize two tuples test_tup1 and test_tup2.
2. Initialize an empty list res.
3. Iterate through the tuples test_tup1 and test_tup2 simultaneously using the zip() function.
4. Multiply the corresponding elements of the tuples using the * operator, and append the result to the list res.
5. Convert the list res to a tuple and store it in res.
6. Print the original tuples and the resultant tuple.

Python3

 `from` `itertools ``import` `starmap` `from` `operator ``import` `mul`   `# function to perform task` `def` `tup_prod(tup1, tup2):` `    ``return` `tuple``(starmap(mul, ``zip``(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))`   `# Cumulative Nested Tuple Column Product` `# using itertools and starmap` `res ``=` `tuple``(starmap(tup_prod, ``zip``(test_tup1, test_tup2)))`   `# printing result` `print``(``"The resultant tuple after product : "` `+` `str``(res))` `#This code is contrinuted by Pushpa.`

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 product : ((6, 21), (12, 45), (2, 9), (7, 30))```

The time complexity : O(n), where n is the length of the tuples.

The auxiliary space : O(n), where n is the length of the tuples.

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Previous
Next