Open In App

Python – Sort Matrix by None frequency

Improve
Improve
Like Article
Like
Save
Share
Report

In the world of Python programming, many developers aim to make matrix operations efficient and elegant in their code. A fascinating challenge that comes up is sorting a matrix based on how often the mysterious “None” element appears, adding an interesting twist to data manipulation in Python.

Given a Matrix, sort according to None elements frequency.

Example :

Input : test_list = [[None, None, 3, None], [12, 4, 5], [None, 3, 4]] 
Output : [[12, 4, 5], [None, 3, 4], [None, None, 3, None]] 
Explanation : 0, 1, 3 counts of None respectively.

Python Sort Returns None Syntax

Syntax : list_name.sort(key=None, reverse=False)

Parameter :

  • key: Optional custom sorting function (default is None).
  • reverse: Boolean indicating whether to sort in descending order (default is False).

Return type : None

Python Sort Returns None

“Sort Matrix by None frequency” refers to arranging a matrix in a specific order based on the frequency of occurrences of the “None” element within its elements.Sorting a matrix by None frequency involves arranging the elements of a matrix based on how often the value “None” appears within it. The goal is to organize the matrix in a way that highlights the distribution or prevalence of the “None” element, providing insights into the structure of the data.

Python Sort Returns None Example

There are various method to Sort Matrix by None frequency in Python , here we are explaining some generally used method for Sort Matrix by None frequency in python those are following .

  1. Using sort() Method
  2. Using sorted() + lambda
  3. Using reduce()
  4. Using list comprehension
  5. Using map() Function
  6. Using functools.cmp_to_key()
  7. Using a Custom Function
  8. Using count(),extend(),sort() and index() Methods
  9. Using operator.countOf(),extend(),sort() and index() Methods

Create Matrix

In this example code sorts the given matrix (test_list) based on the frequency of None elements in each row, in ascending order. It uses the sorted() function with a custom lambda function for sorting.

Python3




# Python3 code to demonstrate working of
# Sort Matrix by None frequency
# Using sorted() + lambda
 
# initializing list
test_list = [[None, None, 4], [None, None, 3, None],
             [12, 4, 5], [None, 3, 4]]
 
# printing original list
print("The original list is : " + str(test_list))


Output :

The original list is : [[None, None, 4], [None, None, 3, None], [12, 4, 5], [None, 3, 4]]

Time Complexity: O(m * n * log(n))
Space Complexity: O(m * n)

Sort Matrix by None frequency using sort()

In this , we perform sort using “sort()” method is used to sort a matrix based on the frequency of the “None” element in each row. The sorting is done in ascending order, with rows having fewer “None” elements appearing first.

Example : In this example the list `test_list` based on the frequency of `None` elements using the `sort()` method with a custom sorting key function `get_None_freq`.

Python3




# sorting using sort()
test_list.sort(key = get_None_freq)
 
# printing result
print("List after sorting : " + str(test_list))


Output:

List after sorting : [[12, 4, 5], [None, 3, 4], [None, None, 4], [None, None, 3, None]]

Time Complexity: O(nlogn)
Auxiliary Space: O(1)

Sort Matrix by None frequency using sorted() + lambda

In this, instead of external function, lambda function is used to solve this problem. The sorted()  is used to perform task of sorting. the `sorted()` function with a lambda function as the key to sort a matrix based on the frequency of the value None in each row.

Example : In this example code sorts a list of lists (test_list) based on the count of elements that are not None in each sub-list, using the sorted() function with a lambda function as the key.

Python3




# sorting using sorted()
# lambda function for None frequency logic
res = sorted(test_list, key=lambda row: len([ele for ele in row if not ele]))
 
# printing result
print("List after sorting : " + str(res))


Output:

 List after sorting : [[12, 4, 5], [None, 3, 4], [None, None, 4], [None, None, 3, None]]

Time Complexity: O(m * n * log(m)),
Auxiliary Space: O(m * n)

Sort Matrix by None frequency using reduce()

This method uses the `reduce()` function to sort a matrix based on the frequency of the value None in each row, effectively organizing rows with fewer None values first.

Example : In this example code sorts a 2D list (test_list) based on the count of None values in each sub-list using the reduce function and the sorted function. The output is the sorted list.

Python3




# sorting using reduce() and sorted()
# lambda function for None frequency logic
res = reduce(lambda x, y: x + [y], sorted(test_list,
                                          key=lambda row: len([ele for ele in row if not ele])), [])
# printing result
print("List after sorting : " + str(res))


Output :

List after sorting : [[12, 4, 5], [None, 3, 4], [None, None, 4], [None, None, 3, None]]

Time complexity: O(n * log(n))
Space complexity: O(n)

Sort Matrix by None Frequency using List Comprehension

This method uses list comprehension to sort a matrix based on the frequency of the value ‘None’ in each row. It arranges rows with fewer ‘None’ values first and those with more ‘None’ values later, effectively sorting the matrix.

Example : In this example the code sorts a 2D matrix (test_list) based on the count of elements in each row that are equal to None.

Python3




# Using list comprehension with sorted()
sorted_matrix = [row for row in sorted(test_list, key=lambda x: len([ele for ele in x if not ele]))]
 
# printing result
print("Matrix sorted by None frequency : " + str(sorted_matrix))


Output :

Matrix sorted by None frequency : [[12, 4, 5], [None, 3, 4], [None, None, 4], [None, None, 3, None]]

Time Complexity : O(m * n * log(m))
Space Complexity : O(m * n * log(m))

Sort Matrix in Python uing map() Function

This method in question involves using the `map()` function to apply the `sorted()` function to each element of a list, but it returns `None` because `sorted()` performs an in-place sort and modifies the original list directly instead of creating a new sorted list.

Example : In this example code sorts a matrix (test_list) based on the frequency of None values in each row. It uses the map() function to extract the rows after sorting them using the sorted() function with a custom key that counts the number of non-None elements in each row.

Python3




# Using map() with sorted()
sorted_matrix = list(map(lambda x: x[1], sorted(enumerate(test_list), key=lambda x: len([ele for ele in x[1] if not ele]))))
 
# printing result
print("Matrix sorted by None frequency : " + str(sorted_matrix))


Output :

Matrix sorted by None frequency : [[12, 4, 5], [None, 3, 4], [None, None, 4], [None, None, 3, None]]

Time Complexity: O(m * n * log(m))
Space Complexity: O(m * n)

Python Sort Matrix Returns None using functools.cmp_to_key()

The `functools.cmp_to_key()` method in Python is used to convert an old-style comparison function (using the `cmp` argument) into a key function. When applied to the `sorted()` function, it allows sorting without modifying the original comparison function.

Example : In this example code sorts a matrix (test_list) based on the count of non-None elements in each row, using the cmp_to_key function to convert the custom comparison function to a key function for sorted(). The output is the matrix sorted by the frequency of non-None elements.

Python3




from functools import cmp_to_key
 
# Using functools.cmp_to_key() with sorted()
sorted_matrix = sorted(test_list, key=cmp_to_key(lambda x, y: len([ele for ele in x if not ele]) - len([ele for ele in y if not ele])))
 
# printing result
print("Matrix sorted by None frequency : " + str(sorted_matrix))


Output :

Matrix sorted by None frequency : [[12, 4, 5], [None, 3, 4], [None, None, 4], [None, None, 3, None]]

Time Complexity: O(m * n * log(n))
Space Complexity: O(m * n)

Sort a counter by frequency in Python using a Custom Function

This method utilizes a custom function to handle None values and incorporates the sort() function for arranging elements, providing a specialized approach to sorting that accommodates instances of None in the data.

Example : In this example code defines a custom function count_none that takes a list (row) and returns the count of None elements in it. It then sorts a given list (test_list) based on the count of None elements in each row using the sorted() function with the custom function as the key. Finally, it prints the sorted list

Python3




# custom function to count None frequency in a row
def count_none(row):
    return row.count(None)
 
# sorting using custom function and sort()
res = sorted(test_list, key=count_none)
 
# printing result
print("List after sorting : " + str(res))


Output:

List after sorting : [[12, 4, 5], [None, 3, 4], [None, None, 4], [None, None, 3, None]]

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

Python Sort Returns None using count(),extend(),sort() and index() Methods

In this method the Python utilizes the `count()`, `extend()`, `sort()`, and `index()` methods to modify a list in place, counting occurrences, extending with additional elements, sorting the list, and finding the index of a specific element. The method does not return a value (`None`).

Example : In this example The code sorts a list test_list based on the count of None values in each element. It creates a new list res with the sorted elements.

Python3




x = []
res = []
for i in test_list:
    x.append(i.count(None))
y = []
y.extend(x)
y.sort()
for i in y:
    res.append(test_list[x.index(i)])
 
# printing result
print("List after sorting : " + str(res))


Output :

List after sorting: [[12, 4, 5], [None, 3, 4], [None, None, 4], [None, None, 3, None]]

Time Complexity: O(N * M * log(N))
Auxiliary Space: O(n)

using operator.countOf(),extend(),sort() and index() Methods

This method uses `operator.countOf()` to count occurrences, `extend()` to add elements, `sort()` to arrange them, and `index()` to find the position in a sequence or list.

Example : In this example code sorts the elements in the test_list based on the frequency of their occurrences, using a separate list x to store the count of occurrences for each element.

Python3




x=[]
res=[]
for i in test_list:
    x.append(op.countOf(i,None))
y=[]
y.extend(x)
y.sort()
for i in y:
    res.append(test_list[x.index(i)])
 
# printing result
print("List after sorting : " + str(res))


Output :

List after sorting : [[None, 3, 4], [12, 4, 5], [None, None, 3, None], [None, None, 4]]

Time Complexity: O(m * n * log(n))
Space Complexity: O(m * n)



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