![]() |
VOOZH | about |
Python provides built-in methods to work with permutations and combinations using the itertools module. These are helpful in problems involving arrangement (order matters) and selection (order doesn’t matter) of elements.
Let's explore them one by one:
A permutation is an arrangement of elements where the order matters. For example, (1, 2) and (2, 1) are two different permutations.
Python offers the permutations() method in the itertools module to generate these.
(1, 2, 3) (1, 3, 2) (2, 1, 3) (2, 3, 1) (3, 1, 2) (3, 2, 1)
Explanation:permutations([1, 2, 3]) returns all possible orderings (3! = 6 permutations).
We can also generate permutations of a specific length r.
(1, 2) (1, 3) (2, 1) (2, 3) (3, 1) (3, 2)
Explanation:permutations([1, 2, 3], 2) returns 2-length ordered arrangements (nPr = 6).
A combination is a way to select elements where the order does not matter. For example, (1, 2) and (2, 1) are considered the same combination.
Python offers the combinations() method for this purpose.
(1, 2) (1, 3) (2, 3)
Explanation:
(2, 1) (2, 3) (1, 3)
Explanation:
Use combinations_with_replacement() to allow repeated elements in combinations.
(1, 1) (1, 2) (1, 3) (2, 2) (2, 3) (3, 3)
Explanation: combinations_with_replacement([1, 2, 3], 2) includes combinations like (1, 1), allowing repetition.
Related articles: