Search code examples
pythontuplespalindrome

Can't figure out how to implement a tuple in a palindrome checker


So I'm learning python from a book, and I'm at the input/output section, in which it gives an example of code that checks for palindromes, but it only works for a word. After that it asks if I can improve the code by having a tuple contain the forbidden characters so that it can check if sentences like "Rise to vote, sir." are palindromes. I've been at it for a couple of time and I just can't wrap my head around how should I implement it.

The example code:

def reverse(text):
    return text[::-1]

def is_palindrome(text):
    return text == reverse(text)

something = input("Enter text: ")
if is_palindrome(something):
    print("Yes, it is a palindrome")

else:
    print("No, it is not palindrome")

What I've tried to do:

def reverse(text):
    return text[::-1]

def sanitize(text):
    text = text.lower
    forbidden = (" ", ".", ",", "!", "?")
    if forbidden in text:
        text.replace(forbidden, "")
    return text

something = input("Enter text: ")

def is_palindrome(text):
    text = sanitize(text)
    return text == reverse(text)

if is_palindrome(something):
    print("Yes, it is a palindrome")

else:
    print("No, it is not palindrome")

Of course this is wrong and throws out an error, but I've tried multiple attempts at it and I just can't figure it out, I'm sure the answer is really simple but I can't find


Solution

  • It might be more efficient (without using additional modules) to implement sanitize like this:

    def sanitize(text):
      forbidden = (" ", ".", ",", "!", "?")
      tl = []
      for c in text:
        if not c in forbidden:
          tl.append(c)
      return ''.join(tl)
    

    Of course, the forbidden variable could be a list, tuple or set.

    Using a list comprehension is more concise but any difference in performance (either way) is likely to be marginal.

    def sanitize(text):
      return ''.join([c for c in text if c not in (" ", ".", ",", "!", "?")])