Open In App

Python | Uneven Sized Matrix Column product

Improve
Improve
Like Article
Like
Save
Share
Report

The usual list of list, unlike conventional C type Matrix, can allow the nested list of lists with variable lengths, and when we require the product of its columns, the uneven length of rows may lead to some elements in that elements to be absent and if not handled correctly, may throw exception. Let’s discuss certain ways in which this problem can be performed in error free manner. 

Method #1 : Using loop + filter() + map() + list comprehension The combination of above three function combined with list comprehension can help us perform this particular task, the external prod function helps to perform the multiplication, filter allows us to check for the present elements and all rows are combined using the map function. Works only with python 2. 

Python




# Python code to demonstrate
# Uneven Sized Matrix Column product
# using loop + filter() + map() + list comprehension
 
# getting Product
def prod(val) :
    res = 1
    for ele in val:
        res *= ele
    return res
 
# initializing list of lists
test_list = [[1, 5, 3], [4], [9, 8]]
 
# printing original list
print ("The original list is : " + str(test_list))
 
# using loop + filter() + map() + list comprehension
# Uneven Sized Matrix Column product
res = [prod(filter(None, j)) for j in map(None, *test_list)]
 
# printing result
print ("The product of columns is : " + str(res))


Output : 

The original list is : [[1, 5, 3], [4], [9, 8]]
The product of columns is : [36, 40, 3]

Time Complexity: O(n*n), where n is the length of the list test_list 
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list 

Method #2 : Using list comprehension + loop + zip_longest() If one desires not to play with the None values, one can opt for this method to resolve this particular problem. The zip_longest function helps to fill the not present column with 1 so that it does not has to handle the void of elements not present. 

Python3




# Python3 code to demonstrate
# Uneven Sized Matrix Column product
# using list comprehension + loop + zip_longest()
import itertools
 
# getting Product
def prod(val) :
    res = 1
    for ele in val:
        res *= ele
    return res
 
# initializing list of lists
test_list = [[1, 5, 3], [4], [9, 8]]
 
# printing original list
print ("The original list is : " + str(test_list))
 
# using list comprehension + loop + zip_longest()
# Uneven Sized Matrix Column product
res = [prod(i) for i in itertools.zip_longest(*test_list, fillvalue = 1)]
 
# printing result
print ("The product of columns is : " + str(res))


Output : 

The original list is : [[1, 5, 3], [4], [9, 8]]
The product of columns is : [36, 40, 3]

Time Complexity: O(n*n), where n is the number of elements in the list “test_list”.
Auxiliary Space: O(n), where n is the number of elements in the list “test_list”.

Method #3 : Using max()

This method works by first finding the length of the longest row in the matrix. It then pads the shorter rows with 1s to make all rows the same length. Finally, it computes the product of each column by iterating over the columns and rows of the padded matrix.

Python3




def column_product(matrix):
    # get the length of the longest row in the matrix
    max_len = max(len(row) for row in matrix)
 
    # pad the shorter rows with 1s to make all rows the same length
    padded_matrix = [row + [1] * (max_len - len(row)) for row in matrix]
 
    # compute the product of each column
    result = [1] * max_len
    for i in range(max_len):
        for row in padded_matrix:
            result[i] *= row[i]
 
    return result
 
matrix = [[1, 5, 3], [4], [9, 8]]
result = column_product(matrix)
print(result)


Output

[36, 40, 3]

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

Method #4 : Using reduce and itertools.zip_longest:

Algorithm:

1.Initialize an empty list to store the product of columns.
2.Get the maximum length of the sublists in the matrix.
3.Loop through each column index up to the maximum length.
4.For each column index, loop through each sublist of the matrix and multiply the corresponding element of the column and the sublist.
5.Append the product of each column to the result list.
6.Return the result list.

Python3




from functools import reduce
import itertools
test_list = [[1, 5, 3], [4], [9, 8]]
# printing original list
print ("The original list is : " + str(test_list))
  
res = [reduce(lambda x, y: x * y, filter(lambda x: x is not None, col), 1) for col in itertools.zip_longest(*test_list)]
 
# printing result
print ("The product of columns is : " + str(res))
#This code is contributed by Jyothi pinjala


Output

The original list is : [[1, 5, 3], [4], [9, 8]]
The product of columns is : [36, 40, 3]

Time complexity: O(n * m), where n is the number of sublists in the matrix and m is the maximum length of the sublists. This is because we need to loop through each column index up to the maximum length and for each column index, we need to loop through each sublist.

Space complexity: O(m), where m is the maximum length of the sublists. This is because we are only storing the product of each column in the result list, which has a length of m.

Method 5: Using numpy

Python3




import numpy as np
 
# initializing list of lists
test_list = [[1, 5, 3], [4], [9, 8]]
 
# padding the inner lists with zeros
max_len = max(len(lst) for lst in test_list)
padded_list = [lst + [0]*(max_len-len(lst)) for lst in test_list]
 
# printing original list
print("The original list is: " + str(test_list))
 
# Uneven Sized Matrix Column product using numpy
arr = np.array(padded_list)
res = np.product(arr, axis=0, where=arr != 0)
 
# printing result
print("The product of columns is: " + str(res))


Output:

The original list is : [[1, 5, 3], [4], [9, 8]]
The product of columns is : [36, 40, 3]

Time complexity: O(nm), where n is the number of rows and m is the maximum number of columns in any row.
Auxiliary space: O(nm), since the numpy array has to be created to compute the column products.

Method #6 : Using a single loop and a dictionary

Step-by-step approach:

  • Initialize an empty dictionary to keep track of the product of each column.
  • Iterate over each row in the matrix.
  • For each row, iterate over the elements in the row and add the element to the corresponding key in the dictionary.
  • If a key does not exist in the dictionary, initialize it to the value of the current element.
  • If a key exists in the dictionary, multiply the value of the key by the current element.
  • Initialize a result list with the length of the longest row in the matrix.
  • Iterate over the keys in the dictionary and set the corresponding value in the result list.
  • Return the result list.

Python3




def column_product(matrix):
    max_len = max(len(row) for row in matrix)
    result = [1] * max_len
    column_dict = {}
 
    for row in matrix:
        for i, element in enumerate(row):
            if i in column_dict:
                column_dict[i] *= element
            else:
                column_dict[i] = element
 
    for key in column_dict:
        result[key] = column_dict[key]
 
    return result
 
# Example usage
matrix = [[1, 5, 3], [4], [9, 8]]
result = column_product(matrix)
print(result)


Output

[36, 40, 3]

Time complexity: O(mn), where m is the number of rows and n is the length of the longest row.
Auxiliary space: O(mn), because we need to store the product of each column in a dictionary with at most n keys



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