我有这个脚本:
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:])