在python类、项目Euler#4中超过了最大递归深度

2024-06-02 06:59:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在为欧拉计划的问题4制定一个解决方案:

“从两个3位数的乘积中找出最大的回文。”

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

我已经离开python一段时间了,所以我使用这些练习来熟悉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)

Tags: inselfreturniftimedefcheckproduct
2条回答

检查此项:maximum recursion depth exceeded while calling a Python object

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

这类似于Java中的StackOverflowError。因为check_next_product本身调用太多,所以嵌套函数调用太多,Python已经放弃了跟踪它们。您可以增加递归限制,但递归太深的事实表明,编写一个迭代解决方案会更好。递归并不适合这个问题。你知道吗

相关问题 更多 >