繁体   English   中英

试图解决 Python 中的递归

[英]Trying to solve recursion in Python

下面的一段代码是我自己和一位同事最近遇到的争论。 我相信该程序是递归的,而他坚持认为不是。

另一个 Stackoverflow 帖子有确切的代码,并被声明为递归的。

请问有人可以给我一个解释,如果它是递归的,为什么?

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;博士; 定义的方法是recursive ,你可以调用它足够的次数来强制一个Recursion Error类型的异常,因为它每次调用自己时都会添加到堆栈中。 但这并不意味着它是最好的方法。

根据定义递归function 旨在通过有限数量的语句来解决问题,同时每次使问题变小,直到您到达基本情况(即从该递归返回时)。 它还暗示 function 在代码中调用自身。

如果我们粗略地将其置于项目符号列表样式中,则递归 function 可以描述为:

  • 基本情况,返回发生在 function
  • Function 调用自身并传递相同的数据,但经过修改,“更小”

到目前为止,您粘贴的代码执行这两个之一 它在 function 中调用自己(尽管它不会简化问题或传递数据)。 function 没有解决问题的基本案例,只有一个案例。

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

当您执行包含所提供代码的文件时,定义之外的调用将执行一次,但随后在 function 内部,只要用户不键入quit ,它就会再次调用自身。 虽然它看起来像是一个花哨的永远循环,但这可以归类为递归方法,因为它在 function 定义中调用自身。 现在,这是一个可怕的递归 function,因为您不需要它递归即可按预期工作。 您永远不会返回任何内容,并且每次调用 function str_replace_interface()时,您都会将其添加到堆栈中,如果您调用它的次数足够多,则可能会导致RecursionError 让我们这样做来看看它的实际效果。 为此,我将删除让用户退出的代码,并删除输入,这样我就不必在一个单词中输入一百万次了。

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

为什么? 因为 function 实际上从来没有返回任何东西,这就是为什么我提到递归地创建一个永久循环是可怕的。 您可以迭代地实现相同的目标,如下所示:

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)
            return True
        return False    

while str_replace_interface():
  pass

在这里,永远循环的力量基于执行 function 后的返回值 您不会在每次调用时都添加到堆栈中,因为 function 实际上会返回。 现在,如果我们像递归调用那样一遍又一遍地强制连续调用会发生什么? 好吧,答案是什么都没有。 你将有一个永远的循环......嗯,永远。 但是您不会收到递归错误,因为 function 在再次调用之前执行并返回。 试试看:

def str_replace_interface():   
        return True

while str_replace_interface():
  pass 

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

我希望这可以帮助您清除它。

这个 function 不是递归的,因为它不调用自身。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM