12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

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

if found:print 'at index', ielse:print X, 'not found'C:\book\tests> python power.pyat index 5As is, the example doesn’t follow normal <strong>Python</strong> coding techniques. Follow thesteps outlined here to improve it (for all the transformations, you may type yourcode interactively, or store it in a script file run from the system command line—using a file makes this exercise much easier):a. First, rewrite this code with a while loop else clause to eliminate the foundflag and final if statement.b. Next, rewrite the example to use a for loop with an else clause, to eliminatethe explicit list-indexing logic. Hint: to get the index of an item, use thelist index method (L.index(X) returns the offset of the first X in list L).c. Next, remove the loop completely by rewriting the example with a simple inoperator membership expression. (See Chapter 8 for more details, or typethis to test: 2 in [1,2,3].)d. Finally, use a for loop and the list append method to generate the powers-of-2 list (L) instead of hardcoding a list literal.Deeper thoughts:e. Do you think it would improve performance to move the 2**Xexpressionoutside the loops? How would you code that?f. As we saw in exercise 1, <strong>Python</strong> includes a map(function, list) tool that cangenerate the powers-of-2 list, too: map(lambda x: 2 ** x, range(7)). Try typingthis code interactively; we’ll meet lambda more formally in Chapter 17.296 | Chapter 14: The Documentation Interlude

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

Saved successfully!

Ooh no, something went wrong!