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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With