我必须列出具有有限重复次数的无序组合 即对于给定的唯一元素列表,说 card_set 创建长度为 combo_len 的所有组合,其中一个元素以最大 repeat_limit 次重复
下面的代码是针对 combo_len = 3 和 repeat_limit = 2 with card_set = range(5)
注意我需要无序组合。 即 (0,0,1) 和 (0,1,0) 相同,所以下面的解决方案链接不满足我的条件
This帖子告诉我如何获得有限重复的排序组合
import itertools
import pprint
card_set = list(range(5))
a = sorted(set(itertools.combinations_with_replacement(card_set,3)))
neg = [(i,i,i) for i in card_set]
b = set(a) - set(neg)
print('a###')
pprint.pprint(a)
print('b###')
pprint.pprint(b)
上面的代码给了我一个无序组合,重复次数有限,即。 neg 包含不需要的重复 (0,0,0) (1,1,1) 等 所以 b = set(a) - set(neg) 给我所需的集合
对于 combo_len = 3 和 repeat_limit = 2,上面的代码有效。我如何为 range(13) combo_len = 7 和 repeat_limit = 4 编写代码
输出:
a###
[(0, 0, 0),
(0, 0, 1),
(0, 0, 2),
(0, 0, 3),
(0, 0, 4),
(0, 1, 1),
(0, 1, 2),
(0, 1, 3),
(0, 1, 4),
(0, 2, 2),
(0, 2, 3),
(0, 2, 4),
(0, 3, 3),
(0, 3, 4),
(0, 4, 4),
(1, 1, 1),
(1, 1, 2),
(1, 1, 3),
(1, 1, 4),
(1, 2, 2),
(1, 2, 3),
(1, 2, 4),
(1, 3, 3),
(1, 3, 4),
(1, 4, 4),
(2, 2, 2),
(2, 2, 3),
(2, 2, 4),
(2, 3, 3),
(2, 3, 4),
(2, 4, 4),
(3, 3, 3),
(3, 3, 4),
(3, 4, 4),
(4, 4, 4)]
b###
{(0, 0, 1),
(0, 0, 2),
(0, 0, 3),
(0, 0, 4),
(0, 1, 1),
(0, 1, 2),
(0, 1, 3),
(0, 1, 4),
(0, 2, 2),
(0, 2, 3),
(0, 2, 4),
(0, 3, 3),
(0, 3, 4),
(0, 4, 4),
(1, 1, 2),
(1, 1, 3),
(1, 1, 4),
(1, 2, 2),
(1, 2, 3),
(1, 2, 4),
(1, 3, 3),
(1, 3, 4),
(1, 4, 4),
(2, 2, 3),
(2, 2, 4),
(2, 3, 3),
(2, 3, 4),
(2, 4, 4),
(3, 3, 4),
(3, 4, 4)}
请您参考如下方法:
您可以使用 collections 模块中的 Counter 类来查找给定元组中每个值的重复次数。为每个元组创建一个 Counter 并检查重复的最大值。如果最大值足够小,则接受元组;否则拒绝。
这是执行此操作的例程。如果我有更多时间,我会美化它。
小心这个例程。对于给定的 range_size=13, combo_len=7, repeat_limit=4 值,结果是一个长度为 49,205 的列表。
from collections import Counter
from itertools import combinations_with_replacement
def unordered_combinations_with_limited_replacements(
range_size, combo_len, repeat_limit):
return [t for t in combinations_with_replacement(range(range_size), combo_len)
if max(Counter(t).values()) <= repeat_limit]
print(unordered_combinations_with_limited_replacements(5, 3, 2))
print(len(unordered_combinations_with_limited_replacements(13, 7, 4)))
这是打印输出:
[(0, 0, 1), (0, 0, 2), (0, 0, 3), (0, 0, 4), (0, 1, 1), (0, 1, 2), (0, 1, 3), (0, 1, 4), (0, 2, 2), (0, 2, 3), (0, 2, 4), (0, 3, 3), (0, 3, 4), (0, 4, 4), (1, 1, 2), (1, 1, 3), (1, 1, 4), (1, 2, 2), (1, 2, 3), (1, 2, 4), (1, 3, 3), (1, 3, 4), (1, 4, 4), (2, 2, 3), (2, 2, 4), (2, 3, 3), (2, 3, 4), (2, 4, 4), (3, 3, 4), (3, 4, 4)]
49205
