Python program that uses the deque
class from the collections
module to left rotate the elements of an array:
from collections import deque
def left_rotate(arr, n):
# Create a deque from the array
d = deque(arr)
# Rotate the deque to the left
d.rotate(-n)
# Convert the deque back to a list
return list(d)
# Example usage
arr = [1, 2, 3, 4, 5]
n = 2
print(left_rotate(arr, n))
The function left_rotate(arr, n)
takes an array arr
and an integer n
as arguments. It first creates a deque object d
from the array arr
using the deque()
constructor from the collections
module. Then, it uses the rotate()
method to rotate the deque to the left by n
positions. The rotate()
method takes an integer as an argument, a positive value rotates the elements to the right and a negative value rotates the elements to the left. Finally, it converts the deque back to a list and returns it.
The example usage creates an array arr
and an integer n
and calls the left_rotate()
function to left rotate the elements of the array arr
by n
positions, and then it prints the resulting list.
You could also use slice notation with concatenation to left rotate the elements of an array.
def left_rotate(arr, n):
return arr[n:] + arr[:n]
This method uses slice notation