general function for sorting a matrix

Marc 'BlackJack' Rintsch bj_666 at gmx.net
Wed Aug 29 12:40:46 EDT 2007


On Wed, 29 Aug 2007 08:47:27 -0700, Xah Lee wrote:

> While reviewing this code, there's something interesting of note.
> 
> Namely, in my perl solution, the approach is drastically different
> than the python version. Instead of sorting by looping thru the
> sorting directives, it parses the directives then generate the
> complete sort code, then eval it in one shot. This is more of a pure
> functional approach.

I don't see why that is more functional.  After all you iterate in both
versions through the directives.  In Perl to build the code, in Python to
sort the list multiple times.  Here's a Python function that sorts the
list just once:

def sort_matrix(matrix, directives):
    tmp = [(column - 1, str if as_string else float, 1 if ascending else -1)
           for (column, as_string, ascending) in directives]
    
    def cmp_func(row_a, row_b):
        for column, convert_func, factor in tmp:
            result = cmp(convert_func(row_a[column]),
                         convert_func(row_b[column])) * factor
            if result:
                return result
        return 0
    
    matrix.sort(cmp=cmp_func)

There's no return value as your reference implementation sorts in place
too.

Ciao,
	Marc 'BlackJack' Rintsch



More information about the Python-list mailing list