Python列表元素被覆盖

2024-04-25 21:34:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个递归函数,它试图找到与某个数相加的数的组合。我将结果存储在名为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交互,该方法应该只将它添加到末尾。你知道吗

是我遗漏了什么还是递归导致的?你知道吗


Tags: to代码in列表forindexiftotal
1条回答
网友
1楼 · 发布于 2024-04-25 21:34:33

使用列表:

        if total == sum:
            validCombinations.append(list(digitList))

你必须得到一份数字列表,而不是数字列表。你知道吗

相关问题 更多 >