尾递归即在递归函数中不使用新的变量,通过在函数中传参的形式传递变量
尾递归基于函数的尾调用, 每一级调用直接返回函数的返回值更新调用栈,而不用创建新的调用栈, 类似迭代的实现, 时间和空间上均优化了一般递归!
把计算出的值存在函数内部(当然不止尾递归)是其计算方法,从而不用在栈中去创建一个新的,这样就大大节省了空间。函数调用中最后返回的结果是单纯的递归函数调用(或返回结果)就是尾递归
推荐博客:https://blog.csdn.net/qq_39521554/article/details/80112748
尾递归其实就是while循环的一种变形,所有能用尾递归写出来的都可以用while循环写出来
斐波那契数
普通递归
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解释器对尾递归没有做优化,所以这样栈的使用还是没有减少,下面使用装饰器
@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)
思考:如果尾递归中的参数中传递一个函数的地址,是否可行,是否会减少逻辑