๐งช Programming
โฑ๏ธ 152s
๐ 1417 chars
๐ฆ 8.8B
๐ง Q4_K_M
Prompt: Write a Python function is_palindrome(s) that returns True if s is a palindrome. One test case.
Response
Certainly! Below is a Python function `is_palindrome(s)` that checks
whether the input string `s` is a palindrome. A palindrome is a word,
phrase, number, or other sequences of characters that reads the same
forward and backward (ignoring spaces, punctuation, and capitalization).
```python
def is_palindrome(s):
# Normalize the string by converting it to lowercase and removing
non-alphanumeric characters
s = ''.join(char.lower() for char in s if char.isalnum())
# Check if the string reads the same forwards and backwards
return s == s[::-1]
# Test case
test_string = "A man, a plan, a canal: Panama"
print(is_palindrome(test_string)) # Expected output: True
```
Explanation:
1. The function first normalizes the input string `s` by converting all
characters to lowercase and filtering out non-alphanumeric characters
(spaces, punctuation, etc.). This is done using a list comprehension
combined with `str.join()`, `str.lower()`, and `str.isalnum()`.
2. It then checks if the normalized string reads the same forwards and
backwards by comparing it to its reverse (`s[::-1]`).
3. The function returns `True` if `s` is a palindrome, otherwise `False`.
The provided test case checks the classic example of a palindrome: "A man,
a plan, a canal: Panama", which should return `True`.