原理

用栈模拟递归,用到了生成器和装饰器的概念

# 生成器对象
from types import GeneratorType

# 装饰器 手写栈
def bootstrap(f, stack=[]):
    # AOP
    def wrappedfunc(*args, **kwargs):
        if stack: # 递归一层返回
            return f(*args, **kwargs)
        else:
            # 遍历生成器函数
            to = f(*args, **kwargs)
            while True:
                if type(to) is GeneratorType: # 新的生成器函数
                    stack.append(to) # 入栈
                    to = next(to) # 递归
                else: # 没有新的生成器函数
                    stack.pop() # 弹出递归入口
                    if not stack: # 全部遍历完了
                        break
                    to = stack[-1].send(to)
            return to # 返回答案
    return wrappedfunc

使用方法

将@bootstrap添加到要递归的函数上面,在函数内需要递归和return的地方加上yield, (注意如果return为空也要添加yield表示返回)

参考

https://codeforces.com/blog/entry/80158