Generating circular shifts / reduced Latin Squares in Python

前端 未结 7 1274
旧时难觅i
旧时难觅i 2020-12-31 19:38

Was just wondering what\'s the most efficient way of generating all the circular shifts of a list in Python. In either direction. For example, given a list [1, 2, 3, 4

7条回答
  •  醉酒成梦
    2020-12-31 20:09

    You can use collections.deque:

    from collections import deque
    
    g = deque([1, 2, 3, 4])
    
    for i in range(len(g)):
        print list(g) #or do anything with permutation
        g.rotate(1) #for right rotation
        #or g.rotate(-1) for left rotation
    

    It prints:

     [1, 2, 3, 4]
     [4, 1, 2, 3]
     [3, 4, 1, 2]
     [2, 3, 4, 1]
    

    To change it for left rotation just replace g.rotate(1) with g.rotate(-1).

提交回复
热议问题