[Python-Dev] Use for enumerate()

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


On Sat, Apr 27, 2002 at 12:24:46AM -0400, Tim Peters wrote:
> [holger krekel]
> > 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 :-)
> 
> What if (the simplest example of what can go wrong) the first line is more
> than 1024 characters long, and the caller asks for lineno 1?

right. i noticed after sending it that you also need to
change
         lineno-= count or lineno
into
         lineno-= count or read and lineno

and the problem of lines longer>1024 and around the 1024 boundary remains.
Solving this probably blows the code by several lines.

But anyway, isn't reading and counting still a faster technique than
using readlines() esp. for larger files? 

     holger