python2.4 generator expression > python2.3 list expression

Duncan Booth duncan.booth at invalid.invalid
Tue Feb 22 04:14:50 EST 2005


Dan Sommers wrote:

>> Seems to work, is there a better way to do this?
> 
> for c in range( 128 ):
>     even_odd = 0
>     print '%3d' % c,
>     while c:
>         c &= c - 1
>         even_odd = not even_odd
>     print int( even_odd )
> 
> Okay, so your inner loop is only counting to 8, but IMO this is a good
> example of how to use a better algorithm instead of optimizing the code
> of a naïve one.  My inner loop only iterates over 1-bits.
> 

Here's yet another way to achieve the same results. This version doesn't 
iterate over any bits at all:

>>> import operator
>>> parity = [ False ]
>>> for i in range(7):
        parity += map(operator.not_, parity)

And if you want the same output:

>>> for even_odd in parity:
        print int(even_odd)



More information about the Python-list mailing list