Python Forum

Full Version: Array Rotation Solution
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello Community folks,

Hope you all are doing well.

So had been practising a few Python programs on Arrays. Need help understanding this very problem, it would really mean alot if someone could comment across each code line on this snippet URL: https://www.interviewbit.com/snippet/549...e98905382/

Problem Statement:
Q) Write a function rotate(arr[], d, n) that rotates arr[] of size n by d elements.
Input : arr[] = [1, 2, 3, 4, 5, 6, 7] d = 2
Output : arr[] = [3, 4, 5, 6, 7, 1, 2]

TIA..!
def rotate(sequence, n):
    return sequence[n:] + sequence[:n]
Or use deque.
from collections import deque


my_sequence = deque([1, 2, 3, 4, 5, 6, 7])
my_sequence.rotate(-2)  # here the direction is different, so have to use -2
print(my_sequence)
To replicate the same functionality with rotate, you can invert n:
def rotate(sequence, n):
    return sequence[-n:] + sequence[:-n]
This is helpful, thanks..!
it works as well (using a single line)
n = 2
arr = [1, 2, 3, 4, 5, 6, 7]
# arr = np.asarray(arr)
arr = np.hstack( (arr[n: ], arr[: n]))
Output:
arr = [3 4 5 6 7 1 2]