[Tutor] can someone explain to me how this works [comparsion functions and sort()]

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Tue Oct 21 19:13:22 EDT 2003



On Tue, 21 Oct 2003, Conrad Koziol wrote:

> Hey thanks for the tips !!!
>
> def compare(a,b):
>          if a[1]>b[1]: return 0
>          else: return -1
>
> i tried this out and it works, but i dont understand the logic behind it
> :( can someone help me out

Hi Conrad,

A "comparison function" is something that takes two things, and checks to
see if one is smaller than another.  In math notation:

    compare(a,b)  =    {  -1     if a < b
                           0     if a == b
                           1     if a > b
                       }

The important thing to see is that a comparison function is not meant to
be a "boolean" true-false thing: it's meant to return either a positive,
zero, or negative value.

Is this what's confusing, or is it something else?  Please feel free to
ask more questions about this, as it is definitely a confusing topic when
we first see it.



> i also dont get how it compares all the tuples in a list. Dont you need
> to enter in two values not just one list?????

Yes, this would be true if we were directly calling compare() on the list
itself.  However, that's not what's happening: instead, we're calling
sort, and sort() itself is calling compare() on pairs of elements on our
list.


Here's a concrete toy example of a similar situation:

###
>>> def applyOnList(function, L):
...     """Destructivly applies a 'function' on the list 'L'."""
...     for index, element in enumerate(L):
...         L[index] = function(element)
...
>>> def square(x): return x * x
...
>>> numbers = range(10)
>>> applyOnList(square, numbers)
>>> numbers
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
###

In this case, we've written a function called applyOnList() that takes in
a function, as well as a list of things.  Notice that the function we pass
in isn't being called on the whole list, but only on single elements of
that list.


sort() does something somewhat similar when it takes in that comparison
function.  sort() uses it as a helper toward some greater goal --- sorting
things --- but doesn't need to try applying it to the whole list at once.


Hope that made some sort of sense.  *grin* Please feel free to ask more
questions: if you'd like, we can talk about how comparsion functions
actually help sort() figure out how to sort.




More information about the Tutor mailing list