[Tutor] rotating a list
kevin parks
kp8 at mac.com
Sat Sep 20 00:21:49 EDT 2003
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?
cheers,
-kp--
--^----------------------------------------
kevin parks
university of virginia
k p p 9 c @ virginia . edu
PS. If my man Danny is out there... 'Hi'
P.P.S if there are any pythonistas out here at UVa, i'd love to hear
from
you. i am new here.
import sys
import random
# 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]
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)):
y = rotate(x)
print y
if __name__ == "__main__":
test()
output is something like:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
[2, 5, 4, 10, 11, 6, 0, 3, 9, 7, 1, 8]
[5, 4, 10, 11, 6, 0, 3, 9, 7, 1, 8, 2]
[5, 4, 10, 11, 6, 0, 3, 9, 7, 1, 8, 2]
[5, 4, 10, 11, 6, 0, 3, 9, 7, 1, 8, 2]
[5, 4, 10, 11, 6, 0, 3, 9, 7, 1, 8, 2]
[5, 4, 10, 11, 6, 0, 3, 9, 7, 1, 8, 2]
[5, 4, 10, 11, 6, 0, 3, 9, 7, 1, 8, 2]
[5, 4, 10, 11, 6, 0, 3, 9, 7, 1, 8, 2]
[5, 4, 10, 11, 6, 0, 3, 9, 7, 1, 8, 2]
[5, 4, 10, 11, 6, 0, 3, 9, 7, 1, 8, 2]
[5, 4, 10, 11, 6, 0, 3, 9, 7, 1, 8, 2]
[5, 4, 10, 11, 6, 0, 3, 9, 7, 1, 8, 2]
[5, 4, 10, 11, 6, 0, 3, 9, 7, 1, 8, 2]
--[End of dumb question]---
More information about the Tutor
mailing list