Documentation Can Speed Up Your Code

I just was documenting some code that looked (roughly) like this:

def a(x, m): for i, o in enumerate(sorted(x)): if o > m: break return i

and my comment was "return how many items in x are less than or equal to m".

The very act of writing the comment made me realise the code could be rewritten as:

def a(x, m): return len([o for o in x if o <= m])

which is not only more succinct but runs 6-8 times faster! (UPDATE: ...on my data size -- as Sergio points out below, the two algorithms differ in complexity)

(Incidentally, the list comprehension also runs twice as fast as the equivalent using filter)

UPDATE (2008-03-26): Fascinating discussion going on in the comments :-) Although still largely orthogonal to the main point which is that I was originally trying to solve a domain-specific problem and it was only when I went to comment the code that I realised that what I was really doing was trying to find how many items in a list are less than or equal to a certain number. How best to do that is a topic for...well, I guess the comment thread :-)

The original post was in the categories: python algorithms but I'm still in the process of migrating categories over.

The original post had 20 comments I'm in the process of migrating over.