Sometimes, we are encountered with such problem in which we need to find the sum of each column in a matrix i.e sum of each index in list of lists. This kind of problem is quite common and useful in competitive programming. Let’s discuss certain ways in which this problem can be solved.
Method #1: Using sum() + list comprehension + zip()
The combination of the above methods are required to solve this particular problem. The sum function is used to get the required sum value and zip function provides the combination of like indices and then list is created using list comprehension.
Python3
test_list = [[ 3 , 7 , 6 ], [ 1 , 3 , 5 ], [ 9 , 3 , 2 ]]
print ( "The original list : " + str (test_list))
res = [ sum (idx) for idx in zip ( * test_list)]
print ( "The Summation of each index list is : " + str (res))
|
Output
The original list : [[3, 7, 6], [1, 3, 5], [9, 3, 2]]
The Summation of each index list is : [13, 13, 13]
Time complexity of this code is O(N*M) where N is the number of rows and M is the number of columns in the matrix. The reason for this is that the code is iterating through each element of the matrix, which requires N * M operations.
Auxiliary space used in this code is O(n), where n is the number of columns in the matrix. This is because the code uses a list comprehension, to sum up each column, which requires O(n) space to store the intermediate results.
Method #2: Using map() + sum() + zip()
This works in almost similar way as the above method, but the difference is just that we use map function to build the sum list rather than using list comprehension.
Python3
test_list = [[ 3 , 7 , 6 ], [ 1 , 3 , 5 ], [ 9 , 3 , 2 ]]
print ( "The original list : " + str (test_list))
res = list ( map ( sum , zip ( * test_list)))
print ( "The Summation of each index list is : " + str (res))
|
Output :
The original list : [[3, 7, 6], [1, 3, 5], [9, 3, 2]]
The Summation of each index list is : [13, 13, 13]
Time complexity: O(n), where n is the number of elements in the matrix.
Auxiliary space: O(m), where m is the number of columns in the matrix.
Method #3: Using for loops
Python3
test_list = [[ 3 , 7 , 6 ], [ 1 , 3 , 5 ], [ 9 , 3 , 2 ]]
print ( "The original list : " + str (test_list))
res = []
for i in range ( 0 , len (test_list)):
s = 0
for j in range ( 0 , len (test_list)):
s + = test_list[j][i]
res.append(s)
print ( "The Summation of each index list is : " + str (res))
|
Output
The original list : [[3, 7, 6], [1, 3, 5], [9, 3, 2]]
The Summation of each index list is : [13, 13, 13]
Time Complexity : O(N*N)
Auxiliary Space : O(N)
Method 4: Using the numpy library.
Step-by-step approach:
- Install and import the numpy library
- Convert the list to a numpy array
- Use the np.sum() function with the axis parameter set to 0 to get the column-wise sum
- Convert the numpy array back to a list using the tolist() function
- Print the result
Below is the implementation of the above approach:
Python3
import numpy as np
test_list = [[ 3 , 7 , 6 ], [ 1 , 3 , 5 ], [ 9 , 3 , 2 ]]
print ( "The original list : " + str (test_list))
np_array = np.array(test_list)
res = np. sum (np_array, axis = 0 )
res_list = res.tolist()
print ( "The Summation of each index list is : " + str (res_list))
|
Output:
The original list : [[3, 7, 6], [1, 3, 5], [9, 3, 2]]
The Summation of each index list is : [13, 13, 13]
Time complexity: O(n^2) since we have to iterate through each element of the matrix.
Auxiliary space: O(n^2) since we have to create a numpy array to store the matrix elements.
Method 5 : Using the built-in function functools.reduce()
- Import the reduce() function from the functools module.
- Initialize the input matrix test_list.
- Print the original input matrix.
- Use the reduce() function to iterate over the columns of the input matrix.
- In the reduce() function, use a lambda function to add the corresponding elements of each row of the input matrix.
- Use the zip() function to pair the elements of the rows.
- Append the result to a list.
- Print the resulting list of column sums.
Python3
from functools import reduce
test_list = [[ 3 , 7 , 6 ], [ 1 , 3 , 5 ], [ 9 , 3 , 2 ]]
print ( "The original list : " + str (test_list))
res = reduce ( lambda x,y: [i + j for i,j in zip (x,y)], test_list)
print ( "The Summation of each index list is : " + str (res))
|
Output
The original list : [[3, 7, 6], [1, 3, 5], [9, 3, 2]]
The Summation of each index list is : [13, 13, 13]
Time complexity: The time complexity of the reduce function is O(n) where n is the number of rows of the input matrix. Within each iteration of the reduce function, the time complexity of the lambda function is O(m) where m is the number of columns of the input matrix. Therefore, the overall time complexity of this approach is O(n*m).
Auxiliary space: The auxiliary space used by this approach is O(m), where m is the number of columns of the input matrix. This is because the resulting list of column sums has length equal to the number of columns of the input matrix. The lambda function also uses O(m) auxiliary space to store the result of the zip() function. Therefore, the overall auxiliary space of this approach is O(m).
Method 6: Using recursion
Step-by-step approach:
- Define a recursive function that takes in a list of lists and an empty list to store the column-wise sums.
- Base case: If the length of the first inner list is 0, return the list of column-wise sums.
- Recursive case: Use a list comprehension to extract the first element of each inner list and append it to a new list. Recursively call the function with the remaining lists and the updated list of column-wise sums.
- Use a for loop to iterate through the column-wise sums list and add the corresponding elements of each inner list.
- Return the resulting list of sums.
Below is the implementation of the above approach:
Python3
def column_sums_recursive(lst, sums):
if len (lst[ 0 ]) = = 0 :
return sums
else :
first_elements = [sublst[ 0 ] for sublst in lst]
sums.append( sum (first_elements))
remaining_lists = [sublst[ 1 :] for sublst in lst]
return column_sums_recursive(remaining_lists, sums)
test_list = [[ 3 , 7 , 6 ], [ 1 , 3 , 5 ], [ 9 , 3 , 2 ]]
print ( "The original list : " + str (test_list))
res_list = column_sums_recursive(test_list, [])
print ( "The Summation of each index list is : " + str (res_list))
|
Output
The original list : [[3, 7, 6], [1, 3, 5], [9, 3, 2]]
The Summation of each index list is : [13, 13, 13]
Time complexity: O(nm), where n is the number of inner lists and m is the length of the longest inner list.
Auxiliary space: O(n), for the list of column-wise sums.
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!
Last Updated :
04 Apr, 2023
Like Article
Save Article