使用收益递归 [英] Recursion using yield

查看:105
本文介绍了使用收益递归的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法混合递归和yield语句?例如,无限数生成器(使用递归)将类似于:

Is there any way to mix recursion and the yield statement? For instance, a infinite number generator (using recursion) would be something like:

def infinity(start):
    yield start
    # recursion here ...

>>> it = infinity(1)
>>> next(it)
1
>>> next(it)
2

我尝试过:

def infinity(start):
    yield start
    infinity(start + 1)

def infinity(start):
    yield start
    yield infinity(start + 1)

但是他们都不满足我的要求,第一个产生start后停止,第二个产生start,然后生成器,然后停止.

But none of them did what I want, the first one stopped after it yielded start and the second one yielded start, then the generator and then stopped.

注意::请知道,您可以使用while循环来做到这一点:

NOTE: Please, I know you can do this using a while-loop:

def infinity(start):
    while True:
        yield start
        start += 1

我只想知道这是否可以递归完成.

I just want to know if this can be done recursively.

推荐答案

是的,您可以这样做:

def infinity(start):
    yield start
    for x in infinity(start + 1):
        yield x

但是,一旦达到最大递归深度,就会出错.

This will error out once the maximum recursion depth is reached, though.

从Python 3.3开始,您将可以使用

Starting from Python 3.3, you'll be able to use

def infinity(start):
    yield start
    yield from infinity(start + 1)

如果仅递归地调用生成器函数而不循环或生成它,则要做的就是构建一个新的生成器,而无需实际运行函数主体或产生任何结果.

If you just call your generator function recursively without looping over it or yield from-ing it, all you do is build a new generator, without actually running the function body or yielding anything.

有关更多详细信息,请参见 PEP 380 .

See PEP 380 for further details.

这篇关于使用收益递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆