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:
- 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) andk
(the number of positions to rotate the array). It returns the rotated array. - 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 arrayn
, we only rotate by the remainder whenk
is divided byn
. This is because rotating an array by its length results in the same array. - Return the Rotated Array:
return arr[-k:] + arr[:-k]
This line uses Python’s slicing feature to rotate the array.
arr[-k:]
gets the lastk
elements of the array, andarr[:-k]
gets the elements from the start up to then-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]