Recursive function to develop permutations

Steven Bethard steven.bethard at gmail.com
Thu Oct 21 02:20:25 EDT 2004


Steve Goldman <steve_g <at> ix.netcom.com> writes:

> But now I have another question.  In the elegant recursive generator, below,
> the yield expression for the terminating condition is followed by a return
> statement.  Why is that necessary?
[snip]
> > def permute(Xs, N):
> >     if N <= 0:
> >         yield []
> >         return
> >     for x in Xs:
> >         for sub in permute(Xs, N-1):
> >             yield [x]+sub

The 'return' statement tells the generator to exit the function (without 
saving the state.  So,

>>> def gen():
... 	yield 1
... 	return
... 	yield 2
... 	
>>> list(gen())
[1]

Note that the second yield is never reached.  So the source of your example 
above chose to use the 'return' statement instead of the perhaps more 
intuitive (but slightly more indented):

def permute(Xs, N):
    if N <= 0:
        yield []
    else:
        for x in Xs:
            for sub in permute(Xs, N-1):
                yield [x]+sub

Steve




More information about the Python-list mailing list