【问题标题】:Why does recursion overwrite values in a list that is passed along?为什么递归会覆盖传递的列表中的值?
【发布时间】:2017-06-07 21:54:22
【问题描述】:

这个rec​​usion 改编自http://www.geeksforgeeks.org/print-all-possible-combinations-of-r-elements-in-a-given-array-of-size-n/,并且确实打印出arr 与长度r 的所有可能的唯一组合。

我想要的是将所有可能的组合保存在一个列表中,以便在另一个程序中进一步使用这个算法。为什么在 recustion 中 combArray 中的值被覆盖,我该如何解决这个问题?

def combRecursive(arr, data, start, end, index, r, combArray):
    if index == r:
        combArray.append(data)
        return combArray

    i = start
    while True:
        if i > end or end - i + 1 < r - index:
            break
        data[index] = arr[i]
        combArray = combRecursive(arr, data, i + 1, end, index + 1, r, combArray)
        i += 1
    return combArray

def main():
    arr = [1, 2, 3, 4, 5]
    r = 3
    n = len(arr)
    data = [9999999, 9999999, 9999999]
    combArray = []

    combArray = combRecursive(arr, data, 0, n-1, 0, r, combArray)
    print("All possible unique combination is: ")
    for element in combArray:
        print(element)

目前结果:

[3, 4, 5]
[3, 4, 5]
[3, 4, 5]
[3, 4, 5]
[3, 4, 5]
[3, 4, 5]
[3, 4, 5]
[3, 4, 5]
[3, 4, 5]
[3, 4, 5]

我想要什么:

[1, 2, 3]
[1, 2, 4]
[1, 2, 5]
[1, 3, 4]
[1, 3, 5]
[1, 4, 5]
[2, 3, 4]
[2, 3, 5]
[2, 4, 5]
[3, 4, 5]

【问题讨论】:

  • @Prune:我在这里看不到任何默认参数。
  • 你想要的是[list(x) for x in itertools.combinations([1, 2, 3, 4, 5], 3)],而不是重新发明轮子。
  • @user2357112:谢谢……我显然点击列表太快了。我无法编辑参考,但这个问题之前已经处理过很多次了。
  • 您的问题的答案是您每次都添加完全相同的列表combArray.append(data)
  • @Prune - 你没错,this 有很多 come times

标签: python recursion tree permutation combinatorics


【解决方案1】:

您初始化data,然后对其进行更改并将其添加到combArray,这意味着您总是将相同的数组添加到combArray,所以它的所有元素是一样的。如果您希望元素成为不同的数组,则需要为每个要添加到 combArrays 的元素创建一个新数组(例如,通过制作 data 的副本)。

【讨论】:

  • 即解决方案是将combArray.append(data) 更改为combArray.append(data[:])。太好了,谢谢!
猜你喜欢
  • 2016-05-27
  • 2019-07-24
  • 1970-01-01
  • 2017-05-18
  • 1970-01-01
  • 2014-03-14
  • 2012-09-04
  • 2016-02-25
  • 1970-01-01
相关资源
最近更新 更多