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.

es[1.4142135623730951, 2.0, 3.0, 4.0, 5.0]>>> map(math.sqrt, values)[1.4142135623730951, 2.0, 3.0, 4.0, 5.0]>>> [math.sqrt(x) for x in values][1.4142135623730951, 2.0, 3.0, 4.0, 5.0]Part V, ModulesSee “Part V Exercises” in Chapter 21 for the exercises.1. Import basics. This one is simpler than you may think. When you’re done, yourfile (mymod.py) and interaction should look similar to the following; rememberthat <strong>Python</strong> can read a whole file into a list of line strings, and the len built-inreturns the length of strings and lists.def countLines(name):file = open(name)return len(file.readlines( ))def countChars(name):return len(open(name).read( ))def test(name):return countLines(name), countChars(name)# Or pass file object# Or return a dictionary% python>>> import mymod>>> mymod.test('mymod.py')(10, 291)Note that these functions load the entire file in memory all at once, and so won’twork for pathologically large files too big for your machine’s memory. To be morerobust, you could read line by line with iterators instead and count as you go:def countLines(name):tot = 0for line in open(name): tot += 1return totdef countChars(name):tot = 0for line in open(name): tot += len(line)return totOn Unix, you can verify your output with a wc command; on Windows, rightclickon your file to view its properties. But note that your script may reportfewer characters than Windows does—for portability, <strong>Python</strong> converts Windows\r\n line-end markers to \n, thereby dropping one byte (character) perline. To match byte counts with Windows exactly, you have to open in binarymode ('rb'), or add the number of bytes corresponding to the number of lines.Part V, Modules | 661

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

Saved successfully!

Ooh no, something went wrong!