Python – Tuple Matrix Columns Summation
Last Updated :
09 Apr, 2023
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 : test_list = [[(4, 5), (1, 2)], [(2, 4), (4, 6)]]
Output : [(6, 9), (5, 8)]
Input : test_list = [[(4, 5), (1, 2), (6, 7)]]
Output : [(4, 5), (1, 2), (6, 7)]
Method #1 : Using list comprehension + zip() + sum() The combination of above functions can be used to solve this problem. In this, we perform the task of sum using sum() and zip() is used to perform column wise pairing of all elements.
step by step approach of the program:
- Define a nested list test_list containing tuples of integers.
- Print the original list.
- Create a list comprehension to iterate over the columns of the matrix.
- Use the zip() function to group the tuples in each column together.
- Apply the sum() function to each group of tuples to get the sum of the elements in that column.
- Wrap the result of the sum() function in a tuple using the tuple() constructor.
- Append the tuple of column sums to the result list for each column.
- Print the result list.
Python3
test_list = [[( 4 , 5 ), ( 3 , 2 )], [( 2 , 2 ), ( 4 , 6 )], [( 3 , 2 ), ( 4 , 5 )]]
print ("The original list is : " + str (test_list))
res = [ tuple ( sum (ele) for ele in zip ( * i)) for i in zip ( * test_list)]
print (" Tuple matrix columns summation : " + str (res))
|
Output :
The original list is : [[(4, 5), (3, 2)], [(2, 2), (4, 6)], [(3, 2), (4, 5)]]
Tuple matrix columns summation : [(9, 9), (11, 13)]
Time complexity: O(n^2) where n is the number of elements in the input list.
Auxiliary space: O(n^2) as well, where n is the number of elements in the input list.
Method #2 : Using map() + list comprehension + zip() The combination of above functions can be used to solve this problem. In this, we perform the task of extension of sum() using map() and rest of the functionalities are performed similar to above method.
Python3
test_list = [[( 4 , 5 ), ( 3 , 2 )], [( 2 , 2 ), ( 4 , 6 )], [( 3 , 2 ), ( 4 , 5 )]]
print ("The original list is : " + str (test_list))
res = [ tuple ( map ( sum , zip ( * ele))) for ele in zip ( * test_list)]
print (" Tuple matrix columns summation : " + str (res))
|
Output :
The original list is : [[(4, 5), (3, 2)], [(2, 2), (4, 6)], [(3, 2), (4, 5)]]
Tuple matrix columns summation : [(9, 9), (11, 13)]
Time Complexity: O(n*n) where n is the number of elements in the list “test_list”. map() + list comprehension + zip() performs n*n number of operations.
Auxiliary Space: O(n), extra space is required where n is the number of elements in the list
Method #3: Using NumPy library
This program imports the NumPy library and converts a given matrix (test_list) into a NumPy array. It then calculates the column-wise sum of the array using the np.sum() function and returns the result as a tuple. Finally, it prints the tuple containing the column-wise sums of the matrix.
Python3
import numpy as np
test_list = [[( 4 , 5 ), ( 3 , 2 )], [( 2 , 2 ), ( 4 , 6 )], [( 3 , 2 ), ( 4 , 5 )]]
arr = np.array(test_list)
res = tuple ( map ( tuple , np. sum (arr, axis = 0 )))
print ( "Tuple matrix columns summation : " + str (res))
|
OUTPUT:
Tuple matrix columns summation : ((9, 9), (11, 13))
The time complexity of the code snippet would be O(n^2), where n is the number of elements in the matrix.
The auxiliary space complexity of the code would be O(n^2) as well, because we are creating a NumPy array to store the matrix elements.
Method #4: Using a for loop and nested loops to iterate over the matrix and sum the columns.
In this method, we use a for loop to iterate over the columns of the matrix. For each column, we initialize a tuple col_sum with zeros, and then use nested loops to iterate over the rows and add the values in each row to col_sum. We use the zip() function to group the values in the same position in each row together, and the map() function to sum these values. Finally, we append col_sum to the result list.
Step-by-step approach:
- Initialize an empty result list res.
- Iterate over each column using a for loop with range() function and the number of columns num_cols.
- For each column, we initialize a tuple col_sum with zeros using (0, 0).
- Iterate over each row using a nested for loop with range() function and the number of rows num_rows.
- For each row, we use the zip() function to group the values in the same position in each row together, and the map() function to sum these values using the sum() function. We add these values to col_sum using the tuple() function to convert the result to a tuple.
- After iterating over all rows, we append col_sum to the result list res.
- After iterating over all columns, we have the required result stored in res.
- We print the result using the print() function and concatenation of string and the list.
Below is the implementation of the above approach:
Python3
test_list = [[( 4 , 5 ), ( 3 , 2 )], [( 2 , 2 ), ( 4 , 6 )], [( 3 , 2 ), ( 4 , 5 )]]
print ( "The original list is : " + str (test_list))
num_rows = len (test_list)
num_cols = len (test_list[ 0 ])
res = []
for j in range (num_cols):
col_sum = ( 0 , 0 )
for i in range (num_rows):
col_sum = tuple ( map ( sum , zip (col_sum, test_list[i][j])))
res.append(col_sum)
print ( "Tuple matrix columns summation : " + str (res))
|
Output
The original list is : [[(4, 5), (3, 2)], [(2, 2), (4, 6)], [(3, 2), (4, 5)]]
Tuple matrix columns summation : [(9, 9), (11, 13)]
The time complexity of this method is O(n^2), where n is the number of rows or columns in the matrix.
The auxiliary space complexity is O(n), since we need to store the result list.
Method #5: Using itertools module
Uses the itertools module to iterate over the columns of the matrix and sum them.
Step-by-step approach:
- Import the itertools module.
- Initialize an empty list to store the column sums.
- Iterate over the columns of the matrix using the zip() function and the * operator to unpack the tuples.
- Use the sum() function to calculate the sum of each column and append it to the list of column sums.
- Convert the list of column sums to a tuple and print it as the result.
Python3
import itertools
test_list = [[( 4 , 5 ), ( 3 , 2 )], [( 2 , 2 ), ( 4 , 6 )], [( 3 , 2 ), ( 4 , 5 )]]
col_sums = []
for col in itertools.zip_longest( * test_list, fillvalue = ( 0 , 0 )):
col_sum = sum ([x[ 0 ] for x in col]), sum ([x[ 1 ] for x in col])
col_sums.append(col_sum)
res = tuple (col_sums)
print ( "Tuple matrix columns summation : " + str (res))
|
Output
Tuple matrix columns summation : ((9, 9), (11, 13))
Time complexity: O(nm), where n is the number of rows and m is the number of columns in the matrix.
Auxiliary space: O(m), where m is the number of columns in the matrix.
Method 6: Using reduce() function from the functools module and lambda function
- Import the reduce() function from the functools module.
- Initialize the test_list with a nested list of tuples.
- Print the original list using the print() function.
- Use the zip() function to group the tuples from the same column of the matrix together.
- Use a list comprehension to iterate over the zipped list of columns and apply the reduce() function with a lambda function that takes two tuples and adds their corresponding elements.
- Convert the resulting tuple back to a tuple and append it to the res list using tuple comprehension.
- Print the res list containing the sum of columns of the matrix.
Python3
from functools import reduce
test_list = [[( 4 , 5 ), ( 3 , 2 )], [( 2 , 2 ), ( 4 , 6 )], [( 3 , 2 ), ( 4 , 5 )]]
print ( "The original list is : " + str (test_list))
res = [ tuple ( reduce ( lambda x, y: (x[ 0 ] + y[ 0 ], x[ 1 ] + y[ 1 ]), i))
for i in zip ( * test_list)]
print ( "Tuple matrix columns summation : " + str (res))
|
Output
The original list is : [[(4, 5), (3, 2)], [(2, 2), (4, 6)], [(3, 2), (4, 5)]]
Tuple matrix columns summation : [(9, 9), (11, 13)]
The time complexity is O(mn), where m is the number of rows and n is the number of columns in the matrix.
The space complexity is O(n), where n is the number of columns in the matrix.
Similar Reads
Summation Matrix columns - Python
The task of summing the columns of a matrix in Python involves calculating the sum of each column in a 2D list or array. For example, given the matrix a = [[3, 7, 6], [1, 3, 5], [9, 3, 2]], the goal is to compute the sum of each column, resulting in [13, 13, 13]. Using numpy.sum()numpy.sum() is a hi
2 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 | 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 ca
7 min read
Python - Cross tuple summation grouping
Sometimes, while working with Python tuple records, we can have a problem in which we need to perform summation grouping of 1st element of tuple pair w.r.t similar 2nd element of tuple. This kind of problem can have application in day-day programming. Let's discuss certain ways in which this task ca
7 min read
Python | Triple List Summation
There can be an application requirement to append elements of 2-3 lists to one list and perform summation. This kind of application has a potential to come into the domain of Machine Learning or sometimes in web development as well. Letâs discuss certain ways in which this particular task can be per
3 min read
Python - Summation of kth column in a matrix
Sometimes, while working with Python Matrix, we may have a problem in which we require to find the summation of a particular column. This can have a possible application in day-day programming and competitive programming. Letâs discuss certain ways in which this task can be performed. Method #1 : Us
8 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 | Conversion to N*N tuple matrix
Sometimes, while working with data, we can have a problem in which we have data in form of tuple Matrix with uneven length rows. In this case there's a requirement to complete the N*N matrix with a default value. Let's discuss certain ways in which this problem can be solved. Method #1 : Using loop
5 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 | 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 cert
9 min read