Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python – Sort Matrix by Palindrome count
When it is required to sort a matrix based on palindrome count, a method is defined that takes a list as parameter. It uses list comprehension and the join() method to iterate and check if an element is a palindrome or not. Based on this count, the matrix rows are sorted and displayed.
What is a Palindrome?
A palindrome is a word that reads the same forwards and backwards, like "level", "noon", or "abcba".
Example
Below is a demonstration of sorting a matrix by palindrome count ?
def get_palindrome_count(row):
return len([element for element in row if ''.join(list(reversed(element))) == element])
my_list = [["abcba", "hdgfue", "abc"], ["peep"], ["py", "is", "best"], ["sees", "level", "non", "noon"]]
print("The list is:")
print(my_list)
my_list.sort(key=get_palindrome_count)
print("The resultant list is:")
print(my_list)
The list is: [['abcba', 'hdgfue', 'abc'], ['peep'], ['py', 'is', 'best'], ['sees', 'level', 'non', 'noon']] The resultant list is: [['py', 'is', 'best'], ['abcba', 'hdgfue', 'abc'], ['peep'], ['sees', 'level', 'non', 'noon']]
How It Works
Let's break down the palindrome counting process ?
def get_palindrome_count(row):
palindromes = []
for element in row:
reversed_element = ''.join(list(reversed(element)))
if reversed_element == element:
palindromes.append(element)
print(f"'{element}' is a palindrome")
else:
print(f"'{element}' is not a palindrome")
return len(palindromes)
# Test with one row
test_row = ["sees", "level", "non", "noon"]
count = get_palindrome_count(test_row)
print(f"Total palindromes: {count}")
'sees' is a palindrome 'level' is a palindrome 'non' is a palindrome 'noon' is a palindrome Total palindromes: 4
Sorting Process
The matrix is sorted based on palindrome count in each row ?
Row 1: ["abcba", "hdgfue", "abc"] ? 1 palindrome ("abcba")
Row 2: ["peep"] ? 1 palindrome ("peep")
Row 3: ["py", "is", "best"] ? 0 palindromes
Row 4: ["sees", "level", "non", "noon"] ? 4 palindromes
After sorting: 0, 1, 1, 4 palindromes respectively.
Alternative Approach
Here's a more readable version using a simpler palindrome check ?
def is_palindrome(word):
return word == word[::-1]
def count_palindromes(row):
return sum(1 for word in row if is_palindrome(word))
matrix = [["abcba", "hdgfue", "abc"], ["peep"], ["py", "is", "best"], ["sees", "level", "non", "noon"]]
print("Original matrix:")
for i, row in enumerate(matrix):
print(f"Row {i+1}: {row} ? {count_palindromes(row)} palindromes")
matrix.sort(key=count_palindromes)
print("\nSorted matrix:")
for i, row in enumerate(matrix):
print(f"Row {i+1}: {row} ? {count_palindromes(row)} palindromes")
Original matrix: Row 1: ['abcba', 'hdgfue', 'abc'] ? 1 palindromes Row 2: ['peep'] ? 1 palindromes Row 3: ['py', 'is', 'best'] ? 0 palindromes Row 4: ['sees', 'level', 'non', 'noon'] ? 4 palindromes Sorted matrix: Row 1: ['py', 'is', 'best'] ? 0 palindromes Row 2: ['abcba', 'hdgfue', 'abc'] ? 1 palindromes Row 3: ['peep'] ? 1 palindromes Row 4: ['sees', 'level', 'non', 'noon'] ? 4 palindromes
Conclusion
Use sort() with a custom key function to sort matrix rows by palindrome count. The [::-1] slice notation provides a simpler way to check palindromes than using reversed() and join().
