Combinations and permutations are different ways in which a group of objects can be selected and arranged into smaller subgroups. They have far-reaching, real-world applications, especially in programmatic problem-solving.
itertoolspackage provides simple functionality to compute combinations and permutations.
combinations method in
itertools takes in a list of values, alongside an integer
r, inputs, and then returns a list of all possible combinations in the form of tuples.
combinations_with_replacement method works more or less the same as the simple
combinations method, but it allows values to be combined with themselves. The following code snippet shows how these methods work:
import itertools vals = [16, 12, 24, 73, 2, 24] comb = itertools.combinations(vals, 3) comb_with_rep = itertools.combinations_with_replacement(vals, 3) print("Combinations without replacement:") for val in comb: print(*val) print("Combinations with replacement:") for val in comb_with_rep: print(*val)
itertools package provides a similar functionality to compute permutations. The
permutations method takes a list as input and an optional integer (
r) that defines the length of the desired permutations. The code below shows how permutations can be computed in Python:
import itertools vals = [16, 12, 24, 73] perm = itertools.permutations(vals) perm_r = itertools.permutations(vals, 2) print("Permutations of length 4:") # Same length as list vals for val in perm: print(*val) print("Permutations of length 2:") for val in perm_r: print(*val)
View all Courses