【发布时间】:2017-06-07 21:54:22
【问题描述】:
这个recusion 改编自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)
标签: python recursion tree permutation combinatorics