What does the Right Shift Mean?
* If every element of the list is moved to its right by one position, it is called right shifting.
Example :
Consider the following list [1,2,3,4,5] After Right shifting the list by one position the list will be [5,1,2,3,4] Here all the list items are moved to right by one position.
Approach 1 to Right Shift the list:
We know that while right-shifting the current element takes the position of the following element
example in the list [1,2,3,4,5] when right shifted it becomes [5,1,2,3,4]. In the Original list, the position of 1 is 0, after right shifting the position changed to 1.
Using an iterative approach we can right-shift the list.
While right Shifting the last element of the list will become the first element.
#Initialize array lst = [1, 2, 3, 4, 5]; #Displays original array print("Original list: " ,lst); #Stores the last element of array last = lst[len(lst)-1]; for i in range(len(lst)-1, -1, -1): #Shift element of array by one lst[i] = lst[i-1]; #Last element of the array will be added to the start of the array. lst[0] = last; #Displays resulting array after rotation print("list after right rotation: ",lst);
Output : Original list: [1, 2, 3, 4, 5] list after right rotation: [5, 1, 2, 3, 4]
Another Approach using the Deque Module :
Right Shifting of a list can be done using the Deque Module of collections. This module provides a double-linked list for faster insertions and deletions at both ends.
For Right Shift, we can use Deque’s rotate() method.
In the rotate() method we can specify the number of rotations.
Note: Shifting can also be considered as rotating.
from collections import deque # Create a deque object from the list lst = [1, 2, 3, 4, 5] deque = deque(lst) # Rotate the deque by 1 positions to the right deque.rotate(1) # Convert the deque back to a list lst = list(deque) print(lst) # Output: [4, 5, 6, 1, 2, 3]
Output : [5, 1, 2, 3, 4]
I hope you learned something new today.
Thank you.