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中的偏函数
Apr 27 Python
基于wxpython开发的简单gui计算器实例
May 30 Python
Python中的自省(反射)详解
Jun 02 Python
Python利用matplotlib.pyplot绘图时如何设置坐标轴刻度
Apr 09 Python
python中使用iterrows()对dataframe进行遍历的实例
Jun 09 Python
Python 查看list中是否含有某元素的方法
Jun 27 Python
说说如何遍历Python列表的方法示例
Feb 11 Python
基于python历史天气采集的分析
Feb 14 Python
利用matplotlib为图片上添加触发事件进行交互
Apr 23 Python
解决导入django_filters不成功问题No module named 'django_filter'
Jul 15 Python
python与c语言的语法有哪些不一样的
Sep 13 Python
OpenCV-Python实现图像平滑处理操作
Jun 08 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实现统计目录文件大小的函数
2015/12/25 PHP
在Mac OS上搭建PHP的Yii框架及相关测试环境
2016/02/14 PHP
PHP url的pathinfo模式加载不同控制器的简单实现
2016/08/12 PHP
PHP生成word文档的三种实现方式
2016/11/14 PHP
jquery关于图形报表的运用实现代码
2011/01/06 Javascript
33个优秀的 jQuery 图片展示插件分享
2012/03/14 Javascript
解释&&和||在javascript中的另类用法
2014/07/28 Javascript
JS验证IP,子网掩码,网关和MAC的方法
2015/07/02 Javascript
javascript实现表单验证
2016/01/29 Javascript
基于jQuery实现歌词滚动版音乐播放器的代码
2016/09/17 Javascript
Vue2.0如何发布项目实战
2017/07/27 Javascript
get  post jsonp三种数据交互形式实例详解
2017/08/25 Javascript
详解angular脏检查原理及伪代码实现
2018/06/08 Javascript
Vue在chrome44偶现点击子元素事件无法冒泡的解决方法
2019/12/15 Javascript
微信小程序图片右边加两行文字的代码
2020/04/23 Javascript
Openlayers实现地图的基本操作
2020/09/28 Javascript
由浅入深讲解python中的yield与generator
2017/04/05 Python
linux环境下的python安装过程图解(含setuptools)
2017/11/22 Python
Python实现判断给定列表是否有重复元素的方法
2018/04/11 Python
Python实现去除列表中重复元素的方法小结【4种方法】
2018/04/27 Python
Python实现Restful API的例子
2019/08/31 Python
pytorch 实现cross entropy损失函数计算方式
2020/01/02 Python
python 中的命名空间,你真的了解吗?
2020/08/19 Python
Python实现微信表情包炸群功能
2021/01/28 Python
纯CSS3实现绘制各种图形实现代码详细整理
2012/12/26 HTML / CSS
全球知名的婚恋交友网站:Match.com
2017/01/05 全球购物
The Body Shop美体小铺西班牙官网:天然化妆品
2019/06/21 全球购物
数据库连接池的工作原理
2012/09/26 面试题
公司中秋节活动方案
2014/02/12 职场文书
初中作文评语集锦
2014/12/25 职场文书
淘宝好评语句大全
2014/12/31 职场文书
泰坦尼克号观后感
2015/06/04 职场文书
《桂花雨》教学反思
2016/02/19 职场文书
员工给公司的建议书
2019/06/24 职场文书
react中props 的使用及进行限制的方法
2021/04/28 Javascript
使用php的mail()函数实现发送邮件功能
2021/06/03 PHP