gpt4 book ai didi

python - 在 python 中返回此递归 coi 函数中的列表

转载 作者:太空宇宙 更新时间:2023-11-04 01:43:25 24 4
gpt4 key购买 nike

我无法让我的列表返回我的代码。它没有返回列表,而是一直返回 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)

最佳答案

您不会返回makeChange2 的递归调用的值。

一旦控制到达对 makeChange2 的任一调用并完成调用,程序将继续执行下一条语句,这是函数的结尾;因此,它返回 None

如果这个概念仍然给您带来麻烦,请尝试在 return n*factorial(n-1) 行中使用和不使用 return 关键字运行这个简单的阶乘程序:

def factorial(n):
if n == 0 or n == 1:
return 1
return n * factorial(n-1)

print factorial(3)

手动遍历代码应该有助于阐明原始程序中的错误。

关于python - 在 python 中返回此递归 coi 函数中的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2572313/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com