程序将数组反转到Python中的给定位置

在本教程中,我们将学习如何将数组反转到给定位置。让我们看看问题陈述。

我们有一个整数数组和一个数字n。我们的目标是将数组的元素从第0个索引反转到第(n-1)个索引。例如,

Input
array = [1, 2, 3, 4, 5, 6, 7, 8, 9] n = 5
Output
[5, 4, 3, 2, 1, 6, 7, 8, 9]

实现目标的程序。

  •  初始化数组和数字

  •  循环直到n / 2。

    •  交换第 (i)个 索引和第(ni-1)个元素。

  • 打印数组,您将获得结果。

示例

## initializing array and a number
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
n = 5
## checking whether the n value is less than length of the array or not
if n > len(arr):
   print(f"{n} value is not valid")
else:
   ## loop until n / 2
   for i in range(n // 2):
      arr[i], arr[n - i - 1] = arr[n - i - 1], arr[i]
   ## printing the array
   print(arr)

如果运行上面的程序,您将得到以下结果。

输出结果

[5, 4, 3, 2, 1, 6, 7, 8, 9]

一种简单的方法是在Python中使用切片。

  • 1.初始化数组和数字

  • 2.将(n-1)切片为0,将 n切片为长度(将它们两个都相加)。

让我们看一下代码。

示例

## initializing array and a number
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
n = 5
## checking whether the n value is less than length of the array or not
if n > len(arr):
   print(f"{n} value is not valid")
else:
   ## reversing the arr upto n
   ## [n-1::-1] n - 0 -1 is for decrementing the index
   ## [n:] from n - length
   arr = arr[n-1::-1] + arr[n:]
   ## printing the arr
   print(arr)

如果运行上述程序,将得到以下结果。

输出结果

[5, 4, 3, 2, 1, 6, 7, 8, 9]

如果您对该程序有任何疑问,请在评论部分中提及它们。