Python Program for Array Rotation

1. Introduction

Array rotation involves moving the elements of an array in a specific direction (left or right) by a certain number of steps. For instance, a left rotation of 2 positions on the array [1, 2, 3, 4, 5] results in [3, 4, 5, 1, 2]. This concept is widely used in algorithms, problem-solving, and data structure manipulation, offering a practical way to understand array indexing and operations. This blog post will explain how to perform an array rotation in Python, focusing on a simple method to rotate an array to the left.

2. Program Steps

1. Define the original array and the number of positions by which it should be rotated.

2. Perform the rotation by slicing the array into two parts and rearranging them.

3. Display the original array and the rotated array.

3. Code Program

# Step 1: Define the array and the number of positions to rotate
original_array = [1, 2, 3, 4, 5]
num_positions = 2

# Display the original array
print("Original array:")
print(original_array)

# Step 2: Rotate the array
# Slicing the array into two parts and concatenating them in reverse order
rotated_array = original_array[num_positions:] + original_array[:num_positions]

# Step 3: Display the rotated array
print("Rotated array:")
print(rotated_array)

Output:

Original array:
[1, 2, 3, 4, 5]
Rotated array:
[3, 4, 5, 1, 2]

Explanation:

1. The program initializes an array and specifies the number of positions (num_positions) for the left rotation. In this example, the array is [1, 2, 3, 4, 5], and we rotate it by 2 positions to the left.

2. To perform the rotation, the array is sliced into two parts at the index corresponding to num_positions. The first slice contains the elements to be moved to the end of the array, and the second slice contains the elements that will now start the array. These slices are then concatenated in reverse order to achieve the rotation.

3. The original array is displayed for reference, followed by the rotated array, which demonstrates the effect of the left rotation operation. This method is efficient and takes advantage of Python's powerful slicing capabilities to manipulate arrays easily.

Comments