Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4525226
  • 博文数量: 1214
  • 博客积分: 13195
  • 博客等级: 上将
  • 技术积分: 9105
  • 用 户 组: 普通用户
  • 注册时间: 2007-01-19 14:41
个人简介

C++,python,热爱算法和机器学习

文章分类

全部博文(1214)

文章存档

2021年(13)

2020年(49)

2019年(14)

2018年(27)

2017年(69)

2016年(100)

2015年(106)

2014年(240)

2013年(5)

2012年(193)

2011年(155)

2010年(93)

2009年(62)

2008年(51)

2007年(37)

分类: Python/Ruby

2015-01-09 22:00:43

Python中递归层级太多,会抛出异常:RuntimeError: maximum recursion depth exceeded
Python中尾递归没有优化功能,网上看到一个代码片段,捕获堆栈异常,再怎么捣鼓赋值,有让其恢复正常。

Python语言
#!/usr/bin/env python2.4
# 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.

代码来自:
阅读(757) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~