我試圖編寫一個程序,該程序從用戶處獲取列表和數字'N'的步驟。該程序將循環移動該列表。如果數字是正數,則列表中的項目將向左移動N個步驟,如果N爲負數,則項目向右移動N個步驟。如果N = 0,則列表不會改變。以圓形方式移動數組
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]
有人可以給我一個線索如何編寫這個程序?
我試圖編寫一個程序,該程序從用戶處獲取列表和數字'N'的步驟。該程序將循環移動該列表。如果數字是正數,則列表中的項目將向左移動N個步驟,如果N爲負數,則項目向右移動N個步驟。如果N = 0,則列表不會改變。以圓形方式移動數組
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]
有人可以給我一個線索如何編寫這個程序?
這可以做到我們ing片:
def shift(array, n):
return array[n:] + array[:n]
使用deque
和否定n
如果要反轉的邏輯:
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)
輸出:
deque([1, 2, 3, 4, 5])
deque([2, 3, 4, 5, 1])
deque([5, 1, 2, 3, 4])
n
可以比元素的數量較大和旋轉仍然有效:
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])
所以基本上旋轉陣列?你只需要一些適當的流行/移位型操作。 –
你應該在python中查看切片。 http://stackoverflow.com/questions/509211/explain-pythons-slice-notation –
它對N = 1和N = -1做同樣的事情嗎? –