p2p.wrox.com Forums

p2p.wrox.com Forums (http://p2p.wrox.com/)
-   BOOK: Python Projects (http://p2p.wrox.com/book-python-projects-773/)
-   -   P19, "even squares", code error (http://p2p.wrox.com/book-python-projects/95120-p19-even-squares-code-error.html)

Egalth October 17th, 2015 11:53 AM

P19, "even squares", code error
 
On page 19, generator expressions are introduced. The following code from that page produces the expexted result in the form of a list of even squares:
Code:

>>> [n*n for n in range(1,11) if not n*n % 2]
[4, 16, 36, 64, 100]

At the bottom of the page there is an example of how to generate an identical result with a conventional for loop. However, the sample code produces odd integers, instead of even squares, because not and n*n are missing:
Code:

>>> result = []
>>> for n in range(1,11):
...    if n*n % 2:              # Missing not
...        result.append(n)    # n instead of n*n
...
>>> print(result)
[1, 3, 5, 7, 9]

This code produces the expected result:
Code:

>>> result = []
>>> for n in range(1,11):
...    if not n*n % 2:
...        result.append(n*n)
...
>>> print(result)
[4, 16, 36, 64, 100]


Egalth October 17th, 2015 12:02 PM

Sorry folks, forgot to mention that this has already been addressed in the Errata section. However, the correction in the Errata section only mentions the missing not so the result is even integers, instead of even squares:
Code:

>>> result = []
>>> for n in range(1,11):
...    if not n*n % 2:          # "not" now included.
...        result.append(n)    # n*n still missing.
...
>>> print(result)
[2, 4, 6, 8, 10]                  # Even integers instead of even squares.


Alan G October 17th, 2015 01:21 PM

That's for spotting that. I can only apologize for the error, not sure how that got
through all the reviews but it obviously did. Your changes are absolutely correct.

Apologies again,

Alan G.

Yehuda Katz June 26th, 2017 07:18 PM

Not real bugs but...
 
I tried to find in the index 'list comprehension' and 'conditional expression'. Not available...

Alan G June 26th, 2017 09:40 PM

You are quite right, I'm not sure why they got missed out. I could say it's because the first chapter is supposed top be revision rather than anything new, but they have included loops so i suspect it is just a simple omission. Index entries are always a bit subjective because you can't index everything but those two probably should be there.

I can only apologize.


All times are GMT -4. The time now is 05:36 PM.

Powered by vBulletin®
Copyright ©2000 - 2017, Jelsoft Enterprises Ltd.
2013 John Wiley & Sons, Inc.