-1

I tried to write a programe that gets a list and a number 'N' of steps from the user. The programe will move in a circular way the list. If the number is positive the items in the list will move N steps left, and if N is negative the items will move N steps right. If N=0 the list won't change.

L=[1,2,3,4,5]
if N==0  > [1,2,3,4,5]
if N==1  > [2,3,4,5,1]
if N==-1 > [5,1,2,3,4]

Can someone give me a clue how to code this program?

rochb
  • 2,249
  • 18
  • 26
Netta
  • 63
  • 8

2 Answers2

4

Use a deque and negate n if you want to reverse the logic:

from collections import deque

deq = deque([1, 2, 3, 4, 5])
n = 0
deq.rotate(-n)
print(deq)

deq = deque([1, 2, 3, 4, 5])
n = 1
deq.rotate(-n)
print(deq)

deq = deque([1, 2, 3, 4, 5])
n = -1
deq.rotate(-n)
print(deq)

Output:

deque([1, 2, 3, 4, 5])
deque([2, 3, 4, 5, 1])
deque([5, 1, 2, 3, 4])

n can be larger than the number of elements and rotate will still work:

In [5]: deq = deque([1, 2, 3, 4, 5])

In [6]: deq.rotate(12)

In [7]: deq
Out[7]: deque([4, 5, 1, 2, 3])
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
  • Since rotating a deque changes the order of the deque itself I would addtionally recommend writing a own function where to pass a list in and convert this list into a deque. Then rotate the deque and return it. So the original data order is kept unchanged. If needed you can convert the deque into a list before returning. – albert Feb 02 '16 at 21:31
  • @albert, if a list is passed in the original list is not going to change, unless the OP needs some list specific behaviour then they should use a deques from the get go. – Padraic Cunningham Feb 02 '16 at 21:42
  • This is much more complicated than slicing. See pp_'s answer and mine. – zondo Feb 02 '16 at 21:59
  • In what way does it not work properly? – zondo Feb 02 '16 at 22:02
  • The question has changed since I posted my answer. I also don't think that insults will improve anything. In my comment, I did not mean to be derogatory. If I was, than I am sincerely sorry. I have deleted my answer, because I now believe that it is not helpful. – zondo Feb 02 '16 at 22:08
2

This can be done using slices:

def shift(array, n):
    return array[n:] + array[:n]
pp_
  • 3,435
  • 4
  • 19
  • 27