问题:
I have the following piece of code which fails with the following error:我有以下代码失败并出现以下错误:
RuntimeError: maximum recursion depth exceeded运行时错误:超出最大递归深度
I attempted to rewrite this to allow for tail recursion optimization (TCO).我试图重写它以允许尾递归优化(TCO)。 I believe that this code should have been successful if a TCO had taken place.我相信如果发生 TCO,此代码应该会成功。
def trisum(n, csum):
if n == 0:
return csum
else:
return trisum(n - 1, csum + n)
print(trisum(1000, 0))
Should I conclude that Python does not do any type of TCO, or do I just need to define it differently?我应该得出结论,Python 不承担任何类型的 TCO,还是我只需要对其进行不同的定义?
解决方案:
参考一: https://stackoom.com/question/v1tK参考二: Does Python optimize tail recursion?