5 Best Ways to Right Rotate the Elements of an Array in Python

Rate this post

πŸ’‘ Problem Formulation: Right rotating an array involves shifting each element of an array to its right for a specified number of times. For instance, if we have an input array [1, 2, 3, 4, 5] and we want to right rotate it by 2 positions, the output should be [4, 5, 1, 2, 3]. This article explores five different methods to achieve this in Python.

Method 1: Using a Loop to Manually Rotate

This method entails manually moving the elements using a loop. We shift elements to their right position and handle the wrap-around by reinserting the moving elements at the beginning of the array.

Here’s an example:

def right_rotate_loop(arr, n):
    length = len(arr)
    for i in range(n):
        last_element = arr.pop()
        arr.insert(0, last_element)
    return arr
example_array = [1, 2, 3, 4, 5]
rotations = 2
print(right_rotate_loop(example_array, rotations))

Output:

[4, 5, 1, 2, 3]

In the given code snippet, the right_rotate_loop() function takes an array and the number of rotations. It then uses a for-loop to move the last element to the first position, mimicking a right rotation effect.

Method 2: Slicing the Array

This method uses Python’s slicing feature to rotate the array. It slices the array into two parts and then joins them in the opposite order to achieve the desired rotation.

Here’s an example:

def right_rotate_slice(arr, n):
    length = len(arr)
    n = n % length
    return arr[-n:] + arr[:-n]
example_array = [1, 2, 3, 4, 5]
rotations = 2
print(right_rotate_slice(example_array, rotations))

Output:

[4, 5, 1, 2, 3]

The right_rotate_slice() function takes an array and the number of rotations, uses the mod operator to normalize rotations beyond the array length, and performs the slice operation to rotate the array.

Method 3: Using Collections Module

The collections module’s built-in deque object provides a straightforward way to rotate elements with its rotate() method. This method efficiently rotates large arrays.

Here’s an example:

from collections import deque
def right_rotate_deque(arr, n):
    d = deque(arr)
    d.rotate(n)
    return list(d)
example_array = [1, 2, 3, 4, 5]
rotations = 2
print(right_rotate_deque(example_array, rotations))

Output:

[4, 5, 1, 2, 3]

The example uses the deque data structure and its rotate() method. It first converts the array into a deque, performs the rotation, and then converts it back to a list.

Method 4: Using NumPy Library

For those working with numerical data in Python, NumPy provides a concise method to rotate arrays using the roll() function.

Here’s an example:

import numpy as np
def right_rotate_numpy(arr, n):
    return np.roll(arr, n)
example_array = np.array([1, 2, 3, 4, 5])
rotations = 2
print(right_rotate_numpy(example_array, rotations))

Output:

[4 5 1 2 3]

The function right_rotate_numpy() uses NumPy’s roll() method to perform the rotation. It’s an efficient solution for large arrays and is highly optimized for numerical operations.

Bonus One-Liner Method 5: List Comprehension

This concise one-liner uses list comprehension and modular arithmetic to rotate the array right, suitable for small arrays or simple scripts.

Here’s an example:

example_array = [1, 2, 3, 4, 5]
rotations = 2
print([(example_array[(i - rotations) % len(example_array)]) for i in range(len(example_array))])

Output:

[4, 5, 1, 2, 3]

This one-liner creates a new list with elements accessed using indices that are adjusted according to the number of rotations and the length of the array.

Summary/Discussion

  • Method 1: Using a Loop to Manually Rotate. Strengths: Easy to understand. Weaknesses: May not be efficient for large arrays or multiple rotations.
  • Method 2: Slicing the Array. Strengths: Pythonic and concise. Weaknesses: Requires additional memory for the result array.
  • Method 3: Using Collections Module. Strengths: Efficient for large arrays. Weaknesses: Depends on an external module.
  • Method 4: Using NumPy Library. Strengths: Highly optimized for numerical computations. Weaknesses: Overhead for small arrays and dependency on NumPy.
  • Method 5: List Comprehension. Strengths: Concise one-liner. Weaknesses: May be harder to read for those unfamiliar with list comprehensions.