【问题标题】:Returning a list in this recursive coi function in python在python的这个递归coi函数中返回一个列表
【发布时间】:2011-02-04 01:33:24
【问题描述】:

我无法让我的列表在我的代码中返回。它没有返回列表,而是继续返回 None,但是如果我在 elif 语句中将返回替换为 print,它会很好地打印列表。我该如何修复这个?

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)

【问题讨论】:

  • Nate, Mark Rushakoff 回答了你的问题;你应该接受他的回答。您可以通过单击答案的投票计数下的复选标记 (✓) 来做到这一点。

标签: python list recursion


【解决方案1】:

您不是 returning 递归调用 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)

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

【讨论】:

  • 我还是不明白。如果数量总是为0,它如何返回到函数的末尾?它不应该到达函数的末尾。另外,我已经经历了这该死的事情10个小时。相信我,我只在万不得已的情况下才问这样的地方。我被难住了,我根本不知道该怎么办。此外,添加 return 不起作用: return makeChange2((amount - coinDenomination[0]), coinDenomination, listofcoins) elif amount == 0: return listofcoins
  • 没关系,我明白你现在在说什么了。我必须在 if 和 else 语句中都返回,否则它会在除最后一个调用之外的每个调用中进入列表末尾。谢谢你的帮助。
猜你喜欢
  • 1970-01-01
  • 2010-10-09
  • 1970-01-01
  • 2021-12-31
  • 2016-05-27
  • 2020-11-18
  • 1970-01-01
  • 1970-01-01
  • 2015-06-25
相关资源
最近更新 更多