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 .
- Using sort() Method
- Using sorted() + lambda
- Using reduce()
- Using list comprehension
- Using map() Function
- Using functools.cmp_to_key()
- Using a Custom Function
- Using count(),extend(),sort() and index() Methods
- 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
test_list = [[ None , None , 4 ], [ None , None , 3 , None ],
[ 12 , 4 , 5 ], [ None , 3 , 4 ]]
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
test_list.sort(key = get_None_freq)
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
res = sorted (test_list, key = lambda row: len ([ele for ele in row if not ele]))
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
res = reduce ( lambda x, y: x + [y], sorted (test_list,
key = lambda row: len ([ele for ele in row if not ele])), [])
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
sorted_matrix = [row for row in sorted (test_list, key = lambda x: len ([ele for ele in x if not ele]))]
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
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]))))
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
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])))
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
def count_none(row):
return row.count( None )
res = sorted (test_list, key = count_none)
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)])
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)])
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)
Similar Reads
Python - Sort rows by Frequency of K
Given a Matrix, the task is to write a Python program to perform sorting on rows depending on the frequency of K. Input : test_list = [[10, 2, 3, 2, 3], [5, 5, 4, 7, 7, 4], [1, 2], [1, 1, 2, 2, 2]], K = 2 Output : [[5, 5, 4, 7, 7, 4], [1, 2], [10, 2, 3, 2, 3], [1, 1, 2, 2, 2]] Explanation : 0 < 1
4 min read
Python | Sort list elements by frequency
Our task is to sort the list based on the frequency of each element. In this sorting process, elements that appear more frequently will be placed before those with lower frequency. For example, if we have: a = ["Aryan", "Harsh", "Aryan", "Kunal", "Harsh", "Aryan"] then the output should be: ['Aryan'
3 min read
Python - Count the frequency of matrix row length
Given a Matrix, the task is to write a Python program to get the count frequency of its rows lengths. Input : test_list = [[6, 3, 1], [8, 9], [2], [10, 12, 7], [4, 11]] Output : {3: 2, 2: 2, 1: 1} Explanation : 2 lists of length 3 are present, 2 lists of size 2 and 1 of 1 length is present. Input :
5 min read
Python - List Strings frequency in Matrix
Sometimes, while working with Matrix, we can have a problem in which we need to check the frequency of argument Strings from List in each row of Matrix. This is a very peculiar problem and can have usefulness in many domains. Let us discuss certain ways in which this task can be solved. Method #1 :
5 min read
Python - Sort Matrix by Row Median
Given a Matrix, sort by median of each row. Input : test_list = [[3, 4, 7], [1, 7, 2], [10, 2, 4], [8, 6, 5]] Output : [[1, 7, 2], [3, 4, 7], [10, 2, 4], [8, 6, 5]] Explanation : 2 < 3 < 4 < 6, sorted increasingly by median element. Input : test_list = [[3, 4, 7], [1, 7, 2], [8, 6, 5]] Outp
4 min read
Python - Sort by Factor count
Given element list, sort by factor count of each element. Input : test_list = [12, 100, 22] Output : [22, 12, 100] Explanation : 3, 5, 8 factors respectively of elements. Input : test_list = [6, 11] Output : [11, 6] Explanation : 1, 4 factors respectively of elements. Method #1 : Using sort() + len(
4 min read
Python - Check for None value in Matrix
Python supports a list as its list element and hence a matrix can be formed. Sometimes we might have a utility in which we require to perform None check in that list of list i.e matrix and its a very common in all the domains of coding, especially Data Science. Letâs discuss certain ways in which th
5 min read
Python - Sort Strings by maximum frequency character
Given a string, the task is to write a Python program to perform sort by maximum occurring character. Input : test_list = ["geekforgeeks", "bettered", "for", "geeks"] Output : ['for', 'geeks', 'bettered', 'geekforgeeks'] Explanation : 1 < 2 < 3 < 4, is ordering of maximum character occurren
3 min read
Python - Sort Matrix by total characters
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
5 min read
Python - Flag None Element Rows in Matrix
Given a Matrix, return True for rows which contain a None Value, else return False. Input : test_list = [[2, 4, None, 3], [3, 4, 1, None], [2, 4, 7, 4], [2, 8, None]] Output : [True, True, False, True] Explanation : 1, 2 and 4th index contain None occurrence. Input : test_list = [[2, 4, None, 3], [3
4 min read