ca123
ca123

Reputation: 9

Finding all combinations of a list in Python with repetition

I am looking to find and print all possible combinations of the set (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12) of length 5. There should be 13 choose 5 combinations (6188) because order does NOT matter, and repetition is allowed. I found this code and was using it:

from itertools import product

N = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
for item in product(N, repeat=5):
      print(item)

However, this is not printing all 6188 combinations. Trying to figure out how to tweak the code so it spits out all of the combos.

Upvotes: 0

Views: 1708

Answers (1)

ywbaek
ywbaek

Reputation: 3031

What you want is to use combinations_with_replacement as @Dani Mesejo commented.
From the doc:

Return r length subsequences of elements from the input iterable allowing individual elements to be repeated more than once.

from itertools import combinations_with_replacement

N = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
l = list(combinations_with_replacement(N, 5))
print(len(l))  # 6188

Upvotes: 2

Related Questions