Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Array Rotation Solution
#1
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..!
Reply
#2
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]
hannah likes this post
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#3
This is helpful, thanks..!
Reply
#4
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]
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Python logging RotatingFileHandler writes to random file after the first log rotation rawatg 0 452 Feb-15-2024, 11:15 AM
Last Post: rawatg
  Calculate transformation and Rotation Sandra2312 1 1,836 Jan-31-2021, 12:53 PM
Last Post: jefsummers
  Level curves don't match after rotation schniefen 1 1,566 Dec-14-2020, 09:56 PM
Last Post: schniefen
  Rotation Effect on live Webcam Feed Leziiy 0 1,633 Sep-12-2020, 04:25 PM
Last Post: Leziiy
  Logger file rotation not working when python code started from windows service as exe nirvantosh 1 6,718 Jun-14-2019, 03:58 PM
Last Post: nirvantosh

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020