palindrome iteration

Matteo Landi landimatte at gmail.com
Sun Aug 29 11:19:24 CEST 2010


Well, I tried the also the solution posted above (recursive w/o
slicing and iterative), and I discovered they were the slowest..

is_palindrome_recursive 2.68151649808
is_palindrome_slice 0.44510699381
is_palindrome_list 1.93861944217
is_palindrome_reversed 3.28969831976
is_palindrome_recursive_no_slicing 6.78929775328
is_palindrome_iterative 4.88826141315

Nothing to say about the iterative function, but the benchmark of the
recursive was unexpected, at least for my point of view: do you think
it is due to the try/except overhead?

On Sun, Aug 29, 2010 at 8:53 AM, Josh English
<joshua.r.english at gmail.com> wrote:
> 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
>    else:
>        return is_palindrome(s[1:-1])
>
> def is_palindrome_slice(s):
>    return s == s[::-1]
>
> def is_palindrome_list(s):
>    l = list(s)
>    l.reverse()
>    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
> is_palindrome_slice")
> print "is_palindrome_slice", min(t.repeat())
>
> t = Timer("is_palindrome_list('madamimadam')", "from __main__ import
> is_palindrome_list")
> 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.
>
> Josh
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Matteo Landi
http://www.matteolandi.net/



More information about the Python-list mailing list