[Python][Coding Pattern] Palindrome

Palindrome

Purpose

We are checking whether a given input string is a palindrome — that means it reads the same forwards and backwards.

Constraints and Requirements

- Case-insensitive: `"RaceCar"` and `"racecar"` should both count.

- Ignore all non-alphanumeric characters like spaces and punctuation.

- Return True if the string is a valid palindrome, otherwise return False.

Step-by-Step Logic

1. Lowercase the entire input string.

This ensures that A and a are treated the same. Use str.lower().

2. Sanitize the text.

We filter out all characters that are not letters or numbers.

Use a loop or list comprehension to check char.isalnum() for each character.

This leaves us with only the characters we actually want to compare.

3. Mirror check with symmetric comparison.

We want to compare the first character with the last, the second with the second-to-last, and so on.

If we apply this in Python, Compare character i with character at index -(i + 1).

Why -(i + 1)?

Because -1 is the last index, and we need to shift one step at a time, moving inward.


4. Iterate only halfway.

We only need to check up to the middle of the string. If all the mirrored characters match, it's a palindrome.


5. Return True if no mismatches were found.

If we hit a mismatch at any point, we return False early. Otherwise, after the loop ends, we return True.

Things to consider

Negative indexing (`-1`, `-2`, etc.) avoids needing to do len() - i - 1 math.

- No need to check for odd or even lengths — if the string is odd, the middle character doesn't need a match.

- This approach avoids popping or modifying the original list.

Functions & Concepts Used

- str.lower(): for case-insensitive comparison

- char.isalnum(): filters out symbols, spaces, punctuation

- Negative indexing (`-1`, `-2`, etc.): for backward comparison

- Slicing and iteration control with range(len // 2)

# Problem:
# Write a function that checks whether a given string is a palindrome. A palindrome is a string that reads the same forwards and backwards.

# Constraints:
# Input is a string.
# Comparison should be case-insensitive.
# Ignore non-alphanumeric characters (punctuation, spaces, etc.).
# Return True if it's a palindrome, False otherwise.


def is_palindrome(text: str) -> bool:
    lowerd_text = text.lower()

    sanitized_text = [char for char in lowerd_text if char.isalnum()]
    for i in range(len(sanitized_text)//2):
        if sanitized_text[i] != sanitized_text[-(i+1)]:
            return False

    return True


if __name__ == '__main__':
    assert is_palindrome("racecar") == True, 'test 1 failed'
    assert is_palindrome("A man, a plan, a canal: Panama") == True, 'test 2 failed'
    assert is_palindrome("No lemon, no melon") == True, 'test 3 failed'
    assert is_palindrome("hello") == False, 'test 4 failed'
    assert is_palindrome("") == True, 'test 5 failed'

Comments