简体   繁体   中英

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

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 (" ", ".", ",", "!", "?")])

I found a few problems with your code.

text.lower should be changed to text.lower() . you should use a for loop to iterate through forbidden . And text should be updated to text.replace(c, “”) and c is each value in forbidden . This should be the code

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

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

something = raw_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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM