[perl-python] generate all possible pairings

Xah Lee xah at xahlee.org
Wed Mar 2 05:06:01 CET 2005


Answer to the previous exercise.
http://xahlee.org/perl-python/generate_pairings.html

# perl
sub genpair ($) {
my $partiSet = $_[0];
my @result;
for (my $head =0; $head <= ((scalar @$partiSet)-2); $head++ ) {
    for (my $tail = $head+1; $tail <= ((scalar @$partiSet)-1); $tail++
) {
        foreach my $ii (@{$partiSet->[$head]}) {
            foreach my $jj (@{$partiSet->[$tail]}) {
                push @result, [$ii,$jj]
            }
        }
    }
}
return \@result;
}

@# python
@def genpair (partiSet):
@    result=[]
@    for head in range(len(partiSet)-1):
@        for tail in range(head+1,len(partiSet)):
@            for ii in partiSet[head]:
@                for jj in partiSet[tail]:
@                    result.append((ii,jj))
@    return result
@
@# by Sean Gugler
@def genpair2 (partiSet):
@    return [(a,b) for s in range(len(partiSet))
@            for t in range(s)
@            for a in partiSet[t]
@            for b in partiSet[s]]
@
@ll=( [[9,1],[5],[2,8,7]])
@t=genpair(ll)
@t2=genpair2(ll)
@if (t.sort()==t2.sort()): print 'yay'


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




More information about the Python-list mailing list