鱼C论坛

 找回密码
 立即注册
查看: 1718|回复: 0

[技术交流] Python实现为递归打印100的阶乘

[复制链接]
发表于 2018-4-3 09:43:48 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
#!/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()
        # 为什么是grandparent, 函数默认的第一层递归是父调用,
        # 对于尾递归, 不希望产生新的函数调用(即:祖父调用),
        # 所以这里抛出异常, 拿到参数, 退出被修饰函数的递归调用栈!(后面有动图分析)
        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 as 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))

=======================

pydev debugger: starting (pid: 4380)
Traceback (most recent call last):
  File "/Users/macbookpro/eclipse-workspace/GrayHatPython/pra012.py", line 37, in func
    return g(*args, **kwargs)
  File "/Users/macbookpro/eclipse-workspace/GrayHatPython/pra012.py", line 50, in factorial
    return factorial(n-1, n*acc)
  File "/Users/macbookpro/eclipse-workspace/GrayHatPython/pra012.py", line 33, in func
    raise TailRecurseException(args, kwargs)
TypeError: exceptions must derive from BaseException

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Applications/Eclipse.app/Contents/Eclipse/plugins/org.python.pydev.core_6.3.2.201803171248/pysrc/pydevd.py", line 1621, in <module>
    main()
  File "/Applications/Eclipse.app/Contents/Eclipse/plugins/org.python.pydev.core_6.3.2.201803171248/pysrc/pydevd.py", line 1615, in main
    globals = debugger.run(setup['file'], None, None, is_module)
  File "/Applications/Eclipse.app/Contents/Eclipse/plugins/org.python.pydev.core_6.3.2.201803171248/pysrc/pydevd.py", line 1022, in run
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "/Applications/Eclipse.app/Contents/Eclipse/plugins/org.python.pydev.core_6.3.2.201803171248/pysrc/_pydev_imps/_pydev_execfile.py", line 25, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "/Users/macbookpro/eclipse-workspace/GrayHatPython/pra012.py", line 52, in <module>
    print(factorial(10000))
  File "/Users/macbookpro/eclipse-workspace/GrayHatPython/pra012.py", line 38, in func
    except TailRecurseException as e:
TypeError: catching classes that do not inherit from BaseException is not allowed

==========================================================

为什么会报错???
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-3-29 03:38

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表