Rotating arbitrary sets of elements within a list

wes weston wweston at att.net
Fri Apr 8 16:19:14 EDT 2005


phil_nospam_schmidt at yahoo.com wrote:
> I'm trying to come up with a good algorithm to do the following:
> 
> Given a list 'A' to be operated on, and a list 'I' of indices into 'A',
> rotate the i'th elements of 'A' left or right by one position.
> 
> Here's are some examples:
> 
> A = [a, b, c, d, e, f]
> I = [0, 3, 4]
> 
> rotate(A, I, 'left') --> [b, c, d, e, f, a]
> rotate(A, I, 'right') --> [b, a, c, f, d, e]
> 
> I = [1, 3, 4]
> 
> rotate(A, I, 'left') --> [b, a, d, e, c, f]
> rotate(A, I, 'right') --> [a, c, b, f, d, e]
> 
> Any ideas?
> 


class CBuf:
     def __init__(self,list=[]):
         self.List = list
         self.Front = 0
     def ActualIndexGet(self,index):
         return (self.Front + index) % len(self.List)
     def ValueGet(self,index):
         return self.List[self.ActualIndexGet(index)]
     def Rotate(self,dir):
         if dir == 'L':
             self.Front += 1
         else:
             self.Front -= 1
         self.Front = self.Front % len(self.List)
     def Show(self):
         i = self.Front
         while 1:
             print self.List[i]," ",
             i = (i+1) % len(self.List)
             if i == self.Front:
                 break
         print


b = CBuf(['a','b','c','d','e','f'])
b.Show()
b.Rotate('L')
b.Show()
b.Rotate('L')
b.Show()


 >>> ================================ RESTART ================================
 >>>
a   b   c   d   e   f
b   c   d   e   f   a
c   d   e   f   a   b
 >>>




More information about the Python-list mailing list