Python – Sort Matrix by Maximum String Length
Last Updated :
10 Apr, 2023
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 lengths of strings, sorted increasingly.
Input : test_list = [['gfg', 'best'], ['cs', 'rocks'], ['gfg', 'cs']]
Output : [['gfg', 'cs'], ['gfg', 'best'], ['cs', 'rocks']]
Explanation : 3 < 4 < 5 maximum lengths of strings, sorted increasingly.
Method #1 : Using sort() + len() + max()
In this, in place sorting is performed using sort(), len() and max() to compute the maximum length of the string in each row to perform the sort.
Python3
def max_len(row):
return max ([ len (ele) for ele in row])
test_list = [[ 'gfg' , 'best' ], [ 'geeksforgeeks' ],
[ 'cs' , 'rocks' ], [ 'gfg' , 'cs' ]]
print ( "The original list is : " + str (test_list))
test_list.sort(key = max_len)
print ( "Sorted Matrix : " + str (test_list))
|
Output:
The original list is : [[‘gfg’, ‘best’], [‘geeksforgeeks’], [‘cs’, ‘rocks’], [‘gfg’, ‘cs’]] Sorted Matrix : [[‘gfg’, ‘cs’], [‘gfg’, ‘best’], [‘cs’, ‘rocks’], [‘geeksforgeeks’]]
Time Complexity: O(n)
Auxiliary Space: O(n)
In this, we perform the task of filtering maximum using lambda function rather than the external function. The task of sorting is performed using sorted().
Python3
test_list = [[ 'gfg' , 'best' ], [ 'geeksforgeeks' ],
[ 'cs' , 'rocks' ], [ 'gfg' , 'cs' ]]
print ( "The original list is : " + str (test_list))
res = sorted (test_list, key = lambda row: max ([ len (ele) for ele in row]))
print ( "Sorted Matrix : " + str (res))
|
Output:
The original list is : [[‘gfg’, ‘best’], [‘geeksforgeeks’], [‘cs’, ‘rocks’], [‘gfg’, ‘cs’]] Sorted Matrix : [[‘gfg’, ‘cs’], [‘gfg’, ‘best’], [‘cs’, ‘rocks’], [‘geeksforgeeks’]]
Time Complexity: O(n)
Auxiliary Space: O(n)
Using a function with sort():
Approach:
In this approach, we define a function that takes a sublist and returns the maximum length of the strings in that sublist. We use this function as the key parameter in the sort() function to sort the list of sublists by the maximum length of their strings.
Python3
def max_string_length(sublist):
return max ( len (s) for s in sublist)
test_list = [[ 'gfg' , 'best' ], [ 'cs' , 'rocks' ], [ 'gfg' , 'cs' ]]
test_list.sort(key = max_string_length)
print (test_list)
|
Output
[['gfg', 'cs'], ['gfg', 'best'], ['cs', 'rocks']]
Time Complexity: O(n log n) – where n is the length of the list of sublists
Space Complexity: O(1) – since we modify the original list in place
Share your thoughts in the comments
Please Login to comment...