Python - Sort Matrix by Maximum String Length

Python - Sort Matrix by Maximum String Length

Let's understand how to sort rows of a matrix based on the maximum string length contained in each row.

Objective:

Given a 2D matrix where each cell contains a string, we want to sort each row of the matrix based on the maximum string length present in that row.

Example:

Matrix:

[ ["apple", "banana"], ["kiwi", "strawberry", "grape"], ["blueberry", "cherry"] ] 

Maximum string length for each row:

  • For the first row: max(len("apple"), len("banana")) = 6
  • For the second row: max(len("kiwi"), len("strawberry"), len("grape")) = 10
  • For the third row: max(len("blueberry"), len("cherry")) = 9

If we sort the rows based on these maximum string lengths, we get:

[ ["kiwi", "strawberry", "grape"], ["blueberry", "cherry"], ["apple", "banana"] ] 

Tutorial:

  • Define a Helper Function to Compute Maximum String Length:

This function will take a list of strings and return the length of the longest string.

def max_string_length(strings_list): return max(len(s) for s in strings_list) 
  • Sort the Rows of the Matrix:

We'll use Python's built-in sorted() function, providing a custom sorting key based on the max_string_length() function we just defined.

def sort_matrix_by_string_length(matrix): return sorted(matrix, key=max_string_length, reverse=True) 
  • Test the Solution:

Now, let's test the solution with the provided example.

matrix = [ ["apple", "banana"], ["kiwi", "strawberry", "grape"], ["blueberry", "cherry"] ] sorted_matrix = sort_matrix_by_string_length(matrix) for row in sorted_matrix: print(row) 

This will output:

["kiwi", "strawberry", "grape"], ["blueberry", "cherry"], ["apple", "banana"] 

Notes:

  • The max_string_length() function utilizes a generator expression to iterate over each string's length and compute the maximum efficiently.
  • This approach is efficient for matrices where each row contains a varied number of strings or different lengths.

More Tags

jestjs bufferedimage sanitization spring-batch flask embedded-resource alamofire autofac arrow-functions cs50

More Programming Guides

Other Guides

More Programming Examples