在Python中的递归coi函数中返回一个列表
我无法让我的列表返回到我的代码中。它没有返回列表,而是一直返回 None,但是如果我在 elif 语句中用 print 替换 return,它就会很好地打印列表。我该如何修复这个问题?
def makeChange2(amount, coinDenomination, listofcoins = None):
#makes a list of coins from an amount given by using a greedy algorithm
coinDenomination.sort()
#reverse the list to make the largest position 0 at all times
coinDenomination.reverse()
#assigns list
if listofcoins is None:
listofcoins = []
if amount >= coinDenomination[0]:
listofcoins = listofcoins + [coinDenomination[0]]
makeChange2((amount - coinDenomination[0]), coinDenomination, listofcoins)
elif amount == 0:
return listofcoins
else:
makeChange2(amount, coinDenomination[1:], listofcoins)
I'm having trouble getting my list to return in my code. Instead of returning the list, it keeps returning None, but if I replace the return with print in the elif statement, it prints the list just fine. How can I repair this?
def makeChange2(amount, coinDenomination, listofcoins = None):
#makes a list of coins from an amount given by using a greedy algorithm
coinDenomination.sort()
#reverse the list to make the largest position 0 at all times
coinDenomination.reverse()
#assigns list
if listofcoins is None:
listofcoins = []
if amount >= coinDenomination[0]:
listofcoins = listofcoins + [coinDenomination[0]]
makeChange2((amount - coinDenomination[0]), coinDenomination, listofcoins)
elif amount == 0:
return listofcoins
else:
makeChange2(amount, coinDenomination[1:], listofcoins)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不会
返回
对makeChange2
的递归调用的值。一旦控制到达对
makeChange2
的调用并完成调用,程序就会继续执行下一条语句,即函数的末尾;因此,它返回None
。如果这个概念仍然给您带来麻烦,请尝试在
return n*factorial(n-1)
行中使用或不使用return
关键字来运行这个简单的阶乘程序:通过代码应该有助于阐明原始程序中的错误。
You're not
return
ing the value of the recursive calls tomakeChange2
.Once control reaches either of those calls to
makeChange2
and completes the call, the program continues to the next statement, which is the end of the function; thus, it returnsNone
.If that concept is still giving you trouble, try running this simple factorial program with and without the
return
keyword in thereturn n*factorial(n-1)
line:Manually walking through the code should help elucidate what was wrong in your original program.