473,396 Members | 1,858 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

[perl-python] sorting matrixes

Today we'll write a program that can sort a matrix in all possible
ways.

Here's the Perl documentation. I'll post a Perl and Python version in 2
days.

-----------

sort_matrix( $matrix, [[$n1, $stringQ, $directionQ], [$n2, $stringQ,
$directionQ], ...]) sorts a matrix by $n1 th column then $n2 th...and
so on.

$matrix must be a reference to references of arrays, having the form
[[$e1, $e2,...], [...], ...]. $stringQ is a boolean indicating
whether to treat corresponding columns as a strings instead of as
number in the sorting process. True means string. $directionQ is a
boolean indicating ascending sort or not for the correpsonding
column. In the column spec $n1 $n2 ..., index counting starts at 0.

Example:

my $ref_matrix =
[
[3, 99, 'a'],
[2, 77, 'a'],
[1, 77, 'a']
];

sort_matrix( $ref_matrix, [ [2,1,1], [1,0,1] ]);
# this means sort by third column, regarding it as strings,
# and in ascending order. If tie, sort by second column,
# regarding it as number, in ascending order.

# returns [[2,77,'a'],[1,77,'a'],[3,99,'a']];

------------------

Note: in the above, ignore the "must be a reference to references of
arrays". That's technical point, because Perl the language do nested
lists thru workaround of "references".

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

Jul 18 '05 #1
2 2191
On 22 Mar 2005 09:02:51 -0800, rumours say that "Xah Lee" <xa*@xahlee.org> might
have written:
Today we'll write a program that can sort a matrix in all possible
ways.

Here's the Perl documentation. I'll post a Perl and Python version in 2
days.


Don't bother writing a Python version... list.sort and its arguments are fine
and send their greetings.
--
TZOTZIOY, I speak England very best.
"Be strict when sending and tolerant when receiving." (from RFC1958)
I really should keep that in mind when talking with people, actually...
Jul 18 '05 #2
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
xa*@xahlee.org
∑ http://xahlee.org/PageTwo_dir/more.html

☄

Jul 18 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Mark Wilson CPU | last post by:
This must be easy, but I'm missing something... I want to execute a Perl script, and capture ALL its output into a PHP variable. Here are my 2 files: -------------------------------------...
3
by: David F. Skoll | last post by:
Hi, I'm tearing my hair out on this one. I'm trying to embed a Perl interpreter into a C program. I need to be able to create and destroy the interpreter periodically, but will never actually...
0
by: Kirt Loki Dankmyer | last post by:
So, I download the latest "stable" tar for perl (5.8.7) and try to compile it on the Solaris 8 (SPARC) box that I administrate. I try all sorts of different switches, but I can't get it to compile....
13
by: Otto J. Makela | last post by:
I'm trying to install to php the Perl-1.0.0.tgz package (from http://pecl.php.net/package/perl, enabling one to call perl libraries) to a pre-existing Solaris system. Unfortunately, the attempt...
6
by: surfivor | last post by:
I may be involved in a data migration project involving databases and creating XML feeds. Our site is PHP based, so I imagine the team might suggest PHP, but I had a look at the PHP documentation...
4
by: billb | last post by:
I installed a perl extension for PHP to use some perl inside my php primarily because I have perl working with oracle and not php and oracle. So I want to use my old perl scripts, and use the...
21
KevinADC
by: KevinADC | last post by:
Note: You may skip to the end of the article if all you want is the perl code. Introduction Uploading files from a local computer to a remote web server has many useful purposes, the most...
1
KevinADC
by: KevinADC | last post by:
Note: You may skip to the end of the article if all you want is the perl code. Introduction Many websites have a form or a link you can use to download a file. You click a form button or click...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.