Open In App

Python – Sort Matrix by Palindrome count

Improve
Improve
Like Article
Like
Save
Share
Report

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))


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




# 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))


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:

  1. Define a function count_palindromes(words) that takes a list of words and returns the count of palindromic words in the list.
  2. 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.
  3. 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.
  4. 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]))


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




# 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))


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.



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