[英]Recursively Generating a List of n choose k combinations in Python - BUT return a list
我正在嘗試通過遵循每個遞歸調用包含或不包含元素的策略來遞歸生成列表的所有n選擇k組合(不檢查唯一性)。 我絕對可以打印出這些組合,但是我一生都無法弄清楚如何在Python中返回正確的列表。 以下是一些嘗試:
class getCombinationsClass:
def __init__(self,array,k):
#initialize empty array
self.new_array = []
for i in xrange(k):
self.new_array.append(0)
self.final = []
self.combinationUtil(array,0,self.new_array,0,k)
def combinationUtil(self,array,array_index,current_combo, current_combo_index,k):
if current_combo_index == k:
self.final.append(current_combo)
return
if array_index >= len(array):
return
current_combo[current_combo_index] = array[array_index]
#if current item included
self.combinationUtil(array,array_index+1,current_combo,current_combo_index+1,k)
#if current item not included
self.combinationUtil(array,array_index+1,current_combo,current_combo_index,k)
在上面的示例中,我嘗試將結果追加到似乎不起作用的外部列表。 我還嘗試通過遞歸構造最終返回的列表來實現此目的:
def getCombinations(array,k):
#initialize empty array
new_array = []
for i in xrange(k):
new_array.append(0)
return getCombinationsUtil(array,0,new_array,0,k)
def getCombinationsUtil(array,array_index,current_combo, current_combo_index,k):
if current_combo_index == k:
return [current_combo]
if array_index >= len(array):
return []
current_combo[current_combo_index] = array[array_index]
#if current item included & not included
return getCombinationsUtil(array,array_index+1,current_combo,current_combo_index+1,k) + getCombinationsUtil(array,array_index+1,current_combo,current_combo_index,k)
當我針對兩個實現對列表[1,2,3]和k = 2進行測試時,我一直在獲取結果[[3,3],[3,3],[3,3]]。 但是,如果我實際在內部if語句(current_combo_index == k)中打印出'current_combo'變量,則會打印出正確的組合。 是什么賦予了? 我誤解了與可變范圍或Python列表有關的東西?
第二種方法出錯,因為該行
return [current_combo]
返回對current_combo的引用。 在程序結束時,返回的所有組合都是對相同current_combo的引用。
您可以通過將current_combo的副本更改為以下內容來解決此問題:
return [current_combo[:]]
第一種方法由於相同的原因而失敗,您需要更改:
self.final.append(current_combo)
至
self.final.append(current_combo[:])
檢查一下: itertools.combinations 。 您也可以看一下實現。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.