in-place string reversal

Felipe Almeida Lessa felipe.lessa at gmail.com
Tue Mar 28 19:16:40 CEST 2006


Em Ter, 2006-03-28 às 17:32 +0100, Sion Arrowsmith escreveu:
> ride. And at some point reversed() will become a win:
> 
> $ python2.4 -mtimeit 'reversed(range(200))'
> 100000 loops, best of 3: 6.65 usec per loop
> $ python2.4 -mtimeit 'range(200)[::-1]'
> 100000 loops, best of 3: 6.88 usec per loop

Not fair:

$ 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.
>>> range(200)[::-1]
[199, 198, ..., 1, 0]
>>> reversed(range(200))
<listreverseiterator object at 0xb7d1224c>
>>> list(reversed(range(200)))
[199, 198, ..., 1, 0]
>>> list(reversed(range(200))) == range(200)[::-1]
True
>>>^D

Now we're in a fair competition:
$ python2.4 -mtimeit -s 'a=range(200)' 'a[::-1]'
100000 loops, best of 3: 2.23 usec per loop
$ python2.4 -mtimeit -s 'a=range(200)' 'list(reversed(a))'
100000 loops, best of 3: 5.62 usec per loop
$ calc 5.62/2.23
        ~2.52017937219730941704
$ python2.4 -mtimeit -s 'a=range(200000)' 'a[::-1]'
100 loops, best of 3: 10.7 msec per loop
$ python2.4 -mtimeit -s 'a=range(200000)' 'list(reversed(a))'
100 loops, best of 3: 11.5 msec per loop
$ calc 11.5/10.7
        ~1.07476635514018691589

But:
$ python2.4 -mtimeit 'range(199, -1, -1)'
100000 loops, best of 3: 4.8 usec per loop
$ python2.4 -mtimeit 'range(200)[::-1]'
100000 loops, best of 3: 7.05 usec per loop
$ calc 7.05/4.8
        1.46875
$ python2.4 -mtimeit 'range(199999, -1, -1)'
100 loops, best of 3: 13.7 msec per loop
$ python2.4 -mtimeit 'range(200000)[::-1]'
10 loops, best of 3: 24 msec per loop
$ calc 24/13.7
        ~1.75182481751824817518

And worse:
$ python2.4 -mtimeit 'list(reversed(range(200)))'
100000 loops, best of 3: 10.5 usec per loop
$ calc 10.5/4.8
        2.1875
$ python2.4 -mtimeit 'list(reversed(range(200000)))'
10 loops, best of 3: 24.5 msec per loop
$ calc 24.5/13.7
        ~1.78832116788321167883


HTH,

-- 
Felipe.




More information about the Python-list mailing list