[Tutor] rotating a list
Bob Gailer
bgailer at alum.rpi.edu
Sat Sep 20 13:53:30 EDT 2003
At 10:21 PM 9/19/2003, 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?
>
>
>
>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]
Exactly what I'd expect. Why did you think you'd get a different result? Do
you suppose you were thinking that n would have a different value for each
pass thru the loop? Yet you are not passing a 2nd parameter in the function
call, so n always takes its default value of 1.
Bob Gailer
bgailer at alum.rpi.edu
303 442 2625
-------------- next part --------------
---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.506 / Virus Database: 303 - Release Date: 8/1/2003
More information about the Tutor
mailing list