Simple Recursive Generator Question

Robert Brewer fumanchu at amor.org
Fri Dec 19 14:50:27 EST 2003


Probably not what you meant, but one of the things you're missing is
that generators nullify the need for recursion in this case:

def big(mask):
    index = 0
    while True:
        if mask == 0:
            break
        if mask & 0x1:
            yield index
        index += 1
        mask = mask >> 1

>>> for x in big(0x16):
... 	print x
... 	
1
2
4

The generator saves you having to pass the "index" param recursively.
You save both object memory size (only one 'index' and one 'mask' object
and their bound names) and function-calling overhead (stack space).


Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org

> -----Original Message-----
> From: MetalOne [mailto:jcb at iteris.com] 
> Sent: Friday, December 19, 2003 11:14 AM
> To: python-list at python.org
> Subject: Simple Recursive Generator Question
> 
> 
> 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?
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 





More information about the Python-list mailing list