在此 Python 程序中,我们需要将数组向右旋转。数组是存储在连续内存位置的相同数据类型元素的集合。我们必须将每个元素向右移动 n 次,其中 n 由用户给定。
例如,考虑一个有 5 个元素的数组 A:A = [1, 2, 3, 4, 5]。假设 n 的值为 2,那么我们必须 向右移动 2 次。
因此,将此逻辑应用于 Python 程序,我们使用 Python 中的嵌套 for loop。一个外部 for loop,它从零循环到 n 的值,并将变量 last 赋值为数组的最后一个元素。外部 for loop 继续执行,直到用户想要向右旋转元素的次数。现在我们使用反向的内部 for loop,这意味着,从数组的最后一个元素减一到零,每次递减一,并应用 array[j] = array[j-1]。最后,我们将 last 中的值作为第一个元素附加。
步骤 1: 初始化一个包含一些预定义值的数组。
步骤 2: 将值添加到 n,以确定我们需要将数组元素向右移动多少次。
步骤 3: 使用 Python 编程语言中的 for loop 和 print 语句显示原始数组。
步骤 4: 添加外部 for loop,从 零 到 n,并使用数组最后一个元素的值赋值给变量 last。
步骤 5: 使用内部 for loop,从数组末尾减一到零,每次递减一。
步骤 6: 赋值 array[j] = arr[j-1] 的值,并从变量 last 中附加第一个元素。
步骤 7: 使用 Python 中的 for loop 显示右移后的数组。
要在 Python 中旋转数组元素,我们需要使用以下概念,我们建议学习这些概念以便更好地理解。
arr = [1, 2, 3, 4, 5];
n = 3; # value of how many times the array should be right shifted
print("Original array: "); # display the real array
for i in range(0, len(arr)):
print(arr[i])
for i in range(0, n):
last = arr[len(arr)-1]; # add the last element of array to a variable
for j in range(len(arr)-1, -1, -1):
arr[j] = arr[j-1]; # use the for loop and assign the value array[j] = array[j-1]
arr[0] = last; # append the first element of array from the variable
print("\nArray after right rotation: "); # print array after rotation
for i in range(0, len(arr)):
print(arr[i])
Original array: 1 2 3 4 5 Array after right rotation: 3 4 5 1 2