Simple Recursive Generator Question

Peter Otten __peter__ at web.de
Fri Dec 19 14:39:36 EST 2003


MetalOne wrote:

> 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?

The bitIndexGenerator(mask>>1, index+1) just returns a new generator which
is immediately discarded. For a generator to do anything, you must invoke
its next() method, and one way to do it is a for loop, e. g (not mask<0
proof):

>>> def big(mask, index=0):
...     if mask != 0:
...             if mask & 1:
...                     yield index
...             for result in big(mask>>1, index+1):
...                     yield result
...
>>> for x in big(0x16):
...     print x,
...
1 2 4

Peter




More information about the Python-list mailing list