【问题标题】:Recursion error, maximum recursion reached递归错误,达到最大递归
【发布时间】:2020-11-20 09:50:06
【问题描述】:

所以,我正在做关于离散数学的 Coursera 课程,其中一个测验让我们使用以下说明实现一个程序:

开发一个 Python 方法 change(amount),它对于 24 到 1000 范围内的任何整数数量返回一个仅由数字 5 和 7 组成的列表,使得它们的总和等于数量。例如,change(28) 可能返回 [7, 7, 7, 7],而 change(49) 可能返回 [7, 7, 7, 7, 7, 7, 7] 或 [5, 5, 5, 5 , 5, 5, 5, 7, 7] 或 [7, 5, 5, 5, 5, 5, 5, 5, 7]。

这就是我到目前为止所做的代码。

def change(amount):
    assert(24 <= amount <= 1000)
    coins = []

    if amount == 24:
        return coins + [7, 7, 5, 5]

    if amount == 25:
        return coins + [5, 5, 5, 5, 5]

    if amount == 28:
        return coins + [7, 7, 7, 7]

    if amount == 49:
        return coins + [7, 7, 7, 7, 7, 7, 7]

    coins = change(amount - 5)
    coins.append(5)
    return coins

#Only submit the change function
x = int(input())
print(change(x))

它一直工作到 69 岁(不错)。从那以后,它说一个递归错误。已达到最大调用量。如果有人可以为我指出如何解决我的困境的正确方向,我将不胜感激!

【问题讨论】:

  • 运行x=26,你会看到问题
  • 我现在明白了,谢谢! >.
  • 我建议放弃递归并尝试为此使用数学
  • 您也可以放弃 49 的案例并添加 26 和 27 的案例,这样就可以覆盖适当的基本案例
  • 问题有一个实现递归的初始解决方案:/ 我们只需要完成它。不过谢谢! @AbhinavMathur!

标签: python algorithm recursion


【解决方案1】:

首先,谢谢回复的人!其次,我将在此处发布我的解决方案,以防任何参加相同 Coursera 课程的人也偶然发现该错误。

def change(amount):
    assert(24 <= amount <= 1000)
    coins = []
    
    if amount == 24:
        return coins + [7, 7, 5, 5]

    if amount == 25:
        return coins + [5, 5, 5, 5, 5]

    if amount == 26:
        return coins + [7, 7, 7, 5]

    if amount == 27:
        return coins + [7, 5, 5, 5, 5]
  
    if amount == 28:
        return coins + [7, 7, 7, 7]

    if amount == 49:
        return coins + [7, 7, 7, 7, 7, 7, 7]

    coins = change(amount - 5)
    coins.append(5)
    return coins

#Only submit the change function
x = int(input())
print(change(x))

【讨论】:

  • 虽然为amount == 49 添加案例会(非常轻微地)改善运行时间,但这是不必要的,因为它超出了您的基本案例
猜你喜欢
  • 2016-12-10
  • 1970-01-01
  • 2018-12-03
  • 2019-07-03
  • 1970-01-01
  • 2020-09-30
  • 1970-01-01
  • 2018-03-04
  • 1970-01-01
相关资源
最近更新 更多