sorting matrixes

Xah Lee xah at xahlee.org
Mon Mar 28 06:24:38 CEST 2005


Here's the solution to previous post.

-------------------------------
perl code:

sub sort_matrix($$) {
    my $ref_matrix = $_[0];
    my @indexMatrix = @{$_[1]};

    my @indexes = map {$_->[0]} @indexMatrix;
    my @operators = map {$_->[1] ? ' cmp ' : ' <=> '} @indexMatrix;
    my @directions = map {$_->[2]} @indexMatrix;

    my $body_code = '';
    my @body_array;
    for (my $i = 0; $i <= $#indexes; $i++) {
        if ($directions[$i]) {
            push(@body_array, "(\$a->[$i]" . $operators[$i]  .
"\$b->[$i])");
        } else {
            push(@body_array, "(\$b->[$i]" . $operators[$i]  .
"\$a->[$i])");
        };
    };
    $body_code = join( ' or ', @body_array);

    my $array_code = '(map { [' . join(q(, ), map {"\$_->[$_]"}
@indexes) . ', $_]} @$ref_matrix)';

    my $code = "map {\$_->[-1]} (sort { $body_code} $array_code)";
    my @result = eval $code;
    return [@result];
};

------------------------------------------
Python code

# python v 2.4

def sort_matrix(matrix, directives):
    result=matrix
    for dir in directives:
        if dir[1]:
            if dir[2]:
                result.sort(lambda x,y: cmp( str(x[dir[0]]),
str(y[dir[0]])) )
            else:
                result.sort(lambda x,y: cmp( str(x[dir[0]]),
str(y[dir[0]])), None, True)
        else:
            if dir[2]:
                result.sort(lambda x,y: cmp(float(x[dir[0]]),
float(y[dir[0]])) )
            else:
                result.sort(lambda x,y: cmp(float(x[dir[0]]),
float(y[dir[0]])), None, True )
    return result

m = [
   [3, 99, 'a'],
   [2, 77, 'a'],
   [1, 77, 'a']
 ]

print sort_matrix(m,[
[2,True,True],
[1,False,True]
])

The Python code has not been tested much.

http://xahlee.org/perl-python/sort_matrix.html

 Xah
 xah at xahlee.orghttp://xahlee.org/PageTwo_dir/more.html


More information about the Python-list mailing list