2016-02-02 49 views
-1

我試圖編寫一個程序,該程序從用戶處獲取列表和數字'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] 

有人可以給我一個線索如何編寫這個程序?

+0

所以基本上旋轉陣列?你只需要一些適當的流行/移位型操作。 –

+1

你應該在python中查看切片。 http://stackoverflow.com/questions/509211/explain-pythons-slice-notation –

+0

它對N = 1和N = -1做同樣的事情嗎? –

回答

2

這可以做到我們ing片:

def shift(array, n): 
    return array[n:] + array[:n] 
4

使用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]) 
+0

因爲旋轉一個deque會改變deque本身的順序,所以我會特別推薦編寫一個自己的函數來傳遞一個列表,並將這個列表轉換成一個deque。然後旋轉deque並將其返回。所以原始數據訂單保持不變。如果需要,您可以在返回之前將該雙端轉換爲列表。 – albert

+0

@albert,如果在原始列表中傳遞一個列表是不會改變的,除非OP需要一些列表特定的行爲,那麼他們應該使用deques。 –

+0

這比切片複雜得多。請參閱pp_的答案和我的。 – zondo