简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM