尾递归

尾递归即在递归函数中不使用新的变量,经过在函数中传参的形式传递变量python

尾递归基于函数的尾调用, 每一级调用直接返回函数的返回值更新调用栈,而不用建立新的调用栈, 相似迭代的实现, 时间和空间上均优化了通常递归!函数

把计算出的值存在函数内部(固然不止尾递归)是其计算方法,从而不用在栈中去建立一个新的,这样就大大节省了空间。函数调用中最后返回的结果是单纯的递归函数调用(或返回结果)就是尾递归优化

推荐博客:https://blog.csdn.net/qq_39521554/article/details/80112748this

尾递归其实就是while循环的一种变形,全部能用尾递归写出来的均可以用while循环写出来.net

 

斐波那契数code

普通递归blog

def Fib(n):
     if n<3:
         return 1
     else:               
         return Fib(n-1) + Fib(n-2)

 

尾递归递归

def Fib(n,b1=1,b2=1,c=3):
     if n<3:
         return 1
     else:
         if n==c:
             return b1+b2
         else:
             return Fib(n,b1=b2,b2=b1+b2,c=c+1)

  

因为python解释器对尾递归没有作优化,因此这样栈的使用仍是没有减小,下面使用装饰器get

@tail_call_optimized
def Fib(n,b1=1,b2=1,c=3):
     if n<3:
         return 1
     else:
         if n==c:
             return b1+b2
         else:
             return Fib(n,b1=b2,b2=b1+b2,c=c+1)

  

 

 

装饰器代码博客

#!/usr/bin/env python2.4
# This program shows off a python decorator(
# which implements tail call optimization. It
# does this by throwing an exception if it is
# it's own grandparent, and catching such
# exceptions to recall the stack.
 
import sys
 
class TailRecurseException:
    def __init__(self, args, kwargs):
        self.args = args
        self.kwargs = kwargs
 
def tail_call_optimized(g):
    """
    This function decorates a function with tail call
    optimization. It does this by throwing an exception
    if it is it's own grandparent, and catching such
    exceptions to fake the tail call optimization.
 
    This function fails if the decorated
    function recurses in a non-tail context.
    """
    def func(*args, **kwargs):
        f = sys._getframe()
        # 为何是grandparent, 函数默认的第一层递归是父调用,
        # 对于尾递归, 不但愿产生新的函数调用(即:祖父调用),
        # 因此这里抛出异常, 拿到参数, 退出被修饰函数的递归调用栈!(后面有动图分析)
        if f.f_back and f.f_back.f_back \
            and f.f_back.f_back.f_code == f.f_code:
            # 抛出异常
            raise TailRecurseException(args, kwargs)
        else:
            while 1:
                try:
                    return g(*args, **kwargs)
                except TailRecurseException, e:
                    # 捕获异常, 拿到参数, 退出被修饰函数的递归调用栈
                    args = e.args
                    kwargs = e.kwargs
    func.__doc__ = g.__doc__
    return func
 
@tail_call_optimized
def factorial(n, acc=1):
    "calculate a factorial"
    if n == 0:
        return acc
    return factorial(n-1, n*acc)
 
print factorial(10000)
 

  

思考:若是尾递归中的参数中传递一个函数的地址,是否可行,是否会减小逻辑

相关文章
相关标签/搜索