Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Palindrome Test
#4
Another way is to write function with short-circuit i.e if first non-match encountered then False is returned. Text cleaning must be performed, this is somewhat easier with built-in tools if you need to test only in english; for other languages one could define allowed letters manually (or exclude punctuation).

One way of accomplishing it (it will ignore non-ascii characters, depending on use-case it may be a problem, using 'if letter not in string.punctuation' might be an alternative):

>>> import string
>>> def palindrome_check(text):
...     cleaned = [letter.lower() for letter in text if letter in string.ascii_letters]
...     for forward, backward in zip(cleaned, cleaned[::-1]):
...         if forward != backward:
...             return False
...     return True
Of course, there is built-in function all() exactly for that purpose:

>>> import string
>>> def palindrome_check(text):
...     cleaned = [letter.lower() for letter in text if letter in string.ascii_letters]
...     return all(forward == backward for forward, backward in zip(cleaned, cleaned[::-1]))
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Messages In This Thread
Palindrome Test - by mcmxl22 - Mar-03-2019, 05:25 PM
RE: Palindrome Test - by perfringo - Mar-04-2019, 07:13 AM
RE: Palindrome Test - by DeaD_EyE - Mar-04-2019, 08:43 AM
RE: Palindrome Test - by perfringo - Mar-04-2019, 09:29 AM
RE: Palindrome Test - by DeaD_EyE - Mar-04-2019, 12:29 PM
RE: Palindrome Test - by perfringo - Mar-04-2019, 01:48 PM
RE: Palindrome Test - by rootVIII - Mar-05-2019, 03:37 AM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020