[Python] python中使用尾递归代码范例 →→→→→进入此内容的聊天室

来自 , 2020-02-05, 写在 Python, 查看 108 次.
URL http://www.code666.cn/view/30ba1057
  1. # This program shows off a python decorator(
  2. # which implements tail call optimization. It
  3. # does this by throwing an exception if it is
  4. # it's own grandparent, and catching such
  5. # exceptions to recall the stack.
  6.  
  7. import sys
  8.  
  9. class TailRecurseException:
  10.   def __init__(self, args, kwargs):
  11.     self.args = args
  12.     self.kwargs = kwargs
  13.  
  14. def tail_call_optimized(g):
  15.   """
  16.  This function decorates a function with tail call
  17.  optimization. It does this by throwing an exception
  18.  if it is it's own grandparent, and catching such
  19.  exceptions to fake the tail call optimization.
  20.  
  21.  This function fails if the decorated
  22.  function recurses in a non-tail context.
  23.  """
  24.   def func(*args, **kwargs):
  25.     f = sys._getframe()
  26.     if f.f_back and f.f_back.f_back and f.f_back.f_back.f_code == f.f_code:
  27.       raise TailRecurseException(args, kwargs)
  28.     else:
  29.       while 1:
  30.         try:
  31.           return g(*args, **kwargs)
  32.         except TailRecurseException, e:
  33.           args = e.args
  34.           kwargs = e.kwargs
  35.   func.__doc__ = g.__doc__
  36.   return func
  37.  
  38. @tail_call_optimized
  39. def factorial(n, acc=1):
  40.   "calculate a factorial"
  41.   if n == 0:
  42.     return acc
  43.   return factorial(n-1, n*acc)
  44.  
  45. print factorial(10000)
  46. # prints a big, big number,
  47. # but doesn't hit the recursion limit.
  48.  
  49. @tail_call_optimized
  50. def fib(i, current = 0, next = 1):
  51.   if i == 0:
  52.     return current
  53.   else:
  54.     return fib(i - 1, next, current + next)
  55.  
  56. print fib(10000)
  57. # also prints a big number,
  58. # but doesn't hit the recursion limit.
  59. #//python/8192

回复 "python中使用尾递归代码范例"

这儿你可以回复上面这条便签

captcha