palindrome iteration

Josh English joshua.r.english at
Sun Aug 29 08:53:54 CEST 2010

This whole conversation got interesting, so I thought I'd run some
speed tests:

The code:
from timeit import Timer

def is_palindrome_recursive(s):
    if len(s) <= 1:
        return True
    if s[0] != s[-1]:
        return False
        return is_palindrome(s[1:-1])

def is_palindrome_slice(s):
    return s == s[::-1]

def is_palindrome_list(s):
    l = list(s)
    return s == ''.join(l)

def is_palindrome_reversed(s):
    return s == ''.join(reversed(s))

t = Timer("is_palindrome_recursive('madamimadam')", "from __main__
import is_palindrome_recursive")
print "is_palindrome_recursive", min(t.repeat())

t = Timer("is_palindrome_slice('madamimadam')", "from __main__ import
print "is_palindrome_slice", min(t.repeat())

t = Timer("is_palindrome_list('madamimadam')", "from __main__ import
print "is_palindrome_list", min(t.repeat())

t = Timer("is_palindrome_reversed('madamimadam')", "from __main__
import is_palindrome_reversed")
print "is_palindrome_reversed", min(t.repeat())

The results:
is_palindrome_recursive 6.32680866827
is_palindrome_slice 1.23618350114
is_palindrome_list 4.60104846653
is_palindrome_reversed 5.99355296513

The slice method is uglier, I have to admit, but it's the fastest of
these four on my machine.


More information about the Python-list mailing list