Open In App

Python – Uneven Sized Matrix Column Minimum

Last Updated : 01 May, 2023
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 minimum 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 min() + filter() + map() + list comprehension 

The combination of above three function combined with list comprehension can help us perform this particular task, the min function helps to perform the minimum, 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 Minimum
# using min() + filter() + map() + list comprehension
 
# initializing list of lists
test_list = [[1, 5, 3], [4], [9, 8]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# using min() + filter() + map() + list comprehension
# Uneven Sized Matrix Column Minimum
res = [min(filter(None, j)) for j in map(None, *test_list)]
 
# printing result
print("The minimum of columns is : " + str(res))


Output : 

The original list is : [[1, 5, 3], [4], [9, 8]]
The minimum of columns is : [1, 5, 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 #2: Using list comprehension + min() + 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 0 so that it does not have to handle the void of elements not present.

Python3




# Python3 code to demonstrate
# Uneven Sized Matrix Column Minimum
# using list comprehension + min() + zip_longest()
import itertools
 
# 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 + min() + zip_longest()
# Uneven Sized Matrix Column Minimum
res = [min(i) for i in itertools.zip_longest(*test_list, fillvalue=1000000)]
 
# printing result
print("The minimum of columns is : " + str(res))


Output : 

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

Time complexity: O(n*m), where n is the number of sublists in the main list and m is the length of the longest sublist. 
Auxiliary space: O(m), where m is the length of the longest sublist. 

Method#3: Using enumerate

Approach:

  1. Define a function min_column which takes a matrix as input. Initialize a list min_col with an infinite value for each column, this will serve as a temporary holder for the minimum values of each column. 
  2. Loop through each row in the matrix. 
  3. For each row, loop through each column using enumerate() function to access both the index and value of the current column. 
  4. If the current column value is less than the value in min_col for that column index, update the value in min_col with the current column value. 
  5. After all, rows have been processed, return the min_col list, which will contain the minimum value for each column in the matrix.

Algorithm

  1. Initialize a list min_col with the first row’s length and assign each element to float(‘inf’).
  2. Traverse through each row of the matrix and get the column value at each index of that row.
  3. Compare the column value with the corresponding element in the min_col list and update the element in min_col if it is greater than the column value.
  4. Return the min_col list as the output.

Python3




def min_column(matrix):
 
    # initialize with first row length
    min_col = [float('inf')] * len(matrix[0])
 
    for row in matrix:
        for i, col_val in enumerate(row):
            if col_val < min_col[i]:
                min_col[i] = col_val
 
    return min_col
 
# Testing the function
 
 
# Input list
matrix = [[1, 5, 3], [4], [9, 8]]
 
# Print the answer
print("The original matrix is :", matrix)
print("The minimum of columns is :", min_column(matrix))


Output

The original matrix is : [[1, 5, 3], [4], [9, 8]]
The minimum of columns is : [1, 5, 3]

Time Complexity: O(N * M), 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. This is because we are only storing the min_col list, which has m elements.

Method#4: Using def 

Approach:

This implementation first finds the maximum number of columns in the matrix, and then for each column index i, it creates a list of values at index i from each row that has at least i+1 columns. It then takes the minimum value from this list and appends it to the result list.

Algorithm:

  1. Define a function column_minimum that takes a matrix as input.
  2. Initialize an empty list to store the minimum values for each column.
  3. Iterate over a range of column indices, from 0 up to the maximum length of any row in the matrix.
  4. Use a list comprehension to find the minimum value for the current column by iterating over the rows and selecting the values at the current column index.
  5. Append the minimum value to the list of minimum values.
  6. Return the list of minimum values.

Python3




def column_minimum(matrix):
    return [min([row[i] for row in matrix if len(row) > i]) for i in range(len(max(matrix, key=len)))]
 
test_list = [[1, 5, 3], [4], [9, 8]]
print("The minimum of columns is :", column_minimum(test_list))


Output

The minimum of columns is : [1, 5, 3]

The time complexity of this implementation is O(n^2) where n is the number of rows in the matrix, since we are iterating over each row and each column. The auxiliary space is O(n) since we are storing a list of length n for the result.

Method#5: Using heapq:

Algorithm:

  1. Import heapq and itertools modules.
  2. Initialize a list of lists, test_list, with some data.
  3. Print the original matrix.
  4. Define res using list comprehension and itertools.zip_longest().
  5. Use heapq.nsmallest to find the minimum value of each column. If a column contains None values (i.e. it is
  6. shorter than the other columns), use filter to remove these values before finding the minimum.
  7. Print the resulting list of minimum values.

Python3




import heapq
import itertools
 
# initializing list of lists
test_list = [[1, 5, 3], [4], [9, 8]]
print("The original matrix is :", test_list)
 
# using heapq + zip_longest()
# Uneven Sized Matrix Column Minimum
res = [heapq.nsmallest(1, filter(lambda x: x is not None, i))[0]
       for i in itertools.zip_longest(*test_list, fillvalue=1000000)]
 
# printing result
print("The minimum of columns is : " + str(res))
 
# This code is contributed by Jyothi pinjala.


Output

The original matrix is : [[1, 5, 3], [4], [9, 8]]
The minimum of columns is : [1, 5, 3]

Time complexity: O(mn log k) where m is the number of rows, n is the number of columns, and k is the length of the longest row. heapq.nsmallest() method has time complexity O(klogk), and the list comprehension iterates over all columns and rows, taking O(mn) time. The zip_longest method runs in O(mn) time in the worst case.

Space complexity: O(mn) for storing the test_list, plus O(k) for the res list created by list comprehension, and O(k) additional space for the fillvalue. Overall, space complexity is O(mn).

Method #6: Using numpy 

Python3




import numpy as np
 
# initializing list of lists
test_list = [[1, 5, 3], [4], [9, 8]]
print("The original matrix is :", test_list)
 
# using numpy
max_len = max(len(sublist) for sublist in test_list)
arr = np.array([sublist + [1000000] * (max_len - len(sublist)) for sublist in test_list])
res = np.min(arr, axis=0)
 
# printing result
print("The minimum of columns is: " + str(res))


Output:
The original matrix is : [[1, 5, 3], [4], [9, 8]]
The minimum of columns is : [1, 5, 3]

Time complexity of O(n), where n is the total number of elements in the matrix.
Auxiliary space complexity of O(n) as well.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads