We had learnt about the Infinite Iterators. Now, we will look at the type of Combinatoric Iterators
The recursive generators that are used to simplify combinatorial constructs such as permutations, combinations, and Cartesian products are called combinatoric iterators.
In Python there are 4 combinatoric iterators:
Product(): This tool computes the cartesian product of input iterables. To compute the product of an iterable with itself, we use the optional repeat keyword argument to specify the number of repetitions.
The output of this function are tuples in sorted order.
from itertools import product print(list(product([1, 2], repeat = 2))) # prints [(1, 1), (1, 2), (2, 1), (2, 2)] print(list(product([1, 2], '2'))) # prints [(1, '2'), (2, '2')] print(list(product('AB', [3, 4]))) # prints [('A', 3), ('A', 4), ('B', 3), ('B', 4)]
Permutations(): Permutations() as the name speaks for itself is used to generate all possible permutations of an iterable. All elements are treated as unique based on their position and not their values. This function takes an iterable and group_size, if the value of group_size is not specified or is equal to None then the value of group_size becomes length of the iterable.
from itertools import permutations print (list(permutations([1, 'InterviewBit'], 2))) # prints [(1, 'InterviewBit'), ('InterviewBit', 1)] print (list(permutations('AB'))) # prints [('A', 'B'), ('B', 'A')] print(list(permutations(range(3), 2))) # prints [(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)]
Combinations(): This iterator prints all the possible combinations(without replacement) of the container passed in arguments in the specified group size in sorted order.
from itertools import combinations print(list(combinations(['A', 2], 2))) # prints [('A', 2)] print(list(combinations('AB', 2))) # prints [('A', 'B')] print(list(combinations(range(2), 1))) # prints [(0,), (1,)]
Combinations_with_replacement(): This function returns a subsequence of length n from the elements of the iterable where n is the argument that the function takes determining the length of the subsequences generated by the function. Individual elements may repeat itself in combinations_with_replacement function.
from itertools import combinations_with_replacement print(list(combinations_with_replacement("AB", 2))) # prints [('A', 'A'), ('A', 'B'), ('B', 'B')] print(list(combinations_with_replacement([1, 2], 2))) # prints [(1, 1), (1, 2), (2, 2)] print(list(combinations_with_replacement(range(2), 1))) # prints [(0,), (1,)]
Try the following excercise in the editor below.
You are given a string S containing distinct characters.
Your task is to print all possible permutations of size K of the string in lexicographic sorted order.
1 <= K <= len(S) String S consist of lowercase letters.
First line contains space separated input S and K.
Print the permutations of the string S of size K on separate lines.
eo en ne no oe on