Python – Uneven Sized Matrix Column Minimum
Last Updated :
01 May, 2023
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
test_list = [[ 1 , 5 , 3 ], [ 4 ], [ 9 , 8 ]]
print ( "The original list is : " + str (test_list))
res = [ min ( filter ( None , j)) for j in map ( None , * test_list)]
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
import itertools
test_list = [[ 1 , 5 , 3 ], [ 4 ], [ 9 , 8 ]]
print ( "The original list is : " + str (test_list))
res = [ min (i) for i in itertools.zip_longest( * test_list, fillvalue = 1000000 )]
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:
- 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.
- Loop through each row in the matrix.
- For each row, loop through each column using enumerate() function to access both the index and value of the current column.
- 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.
- After all, rows have been processed, return the min_col list, which will contain the minimum value for each column in the matrix.
Algorithm
- Initialize a list min_col with the first row’s length and assign each element to float(‘inf’).
- Traverse through each row of the matrix and get the column value at each index of that row.
- 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.
- Return the min_col list as the output.
Python3
def min_column(matrix):
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
matrix = [[ 1 , 5 , 3 ], [ 4 ], [ 9 , 8 ]]
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:
- Define a function column_minimum that takes a matrix as input.
- Initialize an empty list to store the minimum values for each column.
- Iterate over a range of column indices, from 0 up to the maximum length of any row in the matrix.
- 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.
- Append the minimum value to the list of minimum values.
- 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:
- Import heapq and itertools modules.
- Initialize a list of lists, test_list, with some data.
- Print the original matrix.
- Define res using list comprehension and itertools.zip_longest().
- Use heapq.nsmallest to find the minimum value of each column. If a column contains None values (i.e. it is
- shorter than the other columns), use filter to remove these values before finding the minimum.
- Print the resulting list of minimum values.
Python3
import heapq
import itertools
test_list = [[ 1 , 5 , 3 ], [ 4 ], [ 9 , 8 ]]
print ( "The original matrix is :" , test_list)
res = [heapq.nsmallest( 1 , filter ( lambda x: x is not None , i))[ 0 ]
for i in itertools.zip_longest( * test_list, fillvalue = 1000000 )]
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: 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
test_list = [[ 1 , 5 , 3 ], [ 4 ], [ 9 , 8 ]]
print ( "The original matrix is :" , test_list)
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 )
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.
Similar Reads
Python - Rear column in Multi-sized Matrix
Given a Matrix with variable lengths rows, extract last column. Input : test_list = [[3, 4, 5], [7], [8, 4, 6], [10, 3]] Output : [5, 7, 6, 3] Explanation : Last elements of rows filtered. Input : test_list = [[3, 4, 5], [7], [8, 4, 6]] Output : [5, 7, 6] Explanation : Last elements of rows filtered
4 min read
Python - Column Minimum in Tuple list
Sometimes, while working with records, we can have a problem in which we need to find min of all the columns of a container of lists which are tuples. This kind of application is common in web development domain. Letâs discuss certain ways in which this task can be performed. Method #1 : Using min()
6 min read
Python - Row with Minimum Sum in Matrix
We can have an application for finding the lists with the minimum value and print it. This seems quite an easy task and may also be easy to code, but having shorthands to perform the same are always helpful as this kind of problem can come in web development. Method #1 : Using reduce() + lambda The
4 min read
Python | Minimum Difference in Matrix Columns
This particular article focuses on a problem that has utility in competitive as well as day-day programming. Sometimes, we need to get the minimum difference between the like indices when compared with the next list. The minimum difference between the like elements in that index is returned. Letâs d
3 min read
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 | Row with Minimum element in Matrix
We can have an application for finding the lists with the minimum value and print it. This seems quite an easy task and may also be easy to code, but sometimes we need to print the entire row containing it and having shorthands to perform the same are always helpful as this kind of problem can come
5 min read
Python - Column Maximum in Dictionary Value Matrix
Given a Dictionary with Matrix Values, compute maximum of each column of those Matrix. Input : test_dict = {"Gfg" : [[7, 6], [3, 2]], "is" : [[3, 6], [6, 10]], "best" : [[5, 8], [2, 3]]} Output : {'Gfg': [7, 6], 'is': [6, 10], 'best': [5, 8]} Explanation : 7 > 3, 6 > 2, hence ordering. Input :
5 min read
Python | Consecutive Subsets Minimum
Some of the classical problems in programming domain comes from different categories and one among them is finding the minimum of subsets. This particular problem is also common when we need to accumulate the minimum and store consecutive group minimum. Letâs try different approaches to this problem
4 min read
Python - Sort Matrix by K Sized Subarray Maximum Sum
Given Matrix, write a Python program to sort rows by maximum of K sized subarray sum. Examples: Input : test_list = [[4, 3, 5, 2, 3], [6, 4, 2, 1, 1], [4, 3, 9, 3, 9], [5, 4, 3, 2, 1]], K = 3 Output : [[4, 3, 5, 2, 3], [6, 4, 2, 1, 1], [5, 4, 3, 2, 1], [4, 3, 9, 3, 9]] Explanation : 12 = 12 = 12
4 min read
Python - Sort Matrix by Maximum String Length
Given a matrix, perform row sort basis on the maximum length of the string in it. Input : test_list = [['gfg', 'best'], ['geeksforgeeks'], ['cs', 'rocks'], ['gfg', 'cs']] Output : [['gfg', 'cs'], ['gfg', 'best'], ['cs', 'rocks'], ['geeksforgeeks']] Explanation : 3 < 4 < 5 < 13, maximum leng
3 min read