Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python Program for Counting Sort
Next article icon

Python – Sort Matrix by Palindrome count

Last Updated : 08 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
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.



Next Article
Python Program for Counting Sort
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
  • Python string-programs
Practice Tags :
  • python

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 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
  • 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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences