On Sun, 20 Feb 2005 20:56:52 -0800,
snacktime <[EMAIL PROTECTED]> wrote:

> I need to convert a generator expression to a list expression so it
> will work under python 2.3.

> I rewrote this:

> for c in range(128):
>   even_odd = (sum(bool(c & 1<<b) for b in range(8))) & 1

> As this:

> for c in range(128):
>   bo = [bool(c & 1<<b) for b in range(8)]
>   even_odd = sum(bo) & 1


> 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.

"Better," of course is all relative.  Your algorithm obviously counts
bits in an integer.  My algorithm is less clear at first glance (and
even second and third glance), but nearly idiomatic to those of us who
spent lots of time writing embedded assembly code.

If you have the space to spare, a lookup table (pre-calculated or
created during your program's initialization) is probably the best way
to go.

Regards,
Dan

-- 
Dan Sommers
<http://www.tombstonezero.net/dan/>
Never play leapfrog with a unicorn.
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to