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.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…