15.04.2013 Views

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

$ python oddnogen.py<br />

[39, 77, 39, 71, 1]<br />

$ python oddnogen.py<br />

[23, 39, 9, 1, 63, 91]<br />

$ python oddnogen.py<br />

[41, 85, 93, 53, 3]<br />

Refactoring Pass 1<br />

We notice on second glance that odd() is simple enough to be replaced by a lambda expression:<br />

from random import randint<br />

allNums = []<br />

for eachNum in range(9):<br />

allNums.append(randint(1, 99))<br />

print filter(lambda n: n%2, allNums)<br />

Refactoring Pass 2<br />

We have already mentioned how list comprehensions can be a suitable replacement for filter() so here<br />

it is:<br />

from random import randint<br />

allNums = []<br />

for eachNum in range(9):<br />

allNums.append(randint(1, 99))<br />

print [n for n in allNums if n%2]<br />

Refactoring Pass 3<br />

We can further simplify our code by integrating another list comprehension to put together our final list.<br />

As you can see below, because of the flexible syntax of list comps, there is no longer a need for<br />

intermediate variables. (To make things fit, we import randint() with a shorter name into our code.)<br />

from random import randint as ri<br />

print [n for n in [ri(1,99) for i in range(9)] if n%2]<br />

Although longer than it should be, the line of code making up the core part of this example is not as<br />

obfuscated as one might think.<br />

map( )<br />

The map() built-in function is similar to filter() in that it can process a sequence through a function.<br />

However, unlike filter(), map() "maps" the function call to each sequence item and returns a list

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!