
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Python Program for Reversal algorithm for array rotation
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
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.
- Related Articles
- C Program for Reversal algorithm for array rotation
- Java Program for Reversal algorithm for array rotation
- Reversal Algorithm for Array Rotation using C++
- Reversal Algorithm for Right Rotation of an Array using C++
- Python Program for array rotation
- C Program for Program for array rotation?
- Block swap algorithm for array rotation in C++
- Java Program for array rotation
- Golang Program For Array Rotation
- C++ Program to Implement Fisher-Yates Algorithm for Array Shuffling
- JavaScript Program for Left Rotation and Right Rotation of a String
- C Program for Naive algorithm for Pattern Searching
- C Program for KMP Algorithm for Pattern Searching
- C++ program for Finite Automata algorithm for Pattern Searching
- C Program for Rabin-Karp Algorithm for Pattern Searching

Advertisements