了解循环旋转编码挑战?

我想先说谢谢你的帮助。

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

例如,给定

cursor.currentTable().insertRows(cursor.currentTable().cellAt(cursor).row()+1,1)

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

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

我的代码如下:

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

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

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

wsf945162 回答:了解循环旋转编码挑战?

您只需使用此代码即可。

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
本文链接:https://www.f2er.com/1097166.html

大家都在问