Efficient way to rotate a list in python

后端 未结 26 1203
一生所求
一生所求 2020-11-22 03:14

What is the most efficient way to rotate a list in python? Right now I have something like this:

>>> def rotate(l, n):
...     return l[n:] + l[:n]         


        
26条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 04:00

    The following method is O(n) in place with constant auxiliary memory:

    def rotate(arr, shift):
      pivot = shift % len(arr)
      dst = 0
      src = pivot
      while (dst != src):
        arr[dst], arr[src] = arr[src], arr[dst]
        dst += 1
        src += 1
        if src == len(arr):
          src = pivot
        elif dst == pivot:
          pivot = src
    

    Note that in python, this approach is horribly inefficient compared to others as it can't take advantage of native implementations of any of the pieces.

提交回复
热议问题