The Python itertools.combinations_with_replacement() function is used to generate all possible unique combinations of elements from a given iterable, allowing elements to be repeated in each combination.
This function is useful in combinatorial problems where selecting subsets with repetition is required, such as generating lottery numbers with repeated values, coin change problems, or rolling dice combinations.
SyntaxFollowing is the syntax of the Python itertools.combinations_with_replacement() function −
itertools.combinations_with_replacement(iterable, r)Parameters
This function accepts the following parameters −
This function returns an iterator that produces tuples representing all possible unique combinations, allowing repetition of elements.
Example 1Following is an example of the Python itertools.combinations_with_replacement() function. Here, we generate all unique pairs from a list of numbers, allowing repetition −
import itertools numbers = [1, 2, 3] result = itertools.combinations_with_replacement(numbers, 2) for item in result: print(item)
Following is the output of the above code −
(1, 1) (1, 2) (1, 3) (2, 2) (2, 3) (3, 3)Example 2
Here, we specify a combination length of 3, generating unique triplets from the given set while allowing repetition −
import itertools letters = ['A', 'B', 'C'] result = itertools.combinations_with_replacement(letters, 3) for item in result: print(item)
Output of the above code is as follows −
('A', 'A', 'A') ('A', 'A', 'B') ('A', 'A', 'C') ('A', 'B', 'B') ('A', 'B', 'C') ('A', 'C', 'C') ('B', 'B', 'B') ('B', 'B', 'C') ('B', 'C', 'C') ('C', 'C', 'C')Example 3
Now, we use itertools.combinations_with_replacement() function to generate all possible 2-letter combinations from a string while allowing repetition −
import itertools word = "XY" result = itertools.combinations_with_replacement(word, 2) for item in result: print(''.join(item))
The result obtained is as shown below −
XX XY YYExample 4
When working with numerical combinations, the itertools.combinations_with_replacement() function can help generate all possible sum pairs including repeated values −
import itertools numbers = [1, 2, 3, 4] result = itertools.combinations_with_replacement(numbers, 2) for pair in result: print(pair, "Sum:", sum(pair))
The result produced is as follows −
(1, 1) Sum: 2 (1, 2) Sum: 3 (1, 3) Sum: 4 (1, 4) Sum: 5 (2, 2) Sum: 4 (2, 3) Sum: 5 (2, 4) Sum: 6 (3, 3) Sum: 6 (3, 4) Sum: 7 (4, 4) Sum: 8
python_modules.htm
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4