Rotation of Elements of Array - Left and Right in Python
Understanding Array Rotation
Array rotation involves shifting elements either to the left or right by a specified number of positions.
We will explore three different methods to perform left and right rotation in Python.
Method 1: Using Slicing
def left_rotate(arr, d):
return arr[d:] + arr[:d]
def right_rotate(arr, d):
return arr[-d:] + arr[:-d]
def print_array(arr):
print(" ".join(map(str, arr)))
arr = [1, 2, 3, 4, 5]
arr = left_rotate(arr, 2)
print("Array after left rotation:")
print_array(arr)
arr = right_rotate(arr, 2)
print("Array after right rotation:")
print_array(arr)
Output:
Array after left rotation:
3 4 5 1 2
Array after right rotation:
1 2 3 4 5
Method 2: Using Reverse Algorithm
def reverse(arr, start, end):
while start < end:
arr[start], arr[end] = arr[end], arr[start]
start += 1
end -= 1
def left_rotate(arr, d):
n = len(arr)
reverse(arr, 0, d - 1)
reverse(arr, d, n - 1)
reverse(arr, 0, n - 1)
def right_rotate(arr, d):
n = len(arr)
reverse(arr, 0, n - 1)
reverse(arr, 0, d - 1)
reverse(arr, d, n - 1)
def print_array(arr):
print(" ".join(map(str, arr)))
arr = [1, 2, 3, 4, 5]
left_rotate(arr, 2)
print("Array after left rotation:")
print_array(arr)
right_rotate(arr, 2)
print("Array after right rotation:")
print_array(arr)
Output:
Array after left rotation:
3 4 5 1 2
Array after right rotation:
1 2 3 4 5
Method 3: Rotating One by One
def left_rotate_one(arr):
arr.append(arr.pop(0))
def right_rotate_one(arr):
arr.insert(0, arr.pop())
def left_rotate(arr, d):
for _ in range(d):
left_rotate_one(arr)
def right_rotate(arr, d):
for _ in range(d):
right_rotate_one(arr)
def print_array(arr):
print(" ".join(map(str, arr)))
arr = [1, 2, 3, 4, 5]
left_rotate(arr, 2)
print("Array after left rotation:")
print_array(arr)
right_rotate(arr, 2)
print("Array after right rotation:")
print_array(arr)
Output:
Array after left rotation:
3 4 5 1 2
Array after right rotation:
1 2 3 4 5