[Python-Dev] Use for enumerate() (original) (raw)

holger krekel pyth@devel.trillke.net
Sat, 27 Apr 2002 04:41:23 +0200


On Fri, Apr 26, 2002 at 08:56:31PM -0400, Tim Peters wrote:

The attached g2 is about 60% quicker across the text files I tried it on, using this timing driver (which sums the time across all interesting inputs; note that, overall, this is quadratic-time in the number or lines for either method):

measured with your driver script the following code is about 10-20% faster than 'g2' and it gets close to

> Challenge 3: do it faster and with less code.

def g3(filename, lineno): if lineno>0: f = file(filename) while lineno>0: read = f.read(1024) count = read.count('\n') lineno-=count or lineno f.close() if lineno<count: return read.split('\n')[lineno+count-1] return ''

vertically it's one line less but it stretches a bit horizontally. But it is more portable :-)

holger