python: user define sorting with callback

January 8th, 2008 mysurface Posted in Developer, python | Hits: 45485 | 11 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
        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.

11 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!

  5. Many folks need to accessorize and shield their telephone
    so it is an excellent market. Example (Resident Evil Motif, Call Of
    Duty yada yada).Click on Install.Go to home menu. JailbreakMe works with the iOS
    3.1.2 or later.

  6. Your style is so unique compared to other folks I have read stuff
    from. Thank you for posting when you have the opportunity, Guess I will just bookmark this

  7. Jailbreaking your iPhone enables the so called cydia installer is installed by you.
    So be smart and really think of the consequences involved.
    But create certain you end up deciding on Install cydia.

  8. Usually, this will do it for you, but then you need to do this yourself,
    if it does not for one motive or another. Then immediately after that, stop up
    your gadget and run the software program.

  9. There are many USB Keys for PS Jailbreak on sale in the web.

    It is known as much just as the Notification Center is activated.
    Your device must not be stuck on the Link to iTunes logo or emergency call

  10. It’s wise to download software from a website that
    is recognized to keep your computer safe. Many of these will work just
    with AT&T and can’t be unlocked. The thought grew into a working app and “Wi-Fi Sync”
    was born.

  11. Turn on Wi Fi Networks from your iPhone’s ‘settings’ selection to connect with online.
    Your telephone becomes a mini computer by doing so.
    “I’m on dangerous ground here, and I understand that.
    Yes! jailbreak is an easy and safe also.

Leave a Reply