📜 ⬆️ ⬇️

Python - tail recursion optimization

It's no secret that Python does not optimize tail recursion. Moreover, Guido himself is opposed to this. But if anyone needs it, there is a small, elegant solution. Under the cut ...

A simple solution


class recursion(object): "Can call other methods inside..." def __init__(self, func): self.func = func def __call__(self, *args, **kwargs): result = self.func(*args, **kwargs) while callable(result): result = result() return result def call(self, *args, **kwargs): return lambda: self.func(*args, **kwargs) @recursion def sum_natural(x, result=0): if x == 0: return result else: return sum_natural.call(x - 1, result + x) #       # RuntimeError: maximum recursion depth exceeded print(sum_natural(1000000)) 

By the way, you can call each other's functions in any order. The code handles this case perfectly:
 @recursion def sum_natural_x(x, result=0): if x == 0: return result else: return sum_natural_y.call(x - 1, result + x) @recursion def sum_natural_y(y, result=0): if y == 0: return result else: return sum_natural_x.call(y - 1, result + y) print(sum_natural_x(1000000)) 

This is the Erlang particle in Python)

')

Source: https://habr.com/ru/post/158385/


All Articles