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