Mar-04-2019, 09:29 AM
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):
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 TrueOf 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.
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.