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). I believe that this code should have been successful if a TCO had taken place.
JavaScript
x
8
1
def trisum(n, csum):
2
if n == 0:
3
return csum
4
else:
5
return trisum(n - 1, csum + n)
6
7
print(trisum(1000, 0))
8
Should I conclude that Python does not do any type of TCO, or do I just need to define it differently?
Advertisement
Answer
No, and it never will since Guido van Rossum prefers to be able to have proper tracebacks:
Tail Recursion Elimination (2009-04-22)
Final Words on Tail Calls (2009-04-27)
You can manually eliminate the recursion with a transformation like this:
JavaScript
1
9
1
>>> def trisum(n, csum):
2
while True: # Change recursion to a while loop
3
if n == 0:
4
return csum
5
n, csum = n - 1, csum + n # Update parameters instead of tail recursion
6
7
>>> trisum(1000,0)
8
500500
9