Efficient way to rotate a list in python

后端 未结 26 1601
一生所求
一生所求 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 03:37

    def solution(A, K):
        if len(A) == 0:
            return A
    
        K = K % len(A)
    
        return A[-K:] + A[:-K]
    
    # use case
    A = [1, 2, 3, 4, 5, 6]
    K = 3
    print(solution(A, K))
    

    For example, given

    A = [3, 8, 9, 7, 6]
    K = 3
    

    the function should return [9, 7, 6, 3, 8]. Three rotations were made:

    [3, 8, 9, 7, 6] -> [6, 3, 8, 9, 7]
    [6, 3, 8, 9, 7] -> [7, 6, 3, 8, 9]
    [7, 6, 3, 8, 9] -> [9, 7, 6, 3, 8]
    

    For another example, given

    A = [0, 0, 0]
    K = 1
    

    the function should return [0, 0, 0]

    Given

    A = [1, 2, 3, 4]
    K = 4
    

    the function should return [1, 2, 3, 4]

提交回复
热议问题