尝试在Python中解决递归
下面这段代码是我和一位同事最近进行的一场辩论。我相信这个程序是递归的,而他坚持认为不是 另一个Stackoverflow post具有精确的代码,并声明为递归 请有人给我一个解释,如果它是或不是递归的,为什么尝试在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
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;博士定义的方法是递归,您可以调用它足够多次,以强制执行类型为递归错误的异常,因为它每次调用自身时都会添加到堆栈中。但这并不意味着这是最好的方法 通过递归函数,可以通过有限的语句解决问题,同时每次都使问题变小,直到达到基本情况(即从递归性返回时)。它还意味着在代码中调用自身的函数 如果我们粗略地将其放在项目符号列表样式中,则递归函数可以通过以下方式描述:
- 基本情况,返回发生在函数中
- 函数调用自身并传递相同的数据,但修改为“更小”
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