Movatterモバイル変換


[0]ホーム

URL:


Python Tutorial

Python itertools.combinations_with_replacement() Function



The Pythonitertools.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.

Syntax

Following is the syntax of the Python itertools.combinations_with_replacement() function −

itertools.combinations_with_replacement(iterable, r)

Parameters

This function accepts the following parameters −

  • iterable: The input iterable whose elements will be combined.
  • r: The length of each combination.

Return Value

This function returns an iterator that produces tuples representing all possible unique combinations, allowing repetition of elements.

Example 1

Following 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 itertoolsnumbers = [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 itertoolsletters = ['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 itertoolsword = "XY"result = itertools.combinations_with_replacement(word, 2)for item in result:   print(''.join(item))

The result obtained is as shown below −

XXXYYY

Example 4

When working with numerical combinations, the itertools.combinations_with_replacement() function can help generate all possible sum pairs including repeated values −

import itertoolsnumbers = [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
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp