[Tutor] rotating a list

Gregor Lingl glingl at aon.at
Sun Sep 21 04:34:53 EDT 2003


Danny Yoo schrieb:

>  
>
>>PS. If my man Danny is out there... 'Hi'
>>    
>>
>
>Hey Kevin, it's been a long time!
>
>Looks like you've gotten a few responses ...
>If so, Gregor's solution ... will need an amendment ...
>
>One way we can fix the definition is to redefine it so that it always does
>list slicing on its input:
>
>###
>  
>
>>>>def rotate(L):
>>>>        
>>>>
>...     """Mutates list L and rotates all the elements to the left."""
>...     x[:-1], x[-1:] = x[1:], x[:1]
>...
>###
>
>The symmetry in the definition here appeals to me.  *grin*
>
>  
>
Me too! Thanks for the idea! (Of course we should replace L by x (or 
vice versa) ;-) ).
May we use it to generalize it in order to achieve Kevin's original 
funcionality without
sacrificing the symmetry?

 >>> def rotate(x, n=1):
        x[:-n], x[-n:] = x[n:], x[:n]

This works also for n > len(x), but not correctly. Sometimes this will 
be needed to have
some sort of continued rotation:

 >>> def rotate(x, n=1):
        n %= len(x)
        x[:-n], x[-n:] = x[n:], x[:n]

 >>> rotate(l,11)
 >>> l
[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
 >>>
 >>> rotate(l,-2)
 >>> l
[9, 0, 1, 2, 3, 4, 5, 6, 7, 8]

(btw, this idea could be applied also to your handwavy solution from
programming pearls,  which will run into an IndexError, if n is not in 
range(len(l))

Have a happy Sunday!

Gregor

>Talk to you later!
>
>
>_______________________________________________
>Tutor maillist  -  Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor
>
>
>  
>





More information about the Tutor mailing list