在Python中的递归coi函数中返回一个列表

发布于 2024-08-27 18:44:57 字数 761 浏览 6 评论 0原文

我无法让我的列表返回到我的代码中。它没有返回列表,而是一直返回 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

π浅易 2024-09-03 18:44:57

您不会返回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)

:通过代码应该有助于阐明原始程序中的错误。

You're not returning the value of the recursive calls to makeChange2.

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 returns None.

If that concept is still giving you trouble, try running this simple factorial program with and without the return keyword in the return n*factorial(n-1) line:

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

print factorial(3)

Manually walking through the code should help elucidate what was wrong in your original program.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文