๐งช Programming
โฑ๏ธ 72s
๐ 1614 chars
๐ฆ 3.4B
๐ง 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 if a given string `
`s` is a palindrome, along with one test case:
```python
def is_palindrome(s):
# Remove non-alphanumeric characters and convert to lowercase
s = ''.join(c.lower() for c in s if c.isalnum())
# Check if the string is equal to its reverse
return s == s[::-1]
# Test case
test_string = "A man, a plan, a canal: Panama"
print(is_palindrome(test_string)) # Output: True
```
Explanation:
1. The function first removes all non-alphanumeric characters (punctuation,
(punctuation, spaces, etc.) from the string `s` and converts it to
lowercase. This is done using a generator expression inside `join()` that i
iterates over each character `c` in `s`, keeping only those characters for
which `c.isalnum()` returns `True`. The resulting string is then converted
to lowercase.
2. After cleaning the string, the function checks if the cleaned string `s`
`s` is equal to its reverse (`s[::-1]`). If they are equal, it means the or
original string (ignoring non-alphanumeric characters and case) is a
palindrome, and the function returns `True`. Otherwise, it returns `False`.
`False`.
3. The test case demonstrates the usage of the function with the string "A
man, a plan, a canal: Panama", which is a well-known example of a
palindrome when ignoring spaces, punctuation, and capitalization. The
expected output is `True`, indicating that the cleaned version of this
string is indeed a palindrome.