In looking for ways to make couplets of items I've discovered four brilliant methods in the itertools
module.
In making couplets its important to understand how the pairing should be defined. Once an item is chosen, can it be chosen again as the next element in the group? If a set is defined as {0, 1, 2, 3}
, can we define a group as (0, 0)
? This is referred to as replacement.
In making these groups, does the order of the elements matter? is (0, 1)
unique to (1, 0)
? If it doesn't matter than my set of groups should only include one of the pair, but if it does the set should include both. A good analogy to make is if you were choosing a leader for each pair, the leader being the first in the pair, then the order would matter—0
is the leader in (0, 1)
and vice versa—versus if you were just choosing teams where each member held the same status; it wouldn't matter in what order you defined the group they're all the same group.
The itertools methods are the following
from itertools import (
product, combinations,
combinations_with_replacement, permutations)
l = list(range(3))
npairs = 2
print(l)
list(permutations(l, npairs))
This is essentially the different ways to order a pair measured by the Binomial Coefficient
list(combinations(l, npairs))
list(combinations_with_replacement(l, npairs))
product operates on multiple lists, returning pairings between items of different lists. To use on the same list (you probably shouldn't) you would specify the size of the group with the parameter keyword repeat
IF used in this way one think of it as WITH replacement, where order DOES matter, so (0, 0)
is acceptable, and (1,0)
is unique to (0, 1)
list(product(l, repeat=npairs))
A better way to use product is with different lists
shirts = ['hawaii', 'collared']
shoes = ['sneakers', 'slippers']
pants = ['jeans', 'shorts']
outfits = list(product(shirts, shoes, pants))
outfits
Method | With Replacement | Order Matters |
---|---|---|
permutations | X | |
combinations | ||
combinations_with_replacement | X | |
product | X | X |