Palindrome

Andrew Dalke adalke at mindspring.com
Fri Nov 14 19:08:27 EST 2003


Skip:
> Oh, then how about:
  ...

At the end are the three solutions I saw posted, from Ron Adam,
Skip, and me (modified).  The times are

palindrome_adam 128.152670758
palindrome_skip 89.5211577111
palindrome_dalke 11.1900866758

                    Andrew
                    dalke at dalkescientific.com


import re, timeit


# from Ron Adam
def palindrome_adam(p):
    p = re.sub(r'\W','',p.lower())
    i = len(p)//2
    while i and p[i] == p[-i-1]:  i -= 1
    return not i

# from Skip Montanaro
def palindrome_skip(s):
    s = re.sub("[^A-Za-z0-9]+", "", s).lower()
    return s == s[::-1]

# from Andrew Dalke
foldcase = []
punctuation = []
for i in range(256):
    c = chr(i)
    if c.isalnum():  # note 'alnum' instead of 'alpha' ...
        foldcase.append(c.lower())
    else:
        foldcase.append(c)
        punctuation.append(c)
foldcase = "".join(foldcase)
punctuation = "".join(punctuation)
del c, i

def palindrome_dalke(s):
    t = s.translate(foldcase, punctuation)
    return t == t[::-1]

verify_data = [
    ("A man, a plan, a canal -- Panama!", True),
    ("1234", False),
    ("123321", True),
    ("12321", True),
    ("Madam, I'm Adam.", True),
    ("A", True),
    ("ab", False),
    ("Oo!", True),
    ("Bolton", False),
    ("This is not a palindrome!", False),
    ("Was it a car or a cat I saw?", True),
    ("No 'H' type, mate, no spot stops one tame python!", True),
    ("A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal--Panama!",
     True),
    ]

def verify():
    for tester in (palindrome_adam, palindrome_skip,
                   palindrome_dalke):
        for s, result in verify_data:
            assert tester(s) == result, (tester, s)
    print "Verified"

_time_val = None

def find_times():
    global _time_val
    _time_val = verify_data[-1][0]  # the long "a man, a plan ... Panama"
one
    for tester in ("palindrome_adam", "palindrome_skip",
                   "palindrome_dalke"):
        timer = timeit.Timer(setup = "import __main__ as M",
                             stmt = "M." + tester + "(M._time_val)")
        t = timer.timeit()
        print tester, t

if __name__ == "__main__":
    verify()
    find_times()






More information about the Python-list mailing list