Recursion using yield

前端 未结 4 1056
粉色の甜心
粉色の甜心 2020-11-28 05:41

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

         


        
4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-28 06:12

    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.

提交回复
热议问题