[Tutor] cyclically rotate a seq

kevin parks kp8 at mac.com
Fri Mar 11 06:43:59 CET 2005

Hi folks,

I am trying to cyclically rotate a seq until it reached the beginning 
stage again.
I would like to be able to rotate in both directions and using any 
arbitrary interval.
I think that I have this correct, but would be happy for someone to 
check it and also
i am interested in any improvements or enhancements. It is important 
that this
work correctly or the whole rest of my code will be in barf *^-^* hee 
hee. So
any help would be appreciated.

#!/usr/bin/env python

import sys
import random

# cyclically rotate a sequence
# -- --------------------------------------------------------
# should work on any sequence type
# should work with any hop(n) interval
# should also work in both directions (left or right)
# -- --------------------------------------------------------

def rotate(seq, n=1):
	if len(seq) == 0:
		return seq
	# Normalize n, using modulo - even works for negative n
	n = n % len(seq)
	return seq[n:] + seq[:n]

def test():
     start = 1
     x = [7, 2, 1, 0, 11, 6, 5, 4]
     print; print x; print '--' * 8
     for i in range(len(x)):
		out = rotate(x, start)
		print out
		start = start + 1

if __name__ == "__main__":

# -------- EOF --------

More information about the Tutor mailing list