【问题标题】:How to return void in python如何在python中返回void
【发布时间】:2019-09-18 09:24:42
【问题描述】:
这是著名的硬币找零 dp 问题 - 给定一些硬币返回可能的金额 11=2+2+2+5
arr=[2,5]
def Recur(amount,seq):
if amount==0:
print(seq)
return
if amount<0:
return
for coin in arr:
seq+=str(coin)
Recur(amount-coin,seq)
Recur(11,"")
无论我尝试返回什么,该函数都会返回一个 2,也就是说它在数量达到 0 后继续。我试图返回 0,无,只是返回 - 没有任何效果?它总是在 之后继续
【问题讨论】:
标签:
python
recursion
dynamic-programming
【解决方案1】:
arr=[2,5]
def Recur(amount,seq):
if amount==0:
print(seq)
return
if amount<0:
return
for coin in arr:
seq+=str(coin) # error is in this line since you are
#trying to update seq which persist across the method stack due
#to for loop calls Recur method again with this updated seq
#leading to extra addition of extra coin in seq.
Recur(amount-coin,seq)
Recur(11,"")
您需要在调用过程中更新 seq 以便进行以下修改:
arr=[2,5]
def Recur(amount,seq):
if amount==0:
print(seq)
return
if amount<0:
return
for coin in arr:
Recur(amount-coin,seq+str(coin))
Recur(11,"")