将数组向左旋转k个单元格python



我想写一个名为rotateLeft(source,k(的函数将源数组的所有元素向左旋转'k'位置。

我的代码:

def shiftLeft(source, k):
lenth = len(source)
i = 0
while(i < (lenth - k)):
source[i] = source[i+k]
source[i+k] = source[i]
i += 1
source=[10,20,30,40,50,60]
a = shiftLeft(source, 3)
print(source)

预期输出:[ 40, 50, 60, 10, 20, 30]

移位似乎意味着切掉左侧并将其连接到右侧。这是一种在区块中更有效的操作。

一种在不改变原始列表的情况下创建新列表的解决方案:

def shift_left(a, k):
return a[k:] + a[:k]

要修改原来的位置,只需将结果重新分配回列表:

def shift_left(a, k):
a[:] = a[k:] + a[:k]

请注意,如果传入负k,则此值将正确右移。

每次尝试从source数组中移动连续项时,都会用第二个source[i+k]覆盖第一个项source[i],而不首先保存source[i]中的值。

解决方案:

def shiftLeft(source, k):
length = len(source)
i = 0

while(i < (length - k)):
start = source[i]
source[i] = source[i+k]
source[i+k] = start
i += 1
source=[10,20,30,40,50,60]
a = shiftLeft(source, 2)
print(source)

您可以考虑使用deque

from collections import deque
source = deque([10, 20, 30, 40, 50, 60])
k = 3
source.rotate(-k)  # in place rotation
print(source)

deque的限制

对元素的随机访问不是O(1),也就是说,如果用例需要,避免调用source[i]

根据参数的符号,可以使用生成器方法向左或向右旋转。

方法如下:

def rotate(lst, n):
size = len(lst)
n = n-(n//size * size)
for idx in range(size):
ptr = idx+n
if ptr >= size:
ptr -= size
yield lst[ptr]

给定一个列表lst = ['a', 'b', 'c', 'd'],您可以通过以下方式使用它:

list(rotate(lst, 1))
#=> ['b', 'c', 'd', 'a']

list(rotate(lst, -1))
#=> ['d', 'a', 'b', 'c']

您也可以使用大于列表长度的值:

list(rotate(lst, 5))
#=> ['b', 'c', 'd', 'a']

最新更新