python中尾递归用法实例详解

yipeiwu_com6年前Python基础

本文实例讲述了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中字符串对象提供了很多方法来操作字符串,功能相当丰富。 print(dir(str)) [..........'capitalize', 'casefold',...

解决Python3 被PHP程序调用执行返回乱码的问题

因为有一部分程序是 Python 写的,所以需要 PHP 调用 Python 程序返回数据,使用 exec 返回的是乱码 $data = "Geek程序员" $get = exec(...

python 线程的暂停, 恢复, 退出详解及实例

python 线程的暂停, 恢复, 退出详解及实例

python 线程 暂停, 恢复, 退出 我们都知道python中可以是threading模块实现多线程, 但是模块并没有提供暂停, 恢复和停止线程的方法, 一旦线程对象调用start方...

Windows和Linux下Python输出彩色文字的方法教程

Windows和Linux下Python输出彩色文字的方法教程

前言 最近在项目中需要输出彩色的文字来提醒用户,以前写过,但是只能在win上面运行。 今天搜了下看有没有在win和Linux上通用的输出彩色文字的模块,结果发现没有,,于是就自己弄了一个...

Python中处理时间的几种方法小结

从一个字符串开始 在CODE上查看代码片派生到我的代码片 >>>time_str='2008-08-08 08:08:08'  1.1.转换...