Want to learn a language - is Python right?

Steven D'Aprano steve at REMOVETHIScyber.com.au
Tue Jun 21 14:42:22 CEST 2005

On Mon, 20 Jun 2005 17:23:27 -0700, James Stroud wrote:

> By the way, ignore any posts talking about speed of execution. This is 
> generally a non-issue for new programmers. If you want your code to run 
> faster, buy a faster computer.

Oooh, red rag to a bull.

Not everybody can afford to buy a faster computer to try to make their
sort function run as quickly as Python's built-in sort.

def newbie_sort(s):
    """Sort lines of string s, considering that speed of 
    execution is a non-issue.
    # split s into lines
    L = []
    while "\n" in s:
        p = s.find("\n")
        L = L + [s[0:p]]
        s = s[p+1:]
    L = L + [s]
    # sort the lines
    for passes_remaining in range(len(L)-1, 0, -1):
        for p in range(passes_remaining):
            if L[p] > L[p+1]:
                temp = L[p]
                L[p] = L[p+1]
                L[p+1] = temp
    # re-join the lines back into a single string
    s = L[0]
    del L[0]
    for line in L:
        s = s + "\n" + line
    return s

def better_sort(s):
    """Sort lines of string s the right way.
    L = s.split("\n")
    return "\n".join(L)

The first function, newbie_sort, is good for only one thing: to be a
horrible example of how inefficient and slow Python can be. It is also
remarkably similar to a lot of my early Python programs.

I think a better way of putting what James tried to get across is, don't
be too concerned about writing fast code until you have learnt the
basics of the language. Get the code WORKING first, and FAST second.

(And frequently, the best way to get it working is also the best way to
have it run fast.)


More information about the Python-list mailing list