【问题标题】:understanding the cyclic rotation codility challenge?了解循环旋转代码挑战?
【发布时间】:2021-04-20 20:28:56
【问题描述】:

我想先说谢谢你的帮助。

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

例如,给定

 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


    【解决方案1】:

    您只需使用此代码即可。

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

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:

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

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

        【讨论】: