【问题标题】:Why do I keep getting the maximum recursion depth exceeded error?为什么我不断收到超出最大递归深度的错误?
【发布时间】:2016-01-09 08:17:06
【问题描述】:

我正在为一个猜数游戏编写代码,它必须通过递归出售。但是当我执行它时,我得到了这个错误:超出了最大递归深度。这是为什么?

这是我的代码:

import random
n = random.randrange(0,100)
guess = int(input("Introduce a number: "))
def game(guess):
    if guess == n:
        print("Your guess is correct.")
    elif guess > n:
        print("Your guess is too high")
        game(guess)
    elif guess < n:
        print("Your guess is too low")
        game(guess)
game(guess)

【问题讨论】:

  • 因为你永远不会有新的猜测。如果猜测太高或太低,它只会永远重复。
  • @Sebastian 你在吗? :) 请选择一个正确的答案。只有我的答案有递归函数设计。 :)

标签: python recursion


【解决方案1】:

原因是,除非您第一次调用该函数时guess 等于n,否则您将拥有无限递归,因为您调用game 时具有相同的guess 值。您没有提供任何方法来停止递归。

【讨论】:

    【解决方案2】:

    您的游戏功能不需要任何参数。您需要使用else 而不是最后一个elif 并且guess = int(input("Introduce a number: ")) 步骤应该在您的游戏功能中(已测试):

    import random
    n = random.randrange(0,100)
    def game():
        guess = int(input("Introduce a number: "))
        if guess == n:
            print("Your guess is correct.")
        elif guess > n:
            print("Your guess is too high")
            game()
        else:
            print("Your guess is too low")
            game()
    game()
    

    【讨论】:

    • 那可不行,如果你在这个游戏中表现很糟糕,你最终会毁了堆栈。
    • @JeffMercado 我确定塞巴斯蒂安的老师想要一个递归函数来完成他的作业:)
    • 那将是一个延伸。递归在这里没有立足之地,我怀疑任何称职的老师都会以注定失败的方式促进编写代码。
    • @JeffMercado 这是理解递归函数如何工作的基本任务。我在工程部门见过很多次:)
    • 啊,我错过了问题中说需要递归的部分(排序)。无论如何,有更好的方法来教授递归,但这不是它的用例。哦,好吧。
    【解决方案3】:
    1. 你需要像这样使用random.randint()函数:n = random.randint(0, 100)
    2. 建议使用while 循环。
    3. 您没有再次致电guess = int(input("Introduce a number: "))

    import random
    n = random.randint(0, 100)
    guess = int(input("Introduce a number: "))
    
    def game(guess):
        while guess != n:
            if guess > n:
                print("Your guess is too high")
            elif guess < n:
                print("Your guess is too low")
            guess = int(input("Introduce a number: "))
    
        else:
            print("Your guess is correct.")
    
    game(guess)
    

    【讨论】:

      【解决方案4】:

      maximum recursion depth exceeded 在满足guess &gt; nguess &lt; n 条件时由于无限循环而发生。 如需进一步了解,请参阅this question

      下面的代码应该可以按预期工作。

      import random,sys
      n = random.randrange(0,100)
      
      def game(guess):
          if guess == n:
              print("Your guess is correct.")
              sys.exit()
          elif guess > n:
              print("Your guess is too high")
          elif guess < n:
              print("Your guess is too low")
      
      while True:
          guess = int(input("Introduce a number: "))
          game(guess)
      

      【讨论】:

      • 我认为塞巴斯蒂安的老师想要一个递归函数来完成他的作业:) 那么你的答案对他不利:D
      猜你喜欢
      • 2016-12-10
      • 1970-01-01
      • 1970-01-01
      • 2018-12-03
      • 2017-07-18
      • 2021-12-11
      • 2019-07-03
      • 2020-09-30
      • 2017-08-24
      相关资源
      最近更新 更多