Simple Recursive Generator Question

Andrew Koenig ark at
Sun Dec 21 18:04:28 CET 2003

"MetalOne" <jcb at> wrote in message
news:92c59a2c.0312191113.569724ca at
> I am trying to write a generator function that yields the index position
> of each set bit in a mask.
> e.g.
> for x in bitIndexGenerator(0x16): #10110
>     print x
> --> 1 2 4
> 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?

If you really want to make your program work the way you apparently intend,
then you need to activate the generator you create recursively and yield
each value that it yields.  For example:

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

However, unless your purpose in writing this program is to improve your
understanding of recursion, this technique uses much more mechanism that
needed to solve the problem--as other replies have already pointed out.

More information about the Python-list mailing list