Python – Sort Matrix by Palindrome count
Last Updated :
08 May, 2023
Given a String Matrix of N characters, sort each row by the count of the palindromic string in it.
Input : test_list = [[“nitin”, “meem”, “geeks”], [“peep”], [“gfg”, “is”, “best”], [“sees”, “level”, “mom”, “noon”]]
Output : [[‘peep’], [‘gfg’, ‘is’, ‘best’], [‘nitin’, ‘meem’, ‘geeks’], [‘sees’, ‘level’, ‘mom’, ‘noon’]]
Explanation : 1 = 1 < 2 < 4 is palindromic count order.
Input : test_list = [[“nitin”, “meem”, “geeks”], [“peep”], [“sees”, “level”, “mom”, “noon”]]
Output : [[‘peep’], [‘nitin’, ‘meem’, ‘geeks’], [‘sees’, ‘level’, ‘mom’, ‘noon’]]
Explanation : 1 < 2 < 4 is palindromic count order.
Method #1 : Using reversed() + len() + sort()
In this perform in place sort using sort(), the computation of length and check for Palindrome is done using reversed().
Python3
def get_palin_freq(row):
return len ([sub for sub in row if ''.join( list ( reversed (sub))) = = sub])
test_list = [[ "nitin" , "meem" , "geeks" ], [ "peep" ],
[ "gfg" , "is" , "best" ],
[ "sees" , "level" , "mom" , "noon" ]]
print ( "The original list is : " + str (test_list))
test_list.sort(key = get_palin_freq)
print ( "Sorted rows : " + str (test_list))
|
Output
The original list is : [['nitin', 'meem', 'geeks'], ['peep'], ['gfg', 'is', 'best'], ['sees', 'level', 'mom', 'noon']]
Sorted rows : [['peep'], ['gfg', 'is', 'best'], ['nitin', 'meem', 'geeks'], ['sees', 'level', 'mom', 'noon']]
Time Complexity: O(N), Here N is the total count of characters in the matrix
Auxiliary Space: O(N)
Method #2 : Using sorted() + len() + reversed()
Similar to the above method, the difference being sorted() is used along with lambda function to perform a task in one-liner without the external function call.
Python3
test_list = [[ "nitin" , "meem" , "geeks" ], [ "peep" ],
[ "gfg" , "is" , "best" ], [ "sees" , "level" , "mom" , "noon" ]]
print ( "The original list is : " + str (test_list))
res = sorted (test_list, key = lambda row: len (
[sub for sub in row if ''.join( list ( reversed (sub))) = = sub]))
print ( "Sorted rows : " + str (res))
|
Output
The original list is : [['nitin', 'meem', 'geeks'], ['peep'], ['gfg', 'is', 'best'], ['sees', 'level', 'mom', 'noon']]
Sorted rows : [['peep'], ['gfg', 'is', 'best'], ['nitin', 'meem', 'geeks'], ['sees', 'level', 'mom', 'noon']]
Time Complexity: O(N), Here N is the total count of characters in the matrix
Auxiliary Space: O(N)
Method #3 : Using sum() and custom sort()
Here’s a different approach using custom sorting, that can be used in situations where using reversed() and sort() or sorted() is not feasible:
Steps:
- Define a function count_palindromes(words) that takes a list of words and returns the count of palindromic words in the list.
- Initialize a variable count to 0.
Loop through each word in the list words.
If the word is equal to its reverse, increment the count by 1.
Return the count.
Define a function sort_matrix(matrix) that takes a matrix as input and sorts it in descending order based on the count of palindromic words in each row.
- Sort the matrix using a custom sort key function count_palindromes, which takes a row of the matrix as input and returns the count of palindromic words in the row.
Return the sorted matrix.
Define a test matrix test_list.
- Print the sorted matrix in descending order by calling the sort_matrix function on the test_list and reversing the result.
Python3
def count_palindromes(words):
return sum ( 1 for word in words if word = = word[:: - 1 ])
def sort_matrix(matrix):
matrix.sort(key = count_palindromes, reverse = True )
return matrix
test_list = [[ "nitin" , "meem" , "geeks" ], [ "peep" ],
[ "gfg" , "is" , "best" ], [ "sees" , "level" , "mom" , "noon" ]]
print (sort_matrix(test_list)[:: - 1 ])
|
Output
[['gfg', 'is', 'best'], ['peep'], ['nitin', 'meem', 'geeks'], ['sees', 'level', 'mom', 'noon']]
Time Complexity:
The count_palindromes function has a time complexity of O(m), where m is the number of words in the row.
The sort_matrix function sorts the rows of the matrix using the count_palindromes function as the sort key. The time complexity of sorting a list of n items is O(n log n) in the worst case. Since there are n rows and each row has m words, the time complexity of the sort_matrix function is O(n m log(n m)).
The total time complexity of the program is O(n m log(n m)).
Auxiliary Space Complexity:
The count_palindromes function has a constant auxiliary space complexity.
The sort_matrix function uses the built-in sort() method to sort the matrix in place. Therefore, it has a constant auxiliary space complexity.
The total auxiliary space complexity of the program is O(1).
Method #4: Using map() + filter() + sorted()
- Create a function to count the number of palindromic strings in a given list of strings. Let’s call this function count_palindrome.
- Initialize a variable count to 0.
- Iterate through each string in the list.
- If the string is equal to its reverse, increment the count.
- Return the count.
- Use the map() function to apply the count_palindrome function to each row in the matrix.
- Call the map() function with the count_palindrome function and the test_list as arguments.
- Convert the result to a list and store it in a variable called counts.
- Use the filter() function to remove any rows that don’t contain any palindromic strings.
- Call the filter() function with a lambda function that checks if the count of palindromic strings is greater than 0 and the counts list as arguments.
- Convert the result to a list and store it in a variable called filtered_list.
- Use the sorted() function to sort the filtered_list by the count of palindromic strings in each row.
- Call the sorted() function with a lambda function that returns the count of palindromic strings in a given row as the key argument and the filtered_list as the iterable argument.
- Store the result in a variable called sorted_list.
- Print the sorted_list.
Python3
test_list = [[ "nitin" , "meem" , "geeks" ], [ "peep" ],
[ "gfg" , "is" , "best" ], [ "sees" , "level" , "mom" , "noon" ]]
print ( "The original list is : " + str (test_list))
def count_palindrome(lst):
count = 0
for s in lst:
if s = = s[:: - 1 ]:
count + = 1
return count
counts = list ( map (count_palindrome, test_list))
filtered_list = list ( filter ( lambda x: x[ 1 ] > 0 , zip (test_list, counts)))
sorted_list = sorted (filtered_list, key = lambda x: x[ 1 ], reverse = True )
print ( "Sorted rows : " + str ([row[ 0 ] for row in sorted_list]))
|
Output
The original list is : [['nitin', 'meem', 'geeks'], ['peep'], ['gfg', 'is', 'best'], ['sees', 'level', 'mom', 'noon']]
Sorted rows : [['sees', 'level', 'mom', 'noon'], ['nitin', 'meem', 'geeks'], ['peep'], ['gfg', 'is', 'best']]
Time Complexity: O(nmlog(m)), where n is the number of rows and m is the maximum number of strings in a row.
Auxiliary Space: O(n), where n is the number of rows.
Method #5: Using list comprehension and lambda function
We can also solve the problem by using list comprehension and lambda function to count the number of palindromic strings in each row of the matrix. Then, we can sort the rows based on the count of palindromic strings using the sorted() function. Finally, we can extract the rows from the sorted list and print them.
Step-by-step approach:
- Initialize the input matrix.
- Define a lambda function to count the number of palindromic strings in a list.Use a list comprehension to create a list of tuples, where each tuple contains a row of the matrix and its corresponding count of
- palindromic strings.
- Use the sorted() function to sort the list of tuples based on the count of palindromic strings in descending order.
- Extract the rows from the sorted list of tuples and print them.
Python3
test_list = [[ "nitin" , "meem" , "geeks" ], [ "peep" ],
[ "gfg" , "is" , "best" ], [ "sees" , "level" , "mom" , "noon" ]]
print ( "The original list is : " + str (test_list))
count_palindrome = lambda lst: sum (s = = s[:: - 1 ] for s in lst)
counts = [(row, count_palindrome(row)) for row in test_list]
sorted_counts = sorted (counts, key = lambda x: x[ 1 ], reverse = True )
sorted_list = [row for row, count in sorted_counts if count > 0 ]
print ( "Sorted rows : " + str (sorted_list))
|
Output
The original list is : [['nitin', 'meem', 'geeks'], ['peep'], ['gfg', 'is', 'best'], ['sees', 'level', 'mom', 'noon']]
Sorted rows : [['sees', 'level', 'mom', 'noon'], ['nitin', 'meem', 'geeks'], ['peep'], ['gfg', 'is', 'best']]
Time complexity: O(nmlog(m)), where n is the number of rows in the matrix and m is the maximum length of a row.
Auxiliary space: O(n*m), to store the counts and sorted list of tuples.
Similar Reads
Python - Sort Matrix by None frequency
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
9 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 - Sort Matrix by Maximum String Length
Given a matrix, perform row sort basis on the maximum length of the string in it. Input : test_list = [['gfg', 'best'], ['geeksforgeeks'], ['cs', 'rocks'], ['gfg', 'cs']] Output : [['gfg', 'cs'], ['gfg', 'best'], ['cs', 'rocks'], ['geeksforgeeks']] Explanation : 3 < 4 < 5 < 13, maximum leng
3 min read
Python Program for Counting Sort
Counting Sort is a non-comparison-based sorting algorithm. It is particularly efficient when the range of input values is small compared to the number of elements to be sorted. The basic idea behind Counting Sort is to count the frequency of each distinct element in the input array and use that info
7 min read
Python Program for Counting Sort
Counting sort is a sorting technique based on keys between a specific range. It works by counting the number of objects having distinct key values (kind of hashing). Then doing some arithmetic to calculate the position of each object in the output sequence. C/C++ Code # Python program for counting s
2 min read
Test if List is Palindrome - Python
We are given a list we need to find that given list is a palindrome. For example a = [1, 2, 3, 2, 1] we need to check whether it is a palindrome or not so that the output should be 'True'. Using SlicingWe can check if a list is a palindrome by comparing it with its reverse using slicing ([::-1]). If
2 min read
Python - Reverse sort Matrix Row by Kth Column
Sometimes, while working with data, we can have a problem in which we need to perform sorting of each row of records by some of decisive factor like score. This kind of problem is common in competitive programming and web development. Lets discuss certain ways in which this task can be performed. Me
4 min read
Python program to a Sort Matrix by index-value equality count
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 m
6 min read
Python - Sort row by K multiples
Given a Matrix, perform row sorting by number of multiple of K present in row. Input : test_list = [[3, 4, 8, 1], [12, 32, 4, 16], [1, 2, 3, 4], [9, 7, 5]], K = 4 Output : [[9, 7, 5], [1, 2, 3, 4], [3, 4, 8, 1], [12, 32, 4, 16]] Explanation : 0 < 1 < 2 < 4, multiple of 4 occurrence order. I
3 min read
Python Program to Sort the given matrix
Given a n x n matrix. The problem is to sort the given matrix in strict order. Here strict order means that matrix is sorted in a way such that all elements in a row are sorted in increasing order and for row âiâ, where 1 <= i <= n-1, first element of row 'i' is greater than or equal to the la
4 min read