It feels so good, so quick and not C!

John Machin sjmachin at lexicon.net
Tue Mar 18 17:59:07 EST 2003


Steven Taschuk <staschuk at telusplanet.net> wrote in message news:<mailman.1047969613.29891.python-list at python.org>...
> (If there were no list.reverse method, you could, of course, do it
> yourself, perhaps like this:
> 
>     def strrev(orig):
>         rev = list(orig)
>         forwards = range(len(rev)//2)
>         backwards = range(len(rev)-1, -1, -1)
>         for a, b in zip(forwards, backwards):
>             rev[a], rev[b] = rev[b], rev[a]
>         return ''.join(rev)
> 
> If you're just learning Python, you might want to spend a few
> minutes studying this version.  It has one slightly subtle point
> for which I would write a comment if this were real code.)

Which if any of the following "subtle" points did you mean? (1)
"backwards" is as twice as large as it needs to be, with the unwanted
guff jettisoned by zip(). (2) "forwards", "backwards", and the zip()
result constitute about (3 * len(orig)) objects clogging up memory.
(3) The cuteness of swapping by "x, y = y, x" hides the overhead of
packing and unpacking a 2-tuple, which may or may not be faster than
the traditional 3-assignment method.

The original poster might like to contemplate the following
memory-spartan translated-from-C approach:

def strrev2(orig):
   rev = list(orig)
   last = len(rev) - 1
   for k in xrange((last+1) // 2):
      temp = rev[k]
      rev[k] = rev[last-k]
      rev[last-k] = temp
   return ''.join(rev)

or (for something completely different) this:

def strrev3(orig):
   return ''.join([orig[k] for k in xrange(len(orig)-1, -1, -1)])




More information about the Python-list mailing list