码迷,mamicode.com
首页 > 编程语言 > 详细

python中使用尾递归源码范例

时间:2019-02-05 15:38:38      阅读:206      评论:0      收藏:0      [点我收藏+]

标签:rate   lse   throw   zed   war   内容   contex   function   ack   

工作过程中,把写内容过程中经常用的一些内容做个备份,如下资料是关于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.
"""
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:
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

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中使用尾递归源码范例

标签:rate   lse   throw   zed   war   内容   contex   function   ack   

原文地址:https://www.cnblogs.com/stegosaurus/p/10352778.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!