Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would I check if a word or sentence is a palindrome?

Tags:

python

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)

like image 951
FireFume Avatar asked Dec 10 '22 14:12

FireFume


2 Answers

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]
like image 134
inspectorG4dget Avatar answered Jan 05 '23 23:01

inspectorG4dget


To check sentence palindrome-ness, the algorithm seems to be:

  1. Remove any non-alphabetical character
  2. Compare 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
like image 40
Adam Smith Avatar answered Jan 05 '23 22:01

Adam Smith