A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://mail.python.org/pipermail/python-dev/2002-April/023694.html below:

[Python-Dev] Use for enumerate()

[Python-Dev] Use for enumerate()Patrick K. O'Brien pobrien@orbtech.com
Fri, 26 Apr 2002 18:31:29 -0500
[Guido van Rossum]
>
>     def getline(filename, lineno):
> 	if lineno < 1:
> 	    return ''
> 	lineno -= 1
> 	f = open(filename)
> 	for i, line in enumerate(f):
> 	    if i == lineno:
> 		break
> 	else:
> 	    line = ''
> 	f.close()
> 	return line
>
> Challenge 1: do it faster.
>
> Challenge 2: do it with less code.
>
> Challenge 3: do it faster and with less code.
>
> Rules: the semantics must be the same: always close the file, return
> '' for lineno out of range; lineno < 1 should not open the file.

I doubt it's faster and it's barely less code (I had to resist the urge to
add a try/finally), but here is the only decent variation I could come up
with:

def getline(filename, lineno):
    line = ''
    if lineno > 0:
        lineno -= 1
        f = open(filename)
        for i, s in enumerate(f):
            if i == lineno:
                line = s
                break
        f.close()
    return line

I'm ready to give up now. What's the fastest, smallest solution?

---
Patrick K. O'Brien
Orbtech





RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4