无法启动备忘录。如果我将其设置为memo
全局,那么后续的打印函数将在第一次打印期间获取存储的备忘录。请告知
def howsumhelper(targetsum,numbers):
memo = dict() #this memoization will not initiate. Why?
return howsum(targetsum,numbers,[])
def howsum(targetsum,numbers,combo):
print("Debug==",memo)
if targetsum in memo: return memo[targetsum]
if targetsum == 0:return combo
if targetsum < 0: return None
for number in numbers:
remainder = targetsum - number
if howsum(remainder,numbers,combo) != None:
combo.append(number)
memo[targetsum] = combo
return combo
memo[targetsum] = None
return None
print(howsumhelper(7,[3,4])) #output should be [3,4]
print(howsumhelper(8,[2,3])) #output should be [2,2,2,2]
print(howsumhelper(7,[2,4])) #output should be None
建议进行以下更改
Reference Efficient memorization in Python使用已发布的解决方案#2
修订代码
输出
解释
函数签名为:howsum(targetsum,number,combo=None,memo=None):
参数函数定义中的值称为默认参数。 所以combo和memo都有默认参数
Python的默认参数在定义函数时计算一次,而不是每次调用函数时
默认值仅在传递实际值时使用
因此:
但是:
相关问题 更多 >
编程相关推荐