Blaz
Blaz

Reputation: 3618

All possible (monogamous) pairings of two lists (of boys and girls)

I have these two lists:

boys  = [1,2,3]
girls = [1,2,3]

How would you build all possible (monogamous) pairings [boy, girl]? With only 3 of both boys and girls, I think this is the list of all the possible pairings:

[
 [[1,1], [2,2], [3,3]],
 [[1,1], [2,3], [3,2]],
 [[1,2], [2,1], [3,3]],
 [[1,2], [2,3], [3,2]],
 [[1,3], [2,1], [3,2]],
 [[1,3], [2,2], [3,1]]
]

How would you do it in general (in above format)? This is what I've been able to come up ...

pairs = list(itertools.product(boys, girls))
possible_pairings = []
for i, p in enumerate(pairs):
    if i % len(boys) == 0:
        print
    print list(p),
#   possible_pairings.append(pairing)

... which gives this output.

[1, 1] [1, 2] [1, 3]
[2, 1] [2, 2] [2, 3]
[3, 1] [3, 2] [3, 3]

How would you find all possible pairings (written out above for specific example)? These are like the 6 ways you'd have to multiply elements of a 3x3 matrix (to find its determinant). :)

Sven's almost answer (with my enumerate addition)

possible_pairings = []
possible_pairings_temp = []
boys  = ["b1", "b2", "b3"]
girls = ["g1", "g2", "g3"]

for girls_perm in itertools.permutations(girls):
    for i, (b, g) in enumerate(zip(boys, girls_perm)):
        possible_pairings_temp.append([b, g])
        if (i + 1) % len(boys) == 0: # we have a new pairings list
            possible_pairings.append(possible_pairings_temp)
            possible_pairings_temp = []
    print

print possible_pairings

And this completely satisfies the format in the question.

Upvotes: 3

Views: 750

Answers (1)

Sven Marnach
Sven Marnach

Reputation: 602715

What you are describing are the permutations of a set. Simply leave the boys in the given order, and iterate through alll permutations of the girls -- this will give you all possible pairings:

boys = ["b1", "b2", "b3"]
girls = ["g1", "g2", "g3"]
for girls_perm in itertools.permutations(girls):
    for b, g in zip(boys, girls_perm):
        print b + g,
    print

prints

b1g1 b2g2 b3g3
b1g1 b2g3 b3g2
b1g2 b2g1 b3g3
b1g2 b2g3 b3g1
b1g3 b2g1 b3g2
b1g3 b2g2 b3g1

Upvotes: 10

Related Questions