# Python, Perl: Generate All Possible Pairings

By Xah Lee. Date:

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:

[[9,5],[1,5],[9,2],[9,8],[9,7],[1,2],[1,8],[1,7],[5,2],[5,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. Answer below.

```↓
↓
↓
↓
↓
↓
↓
↓
↓

↓
↓
↓
↓
↓
↓
↓
↓
↓

↓
↓
↓
↓
↓
↓
↓
↓
↓

↓
↓
↓
↓
↓
↓
↓
↓
↓

↓
↓
↓
↓
↓
↓
↓
↓
↓

↓
↓
↓
↓
↓
↓
↓
↓
↓

```

## Perl

```# -*- coding: utf-8 -*-
# perl

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

## Python

```# -*- coding: utf-8 -*-
# python 2

def genpair (partiSet):
result=[]
for jj in partiSet[tail]:
result.append((ii,jj))
return result

# by Sean Gugler
# same algorithm as above, different syntax
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],[5],[2,8,7],[2]])
t=genpair(ll)
t2=genpair2(ll)
if (t.sort()==t2.sort()): print 'yay'```

If you have a question, put \$5 at patreon and message me.