Simple Recursive Generator Question

MetalOne jcb at iteris.com
Fri Dec 19 14:13:39 EST 2003


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?




More information about the Python-list mailing list