【问题标题】:Recursively Generating a List of n choose k combinations in Python - BUT return a list在Python中递归生成n个选择k个组合的列表-但返回一个列表
【发布时间】:2016-06-28 17:32:08
【问题描述】:

我正在尝试通过遵循包含或不包含每个递归调用的元素的策略,递归地生成列表的所有 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 ]]。但是,如果我在内部 (current_combo_index == k) if 语句中实际打印出“current_combo”变量,则会打印出正确的组合。是什么赋予了?我误解了与变量范围或 Python 列表有关的事情?

【问题讨论】:

    标签: python algorithm list recursion combinations


    【解决方案1】:

    第二种方法出错是因为行

    return [current_combo]
    

    返回对 current_combo 的引用。在程序结束时,所有返回的组合都是对同一个 current_combo 的引用。

    您可以通过复制 current_combo 来解决此问题,方法是将行更改为:

    return [current_combo[:]]
    

    第一种方法失败同理,需要改一下:

    self.final.append(current_combo)
    

    self.final.append(current_combo[:])
    

    【讨论】:

    • 啊该死的!完全忘记了关于 python 列表的烦人的小细节。谢谢!
    【解决方案2】:

    看看这个:itertools.combinations。你也可以看看实现。

    【讨论】:

    • 是的 itertools.combinations 有效,但我只是好奇为什么我不能返回带有上述实现的列表。我想尝试手动实现组合生成只是为了它。我试图编写和调整它的 python 版本 (geeksforgeeks.org/…) 但只是好奇为什么没有返回正确的列表。
    猜你喜欢
    • 2018-05-16
    • 1970-01-01
    • 1970-01-01
    • 2013-11-08
    • 2015-06-25
    • 1970-01-01
    • 2011-02-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多