python中尾递归用法实例详解

作者:feiwen 时间:2023-10-09 06:46:15 

本文实例讲述了python中尾递归用法。分享给大家供大家参考。具体分析如下:

如果一个函数中所有递归形式的调用都出现在函数的末尾,我们称这个递归函数是尾递归的。当递归调用是整个函数体中最后执行的语句且它的返回值不属于表达式的一部分时,这个递归调用就是尾递归。尾递归函数的特点是在回归过程中不用做任何操作,这个特性很重要,因为大多数现代的编译器会利用这种特点自动生成优化的代码。

原理:

当编译器检测到一个函数调用是尾递归的时候,它就覆盖当前的活跃记录而不是在栈中去创建一个新的。编译器可以做到这点,因为递归调用是当前活跃期内最后一条待执行的语句,于是当这个调用返回时栈帧中并没有其他事情可做,因此也就没有保存栈帧的必要了。通过覆盖当前的栈帧而不是在其之上重新添加一个,这样所使用的栈空间就大大缩减了,这使得实际的运行效率会变得更高。因此,只要有可能我们就需要将递归函数写成尾递归的形式.

代码:


# 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()
 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)
# prints a big, big number,
# but doesn't hit the recursion limit.
@tail_call_optimized
def fib(i, current = 0, next = 1):
if i == 0:
 return current
else:
 return fib(i - 1, next, current + next)
print fib(10000)
# also prints a big number,
# but doesn't hit the recursion limit.

希望本文所述对大家的Python程序设计有所帮助。

标签:python,尾递归
0
投稿

猜你喜欢

  • ASP实现长文章自动分页的函数代码

    2008-10-10 17:09:00
  • 对SQL Server数据库进行优化的经验总结

    2010-07-26 14:52:00
  • 原创一个js对联广告类(兼容FireFox)

    2008-08-01 18:08:00
  • 弹性+固宽布局

    2009-05-15 12:19:00
  • Oracle AS关键字 提示错误

    2011-04-18 12:42:00
  • Go标准容器之Ring的使用说明

    2023-09-21 02:18:14
  • php解析xml提示Invalid byte 1 of 1-byte UTF-8 sequence错误的处理方法

    2023-09-09 18:55:22
  • 微信小程序上传图片功能(附后端代码)

    2023-07-24 04:21:40
  • Python实现图像随机添加椒盐噪声和高斯噪声

    2023-06-13 22:54:36
  • sql函数:去掉html代码

    2008-04-07 12:44:00
  • asp空间判断jmail组件是否安装或支持的代码

    2011-02-16 10:49:00
  • 用Dreamweaver设计实现网页过渡转换功能

    2008-09-04 10:09:00
  • PHP扩展之kafka安装应用案例详解

    2023-09-06 09:53:43
  • Golang并发编程之调度器初始化详解

    2023-07-13 08:47:11
  • CSS3属性box-shadow图层阴影效果使用教程

    2010-05-16 14:54:00
  • CSS网页设计时关于字体大小的设计

    2008-10-23 13:42:00
  • Linux安装Python3如何和系统自带的Python2并存

    2023-08-25 03:42:09
  • 详细讲解如何为MySQL数据库添加新函数

    2008-11-27 17:06:00
  • ASP访问数量统计代码

    2011-04-08 10:59:00
  • asp动态页面生成html页面

    2008-10-24 09:03:00
  • asp之家 网络编程 m.aspxhome.com