python中使用尾递归代码范例,python尾递归范例,# This progr
文章由Byrx.net分享于2019-03-23 09:03:27
python中使用尾递归代码范例,python尾递归范例,# This progr
# 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 sysclass TailRecurseException: def __init__(self, args, kwargs): self.args = args self.kwargs = kwargsdef 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_optimizeddef 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_optimizeddef 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提取url中的域名和端口号,pythonurl,import urlli
- python执行get提交的操作,pythonget提交,import sys,
- django获得用户ip地址,django获得ip,def get_clie
- python 装饰器记录日志,python日志,from time im
- Firefly 开源的游戏服务器端框架,firefly开源,Firefly是免
- 在VIM中使用GOOGLE进行搜索或者翻译,vimgoogle,一个在VI
- easy_install 错误Setup script exited with error: Unable to find vcv
- python简单的函数定义和使用范例,python函数范例,def c
- 找出数组中出现频率超过一半的数,数组超过一半,有一
- 3行Python代码解简单的一元一次方程,3行python,solve("
评论关闭