【发布时间】:2016-02-01 04:27:10
【问题描述】:
我有一个递归函数,它试图找到添加到某个数字的数字组合。我将结果存储在一个名为 validCombinations
代码:
sum = 4
digits = 2
currentDigit = digits
validCombinations = []
#recursion function to find combinations of numbers that add to the sum variable
def recursive(index):
if 10 not in digitList:
if index >= 0:
total = 0
for n in digitList:
total += n
if total == sum:
validCombinations.append(digitList)
digitList[index] += 1
recursive(index-1)
else:
recursive(currentDigit-1)
digitList = []
for n in range(digits,0,-1):
for i in range(n):
digitList.append(0)
recursive(n-1)
digitList = []
currentDigit -= 1
print validCombinations
运行时会输出
[[9, 10], [10, 0]]
当我希望看到这个时
[[2, 2], [4]]
我已经单步执行了代码,它似乎以某种方式覆盖了列表中的元素,但是在我的代码中,我只使用 append() 方法与 validCombinations 进行交互,这应该只是将它添加到结束。
是我遗漏了什么还是递归导致了这个?
【问题讨论】:
-
是
digits应该是应该测试的数字的下限吗? -
我们不期望 [1,3] 作为 4 的有效分解?
标签: python list recursion append