Open In App

Python program to a Sort Matrix by index-value equality count

Last Updated : 28 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a Matrix, the task is to write a Python program that can sort its rows or columns on a measure of the number of values equal to its index number. For each row or column, count occurrences of equality of index number with value. After computation of this count for each row or column, sort the matrix on basis of the count extracted for each row or column in step 1.

Input : test_list = [[3, 1, 2, 5, 4], [0, 1, 2, 3, 4], [6, 5, 4, 3, 2], [0, 5, 4, 2]] 
Output : [[6, 5, 4, 3, 2], [0, 5, 4, 2], [3, 1, 2, 5, 4], [0, 1, 2, 3, 4]] 
Explanation : 0 < 2 < 3 < 5 is ordering for count of index-element equality. 2 is equal to its index position in 2nd list.

Input : test_list = [[0, 1, 2, 3, 4], [6, 5, 4, 3, 2], [0, 5, 4, 2]] 
Output : [[6, 5, 4, 3, 2], [0, 5, 4, 2], [0, 1, 2, 3, 4]] 
Explanation : 0 < 2 < 5 is ordering for count of index-element equality. All elements in last list are equal to its index hence the returned count. 
 

Sorting rows

Method 1 : Using sort(), len() and enumerate()

In this, we check for index and element equality by comparing enumerate components, the summation of result is done by extracting length of list. This is passed as key to sort() which performs inplace sorting.

Example:

Python3




# Python3 code to demonstrate working of
# Sort Matrix by index-value equality count
# Using sort() + len() + enumerate()
 
 
def get_idx_ele_count(row):
 
    # getting required count
    # element and index compared, if equal added
    # in list, length computed using len()
    return len([ele for idx, ele in enumerate(row) if ele == idx])
 
 
# initializing list
test_list = [[3, 1, 2, 5, 4], [0, 1, 2, 3, 4],
             [6, 5, 4, 3, 2], [0, 5, 4, 2]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# inplace sorting using sort()
test_list.sort(key=get_idx_ele_count)
 
# printing result
print("Sorted List : " + str(test_list))


Output:

The original list is : [[3, 1, 2, 5, 4], [0, 1, 2, 3, 4], [6, 5, 4, 3, 2], [0, 5, 4, 2]]

Sorted List : [[6, 5, 4, 3, 2], [0, 5, 4, 2], [3, 1, 2, 5, 4], [0, 1, 2, 3, 4]]

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

Method 2 : Using sorted(), lambda, len() and enumerate()

In this, we perform task of sorting using sorted() and lambda function provides utility to sort combined with len() and enumerate().

Example:

Python3




# Python3 code to demonstrate working of
# Sort Matrix by index-value equality count
# Using sorted() + lambda + len() + enumerate()
 
# initializing list
test_list = [[3, 1, 2, 5], [0, 1, 2, 3],
             [6, 5, 4, 3], [0, 5, 4, 2]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# sorting using sorted()
# utility injection using lambda
# element and index compared, if equal added in list,
# length computed using len()
res = sorted(test_list, key=lambda row: len(
    [ele for idx, ele in enumerate(row) if ele == idx]))
 
# printing result
print("Sorted List : " + str(res))


Output:

The original list is : [[3, 1, 2, 5], [0, 1, 2, 3], [6, 5, 4, 3], [0, 5, 4, 2]]

Sorted List : [[6, 5, 4, 3], [0, 5, 4, 2], [3, 1, 2, 5], [0, 1, 2, 3]]

Sorting columns

Method 1 : Using sort(), len() and enumerate()

In this, we perform transpose of base matrix, and then perform usual task of getting index-value equality count using above method 1, after sorting, matrix is again converted to its transposed format. 

Example:
 

Python3




# Python3 code to demonstrate working of
# Sort Matrix by index-value equality count
# Using sort() + len() + enumerate()
 
 
def get_idx_ele_count(row):
 
    # getting required count
    # element and index compared, if equal added in
    # list, length computed using len()
    return len([ele for idx, ele in enumerate(row) if ele == idx])
 
 
# initializing list
test_list = [[3, 1, 2, 5], [0, 1, 2, 3],
             [6, 5, 4, 3], [0, 5, 4, 2]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# transposing matrix
test_list = list(zip(*test_list))
 
# inplace sorting using sort()
test_list.sort(key=get_idx_ele_count)
 
# performing transpose again to get result.
test_list = zip(*test_list)
 
# converting list of tuples to list of lists
res = [list(sub) for sub in test_list]
 
# printing result
print("Sorted List : " + str(res))


Output:

The original list is : [[3, 1, 2, 5], [0, 1, 2, 3], [6, 5, 4, 3], [0, 5, 4, 2]]

Sorted List : [[3, 2, 5, 1], [0, 2, 3, 1], [6, 4, 3, 5], [0, 4, 2, 5]]

Time Complexity: O(n*logn)

Space Complexity: O(n)

Method 2 : Using sorted(), lambda, len() and enumerate()

In this, we perform transpose of base matrix, and then perform usual task of getting index-value equality count using above method 2, after sorting, matrix is again converted to its transposed format. 

Example:

Python3




# Python3 code to demonstrate working of
# Sort Matrix by index-value equality count
# Using sorted() + lambda + len() + enumerate()
 
# initializing list
test_list = [[3, 1, 2, 5], [0, 1, 2, 3],
             [6, 5, 4, 3], [0, 5, 4, 2]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# transposing matrix
test_list = zip(*test_list)
 
# sorting using sorted()
# utility injection using lambda
# element and index compared, if equal added in
# list, length computed using len()
res = sorted(test_list, key=lambda row: len(
    [ele for idx, ele in enumerate(row) if ele == idx]))
 
# performing transpose again to get result.
res = zip(*res)
 
# converting list of tuples to list of lists
res = [list(sub) for sub in res]
 
# printing result
print("Sorted List : " + str(res))


Output:

The original list is : [[3, 1, 2, 5], [0, 1, 2, 3], [6, 5, 4, 3], [0, 5, 4, 2]]

Sorted List : [[3, 2, 5, 1], [0, 2, 3, 1], [6, 4, 3, 5], [0, 4, 2, 5]]



Previous Article
Next Article

Similar Reads

Python List Equality | Program to check if two given matrices are identical
We are given two square matrices of same order. Check if two given matrices are identical. Examples: Input : A = [ [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]] B = [ [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]] Output: Matrices are identical We have existing solution for this problem please refer C Program to check if two give
3 min read
Python Program to get value of a dictionary given by index of maximum value of given key
Given a dictionary with value as a list, the task is to write a Python program that can find the maximum of any one key and output a similar index column of other key's values. Approach : Get the maximum of the given key.Get the index of the maximum element found.Check if the index of max is present in the search key, if not, return Result not Poss
8 min read
Check the equality of integer division and math.floor() of Regular division in Python
For large quotients, floor division (//) doesn't seem to be necessarily equal to the floor of regular division (math.floor(a/b)) Examples: Input : 269792703866060742 // 3 Output : 89930901288686914 Input : math.floor(269792703866060742 / 3) Output : 89930901288686912 In the above examples, the output for floor division(//) is 89930901288686914 and
2 min read
Python - How to Sort a Dictionary by Kth Index Value
While working with Python, one might come to a problem in which one needs to perform a sort on a dictionary based on Kth index of value list. This can be typically in the case of scoring or web development. Let’s discuss a method by which this task can be performed. Input : test_dict = {'gfg' : [5, 6, 7], 'is' : [1, 4, 7], 'best' : [8, 3, 1]}, K =
6 min read
Python - Sort dictionaries list by Key's Value list index
Given list of dictionaries, sort dictionaries on basis of Key's index value. Input : [{"Gfg" : [6, 7, 8], "is" : 9, "best" : 10}, {"Gfg" : [2, 0, 3], "is" : 11, "best" : 19}, {"Gfg" : [4, 6, 9], "is" : 16, "best" : 1}], K = "Gfg", idx = 0 Output : [{'Gfg': [2, 0, 3], 'is': 11, 'best': 19}, {'Gfg': [4, 6, 9], 'is': 16, 'best': 1}, {'Gfg': [6, 7, 8],
14 min read
Python - Sort Dictionary List by Key's ith Index value
Given List of dictionaries, sort dictionaries on basis of Key's ith index value Input : [{"Gfg" : "Best", "for" : "Geeks"}, {"Gfg" : "Good", "for" : "Me"}, {"Gfg" : "Better", "for" : "All"}], K = "Gfg", i = 1 Output : [{'Gfg': 'Best', 'for': 'Geeks'}, {'Gfg': 'Better', 'for': 'All'}, {'Gfg': 'Good', 'for': 'Me'}] Explanation : Sort in order of e =
7 min read
Python Program to sort rows of a matrix by custom element count
Given Matrix, the following program shows how to sort rows of a matrix by the count of presence of numbers from a specified list. Input : test_list = [[4, 5, 1, 7], [6, 5], [9, 8, 2], [7, 1]], cus_list = [4, 5, 7] Output : [[9, 8, 2], [6, 5], [7, 1], [4, 5, 1, 7]] Explanation : 0 &lt; 1 = 1 &lt; 3 is order of custom elements count.Input : test_list
5 min read
Python - Replace value by Kth index value in Dictionary List
Given a dictionary list, the task is to write a Python program to replace the value of a particular key with kth index of value if the value of the key is list. Examples: Input : test_list = [{'gfg' : [5, 7, 9, 1], 'is' : 8, 'good' : 10}, {'gfg' : 1, 'for' : 10, 'geeks' : 9}, {'love' : 3, 'gfg' : [7, 3, 9, 1]}], K = 2, key = "gfg" Output : [{'gfg':
7 min read
Object Equality in Scala
In programming language, Comparing two values for equality is ubiquitous. We define an equals method for a Scala class so we can compare object instances to each other. In Scala, equality method signifying object identity, however, it's not used much. In scala, Three different equality methods available - The equals MethodThe == and != MethodsThe n
4 min read
Python Program for Odd-Even Sort / Brick Sort
This is basically a variation of bubble-sort. This algorithm is divided into two phases- Odd and Even Phase. The algorithm runs until the array elements are sorted and in each iteration two phases occurs- Odd and Even Phases. In the odd phase, we perform a bubble sort on odd indexed elements and in the even phase, we perform a bubble sort on even i
2 min read