尾递归

本文深入解析尾递归的概念及其与一般递归的区别,通过斐波那契数列的实例对比普通递归与尾递归的实现,强调尾递归在时间和空间上的优化,并介绍如何在Python中通过装饰器实现尾递归优化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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

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

推荐博客:https://blog.youkuaiyun.com/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)
 

  

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

 

转载于:https://www.cnblogs.com/perfey/p/10096649.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值