Generating circular shifts / reduced Latin Squares in Python

前端 未结 7 1270
旧时难觅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 19:56

    For the first part, the most concise way probably is

    a = [1, 2, 3, 4]
    n = len(a)
    [[a[i - j] for i in range(n)] for j in range(n)]
    # [[1, 2, 3, 4], [4, 1, 2, 3], [3, 4, 1, 2], [2, 3, 4, 1]]
    

    and for the second part

    [[a[i - j] for i in range(n)] for j in range(n, 0, -1)]
    # [[1, 2, 3, 4], [2, 3, 4, 1], [3, 4, 1, 2], [4, 1, 2, 3]]
    

    These should also be much more efficient than your code, though I did not do any timings.

提交回复
热议问题