Python 是否优化了尾递归? - Does Python optimize tail recursion?

问题:

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?
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章