[perl-python] generate all possible pairings

X

Xah Lee

20050226 exercise: generate all possible pairings

given a list that is a set partitioned into subsets, generate a list
of all possible pairings of elements in any two subset.

Example:

genpair( [[9,1],[5],[2,8,7]] );

returns:

[[5,8],[9,5],[1,5],[9,2],[9,7],[1,8],[1,7],[5,2],[1,2],[9,8],[5,7]]

(we do not assume the given set has order, so the result is not
ordered.)

Perl code and Python code will be posted in 2 days.

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

Xah
(e-mail address removed)
http://xahlee.org/PageTwo_dir/more.html
 
C

Chris Mattern

Mike said:
assert len(perl-python community) == 1

<mike
Apparently there are actually people who subscribe. Maybe they're
people in search of a good laugh...

I suppose they could be sock-puppets, but even for Xah, inventing
sock-puppets just to up the subscription count of your mail list
seems a bit much...

--
Christopher Mattern

"Which one you figure tracked us?"
"The ugly one, sir."
"...Could you be more specific?"
 
X

Xah Lee

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]
@
@ll=( [[9,1],[5],[2,8,7]])
@t=genpair(ll)
@t2=genpair2(ll)
@if (t.sort()==t2.sort()): print 'yay'


Xah
(e-mail address removed)
http://xahlee.org/PageTwo_dir/more.html
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top