[英]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.