我写了一个代码,用户输入一个代码,程序会按所需的量旋转它,但每次都会旋转两个而不是一个。 例如,1 2 3 4 5 旋转一将变为 4 5 1 2 3 我的代码是:
arSize = int(input("Please enter the size of the list "))
arr = []
d = int(input("How many times do you want to rotate it to the right? :"))
for i in range(0, arSize) :
number = int(input("Please enter array[" + str(i) + "] value: "))
arr.append(number)
n = arSize
def rightRotate(arr, d, n):
for i in range(d):
rightRotatebyTwo(arr, n)
def rightRotatebyTwo(arr, n):
temp = arr[0]
temp1 = arr[1]
arr[1] = arr[n-1]
arr[0] = arr[n-2]
for i in range(2, n-1):
temp2 = arr[i]
temp3 = arr[i+1]
arr[i] = temp
arr[i+1] = temp1
temp = temp1
temp1 = temp2
def printArray(arr, size):
for i in range(size):
print (arr[i])
rightRotate(arr, d, n)
printArray(arr, n)
结果如下:
Please enter the size of the list 6
How many times do you want to rotate it to the right? :1
Please enter array[0] value: 1
Please enter array[1] value: 2
Please enter array[2] value: 3
Please enter array[3] value: 4
Please enter array[4] value: 5
Please enter array[5] value: 6
5
6
1
2
3
2
你的方法有点太复杂了。您应该尝试不同的方法。
例如: 一个简单的切片操作在这里就可以了。
def rotateRight(no_of_rotations):
arr = [1, 2, 3, 4, 5]
arr = arr[no_of_rotations:] + arr[:no_of_rotations]
return arr
万事如意!:)