Wednesday, March 5, 2008

1 line qsort() in python

quick sort is very simple, but generally fast algorithm. If it is implemented in python, seeing the simplicity is obvious. Thanks to ease of boundary check, code will look like this:

def qsort(lst):
    if len(lst) <= 1: return lst
    left = [ e for e in lst[1:] if e <= lst[0] ]
    right = [ e for e in lst[1:] if e > lst[0] ]
    return qsort(left) + [lst[0]] + qsort(right)

Now, if evil lambda comes into play, we express this in one line.

qs = lambda lst: qs([ e for e in lst[1:] if e<=lst[0] ]) + \
    [lst[0]] + qs([ e for e in lst[1:] if e>lst[0]]) \
    if len(lst) > 1 else lst

hehe.. Okay, I admit that it is not simple one line. I am insisting this to be one line.
I appologize for trolling :) Maybe I am going wierd at 3:30 in the morning.

2 comments:

IHOR B said...

you should switch to ruby

Raymond said...

I actually considered once :)