Open In App

Python – Sort Matrix by total characters

Improve
Improve
Like Article
Like
Save
Share
Report

Given a String Matrix, sort by total data, i.e total characters in each row.

Input : test_list = [[“Gfg”, “is”, “Best”], [“Geeksforgeeks”, “Best”], [“ILvGFG”]] 
Output : [[‘ILvGFG’], [‘Gfg’, ‘is’, ‘Best’], [‘Geeksforgeeks’, ‘Best’]] 
Explanation : 6 < 11 < 17 total characters respectively after sorting.

Input : test_list = [[“Geeksforgeeks”, “Best”], [“ILvGFG”]] 
Output : [[‘ILvGFG’], [‘Geeksforgeeks’, ‘Best’]] 
Explanation : 6 < 17 total characters respectively after sorting. 

Method #1 : Using sort() + len() + sum()

In this, we perform task of sorting using sort(), and task of getting total characters is done using len() and sum().

Python3




# Python3 code to demonstrate working of
# Sort Matrix by total characters
# Using sort() + len() + sum()
 
 
def total_chars(row):
 
    # getting total characters
    return sum([len(sub) for sub in row])
 
 
# initializing list
test_list = [["Gfg", "is", "Best"], ["Geeksforgeeks", "Best"],
             ["GFg", "4", "good"], ["ILvGFG"]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# calling utility fnc
test_list.sort(key=total_chars)
 
# printing result
print("Sorted results : " + str(test_list))


Output:

The original list is : [[‘Gfg’, ‘is’, ‘Best’], [‘Geeksforgeeks’, ‘Best’], [‘GFg’, ‘4’, ‘good’], [‘ILvGFG’]] Sorted results : [[‘ILvGFG’], [‘GFg’, ‘4’, ‘good’], [‘Gfg’, ‘is’, ‘Best’], [‘Geeksforgeeks’, ‘Best’]]

Time Complexity: O(n)
Space Complexity: O(n)

Method #2 : Using sorted() + lambda

In this, sorted() is used to get the sorted result and the lambda function is used inplace of external function to get the logic of sorting strings.

Python3




# Python3 code to demonstrate working of
# Sort Matrix by total characters
# Using sorted() + lambda
 
# initializing list
test_list = [["Gfg", "is", "Best"], ["Geeksforgeeks", "Best"],
             ["GFg", "4", "good"], ["ILvGFG"]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# sorted() gives sorted result
# lambda function providing logic
res = sorted(test_list, key = lambda row : sum([len(sub) for sub in row]))
 
# printing result
print("Sorted results : " + str(res))


Output:

The original list is : [[‘Gfg’, ‘is’, ‘Best’], [‘Geeksforgeeks’, ‘Best’], [‘GFg’, ‘4’, ‘good’], [‘ILvGFG’]] 

Sorted results : [[‘ILvGFG’], [‘GFg’, ‘4’, ‘good’], [‘Gfg’, ‘is’, ‘Best’], [‘Geeksforgeeks’, ‘Best’]]

Time Complexity: O(n)
Space Complexity: O(n)

Approach 3: Using List Comprehension, zip
In this approach, we first find the length of each sublist and store it in a list. Then we use this list to sort the main matrix.

Python3




def total_chars(test_list):
    # Finding the length of each sublist
    length = [sum([len(sub) for sub in row]) for row in test_list]
     
    # Creating a zip of sublist and length list
    zipped = zip(test_list, length)
     
    # Sorting the matrix based on length
    sorted_matrix = [_ for _, x in sorted(zipped, key=lambda x: x[1])]
     
    return sorted_matrix
 
# Initializing the list
test_list = [["Gfg", "is", "Best"], ["Geeksforgeeks", "Best"],
             ["GFg", "4", "good"], ["ILvGFG"]]
 
# Printing the original list
print("The original list is : " + str(test_list))
 
# Sorting the matrix based on length of each sublist
result = total_chars(test_list)
 
# Printing the sorted result
print("Sorted results : " + str(result))


Output

The original list is : [['Gfg', 'is', 'Best'], ['Geeksforgeeks', 'Best'], ['GFg', '4', 'good'], ['ILvGFG']]
Sorted results : [['ILvGFG'], ['GFg', '4', 'good'], ['Gfg', 'is', 'Best'], ['Geeksforgeeks', 'Best']]

Time Complexity: O(n)
Auxiliary Space: O(n)

Method 4 :  use the built-in function map() 

Step-by-step approach:

  1. Define a function named total_chars that takes a single argument test_list, which is a list of sublists.
  2. Use the built-in function map() with a lambda function to transform each sublist into a tuple containing the length of the sublist (calculated using map() and len()) and the original sublist. The resulting list of tuples is assigned to the variable length_and_sublist.
  3. Use the built-in function sorted() to sort the list of tuples length_and_sublist based on the first element of each tuple (i.e., the length of the sublist). The key argument is a lambda function that extracts the first element of each tuple. The resulting sorted list of tuples is assigned to the variable sorted_length_and_sublist.
  4. Use a list comprehension to extract only the second element of each tuple in the sorted list of tuples sorted_length_and_sublist, which contains the original sublists. The resulting list of sublists is assigned to the variable sorted_matrix.
  5. Return the sorted list of sublists sorted_matrix.
  6. Define a variable test_list that contains a list of sublists.
  7. Print the original list of sublists test_list.
  8. Call the function total_chars with the argument test_list and assign the result to the variable sorted_list.
  9. Print the sorted list of sublists sorted_list.

Below is the implementation of the above approach:

Python3




def total_chars(test_list):
    # Transform each sublist into a tuple containing the length and the sublist
    length_and_sublist = list(map(lambda x: (sum(map(len, x)), x), test_list))
     
    # Sort the list of tuples based on the first element (the length)
    sorted_length_and_sublist = sorted(length_and_sublist, key=lambda x: x[0])
     
    # Return only the original sublists
    sorted_matrix = [x[1] for x in sorted_length_and_sublist]
     
    return sorted_matrix
 
 
# Example usage
test_list = [["Gfg", "is", "Best"], ["Geeksforgeeks", "Best"],
             ["GFg", "4", "good"], ["ILvGFG"]]
 
print("Original list:")
print(test_list)
 
sorted_list = total_chars(test_list)
 
print("Sorted list:")
print(sorted_list)


Output

Original list:
[['Gfg', 'is', 'Best'], ['Geeksforgeeks', 'Best'], ['GFg', '4', 'good'], ['ILvGFG']]
Sorted list:
[['ILvGFG'], ['GFg', '4', 'good'], ['Gfg', 'is', 'Best'], ['Geeksforgeeks', 'Best']]

Time complexity: O(nmlog(nm)) where n is the number of sublists and m is the maximum length of a sublist.
Auxiliary space: O(nm) (to store the list of tuples).



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