gpt4 book ai didi

python - 我尝试使用 Python 将列表每次旋转两次

转载 作者:行者123 更新时间:2023-12-01 06:37:34 24 4
gpt4 key购买 nike

我编写了一个代码,其中用户输入一个代码,程序将其旋转所需的量,但每次它旋转两次而不是一次。例如。 1 2 3 4 5 旋转 1 就变成 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

祝一切顺利! :)

关于python - 我尝试使用 Python 将列表每次旋转两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59599588/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com