Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Recursive Generator doesn't work in Python 3.3?

I'm trying to create a recursive generator in Python, but I'm doing something wrong. Here's a minimal example. I would expect the function f() to return an iterable that would give me all the positive numbers >= n.

>>> def f(n):
...     yield n
...     if n>0:
...         f(n-1)
... 
>>> [ i for i in f(30) ]
[30]

Why is the iteration stopping after the first number?

like image 299
mojo Avatar asked Mar 14 '14 02:03

mojo


1 Answers

Since f(n-1) is again a generator, which can be consumed only with the next protocol. If you are using Python 3.3+, you can use yield from, like this

def f(n):
    yield n
    if n > 0:
        yield from f(n-1)

print(list(f(10)))
# [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

If you want to fix with out yield from or using a Python version which doesn't have yield from, then you have to manually iterate and yield like this

def f(n):
    yield n
    if n > 0:
        for item in f(n-1):
            yield item
like image 114
thefourtheye Avatar answered Oct 26 '22 22:10

thefourtheye