Simple Recursive Generator Question

David Eppstein eppstein at ics.uci.edu
Fri Dec 19 15:05:18 EST 2003


In article <92c59a2c.0312191113.569724ca at posting.google.com>,
 jcb at iteris.com (MetalOne) wrote:

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

The actual answer to your question is that when you recursively call a 
generator, its return value (the iterator of its results) needs to be 
used not ignored.

But the reason I'm posting is to suggest an alternative approach:


bitIndices = dict([(1L<<i,i) for i in range(32)])

def bitIndexGenerator(mask):
    while mask:
        bit = mask &~ (mask - 1)
        yield bitIndices[bit]
        mask &=~ bit

-- 
David Eppstein                      http://www.ics.uci.edu/~eppstein/
Univ. of California, Irvine, School of Information & Computer Science




More information about the Python-list mailing list