# Palindrome

Alan Kennedy alanmk at hotmail.com
Thu Nov 13 18:32:06 CET 2003

[Ulrich Schramme]
> there might be a million ways to solve the palindrome problem. I think
> that another good way would be the use of regular expressions.

The same occurred to me, so I had a go. This is as well as I was able
to do in my lunchtime.

#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
import re

ignore = """ ",.'`!?-"""

def isPalindrome(s):
testphrase = re.sub("[%s]" % ignore, '', s)
numtomatch = len(testphrase)/2
regx = "(\S)?"
for x in range(numtomatch):
regx = "(\S)%s(\%d)" % (regx, numtomatch-x)
rxc = re.compile(regx, re.I)
result = rxc.match(testphrase)
return result is not None

phrases = [
"Able was I, `ere I saw Elba",
"A man, a plan, a canal, Panama",
"Go Hang a Salami! I'm a Lasagna Hog!",
"Sit on a Potato Pan, Otis",
"Too Hot to Hoot",
"So Many Dynamos",
"Santa, Oscillate My Metallic Sonatas",
"Knob, testes set? Set. Bonk!",
]

if __name__ == "__main__":
print "Palindromes:"
for phrase in phrases:
if isPalindrome(phrase):
print "Yes: '%s'" % phrase
else:
print "No : '%s'" % phrase
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

I'm not too happy with it though. There must be some way to have a
single fixed regular expression that can be used to test every
palindrome.

regards,

--
alan kennedy
-----------------------------------------------------