问题
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
for item in product([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
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.
回答1:
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
l = list(combinations_with_replacement([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], 5))
print(len(l)) # 6188
来源:https://stackoverflow.com/questions/60934189/finding-all-combinations-of-a-list-in-python-with-repetition