使用 yield 递归 [英] Recursion using yield

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

问题描述

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

定义无穷大(开始):产量开始# 这里递归...>>>它 = 无穷大(1)>>>下一个(它)1>>>下一个(它)2

我试过了:

定义无穷大(开始):产量开始无穷大(开始 + 1)

定义无穷大(开始):产量开始产量无穷大(开始 + 1)

但他们都没有做我想要的,第一个在它产生 start 后停止,第二个产生 start,然后生成器然后停止.

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

定义无穷大(开始):而真:产量开始开始 += 1

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

解决方案

是的,您可以这样做:

定义无穷大(开始):产量开始对于无穷大中的 x(开始 + 1):产量 x

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

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

定义无穷大(开始):产量开始从无穷大产生(开始 + 1)

如果你只是递归调用你的生成器函数而不循环它或yield from-ing它,你所做的就是构建一个新的生成器,而不实际运行函数体或产生任何东西.>

有关详细信息,请参阅 PEP 380.

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

I tried:

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

and

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

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.

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.

解决方案

Yes, you can do this:

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.

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.

See PEP 380 for further details.

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

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