Reputation: 4132
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?
Upvotes: 6
Views: 184
Reputation: 239473
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
Upvotes: 11
Reputation: 28993
Your function is doing:
return a generator that generates "n"
call function f(n-1) which returns a generator
throw that inner generator away, never use it
quit
Upvotes: 0