Claude Opus 4.6
Unrated10,868ms786 tokens
```python
def is_palindrome(s: str) -> bool:
"""
Check if a string is a palindrome, ignoring case and non-alphanumeric characters.
Args:
s: The input string to check.
Returns:
True if the string is a palindrome, False otherwise.
Examples:
>>> is_palindrome("A man, a plan, a canal: Panama")
True
>>> is_palindrome("racecar")
True
>>> is_palindrome("hello")
False
>>> is_palindrome("")
True
>>> is_palindrome("Was it a car or a cat I saw?")
True
"""
# Filter out non-alphanumeric characters and convert to lowercase
cleaned: str = "".join(char.lower() for char in s if char.isalnum())
# Compare the cleaned string with its reverse
return cleaned == cleaned[::-1]
# --- Demo / Testing ---
if __name__ == "__main__":
test_cases: list[tuple[str, bool]] = [
("A man, a plan, a canal: Panama", True),
("racecar", True),
("hello", False),
("", True),
("Was it a car or a cat I saw?", True),
("No 'x' in Nixon", True),
("12321", True),
("abc123", False),
("Madam, I'm Adam", True),
(" ", True),
]
print("Testing is_palindrome function:")
print("-" * 55)
for text, expected in test_cases:
result: bool = is_palindrome(text)
status: str = "✅ PASS" if result == expected else "❌ FAIL"
print(f'{status} | is_palindrome("{text}") = {result}')
```
## How It Works
1. **Cleaning the string:**
- `char.isalnum()` filters out any character that isn't a letter or digit (spaces, punctuation, etc.)
- `char.lower()` converts each remaining character to lowercase for case-insensitive comparison
- `"".join(...)` combines the filtered characters back into a single string
2. **Palindrome check:**
- `cleaned[::-1]` creates a reversed copy of the cleaned string
- A simple equality check (`==`) determines if the string reads the same forwards and backwards
## Key Design Choices
| Feature | Detail |
|---|---|
| **Type hints** | `s: str` for input, `-> bool` for return type |
| **Ignores case** | `"Racecar"` → `"racecar"` |
| **Ignores non-alphanumeric** | `"A man, a plan..."` → `"amanaplanacanalpanama"` |
| **Edge cases** | Empty strings and whitespace-only strings return `True` (vacuously palindromic) |
| **Time complexity** | O(n) where n is the length of the string |