473,804 Members | 2,249 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
13 1880

"Christos TZOTZIOY Georgiou" <tz**@sil-tec.gr> wrote in message
news:0i******** *************** *********@4ax.c om...
On 21 Feb 2005 06:48:19 -0500, rumours say that Dan Sommers
<me@privacy.net >
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').


Cute. I tried it a few times until I saw why it works. But it is also
dangerous (within a loop like the above) in a language like current Python
(and unlike C/assembler) in which the binary representation of -1 is
effectively a left infinite string of '1's: ...1111111111

Terry J. Reedy

Jul 18 '05 #11
On Mon, 21 Feb 2005 10:55:05 -0800, rumours say that Bryan <be****@gmail.c om>
might have written:
[i]
is to reset the rightmost (less significant) '1' bit of a number (ie
change it to '0').
[bryan]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

<snip>

[Duncan] 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.

<snip>

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


Don't worry, Bryan, I'm probably more to blame, since I have this tendency to
interject parenthesized sub-sentences all over my paragraphs, that probably
confuse more than clarify things ( self.remind(pro se is not code) :).

Perhaps I should crosspost my replies (esp. the ones with nested parentheses) to
comp.lang.lisp ...
--
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 #12
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.no t_, parity)

And if you want the same output:
for even_odd in parity:

print int(even_odd)
Jul 18 '05 #13
On 22 Feb 2005 09:14:50 GMT,
Duncan Booth <du**********@i nvalid.invalid> wrote:
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.no t_, parity)


Very clever! :-)

Picking a nit, that version iterates over *two* sets of bits. The "for"
loop over each possible bit in the input values. The "map" function
over the parity bits accumulated up to that point. And the "+="
operator over those same bits again. Make that *three* sets of bits.

I stand humbled.

Regards,
Dan

--
Dan Sommers
<http://www.tombstoneze ro.net/dan/>
μ₀ × ε₀ × c² = 1
Jul 18 '05 #14

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

Similar topics

72
4431
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
3362
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
1913
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
3054
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
1409
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
2301
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
2286
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
8119
by: Laurent Pointal | last post by:
on win32] Given the following: 45 .... (<generator object at 0x00A79788>,) .... File "<stdin>", line 1 SyntaxError: invalid syntax
0
9714
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
9594
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,...
1
10347
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10090
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
6863
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5531
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
5673
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3832
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3001
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.