python中尾递归用法实例详解


Posted in Python onApril 28, 2015

本文实例讲述了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 相关文章推荐
python使用scrapy解析js示例
Jan 23 Python
Python下的Mysql模块MySQLdb安装详解
Apr 09 Python
Python发送以整个文件夹的内容为附件的邮件的教程
May 06 Python
Django中处理出错页面的方法
Jul 15 Python
Windows和Linux下Python输出彩色文字的方法教程
May 02 Python
浅谈django url请求与数据库连接池的共享问题
Aug 29 Python
django admin 根据choice字段选择的不同来显示不同的页面方式
May 13 Python
如何让python的运行速度得到提升
Jul 08 Python
Pytorch框架实现mnist手写库识别(与tensorflow对比)
Jul 20 Python
Python自动巡检H3C交换机实现过程解析
Aug 14 Python
PyCharm Ctrl+Shift+F 失灵的简单有效解决操作
Jan 15 Python
详细介绍python类及类的用法
May 31 Python
在Python中使用元类的教程
Apr 28 #Python
python删除列表中重复记录的方法
Apr 28 #Python
python3实现短网址和数字相互转换的方法
Apr 28 #Python
python实现从网络下载文件并获得文件大小及类型的方法
Apr 28 #Python
浅析Python中的多重继承
Apr 28 #Python
python输出当前目录下index.html文件路径的方法
Apr 28 #Python
Python实现基于权重的随机数2种方法
Apr 28 #Python
You might like
php加水印的代码(支持半透明透明打水印,支持png透明背景)
2013/01/17 PHP
PHP编程实现计算抽奖概率算法完整实例
2017/08/09 PHP
[原创]PHP实现生成vcf vcard文件功能类定义与使用方法详解【附demo源码下载】
2017/09/02 PHP
javascript 鼠标悬浮图片显示原图 移出鼠标后原图消失(多图)
2009/12/28 Javascript
Javascript学习笔记6 prototype的提出
2010/01/11 Javascript
jQuery.clean使用方法及思路分析
2013/01/07 Javascript
求数组最大最小值方法适用于任何数组
2013/08/16 Javascript
JavaScript sub方法入门实例(把字符串显示为下标)
2014/10/17 Javascript
简单谈谈jQuery(function(){})与(function(){})(jQuery)
2014/12/19 Javascript
使用VS开发 Node.js指南
2015/01/06 Javascript
javascript中一些util方法汇总
2015/06/10 Javascript
JavaScript基本数据类型及值类型和引用类型
2015/08/25 Javascript
jqueryUI tab标签页代码分享
2017/10/09 jQuery
JS实现验证码倒计时的注册页面
2018/01/02 Javascript
vue2.0使用v-for循环制作多级嵌套菜单栏
2018/06/25 Javascript
解决vue+element 键盘回车事件导致页面刷新的问题
2018/08/25 Javascript
js实现前面自动补全位数的方法
2018/10/10 Javascript
Angular 中使用 FineReport不显示报表直接打印预览
2019/08/21 Javascript
vant 中van-list的用法说明
2020/11/11 Javascript
深入了解Vue动态组件和异步组件
2021/01/26 Vue.js
python使用标准库根据进程名如何获取进程的pid详解
2017/10/31 Python
Python如何快速上手? 快速掌握一门新语言的方法
2017/11/14 Python
Python使用Pickle库实现读写序列操作示例
2018/06/15 Python
Python + Requests + Unittest接口自动化测试实例分析
2019/12/12 Python
CSS3制作缩略图的详细过程
2016/07/08 HTML / CSS
CSS3中媒体查询结合rem布局适配手机屏幕
2019/06/10 HTML / CSS
Sneaker Studio捷克:购买运动鞋
2018/07/08 全球购物
Myprotein丹麦官网:欧洲第一运动营养品牌
2019/04/15 全球购物
软件专业毕业生个人自我鉴定
2014/04/17 职场文书
2014医学院领导干部四风对照检查材料思想汇报
2014/09/16 职场文书
党员学习群众路线心得体会
2014/11/04 职场文书
2014年维修电工工作总结
2014/11/20 职场文书
2015年党员个人剖析材料
2014/12/18 职场文书
硕士毕业答辩开场白
2015/05/27 职场文书
学生会宣传部竞选稿
2015/11/21 职场文书
部分武汉产收音机展览
2022/04/07 无线电