Array Rotation in Python

This document explains how to rotate an array by k positions using Python. Array rotation means shifting the elements of the array to the right by a specified number of positions. The elements that fall off the end are wrapped around to the beginning of the array.

Python Program


def rotate_array(arr, k):
"""
Rotates an array by k positions.

Parameters:
arr (list): The array to be rotated.
k (int): The number of positions to rotate the array.

Returns:
list: The rotated array.
“””
n = len(arr)
k = k % n # Handle cases where k is greater than the length of the array
return arr[-k:] + arr[:-k]

# Example usage
if __name__ == “__main__”:
array = [1, 2, 3, 4, 5, 6, 7]
k = 3
rotated_array = rotate_array(array, k)
print(“Original array:”, array)
print(“Rotated array:”, rotated_array)

Explanation

Here is a step-by-step explanation of the program:

  1. Function Definition:
    def rotate_array(arr, k):
        """
        Rotates an array by k positions.
        
        Parameters:
        arr (list): The array to be rotated.
        k (int): The number of positions to rotate the array.
        
        Returns:
        list: The rotated array.
        """
        n = len(arr)
        k = k % n  # Handle cases where k is greater than the length of the array
        return arr[-k:] + arr[:-k]
    

    This function rotate_array takes two arguments: arr (the array to be rotated) and k (the number of positions to rotate the array). It returns the rotated array.

  2. Calculate the Effective Rotation:
    k = k % n  # Handle cases where k is greater than the length of the array

    This line ensures that if k is greater than the length of the array n, we only rotate by the remainder when k is divided by n. This is because rotating an array by its length results in the same array.

  3. Return the Rotated Array:
    return arr[-k:] + arr[:-k]

    This line uses Python’s slicing feature to rotate the array. arr[-k:] gets the last k elements of the array, and arr[:-k] gets the elements from the start up to the n-k position. Concatenating these two slices results in the rotated array.

Example Usage

The example usage demonstrates how to use the rotate_array function:

if __name__ == "__main__":
    array = [1, 2, 3, 4, 5, 6, 7]
    k = 3
    rotated_array = rotate_array(array, k)
    print("Original array:", array)
    print("Rotated array:", rotated_array)

When you run this code, it will output:

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

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)