Advertisement
Guest User

Untitled

a guest
Jul 16th, 2019
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.84 KB | None | 0 0
  1. class BreakOutStack(Exception):
  2. """Raised to clear stack frame and reset"""
  3. def __init__(self, *args):
  4. self.args = args
  5.  
  6. def tail_recursive(fn):
  7. def _wrapped_tail_recursive(*args):
  8. while True:
  9. try:
  10. return fn(*args)
  11. except BreakOutStack as b:
  12. args = b.args
  13.  
  14. return _wrapped_tail_recursive
  15.  
  16. def recurse(*args):
  17. raise BreakOutStack(*args)
  18.  
  19. @tail_recursive
  20. def factoral(n, a = 1):
  21.  
  22. if n < 1:
  23. raise Exception("Bad Input")
  24.  
  25. if n == 1:
  26. return a
  27.  
  28. return recurse(n - 1, n * a)
  29.  
  30. @tail_recursive
  31. def fibonnacci(n, a = 0, b = 1):
  32.  
  33. if n < 0:
  34. raise Exception("Bad Input")
  35.  
  36. if n == 0:
  37. return a
  38.  
  39. if n == 1:
  40. return b
  41.  
  42. return recurse(n - 1, b, a + b)
  43.  
  44. n = 100000
  45. fn = fibonnacci
  46.  
  47. print("fn({}) => {}".format(n, fn(n)))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement