Program to reverse an array up to a given position in Python

PythonServer Side ProgrammingProgramming

In this tutorial, we will learn how to reverse an array upto a given position. Let's see the problem statement.

We have an array of integers and a number n. Our goal is to reverse the elements of the array from the 0th index to (n-1)th index. For example,

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

Procedure to achieve the goal.

  •  Initialize an array and a number
  •  Loop until n / 2.
    •  Swap the (i)th index and (n-i-1)th elements.
  • Print the array you will get the result.

Example

## 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)

If you run the above program, you will get the following results.

Output

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

A simple way to do this is to use the slicing in Python.

  • 1. Initialize an array and a number
  • 2. Slice from (n-1) to 0 and n to length(Add both of them).

Let's see the code.

Example

## 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)

If you run the above program, you will get the following result.

Output

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

If you have any doubts regarding the program, please do mention them in the comment section.

raja
Published on 27-Aug-2019 13:02:36
Advertisements