π§ͺ Programming
β±οΈ 74s
π 1254 chars
π¦ 3.8B
π§ Q4_K_M
Prompt: Write a Python function is_palindrome(s) that returns True if s is a palindrome. One test case.
Response
Hereβs a Python function `is_palindrome(s)` that checks whether a given
string `s` is a palindrome (reads the same forwards and backwards),
ignoring case and non-alphanumeric characters:
```python
import re
def is_palindrome(s):
# Remove all non-alphanumeric characters and convert to lowercase
cleaned_s = re.sub(r'[^a-zA-Z0-9]', '', s).lower()
return cleaned_s == cleaned_s[::-1]
# Test case:
test_string = "A man, a plan, a canal: Panama"
print(is_palindrome(test_string)) # Output: True
```
### Explanation:
1. **Cleaning the string**:
- `re.sub(r'[^a-zA-Z0-9]', '', s)` removes all non-alphanumeric
characters (like spaces, punctuation).
- `.lower()` converts the string to lowercase for case-insensitive
comparison.
2. **Palindrome check**:
- `cleaned_s == cleaned_s[::-1]` compares the cleaned string with its re
reverse (`[::-1]` reverses the string).
### Test Case:
```python
print(is_palindrome("racecar")) # True (simple palindrome)
print(is_palindrome("No lemon, no melon")) # True (ignores
spaces/punctuation)
print(is_palindrome("hello")) # False
```
Would you like any modifications or additional test cases?