473,473 Members | 1,814 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

[perl-python] problem: reducing comparison

here's a interesting real-world algoritm to have fun with.

attached below is the Perl documentation that i wrote for a function
called "reduce", which is really the heart of a larger software.

The implementation is really simple, but the key is to understand what
the function should be. I'll post Perl and Python codes tomorrow for
those interested. If you are a perl programer, try to code it in
Python. (it's easy.)

This is brought to you by the Perl-Python a-day community. To
subscribe, see
http://xahlee.org/perl-python/python.html

Xah
xa*@xahlee.org
http://xahlee.org/PageTwo_dir/more.html

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

=pod

e.g. reduce( $pairings, $a_pair) retured the first argument with some
pairs deleted.

Detail:

we have n things, represented by numbers 1 to n. Some of these are
identical. We want to partition the range of numbers 1 to n so that
identical ones are grouped together.

To begin comparison, we generate a list of pairings that's all
possible parings of numbers 1 to n. (of course order does not matter,
and the pairing does not contain repeations) This is the first
argument to reduce.

We'll go thru this pairings list one by one and do comparisons, remove
the pair once it has been compared. However, more pairs can be removed
if a we find a pair identical.

For example, suppose we know that 2 and 4 are identical, and if the
pairing list contains (2,3) and (4,3), one of them can be deleted
because now 2 and 4 are the same thing.

(We do this because we expect the comparison operation will be
expensive.)

reduce( $pairings, $a_pair) returns a reduced $pairings knowing that
$a_pair are identical.

The first argument $pairings must be in the form of a hash. e.g.

{'1,5' => [1,5],'3,5' => [3,5],'2,4' => [2,4],'4,5' => [4,5],'1,3' =>
[1,3],'2,5' => [2,5],'1,2' => [1,2],'3,4' => [3,4],'2,3' =>
[2,3],'1,4' => [1,4]}

(Note that keys are strings of the pairs separated by a comma.)

$a_pair is a reference to a list of the form [$a,$b].

(different pairs may be deleted if the hash's pairs are given in
different order. i.e. 3,4 instead of 4,3)

The return value is a reference to a hash.

The program is deterministic but exactly which pairs are deleted is
unspecified. If the input is all possible pairs of 2 things out of n,
maximum reduction is guaranteed.

=cut

Jul 18 '05 #1
9 1907
here are the answers:

Perl code:

sub reduce ($$) {
my %hh= %{$_[0]}; # e.g. {'1,2'=>[1,2],'5,6'=>[5,6],...}
my ($j1,$j2)=($_[1]->[0],$_[1]->[1]); # e.g. [3,4]
delete $hh{"$j1,$j2"};
foreach my $k (keys %hh) {
$k=~m/^(\d+),(\d+)$/;
my ($k1,$k2)=($1,$2);
if ($k1==$j1) {
if ($j2 < $k2) {
delete $hh{"$j2,$k2"};
}
else {
delete $hh{"$k2,$j2"};
};
};
if ($k2==$j1) {
if ($k1 < $j2) {
delete $hh{"$k1,$j2"};
}
else {
delete $hh{"$j2,$k1"};
};
};
}
return \%hh;
}
©Python code.
©
©def reduce(pairings, pair):
© ps=pairings.copy(); j=pair;
© ps.pop("%d,%d"%(j[0],j[1]),0)
© for k in pairings.itervalues():
© if (k[0]==j[0]):
© if (j[1] < k[1]):
© ps.pop("%d,%d"%(j[1],k[1]),0)
© else:
© ps.pop("%d,%d"%(k[1],j[1]),0)
© if (k[1]==j[0]):
© if (k[0] < j[1]):
© ps.pop("%d,%d"%(k[0],j[1]),0)
© else:
© ps.pop("%d,%d"%(j[1],k[0]),0)
© return ps
©

In imperative languages such as Perl and Python and Java, in general it
is not safe to delete elements when looping thru a list-like entity.
(it screws up the iteration) One must make a copy first, and work with
the copy.

Note also that in Python there's already a function called reduce. (it
is equivalent to Mathematica's Fold.) In Python, looks like user can
over-ride default functions.

This post is archived at
http://xahlee.org/perl-python/pairing_reduce.html
Possible errata or addenda will appear there.

Xah
xa*@xahlee.org
http://xahlee.org/PageTwo_dir/more.html

Jul 18 '05 #2
my Python coding is not experienced. In this case, is
ps.pop("%d,%d"%(j[1],k[1]),0) out of ordinary?

if i have long paragraphs of documentation for a function, do i still
just attach it below the fun def?

Xah

Xah Lee wrote:
here are the answers:

©Python code.
©
©def reduce(pairings, pair):
© ps=pairings.copy(); j=pair;
© ps.pop("%d,%d"%(j[0],j[1]),0)
© for k in pairings.itervalues():
© if (k[0]==j[0]):
© if (j[1] < k[1]):
© ps.pop("%d,%d"%(j[1],k[1]),0)
© else:
© ps.pop("%d,%d"%(k[1],j[1]),0)
© if (k[1]==j[0]):
© if (k[0] < j[1]):
© ps.pop("%d,%d"%(k[0],j[1]),0)
© else:
© ps.pop("%d,%d"%(j[1],k[0]),0)
© return ps
©

In imperative languages such as Perl and Python and Java, in general it is not safe to delete elements when looping thru a list-like entity.
(it screws up the iteration) One must make a copy first, and work with the copy.

Note also that in Python there's already a function called reduce. (it is equivalent to Mathematica's Fold.) In Python, looks like user can
over-ride default functions.

This post is archived at
http://xahlee.org/perl-python/pairing_reduce.html
Possible errata or addenda will appear there.

Xah
xa*@xahlee.org
http://xahlee.org/PageTwo_dir/more.html


Jul 18 '05 #3
Xah Lee wrote:
here's a interesting real-world algoritm to have fun with.


From you? Doubtful.

Sorry, dude, but you've been replaced by über-troll Ilias Lazaridis.
Security will escort you to the door.
--
Soraia: http://www.soraia.com

Jul 18 '05 #4
©someone sent me the following code, which performs identically with
the original reduce. (tested for pairings of comb(n) with large n)
Superb.
©
©def reduce2( pairings, pair ):
© result={}
© for i,j in pairings.itervalues():
© if i in pair: i=pair[0]
© if j in pair: j=pair[0]
© if i>j: (i,j) = (j,i)
© if i!=j: result["%d,%d"%(i,j)] = (i,j)
© return result
©
©
©def reduce(pairings, pair):
© ps=pairings.copy(); j=pair;
© ps.pop("%d,%d"%(j[0],j[1]),0)
© for k in pairings.itervalues():
© if (k[0]==j[0]):
© if (j[1] < k[1]):
© ps.pop("%d,%d"%(j[1],k[1]),0)
© else:
© ps.pop("%d,%d"%(k[1],j[1]),0)
© if (k[1]==j[0]):
© if (k[0] < j[1]):
© ps.pop("%d,%d"%(k[0],j[1]),0)
© else:
© ps.pop("%d,%d"%(j[1],k[0]),0)
© return ps
©
©is reduce2 more efficient? It works entirely differently. I'll have
to think about it... besides algorithmic... onto the minute academic
diddling, i wonder if it is faster to delete entries in dict or add
entries...

Xah
xa*@xahlee.org
http://xahlee.org/PageTwo_dir/more.html

Xah Lee wrote:
here are the answers:

Perl code:

sub reduce ($$) {
my %hh= %{$_[0]}; # e.g. {'1,2'=>[1,2],'5,6'=>[5,6],...}
my ($j1,$j2)=($_[1]->[0],$_[1]->[1]); # e.g. [3,4]
delete $hh{"$j1,$j2"};
foreach my $k (keys %hh) {
$k=~m/^(\d+),(\d+)$/;
my ($k1,$k2)=($1,$2);
if ($k1==$j1) {
if ($j2 < $k2) {
delete $hh{"$j2,$k2"};
}
else {
delete $hh{"$k2,$j2"};
};
};
if ($k2==$j1) {
if ($k1 < $j2) {
delete $hh{"$k1,$j2"};
}
else {
delete $hh{"$j2,$k1"};
};
};
}
return \%hh;
}

...
In imperative languages such as Perl and Python and Java, in general it is not safe to delete elements when looping thru a list-like entity.
(it screws up the iteration) One must make a copy first, and work with the copy.

Note also that in Python there's already a function called reduce. (it is equivalent to Mathematica's Fold.) In Python, looks like user can
over-ride default functions.

This post is archived at
http://xahlee.org/perl-python/pairing_reduce.html
Possible errata or addenda will appear there.

Xah
xa*@xahlee.org
http://xahlee.org/PageTwo_dir/more.html


Jul 18 '05 #5
Xah Lee wrote:
attached below is the Perl documentation that i wrote for a function
called "reduce", which is really the heart of a larger software.


Don't shadow built-ins. Especially for a function name.
--
Michael Hoffman
Jul 18 '05 #6

Xah Lee wrote:
In imperative languages such as Perl and Python and Java, in general it is not safe to delete elements when looping thru a list-like entity.
(it screws up the iteration) One must make a copy first, and work with the copy.


Correction:
When looping thru a list-like entity and delete elements in the vary
list, there's a question whether it will change the iteration. (For
example, if one loops thru 1 to 9, and deleted 8 while at 2, should the
loop still do 8?) For some languages and or list entities, the answer
may be yes or no. However, in imperative languages such as Perl and
Python and Java, often this is not allowed by the language, partially
as a protection to safeguard and assume programers as ignoramuses, but
partially because the internal issues of these languages can't handle
it.

The work around in these languages is always to make a copy of the
list-entity, and work with the copy.

Xah
xa*@xahlee.org
http://xahlee.org/PageTwo_dir/more.html

Jul 18 '05 #7
Xah Lee wrote:
In imperative languages such as Perl and Python
and Java, in general it is not safe to delete
elements when looping thru a list-like entity.
(it screws up the iteration) One must make a
copy first, and work with the copy.


Correction:
When looping thru a list-like entity and delete elements in the vary
list, there's a question whether it will change the iteration. (For
example, if one loops thru 1 to 9, and deleted 8 while at 2, should the
loop still do 8?) For some languages and or list entities, the answer
may be yes or no. However, in imperative languages such as Perl and
Python and Java, often this is not allowed, justified as a protection
to safeguard programers as ignoramuses, but partially because the
internal issues of these languages. (These languages have molded a
generation of programers to question and discourse man-made issues.)

The work around in these languages is always to make a copy of the
list-entity, and work with the copy.

Xah
xa*@xahlee.org
http://xahlee.org/PageTwo_dir/more.html

Jul 18 '05 #8
Xah Lee wrote:
In imperative languages such as Perl and Python
and Java, in general it is not safe to delete
elements when looping thru a list-like entity.
(it screws up the iteration) One must make a
copy first, and work with the copy.


Correction:
When looping thru a list-like entity and delete elements in the vary
list, there's a question whether it will change the iteration. (For
example, if one loops thru 1 to 9, and deleted 8 while at 2, should the
loop still do 8?) This is a design issue. Both behavior are useful. For
some languages and or list entities, the answer may be yes or no.
However, in imperative languages such as Perl and Python and Java,
often modifying a list while looping simply cannot be done, justified
as a protection to safeguard programers as ignoramuses, but partially
because the internal issues of these languages. (These languages have
molded a generation of programers to question and discourse man-made
complexities.)

The work around in these languages is always to make a copy of the
list-entity, and work with the copy.

Xah
xa*@xahlee.org
http://xahlee.org/PageTwo_dir/more.html

Jul 18 '05 #9
This could have been a really unique thread: 15 messages, 1 author

Jul 18 '05 #10

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: -------------------------------------...
6
by: John Smith | last post by:
Hello, I have a rather odd question. My company is an all java/oracle shop. We do everything is Java... no matter what it is... parsing of text files, messaging, gui you name it. My question...
4
by: Firewalker | last post by:
Hey guys, I am newbie to perl. I am trying to deal with dates ( such trying to find what the date would be after month). Is therea function or date class( I am a java programmer, I couldnt find...
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...
4
by: Ignoramus6539 | last post by:
There were some strange requests to my server asking for config.php file (which I do not have in the requested location). I did some investigation. Seems to be a virus written in perl,...
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...
223
by: Pilcrow | last post by:
Given that UNIX, including networking, is almost entirely coded in C, how come so many things are almost impossible in ordinary C? Examples: Network and internet access, access to UNIX...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
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...
1
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
1
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.