【问题标题】:maximum recursion depth exceeded in python class, project Euler #4python 类中超出的最大递归深度,项目 Euler #4
【发布时间】:2016-07-12 03:11:08
【问题描述】:

我正在为 Project Euler 的问题 #4 制定解决方案:

“找出由两个 3 位数乘积构成的最大回文数。”

我可以只写一个基本的脚本和循环,但我倾向于在类中写东西。

我已经有一段时间没有使用 python了,所以我正在使用这些练习来熟悉该语言。

在遍历因素以找出答案时,我收到此错误:

File "p4.py", line 35, in is_palindrome
n = str(p)
RuntimeError: maximum recursion depth exceeded while getting the str of an object 

我猜这是我格式化递归方法的方式,但我不知道如何修复它。

有人可以向我解释我在构造递归方法方面做错了什么吗?

代码:

import math

class PalindromeCalculator:

  def __init__(self, min_factor=100, max_factor=999):
    self.stable_factor = max_factor
    self.variable_factor = max_factor

  def find_max_palindrome(self):
    return self.check_next_product()

  def check_next_product(self):
    product = self.stable_factor * self.variable_factor;
    if self.is_palindrome(product):
      print("We found a palindrome! %s" % product)
      return str(product)
    else:
      # Reduce one of the factors by 1
      if self.variable_factor == 100:
        self.variable_factor = 999
        self.stable_factor -= 1
      else:
        self.variable_factor -= 1

      self.check_next_product()

  def is_palindrome(self, p):
    # To check palindrom, pop and shift numbers off each side and check if  they're equal
    n = str(p)
    length = len(n)

    if length % 2 == 0:
      iterations = length / 2
    else:
      iterations = (length - 1) / 2

    for i in range(0, iterations):
      first_char = n[i:i+1]
      last_char = n[-(i+1)]

      if first_char != last_char:
        return False

    return True

并运行函数:

start = time.time()
calculator = PalindromeCalculator();
M = calculator.find_max_palindrome()
elapsed = (time.time() - start)

print "My way: %s found in %s seconds" % (M, elapsed)

【问题讨论】:

  • 只是一个小错字,但很难找到:您从未在构造函数中使用 min_factor 参数。

标签: python recursion


【解决方案1】:

检查这个:maximum recursion depth exceeded while calling a Python object

无论如何,为它编写一个迭代算法非常简单,因此不需要使用递归。

【讨论】:

    【解决方案2】:

    这类似于 Java 中的 StackOverflowError。因为check_next_product 如此频繁地调用自己,所以嵌套的函数调用太多,Python 已经放弃了对它们的跟踪。您可以增加递归限制,但递归如此之深的事实表明您最好编写一个迭代解决方案。递归并不真正适合这个问题。

    【讨论】:

      猜你喜欢
      • 2011-12-31
      • 1970-01-01
      • 1970-01-01
      • 2020-07-13
      • 2021-02-07
      • 2017-03-18
      • 2015-04-15
      • 1970-01-01
      • 2013-12-01
      相关资源
      最近更新 更多