[Tutor] Sort and compare

Alfred Milgrom fredm at smartypantsco.com
Wed Oct 22 21:15:19 EDT 2003


Hi Conrad:

Let me try to explain it.
If you have a list  and try to sort it, then obviously you have to use some 
type of sorting criteria.

x = [('hello', 2), ('goodbye', 3), ('python', 1)]
x.sort()

what you are saying is "sort the list x"  but you should note that this 
also implies "using the built-in function cmp()".

What the function cmp() does is check any two items and compare them. If 
the first element given to cmp() is greater than the second it returns 0, 
otherwise it returns -1.
The function cmp() can compare most types. In the case of a tuple if 
compares the first element of each item.

Think of of the sorting process as basically going through each pair of 
elements in the list and comparing them. If they are in the wrong order it 
swaps them, and if they are OK it goes on to the next pair. It keeps on 
doing this until there are no more swaps needed.

By defining a new comparison function, then we can use the statement

x.sort(compare)

This can be read as "sort the list x using the function compare() to 
compare adjacent items in the list".
You can define functions to do compares any way that you need for your 
particular application.

In this case, compare(a,b) compares a[1] and b[1]. In other words, when 
sort does its work, it uses the results from compare() which is based on 
the results of comparing each item[1].

Note that the syntax is
         x.sort(compare)
and not
         x.sort(compare(x))

As I mentioned in my original email, the compare function I wrote is not 
very good as it does not do error checking, etc.
A better and simpler implementation (as was pointed out by Danny on this 
list) is:

def compare(a,b):
         return cmp(a[1], b[1])

This uses the built-in function cmp to return the proper arguments for us.

Hope this helps,
Fred Milgrom

At 04:26 PM 22/10/03 -0700, Conrad Koziol wrote:
>def compare(a,b):
>          if a[1]>b[1]: return 0
>          else: return -1
>
>x = [('hello', 2), ('goodbye', 3), ('python', 1)]
>
>x.sort(compare(x))
>
>can you explain what happens to me step by step. That'a were im lost.
>
>Does x sort [-1, 0, 1, -1]????





More information about the Tutor mailing list