Effortless Palindrome Checking in Python: Techniques

python @ Freshers.in

Python, with its robust string handling capabilities, offers several straightforward ways to determine if a string is a palindrome. These methods range from basic string manipulation to more sophisticated algorithmic approaches.

Basic Method: Reversing a String

The simplest way to check for a palindrome is to reverse the string and compare it with the original.

Example:

def is_palindrome(s):
    # Remove non-alphanumeric characters and convert to lowercase
    cleaned_s = ''.join(char.lower() for char in s if char.isalnum())
    return cleaned_s == cleaned_s[::-1]
print(is_palindrome("A man, a plan, a canal, Panama"))

Using a Loop

A more manual approach involves comparing characters from each end of the string moving towards the center.

Example:

def is_palindrome(s):
    cleaned_s = ''.join(char.lower() for char in s if char.isalnum())
    left, right = 0, len(cleaned_s) - 1
    while left < right:
        if cleaned_s[left] != cleaned_s[right]:
            return False
        left, right = left + 1, right - 1
    return True
print(is_palindrome("No lemon, no melon"))

Recursive Method

For those who prefer a recursive approach, palindrome checking can be performed by recursively comparing characters while slicing the string.

Example:

def is_palindrome(s):
    def check_palindrome(cleaned_s):
        if len(cleaned_s) <= 1:
            return True
        if cleaned_s[0] != cleaned_s[-1]:
            return False
        return check_palindrome(cleaned_s[1:-1])

    cleaned_s = ''.join(char.lower() for char in s if char.isalnum())
    return check_palindrome(cleaned_s)
print(is_palindrome("Was it a car or a cat I saw?"))
Author: user