python - Checking Palindrome text, with ignored punctuation marks, spaces and case -
homework exercise: checking whether text palindrome should ignore punctuation, spaces , case. example, "rise vote, sir." palindrome our current program doesn't is. can improve above program recognize palindrome?
origin code:
def reverse(text): return text[::-1] def is_palindrome(text): return text == reverse(text) = input('enter text: ') if (is_palindrome(something)): print("yes, palindrome") else: print("no, not palindrome")
my try:
import re def reverse(text): global words words = text.split() return words[::-1] def is_palindrome(text): return words==reverse(text) = input('enter text: ') if (is_palindrome(something)): print("yes, palindrome") else: print("no, not palindrome")
error:
enter text: jfldj traceback (most recent call last): file "/users/apple/pycharmprojects/problem solving/user_input.py", line 13, in <module> print("yes, palindrome") file "/users/apple/pycharmprojects/problem solving/user_input.py", line 10, in is_palindrome nameerror: name 'words' not defined
how should change code?
latest code:
import string def remove_punctuations(word): return "".join(i.lower() in word if not in string.ascii_letters) def reverse(text): return text[::-1] def is_palindrome(text): text = remove_punctuations(text) return text == reverse(text) = input('enter text: ') if (is_palindrome(something)): print("yes, palindrome" else: print("no, not palindrome")
no matter input, output yes.
enter text: hggjkgkkkk yes, palindrome
what's wrong?
to ignore punctuations, spaces , case of given text need define function remove_punctuations()
takes word parameter , returns word lower case characters, remove punctuation marks , removed spaces.
to remove unwanted characters need iterate on given text, if current character falls in strings.ascii_letters
, generate character converting lower caps using str.lower()
method. using "".join()
method concatenate generated str
elements.
import string def remove_punctuations(word): return "".join(i.lower() in word if in string.ascii_letters) def reverse(text): return text[::-1] def is_palindrome(text): text = remove_punctuations(text) return text==reverse(text) = "rise vote, sir." if (is_palindrome(something)): print("yes, palindrome") else: print("no, not palindrome")
Comments
Post a Comment