473,796 Members | 2,376 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

python2.4 generator expression > python2.3 list expression

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?
Jul 18 '05 #1
13 1879
snacktime 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?


Well, if you were happy with your generator expression, you can use
almost exactly the same syntax:

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

No need for the 'bo' variable...

STeVe
Jul 18 '05 #2
snacktime 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?


If you want to keep it as a generator that doesn't build a list
in memory, you can use itertools:

import itertools

for c in range(128):
def _even_odd_func( b): return bool(c & 1<<b)
even_odd = (sum(itertools. imap(_even_odd_ func, xrange(8)))) & 1

The fact that you used range() instead of xrange() indicates that
you may not care about this, though. ;-)
--
Michael Hoffman
Jul 18 '05 #3
snacktime 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?


Summing over zeros seems pointless, so
for c in range(128):

.... print len([1 for b in range(8) if c & 1 << b]) & 1,
....
0 1 1 0 1 0 0 1 1 0 0 1 0 1 1 0 1 0 0 1 0 1 1 0 0 1 1 0 1 0 0 1 1 0 0 1 0 1
1 0 0 1 1 0 1 0 0 1 0 1 1 0 1 0 0 1 1 0 0 1 0 1 1 0 1 0 0 1 0 1 1 0 0 1 1 0
1 0 0 1 0 1 1 0 1 0 0 1 1 0 0 1 0 1 1 0 0 1 1 0 1 0 0 1 1 0 0 1 0 1 1 0 1 0
0 1 0 1 1 0 0 1 1 0 1 0 0 1

The same simplification works for genexps, but you have to use sum() there
instead of len(). Another optimization would be to precalculate the
bitmasks [1 << b for b in range(8)] outside the loop.

Peter

Jul 18 '05 #4
On Sun, 20 Feb 2005 20:56:52 -0800,
snacktime <sn*******@gmai l.com> 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.tombstoneze ro.net/dan/>
Never play leapfrog with a unicorn.
Jul 18 '05 #5
On 21 Feb 2005 06:48:19 -0500, rumours say that Dan Sommers <me@privacy.net >
might have written:

[snip: snacktime posts code to count bits]
Seems to work, is there a better way to do this?

[Dan]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 )


Just for the sake of people who haven't messed with bit manipulation in C or
assembly, the effect of

c &= c - 1

is to reset the rightmost (less significant) '1' bit of a number (ie change it
to '0').
--
TZOTZIOY, I speak England very best.
"Be strict when sending and tolerant when receiving." (from RFC1958)
I really should keep that in mind when talking with people, actually...
Jul 18 '05 #6
Christos TZOTZIOY Georgiou wrote:
On 21 Feb 2005 06:48:19 -0500, rumours say that Dan Sommers <me@privacy.net >
might have written:

[snip: snacktime posts code to count bits]

Seems to work, is there a better way to do this?

[Dan]
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 )

Just for the sake of people who haven't messed with bit manipulation in C or
assembly, the effect of

c &= c - 1

is to reset the rightmost (less significant) '1' bit of a number (ie change it
to '0').


i tried c &= c - 1 but i'm not getting the least significant or rightmost bit
reset to zero. am i misunderstandin g something?
2 & 1 # 2 = 0x10; reset right most would be 0x10 0 10 & 9 # 10 = 0x1010; reset right most would be 0x1010

8

bryan

Jul 18 '05 #7
Bryan wrote:
is to reset the rightmost (less significant) '1' bit of a number (ie
change it to '0').


i tried c &= c - 1 but i'm not getting the least significant or
rightmost bit reset to zero. am i misunderstandin g something?
2 & 1 # 2 = 0x10; reset right most would be 0x10 0 10 & 9 # 10 = 0x1010; reset right most would be 0x1010 8


The difference between the original "reset the rightmost '1' bit", and your
interpretation: "reset the rightmost bit" is the "'1'".

The rightmost bit that is set is reset. So 0x10 -> 0, and 0x1010 -> 0x1000.

If you want to extract the least significant set bit from a number 'x' you
can use (x&-x):
x = 0xab4
while x: print hex(x&-x), hex(x)
x ^= (x&-x)
0x4 0xab4
0x10 0xab0
0x20 0xaa0
0x80 0xa80
0x200 0xa00
0x800 0x800


(but don't try this if x is negative: it works but never terminates).
Jul 18 '05 #8
Duncan Booth wrote:
The difference between the original "reset the rightmost '1' bit", and your
interpretation: "reset the rightmost bit" is the "'1'".

The rightmost bit that is set is reset. So 0x10 -> 0, and 0x1010 -> 0x1000.

If you want to extract the least significant set bit from a number 'x' you
can use (x&-x):


My interpretation of Bryan's (mis?)interpret ation (heh) was that since
in the numbers 2 and 10 (as in his examples), the least significant bit
was already 0, performing an operation that set it to 0 should result in
the number unchanged. As his tests show, this is not the case. This is
because the operation works only if the least significant bit actually
NEEDS to be unset. To zero the least significant bit unconditionally , we
can use:

x &= ~1

--
Brian Beck
Adventurer of the First Order
Jul 18 '05 #9
Duncan Booth wrote:
Bryan wrote:

is to reset the rightmost (less significant) '1' bit of a number (ie
change it to '0').


i tried c &= c - 1 but i'm not getting the least significant or
rightmost bit reset to zero. am i misunderstandin g something?

>2 & 1 # 2 = 0x10; reset right most would be 0x10


0
>10 & 9 # 10 = 0x1010; reset right most would be 0x1010


8

The difference between the original "reset the rightmost '1' bit", and your
interpretation: "reset the rightmost bit" is the "'1'".

The rightmost bit that is set is reset. So 0x10 -> 0, and 0x1010 -> 0x1000.

If you want to extract the least significant set bit from a number 'x' you
can use (x&-x):

x = 0xab4
while x:


print hex(x&-x), hex(x)
x ^= (x&-x)
0x4 0xab4
0x10 0xab0
0x20 0xaa0
0x80 0xa80
0x200 0xa00
0x800 0x800
(but don't try this if x is negative: it works but never terminates).


thanks duncan... you're right, i did intrepret this as "reset the rightmost bit"
instead of "reset the rightmost '1' bit". and i must have read what christos
wrote 100 times!!!

bryan

Jul 18 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

72
4419
by: Raymond Hettinger | last post by:
Peter Norvig's creative thinking triggered renewed interest in PEP 289. That led to a number of contributors helping to re-work the pep details into a form that has been well received on the python-dev list: http://www.python.org/peps/pep-0289.html In brief, the PEP proposes a list comprehension style syntax for creating fast, memory efficient generator expressions on the fly: sum(x*x for x in roots)
24
3360
by: Mahesh Padmanabhan | last post by:
Hi, When list comprehension was added to the language, I had a lot of trouble understanding it but now that I am familiar with it, I am not sure how I programmed in Python without it. Now I see that generator expressions have been added to the language with 2.4 and I question the need for it. I know that it allows for lazy evaluation which speeds things up for larger lists but why was it necessary to add it instead of improving list...
10
1909
by: John Machin | last post by:
Please consider the timings below, where a generator expression starts out slower than the equivalent list comprehension, and gets worse: >python -m timeit -s "orig=range(100000)" "lst=orig;lst=(x for x in orig)" 10 loops, best of 3: 6.84e+004 usec per loop >python -m timeit -s "orig=range(200000)" "lst=orig;lst=(x for x in orig)" 10 loops, best of 3: 5.22e+005 usec per loop
45
3050
by: Joh | last post by:
hello, i'm trying to understand how i could build following consecutive sets from a root one using generator : l = would like to produce : , , , ,
10
1407
by: jamesthiele.usenet | last post by:
I wrote this little piece of code to get a list of relative paths of all files in or below the current directory (*NIX): walkList = , x) for x in os.walk(".")] filenames = for dir, files in walkList: filenames.extend() for f in files]) It works fine, I don't need to change it, but I know there is a one liner list/generator comprehension to do this - I'm just not well
16
2300
by: Peter Otten | last post by:
To confuse a newbies and old hands alike, Bengt Richter wrote: > Need something more straightforward, e.g., a wrapped one-liner: > > >>> def guess(n=3): print ("You're right!", 'No more tries for > >>> you!!!') > ... (x for x in xrange(n) for t in > ... if not t or iter().next())] > ... > >>> guess()
23
2282
by: Mike Meyer | last post by:
Ok, we've added list comprehensions to the language, and seen that they were good. We've added generator expressions to the language, and seen that they were good as well. I'm left a bit confused, though - when would I use a list comp instead of a generator expression if I'm going to require 2.4 anyway? Thanks, <mike --
9
2025
by: bonono | last post by:
Hi, I initially thought that generator/generator expression is cool(sort of like the lazy evaluation in Haskell) until I notice this side effect. >>>a=(x for x in range(2)) >>>list(a) >>>list(a)
7
8118
by: Laurent Pointal | last post by:
on win32] Given the following: 45 .... (<generator object at 0x00A79788>,) .... File "<stdin>", line 1 SyntaxError: invalid syntax
0
9680
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9528
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10455
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10228
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10006
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9052
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5441
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5573
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4116
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.