【问题标题】:python3 holding on to data after recursionpython3在递归后保留数据
【发布时间】:2022-01-13 15:29:36
【问题描述】:

我编写了一些代码,通过将列表中的数字相加,找到了获得数字总和的最快方法,例如: bestSum(3, [800, 1, 3]) 将返回 [3],因为这将是使用提供的数字获得 3(第一个数字)的最佳方法,只需添加 3。代码:

def bestSum(target, lst, mochi = {}):
    if target in mochi:
        return mochi[target]

    if target == 0:
        return []
    if target < 0:
        return None

    shortestCombination = None

    for i in lst:
        remainderCombination = bestSum(target - i, lst, mochi)
        if remainderCombination is not None:
        remainderCombination = [*remainderCombination, i]
            if shortestCombination is None or len(remainderCombination) < len(shortestCombination):
                shortestCombination = remainderCombination

    mochi[target] = shortestCombination

    return shortestCombination

我遇到了这个问题,在我运行代码之间会保存数据,例如,如果我只运行

print(bestSum(8, [4])

它返回

[4, 4]

但是如果我跑了

print(bestSum(8, [2, 3, 5]))
print(bestSum(8, [4]))

它返回:

[5, 3]
[5, 3]

我在这里做错了吗?这可能是一个安全漏洞吗?有没有办法让这个返回正确?什么会导致 python 做这样的事情?

【问题讨论】:

标签: python-3.x


【解决方案1】:

当使用可变参数作为默认参数时,这是documented behavior(请参阅“执行函数定义时从左到右计算默认参数值。”)。

如文档中所述,“解决此问题的一种方法是使用 None 作为默认值,并在函数体中显式测试它”。

[虽然记录在案,但我在几天前才知道here on SO]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-30
    • 1970-01-01
    • 2012-01-12
    相关资源
    最近更新 更多