[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)
Comments
Post a Comment