编辑:编辑代码以满足更新的要求(规则3).
码:
import itertools as it
def unique_group(iterable, k, n):
"""Return an iterator, comprising groups of size `k` with combinations of size `n`."""
# Build separate combinations of `n` characters
groups = ("".join(i) for i in it.combinations(iterable, n)) # 'AB', 'AC', 'AD', ...
# Build unique groups of `k` by keeping the longest sets of characters
return (i for i in it.combinations(groups, k)
if len(set("".join(i))) == sum((map(len, i)))) # ('AB', 'CD'), ('AB', 'CE'), ...
def combined(groups1, groups2):
"""Return an iterator with unique combinations of groups (k and l)."""
# Build a unique cartesian product of groups `k` and `l`, filtering non-disjoints
return (i[0] + i[1]
for i in it.product(groups1, groups2)
if set("".join(i[0])).isdisjoint(set("".join(i[-1]))))
iterable = "ABCDEFG"
g1 = unique_group(iterable, 2, 2)
g2 = unique_group(iterable, 1, 3)
result = list(combined(g1, g2))
print(len(result))
result
输出:
105
[('AB', 'CD', 'EFG'),
('AB', 'CE', 'DFG'),
...,
('BC', 'AD', 'EFG'),
('BC', 'AE', 'DFG'),
...,
]
详细信息和见解可以在demonstration中找到.