尝试在Python中解决递归

尝试在Python中解决递归,python,recursion,Python,Recursion,下面这段代码是我和一位同事最近进行的一场辩论。我相信这个程序是递归的,而他坚持认为不是 另一个Stackoverflow post具有精确的代码,并声明为递归 请有人给我一个解释,如果它是或不是递归的,为什么 def str_replace_interface(): word = input("Enter a word: ") if word != 'quit': substring = input("Please enter the substring y

下面这段代码是我和一位同事最近进行的一场辩论。我相信这个程序是递归的,而他坚持认为不是

另一个Stackoverflow post具有精确的代码,并声明为递归

请有人给我一个解释,如果它是或不是递归的,为什么

def str_replace_interface():   
    word = input("Enter a word: ")
    if word != 'quit':
        substring = input("Please enter the substring you wish to find: ")
        new_entry = input("Please enter a string to replace the given substring:")
        new_word = word.replace(substring, new_entry)
        print("Your new string is: " + new_word)
        str_replace_interface()

str_replace_interface() 

上面提到的代码可能运行得很好,但它是否仍被归类为“递归”?

tl;博士定义的方法是递归,您可以调用它足够多次,以强制执行类型为递归错误的异常,因为它每次调用自身时都会添加到堆栈中。但这并不意味着这是最好的方法

通过递归函数,可以通过有限的语句解决问题,同时每次都使问题变小,直到达到基本情况(即从递归性返回时)。它还意味着在代码中调用自身的函数

如果我们粗略地将其放在项目符号列表样式中,则递归函数可以通过以下方式描述:

  • 基本情况,返回发生在函数中
  • 函数调用自身并传递相同的数据,但修改为“更小”
到目前为止,您粘贴的代码只执行这两个代码中的一个。它在函数中调用自身(尽管它不会简化问题或传递数据)。函数没有解决问题的基本情况,只有一种情况

粘贴在问题中的代码似乎希望成为一个不断迭代的循环,但实现这一点的方法是通过递归调用完成的:

当执行包含所提供代码的文件时,定义之外的调用将执行一次,但在函数内部,只要用户不键入quit,它将再次调用自身。虽然它看起来像是一个奇特的永久循环,但它可以被归类为一个递归方法,因为它在函数定义内部调用自己。现在,它是一个糟糕的递归函数,因为你不需要它是递归的才能按预期工作。您从不返回任何内容,每次调用函数str\u replace\u interface()时,您都在向堆栈中添加内容,如果调用次数足够多,可能会导致递归错误。让我们这样做,看看它的行动。为了实现这一点,我将删除允许用户退出的代码,并删除输入,这样我就不必一个字输入一百万次

def str_replace_interface():   
        str_replace_interface()


str_replace_interface() 
当我执行时,正如预期的那样,我得到了以下信息:

Traceback (most recent call last):
  File "main.py", line 8, in <module>
    str_replace_interface()
  File "main.py", line 5, in str_replace_interface
    str_replace_interface()
  File "main.py", line 5, in str_replace_interface
    str_replace_interface()
  File "main.py", line 5, in str_replace_interface
    str_replace_interface()
  [Previous line repeated 992 more times]
  File "main.py", line 4, in str_replace_interface
RecursionError: maximum recursion depth exceeded while calling a Python object
在这里,永久循环的威力基于执行函数后返回的而产生。您没有在每次调用时添加到堆栈中,因为函数实际返回。现在,如果我们像递归调用一样一遍又一遍地强制执行连续调用,会发生什么?答案是什么都没有。你会有一个永远的循环…好吧,永远。但不会出现递归错误,因为函数在再次调用之前执行并返回。试一试:

def str_replace_interface():   
        return True

while str_replace_interface():
  pass 
看看它如何不引发异常?它只是挂在那里。您必须强制终止执行以使其停止,但不会发生异常


我希望这能帮你把事情弄清楚

由于更新后的问题将其全部删除,评论已被删除。非常感谢您最终结束了这场辩论!你的回答措辞完美,并用最简单的形式加以分解。非常感谢。@adamgreeve没问题,这就是社区的目的:)回答这个问题很有趣,找到一个合适的解释方法。
def str_replace_interface():   
        return True

while str_replace_interface():
  pass