Re: Simple Recursive Generator Question

From: Samuel Bronson (naesten_at_myrealbox.com)
Date: 12/19/03


Date: 19 Dec 2003 16:00:09 EST

MetalOne wrote:
> This is what I have, but it does not work.
> Changing yield to print, shows that the recursion works correctly.
>
> def bitIndexGenerator(mask, index=0):
> if mask == 0: return
> elif mask & 0x1: yield index
> bitIndexGenerator(mask >> 1, index+1)
>
> What am I missing?

Everything needs to be yielded from the outermost generator, like

def bitIndexGenerator(mask, index=0):
     if mask == 0: return
     elif mask & 0x1: yield index
     for i in bitIndexGenerator(mask >> 1, index+1):
         yield i

However, this is ugly ;-), and kind of defeats the purpose of
generators. Why do you want to use recursion like this?