Alan Kennedy alanmk at
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",
  "If I Had a Hi-Fi",
  "So Many Dynamos",
  "Madam I'm Alan",
  "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
      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


alan kennedy
check http headers here:
email alan:    

More information about the Python-list mailing list