[perl-python] problem: reducing comparison

Xah Lee xah at xahlee.org
Tue Feb 15 07:48:24 EST 2005


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
 xah at xahlee.org
 http://xahlee.org/PageTwo_dir/more.html




More information about the Python-list mailing list