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版
Dec 07 Python
python抓取网页图片并放到指定文件夹
Apr 24 Python
高质量Python代码编写的5个优化技巧
Nov 16 Python
django2 快速安装指南分享
Jan 05 Python
Python+OpenCV采集本地摄像头的视频
Apr 25 Python
对python tkinter窗口弹出置顶的方法详解
Jun 14 Python
python 修改本地网络配置的方法
Aug 14 Python
Python获取、格式化当前时间日期的方法
Feb 10 Python
spyder 在控制台(console)执行python文件,debug python程序方式
Apr 20 Python
让Django的BooleanField支持字符串形式的输入方式
May 20 Python
详解selenium + chromedriver 被反爬的解决方法
Oct 28 Python
单身狗福利?Python爬取某婚恋网征婚数据
Jun 03 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
MySQL数据库转移,access,sql server 转 MySQL 的图文教程
2007/09/02 PHP
PHP中str_replace函数使用小结
2008/10/11 PHP
为IP查询添加GOOGLE地图功能的代码
2010/08/08 PHP
dedecms中使用php语句指南
2014/11/13 PHP
PHP生成plist数据的方法
2015/06/16 PHP
js之WEB开发调试利器:Firebug 下载
2007/01/13 Javascript
jquery 与NVelocity 产生冲突的解决方法
2011/06/13 Javascript
如何使Chrome控制台支持多行js模式——意外发现
2013/06/13 Javascript
PHP实现的各种中文编码转换类分享
2015/01/23 Javascript
Javascript writable特性介绍
2015/02/27 Javascript
利用vue写todolist单页应用
2016/12/15 Javascript
vue轮播图插件vue-concise-slider的使用
2018/03/13 Javascript
nodejs 日志模块winston的使用方法
2018/05/02 NodeJs
Vue.set() this.$set()引发的视图更新思考及注意事项
2018/08/30 Javascript
在vue项目中使用Jquery-contextmenu插件的步骤讲解
2019/01/27 jQuery
layui type2 通过url给iframe子页面传值的例子
2019/09/06 Javascript
vue实现按钮切换图片
2021/01/20 Vue.js
[54:41]2018DOTA2亚洲邀请赛3月30日 小组赛B组 VGJ.T VS paiN
2018/03/31 DOTA
[原创]python爬虫(入门教程、视频教程)
2018/01/08 Python
详解python深浅拷贝区别
2019/06/24 Python
python的pytest框架之命令行参数详解(下)
2019/06/27 Python
wxpython绘制音频效果
2019/11/18 Python
Python测试Kafka集群(pykafka)实例
2019/12/23 Python
Python破解BiliBili滑块验证码的思路详解(完美避开人机识别)
2020/02/17 Python
Python如何测试stdout输出
2020/08/10 Python
美国玛丽莎收藏奢华时尚商店:Marissa Collections
2016/11/21 全球购物
Clarks鞋法国官方网站:英国其乐鞋品牌
2018/02/11 全球购物
TripAdvisor斯洛伐克:阅读评论、比较价格和酒店预订
2018/04/25 全球购物
北京SQL新华信咨询
2016/09/30 面试题
党支部组织生活会整改方案
2014/09/30 职场文书
婚礼女方父母答谢词
2015/01/04 职场文书
2015年出纳工作总结与计划
2015/05/18 职场文书
党员理论学习心得体会
2016/01/21 职场文书
关于做家务的心得体会
2016/01/23 职场文书
SQLServer之常用函数总结详解
2021/08/30 SQL Server
Linux中sftp常用命令整理
2022/06/28 Servers