Finding all combinations of a list in Python with repetition

人走茶凉 提交于 2021-01-07 07:06:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!