Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create array_rotaion.py #11009

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions data_structures/arrays/array_rotaion.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# https://www.geeksforgeeks.org/array-rotation/

def rotate_array(input_array, positions_to_rotate):
"""
Rotate an input array to the right by a specified number of positions.

Parameters:
- input_array (list): The input array to be rotated.
- positions_to_rotate (int): The number of positions to rotate the input array to the right.

Returns:
- list: The rotated array.

>>> rotate_array([1, 2, 3, 4, 5], 2)
[4, 5, 1, 2, 3]
>>> rotate_array([7, 9, 1, 4, 6], 3)
[1, 4, 6, 7, 9]
>>> rotate_array([11, 12, 13, 14, 15], 5)
[11, 12, 13, 14, 15]
>>> rotate_array(['a', 'b', 'c', 'd'], 2)
['c', 'd', 'a', 'b']
>>> rotate_array([], 3)
[]
"""

if not input_array:
return input_array

positions_to_rotate = positions_to_rotate % len(input_array) # Ensure positions_to_rotate is within the array size
rotated_array = input_array[-positions_to_rotate:] + input_array[:-positions_to_rotate]

return rotated_array

if __name__ == "__main__":
import doctest

doctest.testmod()