Python β Itertools.Combinations_with_replacement()
Itertools in Python refers to module provided in Python for the creation of iterators which helps in efficient looping, time and space efficiency as well. Itertools helps us to solve complex problems easily and efficiently. There are in general 3 types of iterators.
Different types of iterators provided by this module are:
Note: For more information, refer to Python Itertools
Itertools.Combinations_with_replacement()
Itertools.Combinations_with_replacement() lies in the Combinatoric Generator subtype of itertools. Combinatoric generators refer to those iterators which deal with the different arrangements possible for an iterator. Here the elements are referred with there index value and not by their value or type.
How to use Itertools.Combinations_with_replacement() function?
As understood by name βcombinationsβ means all the possible subsets or arrangements of the iterator and the word βcombinations_with_replacementβ means all the possible arrangements or subsets that allow an element to repeat in a subset. This function takes βrβ as input here βrβ represents the size of different combinations that are possible. All the combinations with repetition of elements are emitted and are of length βrβ and βrβ is a necessary argument here.
Example 1:-
Python3
from itertools import combinations_with_replacement a = "GEeks" l = list (combinations_with_replacement(a, 2 )) print ( "COMBINATIONS WITH REPLACEMENTS OF STRING GEeks OF SIZE 2." ) print (l) |
Output:-
COMBINATIONS WITH REPLACEMENTS OF STRING GEeks OF SIZE 2.
[(βGβ, βGβ), (βGβ, βEβ), (βGβ, βeβ), (βGβ, βkβ), (βGβ, βsβ), (βEβ, βEβ), (βEβ, βeβ), (βEβ, βkβ), (βEβ, βsβ), (βeβ, βeβ), (βeβ, βkβ), (βeβ, βsβ), (βkβ, βkβ), (βkβ, βsβ), (βsβ, βsβ)]
Example 2:-
Python3
from itertools import combinations_with_replacement print ( "All the combination of List in sorted order(with replacement) is:" ) print ( list (combinations_with_replacement( 'D.P.S.' , 2 ))) print () print ( "All the combination of list in sorted order(with replacement) is:" ) print ( list (combinations_with_replacement( range ( 1 , 5 ), 2 ))) |
Output:-
All the combination of List in sorted order(with replacement) is:
[(βDβ, βDβ), (βDβ, β.β), (βDβ, βPβ), (βDβ, β.β), (βDβ, βSβ), (βDβ, β.β), (β.β, β.β), (β.β, βPβ), (β.β, β.β), (β.β, βSβ), (β.β, β.β), (βPβ, βPβ), (βPβ, β.β), (βPβ, βSβ), (βPβ, β.β), (β.β, β.β), (β.β, βSβ), (β.β, β.β), (βSβ, βSβ), (βSβ, β.β), (β.β, β.β)]
All the combination of list in sorted order(with replacement) is:
[(1, 1), (1, 2), (1, 3), (1, 4), (2, 2), (2, 3), (2, 4), (3, 3), (3, 4), (4, 4)]