Python Program for Reversal algorithm for array rotation

PythonServer Side ProgrammingProgramming

When it is required to reverse a rotated array, a method is defined, that iterates through the list and reverse the list. Another method is defined, that rotates the list, and another method is defined that displays the list. A simple loop and indexing is used to achieve this.

Below is a demonstration for the same −

Example

 Live Demo

def reverse_list(my_list, begin, end):
   while (begin < end):
      temp = my_list[begin]
      my_list[begin] = my_list[end]
      my_list[end] = temp
      begin += 1
      end = end-1
def left_rotate(my_list, to_rotate):
   n = len(my_list)
   reverse_list(my_list, 0, to_rotate-1)
   reverse_list(my_list, to_rotate, n-1)
   reverse_list(my_list, 0, n-1)
def print_it(my_list):
   for i in range(0, len(my_list)):
      print(my_list[i])
my_list = [34, 42, 56, 78, 9, 0, 23]
print("The list is :")
print(my_list)
print("The left_rotate method is being called")
left_rotate(my_list, 3)
print("The list after rotation is : ")
print_it(my_list)

Output

The list is :
[34, 42, 56, 78, 9, 0, 23]
The left_rotate method is being called
The list after rotation is :
78
9
0
23
34
42
56

Explanation

  • A method named ‘reverse_list’ is defined, that reverses the given list.
  • Another method named ‘rotate_list’ is defined, that rotates the list based on a specific pivot value.
  • Another method named ‘print_it’ is defined, that prints the list on the console.
  • A list is defined, and is displayed on the console.
  • The ‘left_rotate’ method is called on this list, and elements are displayed on the console after rotation and reversal.
raja
Published on 12-Mar-2021 12:16:15
Advertisements