Rotating arbitrary sets of elements within a list

phil_nospam_schmidt at yahoo.com phil_nospam_schmidt at yahoo.com
Fri Apr 8 11:50:20 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.



Ok, here's what I've got. It seems to work right, but can it be
improved upon?

def list_rotate(A, I, direction=1):
    A1 = [A[i] for i in I]
    A2 = [A[i] for i in range(len(A)) if i not in I]
    if direction:
        I1 = [(i-1)%len(A) for i in I]     # rotate left
    else:
        I1 = [(i+1)%len(A) for i in I]     # rotate right
    I2 = [i for i in range(len(A)) if i not in I1]
    for i in range(len(I1)): A[I1[i]] = A1[i]
    for i in range(len(I2)): A[I2[i]] = A2[i]




More information about the Python-list mailing list