了解循环旋转的挑战?

问题描述 投票:0回答:7

首先我想感谢您的帮助。

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

例如,给定

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

该函数应返回 [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 的前面。

因此,任何帮助或指出正确方向都会有所帮助,再次感谢您。

python rotation programming-languages cyclic
7个回答
2
投票

您只需使用此代码即可完成。

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

您可以在此处查看更多方法。 在Python中旋转列表的有效方法


1
投票

所以我意识到我只需要循环 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

0
投票

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

from collections import deque
def solution(A, K):
    m=deque(A)
    m.rotate(K)
    return list(m)

0
投票
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

0
投票
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

0
投票

我认为我找到的解决方案似乎更像是干净的代码

def solution(A, K):

        n = len(A)`enter code here`
        K = K % n # Ensure K is within the range of array size 
        rotated_arr = A[K:] + A[:K] # Rotating from end to the starting
        return rotated_arr
    A = [1, 2, 3, 4]
    K = int(input())
    rotated_arr = solution(A, K)
    print(rotated_arr)

0
投票

我使用列表理解的解决方案:

def solution(A, K):
    n = len(A)
    return [A[(i-K)%n] for i,_ in enumerate(A)]
© www.soinside.com 2019 - 2024. All rights reserved.