[Tutor] Re: rotating a list

Andrei project5 at redrival.net
Sat Sep 20 05:09:25 EDT 2003


Hi Kevin,

kevin parks wrote:
> Hi. My python chops are a bit rusty but i need another pair of eyes to 
> tell me what i am doing wrong. I am sure that it is something very 
> stupid but i can't see what it is.. I am trying to cycle through a list 
> like so
> 
> [a, b, c]
> [b, c, a]
> [c, a, b]
> [a, b, c]
> 
> only, that aint be what is coming out the other side...
> 
> anyone see where things are going wrong?
<snip>
> # cyclically rotate a sequence
> 
> # should work on any sequence type (list, tuple, string) and should work 
> with
> # any hop(n) interval and also work in both directions (left or right)
> 
> def rotate(seq, n=1):
>     if len(seq) == 0:
>         return seq
>     n = n % len(seq) # Normalize n, using modulo - even works for 
> negative n
> 
>     return seq[n:] + seq[:n]

Works fine here:
 >>> rotate([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 0]
 >>> rotate([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 0])
[2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 0, 1]
 >>> rotate([2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 0, 1])
[3, 4, 5, 6, 7, 8, 9, 10, 11, 0, 1, 2]

> 
> def test():
>     random.seed(720)        # reproducable results
>     x = range(0, 12, 1)     # create a list for test purposes
>     print x; print          # look at it
>     random.shuffle(x)       # scramble it up
>     print x; print          # look at again...
>     # Now rotate the list one at a time till we've done come to
>     # the beginning once again
>     for i in range(len(x)):

Here's your problem your rotate x and assign the result to y:

>         y = rotate(x)

Now x is unchanged, y is the result, so you go back and rotate the same old x 
again. Obviously the result won't change.

>         print y

Here's the improved version:
     for i in range(len(x)):
         x = rotate(x)
         print x

Results:
 >>> test()
[0, 1, 2, 3, 4]

[0, 1, 4, 2, 3]

[1, 4, 2, 3, 0]
[4, 2, 3, 0, 1]
[2, 3, 0, 1, 4]
[3, 0, 1, 4, 2]
[0, 1, 4, 2, 3]

-- 
Yours,

Andrei

=====
Mail address in header catches spam. Real contact info (decode with rot13):
cebwrpg5 at bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur 
yvfg, fb gurer'f ab arrq gb PP.





More information about the Tutor mailing list