Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursion using yield

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.

like image 802
juliomalegria Avatar asked Jan 24 '12 18:01

juliomalegria


People also ask

What is a good example of recursion?

A classic example of recursion For example, factorial(5) is the same as 5*4*3*2*1 , and factorial(3) is 3*2*1 .

What is recursion with example?

Recursion is the process of defining a problem (or the solution to a problem) in terms of (a simpler version of) itself. For example, we can define the operation "find your way home" as: If you are at home, stop moving. Take one step toward home.

What makes generator recursive in Python?

The important thing to note in this example is: the generator function recursively calls itself in a for loop, which sees an iterator and automatically uses the iteration protocol on it, so it actually gets values from it.


1 Answers

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.

like image 164
Sven Marnach Avatar answered Sep 16 '22 21:09

Sven Marnach