[英]python recursive function error RuntimeError: maximum recursion depth exceeded
我有这个脚本:
def number_of_occurences(c, message):
position = message.find(c)
if position == -1:
return 0
else:
if len(message[position:]) == 0:
return position
else:
return position + number_of_occurences(c, message[position:])
number_of_occurences('a', 'azertya')
但是当我运行它时,我得到这个错误:
Traceback (most recent call last):
File "frequency_analysis.py", line 31, in <module>
number_of_occurences('a', 'azertya')
File "file_name.py", line 29, in number_of_occurences
return position + number_of_occurences(c, message[position:])
...
...
...
File "file_name.py", line 29, in number_of_occurences
return position + number_of_occurences(c, message[position:])
RuntimeError: maximum recursion depth exceeded
而且我知道这个类似的问题,但是并没有帮助,虽然花费了更长的时间,但是却给出了相同的错误:
sys.setrecursionlimit(10000)
和这个:
sys.setrecursionlimit(30000)
但是为此:
sys.setrecursionlimit(50000)
它给出了这个错误:
分段故障(核心已转储)
我在这里做错了什么? 提前致谢。
感谢@abarnet,这里是正确的代码:
def number_of_occurences(c, message):
position = message.find(c)
nbr = 0.0
if position == -1:
return 0
else:
nbr += 1
if len(message[position:]) == 0:
return nbr
else:
return nbr + number_of_occurences(c, message[position + 1:])
问题是您使用相同的参数递归调用自己,从而保证了无限递归。 设置递归限制有多高都没有关系。 您无法将其设置为无限远。*
使用您的参数手动跟踪它。
position = message.find(c) # = 'azertya'.find('a') = 0
if position == -1: # Nope
else:
if len(message[position:]) == 0: # len('azertya'[0:]) == len('azertya') == 7 != 0
else:
return position + number_of_occurences(c, message[position:])
# 0 + number_of_occurences('a', 'azertya'[0:])
# == 0 + number_of_occurences('a', 'azertya')
# which is exactly what we were called with
即使不以第一个字符开头,也可以以字符串中的任何字符开头,但最终还是会遇到相同的问题。 同样,尝试使用'r'
而不是'a'
跟踪。
通过像交互式可视化器运行这一个是比手动跟踪简单得多(和漂亮,更难以拧向上)。
另外,尝试每次print
出c
, message
和position
,这显然是怎么回事。
解决方法非常简单:
return position + number_of_occurences(c, message[position+1:])
*即使可以,即使堆栈与堆冲突,至少与CPython冲突,也会出现段错误。 这就是为什么只有50000出现段错误的原因。但是即使采用其他实现,例如Stackless或PyPy,一旦没有空间容纳更多堆栈帧,也会出现内存错误。 但是,如果您有无限的寻址空间和无限的虚拟页表空间,那么这不是问题,并且愿意永远等待……这仍然行不通,但是至少它永远不会失败。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.