2017-07-24 39 views
1

我想編寫一個遞歸代碼,該列表找出所有要從列表中選擇的重複項,k元素。該代碼將返回包含所有選項的列表列表。在給定的列表元素的給定長度中查找所有具有重複的排列

我的代碼:

def repetitions(elements,k): 
    if elements==[]: 
     return [] 
    if k==0: 
     return [[]] 
    else: 
     result=[] 
     result = repetitions(elements,k-1) 
     for e in result: 
      e.append(elements[0]) 
     result.extend(repetitions(elements[1:],k)) 
    return result 

我的問題是,代碼不保留原始列表的順序。

例如:

repetitions([1,2],3) 
[[1, 1, 1], [2, 1, 1], [2, 2, 1], [2, 2, 2]] 

代替:

[[1, 1, 1], [1, 1, 2], [1, 2, 2], [2, 2, 2]] 

我怎麼能修復我的代碼?

任何幫助表示讚賞。

回答

1

爲了得到正確的順序,只是開始而不是結束插入:所以更換

e.append(elements[0]) 

由:

e.insert(0,elements[0]) 

不管怎樣,爲什麼重新發明輪子?只需使用itertools.combinations_with_replacement

import itertools 

def repetitions(r,n): 
    return list(itertools.combinations_with_replacement(r,n)) 

print(repetitions([1,2],3)) 

結果:

[(1, 1, 1), (1, 1, 2), (1, 2, 2), (2, 2, 2)] 

(或[list(x) for x in itertools.combinations_with_replacement(r,n)]如果你真的列表而不是元組的列表的需求列表)

小挑剔:

  • if elements==[] =>if elements
  • 沒有必要設置result = [],因爲它的下一行
+0

@Lafexlos分配:對信息的感謝。與此同時,我試圖修復OP代碼。 –

相關問題