Producing permutations and combinations
Given a set of elements, if you ever felt the need to do something for each possible permutation of those elements, you might have wondered what the best way to generate all those permutations was.
Python has various functions in the itertools
module that will help with permutations and combinations, the differences between those are not always easy to grasp, but once you investigate what they do, they will become clear.
How to do it...
The Cartesian product is usually what people think of when talking about combinations and permutations.
- Given a set of elements,
A
,B
, andC
, we want to extract all possible couples of two elements,AA
,AB
,AC
, and so on:
>>> import itertools
>>> c = itertools.product(('A', 'B', 'C'), repeat=2)
>>> list(c)
[('A', 'A'), ('A', 'B'), ('A', 'C'),
('B', 'A'), ('B', 'B'), ('B', 'C'),
('C', 'A'), ('C', 'B'), ('C', 'C')]
- In case you want to omit the duplicated entries (
AA
,BB
,CC
), you can just use permutations...