【发布时间】:2020-09-29 12:45:54
【问题描述】:
为左数组旋转编写了一个简单的代码,得到相同的数组而没有对它进行任何旋转作为错误的输出。
def leftRotate(arr, d, n):
while (d-1) > 0:
leftRotatebyOne(arr, n)
def leftRotatebyOne(arr, n):
temp = arr[0]
for i in range(n-1):
arr[i] = arr[i + 1]
arr[n - 1] = temp
def PrintArray(arr, size):
for i in range(size):
print("%d" % arr[i], end=" ")
arr = []
l = int(input("Enter the number of elements: "))
for i in range(0, l):
ele = int(input())
arr.append(ele)
d = int(input("Enter the number of rotations: "))
n = len(arr)
leftRotate(arr, d, n)
PrintArray(arr, n)
这是我得到的输出示例,
Enter the number of elements: 3
1
2
3
Enter the number of rotations: 1
1 2 3
我预计旋转一圈后的输出为 2 3 1。
【问题讨论】:
-
您没有更新
leftRotate()中的d值,因此d = 1将变为(1-1) > 0
标签: python arrays python-3.x output