python: user define sorting with callback

January 8th, 2008 mysurface Posted in Developer, python | Hits: 39708 | 4 Comments »

Theres a lots of people treated python as scripting language like bash, but I am going to tell you, python is real programming language. Python support callback like c/c++, and this feature is really God-like, because it is so simple to implement callback in python.

What is Callback?

In computer programming, a callback is executable code that is passed as an argument to other code. It allows a lower-level software layer to call a subroutine (or function) defined in a higher-level layer.

Quote from wikipedia

When we talk about callback, it usually in the form of function, therefore we also call it as callback function. We define our own algorithm in a callback function, and pass our function name as parameter to another function, where this function will callback our function for certain execution depends on the context.

Lets look at how we can apply callbacks in python. Lets look into how to define our own sorting function with callback technique.

Llist object support sorting by default, you can sort data in list as below:

In [1]: mylist=[2,3,8,4,7,1]

In [2]: print mylist
[2, 3, 8, 4, 7, 1]

In [3]: mylist.sort()

In [4]: print mylist
[1, 2, 3, 4, 7, 8]

What if we have value in string?

In [1]: mylist=['John', 'Thomas','Dick','Harry']

In [2]: print mylist
['John', 'Thomas', 'Dick', 'Harry']

In [3]: mylist.sort()

In [4]: print mylist
['Dick', 'Harry', 'John', 'Thomas']

But, look at this, it will fails to sort as expected:

In [1]: mylist=["r1","r13","r3","r5","r100","r103"]

In [2]: mylist.sort()

In [3]: print mylist
['r1', 'r100', 'r103', 'r13', 'r3', 'r5']

What are we expect is ['r1','r3','r5','r13','r100','r103'] but end up sorted alphanumerically.

So, what should we do? create our own sorting function? how are we going to embed this sorting to the list object?

If you learn about algorithms before, you may understand that to perform sorting, we compare the every single value in a set, and thats how we sort it out. There are various sorting techniques, the simplest one is bubble sort.

You can use nested for loops to implement bubble sort, but here, you do NOT need to. You do not need create the entire sorting function yourself, you just need to define your own compare algorithms into callback function and pass it’s name to sort(), and python will sort accordingly for you.

Let us look at a sample user define compare callback:

def compare(x,y):
    if int(x[1:]) > int(y[1:]):
        return 1
    elif int(x[1:]) < int(y[1:]):
        return -1
    else:
        return 0

Next! lets see the results:

In [28]: mylist.sort(compare)

In [29]: print mylist
['r1', 'r3', 'r5', 'r13', 'r100', 'r103']

To define a compare function for sort(), you must follow certain pattern.
1. Compare function must take TWO param: x and y,
2. It should return positive number if x > y, return negative number if x< y and return 0 if they are equal for Ascending sort.

So this is callback, the sort function will now call your compare callback in the sorting algorithm instead of the default one.

P.S. I always having difficulties to explain programming, my wish is to introduce callbacks for those who are learning python. Hope that this is useful for you.

FYI: In case you are curious why my python's prompt is so funny, I am using ipython, an Enhanced Python Shell.

4 Responses to “python: user define sorting with callback”

  1. Thanks! Short, straight to the point and yet easy to understand. Now I know callbacks. :)

  2. Thanks, this article is really helpful.

  3. Great wordpress blog here.. It’s hard to find quality writing like yours these days. I really appreciate people like you! take care :)

  4. Gertha Trigg Says:

    Ok so am i allowed to just declare I LOVE YOUR FILMS!!!! I will be as a significant cooling fan! (#(: I actually hVe learned a great deal of about consuming caution if my dolls(#(: can you generate a video of some tips on for instance, takin care e them and…. like…. things like. to guide you in emergencies! (#(: thanks a lot EVA!

Leave a Reply