in-place string reversal

Felipe Almeida Lessa felipe.lessa at gmail.com
Tue Mar 28 17:56:11 CEST 2006


Em Ter, 2006-03-28 às 16:03 +0100, Sion Arrowsmith escreveu:
> Rather than writing
> your own reversing code, you might like to look at:
> 
> >>> "".join(reversed("foo"))

Or not:

----
$ python2.4
Python 2.4.2 (#2, Nov 20 2005, 17:04:48)
[GCC 4.0.3 20051111 (prerelease) (Debian 4.0.2-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> "".join(reversed("foo"))
'oof'
>>> "foo"[::-1]
'oof'

$ python2.4 -mtimeit '"".join(reversed("foo"))'
100000 loops, best of 3: 2.58 usec per loop

$ python2.4 -mtimeit '"foo"[::-1]'
1000000 loops, best of 3: 0.516 usec per loop

$ calc 2.58/0.516
        5
----

"foo"[::-1] is cleaner and performs 5 times better -- 'nuff said.

Cheers,

-- 
Felipe.




More information about the Python-list mailing list