简体   繁体   English

在Python中递归生成n个选择k组合的列表-但返回列表

[英]Recursively Generating a List of n choose k combinations in Python - BUT return a list

I'm attempting to generate all n choose k combinations of a list (not checking for uniqueness) recursively by following the strategy of either include or not include an element for each recursive call. 我正在尝试通过遵循每个递归调用包含或不包含元素的策略来递归生成列表的所有n选择k组合(不检查唯一性)。 I can definitely print out the combinations but I for the life of me cannot figure out how to return the correct list in Python. 我绝对可以打印出这些组合,但是我一生都无法弄清楚如何在Python中返回正确的列表。 Here are some attempts below: 以下是一些尝试:

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)

In the above example I tried to append the result to an external list which didn't seem to work. 在上面的示例中,我尝试将结果追加到似乎不起作用的外部列表。 I also tried implementing this by recursively constructing a list which is finally returned: 我还尝试通过递归构造最终返回的列表来实现此目的:

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)

When I tested this out for the list [1,2,3] and k = 2, for both implementations, I kept getting back the result [[3,3],[3,3],[3,3]]. 当我针对两个实现对列表[1,2,3]和k = 2进行测试时,我一直在获取结果[[3,3],[3,3],[3,3]]。 However, if I actually print out the 'current_combo' variable within the inner (current_combo_index == k) if statement, the correct combinations print out. 但是,如果我实际在内部if语句(current_combo_index == k)中打印出'current_combo'变量,则会打印出正确的组合。 What gives? 是什么赋予了? I am misunderstanding something to do with variable scope or Python lists? 我误解了与可变范围或Python列表有关的东西?

The second method goes wrong because the line 第二种方法出错,因为该行

return [current_combo]

returns a reference to current_combo. 返回对current_combo的引用。 At the end of the program, all the combinations returned are references to the same current_combo. 在程序结束时,返回的所有组合都是对相同current_combo的引用。

You can fix this by making a copy of the current_combo by changing the line to: 您可以通过将current_combo的副本更改为以下内容来解决此问题:

return [current_combo[:]]

The first method fails for the same reason, you need to change: 第一种方法由于相同的原因而失败,您需要更改:

self.final.append(current_combo)

to

self.final.append(current_combo[:])

Check this out: itertools.combinations . 检查一下: itertools.combinations You can take a look at the implementation as well. 您也可以看一下实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM