Skip to content

Instantly share code, notes, and snippets.

@en0
Created July 4, 2019 20:50
Show Gist options
  • Save en0/38e82430a04884bfd212a4cbb1246eb0 to your computer and use it in GitHub Desktop.
Save en0/38e82430a04884bfd212a4cbb1246eb0 to your computer and use it in GitHub Desktop.
Tail Recursion Optimizations in Python
class BreakOutStack(Exception):
"""Raised to clear stack frame and reset"""
def __init__(self, *args):
self.args = args
def tail_recursive(fn):
def _wrapped_tail_recursive(*args):
while True:
try:
return fn(*args)
except BreakOutStack as b:
args = b.args
return _wrapped_tail_recursive
def recurse(*args):
raise BreakOutStack(*args)
@tail_recursive
def factoral(n, a = 1):
if n < 1:
raise Exception("Bad Input")
if n == 1:
return a
return recurse(n - 1, n * a)
@tail_recursive
def fibonnacci(n, a = 0, b = 1):
if n < 0:
raise Exception("Bad Input")
if n == 0:
return a
if n == 1:
return b
return recurse(n - 1, b, a + b)
n = 100000
fn = fibonnacci
print("fn({}) => {}".format(n, fn(n)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment