【问题标题】:Prevent Exceeding Maximum Recursion Depth防止超过最大递归深度
【发布时间】:2015-08-14 06:56:16
【问题描述】:

我正在尝试制作一个小脚本,而一种有效的方法是在其内部调用一个函数。但是,这会给出消息“RuntimeError:获取对象的 str 时超出最大递归深度”。

我试图让程序在达到此目标之前退出,但它似乎没有完成这项工作。我想知道是否有任何方法可以在运行一定次数后停止程序,这样就不会发生此错误。这是我试图解决这个问题的方法:

import sys
n = 0
def cycle(b,n):
    total = 0
    for i in str(n):
        for y in i:
         total+=int(y)**b
    n+=1
    print(total)
    if n == 10:
     sys.exit()
    else:
     cycle(b,total)
cycle(2,562)

谢谢。

【问题讨论】:

  • "获取对象的 str 时超出递归深度" 表明错误不在您显示的代码中。请提供minimal example
  • 为什么函数没有返回任何东西?另请注意,函数内的n 与您设置为零的n 不同。
  • 为什么你在顶部分配n = 0,然后什么都不做?当i 已经是单个字符时,for y in i 有什么意义?
  • 如果您能告诉我们这个计算的意义,我认为您更有可能看到进展。
  • @user1956027,你的逻辑不正确不是递归

标签: python recursion


【解决方案1】:

您需要返回并使用适当的基本情况:

def cycle(b, n, seen):
    total = 0
    if n == 1 or n in seen:
        return n == 1
    for i in str(n):
        for y in i:
            total += int(y) ** b
    seen.add(n)
    n += 1
    return cycle(b, total, seen)


print(cycle(2, 19,set()))

输出:

In [34]: cycle(2,562,set())
Out[34]: False

In [35]: cycle(2,19,set())
Out[35]: True

In [36]: cycle(2,1,set())
Out[36]: True

In [37]: cycle(2,2,set())
Out[37]: False

In [38]: cycle(2,7,set())
Out[38]: True

【讨论】:

    【解决方案2】:

    快乐的数字(这就是你在那里所做的)end in 1 or end up in the cycle 4, 16, 37, 58, 89, 145, 42, 20, 4, ...。所以当你到达 1 或 4 时就停止。虽然一般来说,如果你的递归太深,你应该考虑一个迭代解决方案。

    【讨论】:

    • 我知道我可以做到,但我觉得那是作弊,我希望不管数字循环如何,它都能正常工作。
    【解决方案3】:

    递归调用函数可能很方便,但肯定效率不高(至少在您使用的 python 实现中,因为您收到此错误)。

    然而,您正在尝试做的事情,即限制递归深度,已经发生了,因为您遇到了与递归深度相关的运行时错误。

    您为什么不在更高级别捕获运行时错误?

    【讨论】:

      【解决方案4】:

      尝试传入一个计数器并避免给出令人困惑的变量名称:

      import sys
      def cycle(b,n, counter):
          total = 0
          for i in str(n):
              for y in i:
               total+=int(y)**b
          counter+=1
          print(total)
          if counter == 10:
           sys.exit()
          else:
           cycle(b,total,counter)
      cycle(2,562,0)
      

      Run it here.

      【讨论】:

      • 谢谢!这是我试图用 n = 0 做的,但它似乎没有用。
      猜你喜欢
      • 1970-01-01
      • 2017-11-05
      • 2013-11-30
      • 2020-12-13
      • 2013-03-03
      • 2016-07-09
      • 2011-04-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多