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 −
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)
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