了解循环旋转可塑性挑战?

understanding the cyclic rotation codility challenge?

首先我要说谢谢你的帮助。

我正在解决循环旋转问题,您必须将 list/array 的内容向右移动并有效地环绕元素,例如:

例如给定

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

函数应该 return [9, 7, 6, 3, 8]。进行了三轮旋转:

 [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] 

我的代码如下:

def solution(A, K):
    new_list = []
    first_index = 0
    for i in range(0, K):
        for num in range(0, len(A) - 1):
            new_list.insert(0, A.pop())
            print('new list {}'.format(new_list))
            print('old list {}'.format(A))
            if len(new_list) == 3:
                new_list.insert(len(new_list), A.pop(first_index))
                print(new_list)

经过 3 次旋转后,我得到的列表为 A = [8, 9, 7, 6, 3] 所以对我来说,它似乎将 A 中的最后一个元素放在 new_list 的前面。

所以任何帮助或正确方向的观点都会有所帮助,再次感谢。

你可以简单地用这段代码来完成。

def solution(A, K):
    K = K % len(A)
    return A[-K:] + A[:-K]

您可以在此处查看更多执行此操作的方法。 Efficient way to rotate a list in python

所以我意识到我只需要循环 K 次并检查一个空列表。而我最后得到的是:

def solution(A, K):
    for i in range(0, K): # will perform K iterations of the below code
        if A == []: # check if list is empty
            return A # return A if A is the empty list
        A.insert(0, A.pop()) # inserts at the first index of A the last element of A
    return A # will return the list A

另一个使用集合模块中的双端队列的解决方案。它有一个内置的旋转功能。

from collections import deque
def solution(A, K):
    m=deque(A)
    m.rotate(K)
    return list(m)
def slice(A):
    B = []
    for i  in range(0,len(A)) :
        B.append(A[-1+i])
    return B 

def solution(A, K):
    for i in range (1,K+1):
        A = slice(A)
    return A
def solution(A,K):        
    for k in np.arange(K):
        B=[]
        for i in range(len(A)):
            B.append(A[i-1])
        A=B
    return B