Array Rotation in Python Programming Language

 

 

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]

 

Leave a Reply

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