Simple Recursive Generator Question

From: MetalOne (jcb_at_iteris.com)
Date: 12/19/03


Date: 19 Dec 2003 11:13:39 -0800

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?



Relevant Pages

  • Re: hash table
    ... It could mask a failure to #include, which yields ... undefined behavior. ...
    (comp.lang.c)
  • Re: Simple Recursive Generator Question
    ... > I am trying to write a generator function that yields the index position ... shows that the recursion works correctly. ... If you really want to make your program work the way you apparently intend, ... each value that it yields. ...
    (comp.lang.python)