Python - Permutations And Combinations
Last Updated: 2202Z 11SEP19
(Created: 2202Z 11SEP19)
Signatures:
itertools.combinations(iterable, r)
Return r length subsequences of elements from input iterable.
itertools.permutations(iterable, r=None)
Return successive r length permutations of elements in iterable
If r is not specified or is None, then r defaults to length of iterable.
Examples:
import itertools
friends = ['Monique', 'Ashish', 'Devon', 'Bernie']
# Order of elements doesn't matter
list(itertools.combinations(friends, r=2))
# [
# ('Monique', 'Ashish'), ('Monique', 'Devon'), ('Monique', 'Bernie'),
# ('Ashish', 'Devon'), ('Ashish', 'Bernie'), ('Devon', 'Bernie')
# ]
# Order matters
list(itertools.permutations(friends, r=2))
# [
# ('Monique', 'Ashish'), ('Monique', 'Devon'), ('Monique', 'Bernie'),
# ('Ashish', 'Monique'), ('Ashish', 'Devon'), ('Ashish', 'Bernie'),
# ('Devon', 'Monique'), ('Devon', 'Ashish'), ('Devon', 'Bernie'),
# ('Bernie', 'Monique'), ('Bernie', 'Ashish'), ('Bernie', 'Devon')
# ]
References: