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
# Python3 code to demonstrate working of
# Sort Matrix by Palindrome count
# Using reversed() + len() + sort()
# get palin
def get_palin_freq(row):
# returning length
return len([sub for sub in row if ''.join(list(reversed(sub))) == sub])
# initializing list
test_list = [["nitin", "meem", "geeks"], ["peep"],
["gfg", "is", "best"],
["sees", "level", "mom", "noon"]]
# printing original list
print("The original list is : " + str(test_list))
# performing sort
test_list.sort(key=get_palin_freq)
# printing result
print("Sorted rows : " + str(test_list))
OutputThe 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
# Python3 code to demonstrate working of
# Sort Matrix by Palindrome count
# Using sorted() + len() + reversed()
# initializing list
test_list = [["nitin", "meem", "geeks"], ["peep"],
["gfg", "is", "best"], ["sees", "level", "mom", "noon"]]
# printing original list
print("The original list is : " + str(test_list))
# performing sort
# sorted() and lambda used to get 1 sentence approach
res = sorted(test_list, key=lambda row: len(
[sub for sub in row if ''.join(list(reversed(sub))) == sub]))
# printing result
print("Sorted rows : " + str(res))
OutputThe 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
# Python3 code to demonstrate working of
# Sort Matrix by Palindrome count
# Using map() + filter() + sorted()
# initializing list
test_list = [["nitin", "meem", "geeks"], ["peep"],
["gfg", "is", "best"], ["sees", "level", "mom", "noon"]]
# printing original list
print("The original list is : " + str(test_list))
# function to count palindromic strings in a list
def count_palindrome(lst):
count = 0
for s in lst:
if s == s[::-1]:
count += 1
return count
# use map() to get list of counts for each row
counts = list(map(count_palindrome, test_list))
# use filter() to remove rows with no palindromic strings
filtered_list = list(filter(lambda x: x[1] > 0, zip(test_list, counts)))
# use sorted() to sort the filtered_list by count of palindromic strings
sorted_list = sorted(filtered_list, key=lambda x: x[1], reverse=True)
# print the sorted list
print("Sorted rows : " + str([row[0] for row in sorted_list]))
OutputThe 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
# Python3 code to demonstrate working of
# Sort Matrix by Palindrome count
# Using list comprehension and lambda function
# initializing list
test_list = [["nitin", "meem", "geeks"], ["peep"],
["gfg", "is", "best"], ["sees", "level", "mom", "noon"]]
# printing original list
print("The original list is : " + str(test_list))
# lambda function to count palindromic strings in a list
count_palindrome = lambda lst: sum(s == s[::-1] for s in lst)
# use list comprehension to get list of counts for each row
counts = [(row, count_palindrome(row)) for row in test_list]
# use sorted() to sort the counts by count of palindromic strings
sorted_counts = sorted(counts, key=lambda x: x[1], reverse=True)
# extract the rows from the sorted list
sorted_list = [row for row, count in sorted_counts if count > 0]
# print the sorted list
print("Sorted rows : " + str(sorted_list))
OutputThe 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 - 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
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 program to Sort Matrix by Maximum Row element
Given a Matrix, sort rows by maximum element. Input : test_list = [[5, 7, 8], [9, 10, 3], [10, 18, 3], [0, 3, 5]] Output : [[10, 18, 3], [9, 10, 3], [5, 7, 8], [0, 3, 5]] Explanation : 18, 10, 8 and 5 are maximum elements in rows, hence sorted. Input : test_list = [[9, 10, 3], [10, 18, 3], [0, 3, 5]
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 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
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 - Sort by a particular digit count in elements
Given a list of elements, sort by K digit in each element. Examples: Input : test_list = [4322, 2122, 123, 1344], K = 2 Output : [1344, 123, 4322, 2122] Explanation : 0 < 1 < 2 < 3, sorted by count of 2 in each element. Input : test_list = [4322, 2122, 1344], K = 2 Output : [1344, 4322, 212
5 min read