【发布时间】:2016-12-15 14:59:44
【问题描述】:
我创建了一个接收(amount, bills, n) 的代码。 bills 是可用现金账单的元组,n 是您必须准确使用账单才能收到金额的次数。
例如:
atm_rec ( 70 (5,10) 7 )=真
和:
atm_rec ( 10 (2,3,5) 6 )=假
我使用递归创建了以下代码
def atm_rec(amount, bills, n):
if amount==0:
if n==0:
return True
else:
return False
elif amount<0:
return False
elif len(bills)==0 and amount!=0:
return False
else:
tmp = atm_rec(amount - bills[-1],bills,n-1)
tmp2 = atm_rec(amount,bills[0:-1], n)
return tmp or tmp2
现在我想通过使用 memoization 来提高效率(字典键是 amount 和 n 的元组,值是布尔值)但不知何故代码要滞后得多。有什么建议吗?
def atm_mem(amount, bills, n,memo = None):
if amount==0:
if n==0:
return True
else:
return False
elif amount<0:
return False
elif len(bills)==0 and amount!=0:
return False
if memo==None:
memo={}
key = (amount, n)
if memo is not None and key not in memo:
tmp = atm_mem(amount - bills[-1], bills, n - 1, memo)
tmp2 = atm_mem(amount, bills[0:-1], n, memo)
memo[key] = tmp or tmp2
return memo[key]
【问题讨论】:
标签: python recursion memoization