在大小的数组上的左旋转操作将每个阵列的元素1单元向左移位。例如,如果在数组[1,2,3,4,5]上执行了2次左旋转,则数组将变为[3,4,5,1,2]。
给定一个整数数组和一个数字,在数组上执行左旋转。然后将更新的数组打印为单行空格分隔的整数。
样本输入:5,4 1 2 3 4 5样品输出:5 1 2 3 4我的输出为:2 2 3 4 1
#!/bin/python3
import sys
def leftRotation(a, d):
#Main Logic here
length=len(a)
for j in range(0,d):
for i in range(0,length):
temp=a[0]
a[i]=a[i+1]
a[length-1]=temp
return a
return a
return a
if __name__ == "__main__":
n, d = input().strip().split(' ')
n, d = [int(n), int(d)]
a = list(map(int, input().strip().split(' ')))
result = leftRotation(a, d)
print (" ".join(map(str, result)))
1)返回将停止执行代码,因此代码只会在返回之前循环一次。
2)这些行包含逻辑错误:
temp=a[0]
a[i]=a[i+1]
a[length-1]=temp
要进行左旋转,我们将最后一个值插入第一个位置。你的问题是你在循环内部而不是外部分配temp = a[0]
。您还要重新分配循环中的最后一个值。
修复了所有错误:
def leftRotation(a, d):
#Main Logic here
length=len(a)
for j in range(0,d):
temp=a[0]
for i in range(0,length - 1):
a[i]=a[i+1]
a[length-1]=temp
return a
给你正确的答案。
(P.S.使用标准的list方法有一种更简单的左旋转方式:a.append(a.pop(0))
。)
Rassar已经涵盖了代码的问题,我只想使用答案中提到的list
方法添加更好的解决方案:
def left_rotation(l, offset):
offset %= len(l)
return l[offset:] + l[:offset]
result = left_rotation([1, 2, 3, 4, 5], 12)
print(" ".join(str(item) for item in result)) # 3 4 5 1 2
其他人已经在您的代码中指出了问题,您也可以使用collections.deque
尝试此解决方案:
from collections import deque
def left_rotation(lst, n):
queue = deque(lst)
removed = [queue.popleft() for i in range(n)]
return list(queue) + removed
print(" ".join(map(str, left_rotation([1,2,3,4,5], 2))))
哪些输出:
3 4 5 1 2
注意:popleft()
在这里是O(1)
,这比pop(0)
更有效率,这是O(n)
。
def leftRotation(a, d):
#Main Logic here
length=len(a)
for j in range(0,d):
temp=a[0]
for i in range(0,length):
a[i]=a[i+1] # a[i](i == 0) & a[i+1](i == 1) will have same values
a[length-1]=temp
return a #Because your program is ending here
IndexError
,因为您正在运行循环(0,长度),当您的i = length-1 => i + 1 = length并且在列表中我们仅将“零”索引为“length” -1“在列表中现在解决了这两个问题之后,这可能会起作用: -
def leftRotation(a, d):
#Main Logic here
length=len(a)
for j in range(0,d):
temp=a[0]
for i in range(0,length-1):
a[i]=a[i+1]
a[length-1]=temp
return a
使用列表切片更好的答案: - 。
function rotate_list(a,d):
return a[d:] + a[d:]