I am supposed to check if a word or sentence is a palindrome using code, and I was able to check for words, but I'm having trouble checking sentences as being a palindrome. Here's my code, it's short but I'm not sure how else to add it to check for sentence palindromes. I'm sort of a beginner at python, and I've already looked at other people's code, and they are too complicated for me to really understand. Here's what I wrote:
def is_palindrome(s):
if s[::1] == s[::-1]:
return True
else:
return False
Here is an example of a sentence palindrome: "Red Roses run no risk, sir, on nurses order." (If you ignore spaces and special characters)
import string
def is_palindrome(s):
whitelist = set(string.ascii_lowercase)
s = s.lower()
s = ''.join([char for char in s if char in whitelist])
return s == s[::-1]
To check sentence palindrome-ness, the algorithm seems to be:
new_s
to new_s[::-1]
case-insensitively.You can do the former by doing:
import string
valid = set(string.ascii_letters)
result_s = ''.join([ch for ch in original_s if ch in valid])
Then the latter by doing:
result_s.casefold() == result_s.casefold()[::-1]
Put the whole thing together with:
import string
s = "Red roses run no risk, sir, on nurses order"
s2 = "abcba"
s_fail = "blah"
def is_palindrome(s):
valid = set(string.ascii_letters)
result_s = ''.join([ch for ch in s if ch in valid])
cf_s = result_s.casefold()
return cf_s == cf_s[::-1]
assert(is_palindrome(s))
assert(is_palindrome(s2))
assert(is_palindrome(s_fail)) # throws AssertionError
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With