w3resource

Palindrome Checker Project: Basic and Class-Based Python Solutions


Palindrome Checker:

Create a program that checks if a given word or phrase is a palindrome.

Input values:
User provides a word or phrase to be checked for palindrome.

Output value:
Feedback indicates whether the provided word or phrase is a palindrome or not.

Example:

Input values:
Enter a word or phrase: radar
Output value:
"radar" is a palindrome.
Input values:
Enter a word or phrase: hello
Output value:
"hello" is not a palindrome.
Input values:
Enter a word or phrase: A man, a plan, a canal, Panama!
Output value:
"A man, a plan, a canal, Panama!" is a palindrome.

Here are two different solutions for creating a palindrome checker in Python. Each solution will take user input, check if the input is a palindrome, and provide feedback.

Solution 1: Basic Approach using String Manipulation

Code:

# Solution 1: Basic Approach Using String Manipulation

def is_palindrome(text):
    """Check if the given text is a palindrome."""
    # Convert text to lowercase to make the check case-insensitive
    text = text.lower()
    
    # Remove non-alphanumeric characters from the text
    filtered_text = ''.join(char for char in text if char.isalnum())
    
    # Check if the filtered text is the same forwards and backwards
    return filtered_text == filtered_text[::-1]

def main():
    """Main function to interact with the user and check for palindrome."""
    # Get user input
    user_input = input("Enter a word or phrase: ")
    
    # Check if the input is a palindrome
    if is_palindrome(user_input):
        print(f'"{user_input}" is a palindrome.')
    else:
        print(f'"{user_input}" is not a palindrome.')

# Run the palindrome checker
main() 

Output:

Enter a word or phrase: Madam
"Madam" is a palindrome.
Enter a word or phrase: Orange
"Orange" is not a palindrome

Explanation:

  • is_palindrome(text) Function:
    • Converts the input text to lowercase to ignore case differences.
    • Removes non-alphanumeric characters (like spaces, punctuation) using a generator expression.
    • Compares the filtered text with its reverse to check if it is a palindrome.
  • main() Function:
    • Gets user input and checks if it's a palindrome using the is_palindrome() function.
    • Prints the appropriate message based on the result.

Solution 2: Class-Based Approach with Regular Expressions

This solution uses a class to encapsulate the palindrome checking functionality and uses regular expressions for filtering non-alphanumeric characters.

Code:

# Solution 2: Class-Based Approach with Regular Expressions

import re  # Import the regex module to handle non-alphanumeric characters

class PalindromeChecker:
    """Class to handle palindrome checking functionality."""

    def __init__(self, text):
        """Initialize with the text to be checked."""
        self.text = text

    def clean_text(self):
        """Remove non-alphanumeric characters and convert to lowercase."""
        # Use regex to keep only alphanumeric characters and convert to lowercase
        return re.sub(r'[^a-zA-Z0-9]', '', self.text).lower()

    def is_palindrome(self):
        """Check if the cleaned text is a palindrome."""
        # Clean the text using the clean_text method
        cleaned_text = self.clean_text()
        # Check if the cleaned text reads the same forwards and backwards
        return cleaned_text == cleaned_text[::-1]

    def check(self):
        """Check and print whether the original text is a palindrome."""
        if self.is_palindrome():
            print(f'"{self.text}" is a palindrome.')
        else:
            print(f'"{self.text}" is not a palindrome.')

def main():
    """Main function to get user input and check for palindrome."""
    # Get user input
    user_input = input("Enter a word or phrase: ")
    
    # Create an instance of PalindromeChecker and check for palindrome
    checker = PalindromeChecker(user_input)
    checker.check()

# Run the palindrome checker
main()  

Output:

Enter a word or phrase: Madam
"Madam" is a palindrome.
Enter a word or phrase: Madam
"Madam" is a palindrome.

Explanation:

  • PalindromeChecker Class:
    • __init__() Constructor: Initializes the class with the text to be checked.
    • clean_text() Method: Uses a regular expression (re.sub) to remove all non-alphanumeric characters and converts the text to lowercase.
    • is_palindrome() Method: Cleans the text and checks if it reads the same forwards and backwards.
    • check() Method: Calls is_palindrome() and prints whether the text is a palindrome.
  • main() Function:
    • Gets user input and creates an instance of the PalindromeChecker class.
    • Calls the check() method to determine if the input is a palindrome and print the result.

Differences Between the Two Solutions:

  • Solution 1: Basic Approach Using String Manipulation:
    • Uses basic string manipulation techniques.
    • Simple and effective for basic palindrome checks.
    • No additional libraries required.
  • Solution 2: Class-Based Approach with Regular Expressions:
    • Encapsulates the palindrome checking logic in a class.
    • Uses regular expressions for more advanced text cleaning.
    • More modular and extendable, suitable for larger applications.

Both solutions effectively check if a word or phrase is a palindrome, but the second solution offers a more structured and modular approach.



Follow us on Facebook and Twitter for latest update.