python - 获取 K 组 N 成员和 L 组 M 成员的组合列表

标签 python algorithm python-2.7 combinations

在 Python 中;获取 kn 成员和 lm 组合列表的最佳方法是什么给定可能成员列表的成员 g?

示例,给定一个元素列表:

g = ["A", "B", "C", "D", "E", "F", "G"]

我想要的是拥有所有组合的列表 li,例如2(=k) 组 2(=n) 和 1(=l) 组 3(=m):

[["AB", "CD", "EFG"],
 ["AC", "BD", "EFG"],
 ["AD", "CB", "EFG"],
 ["AE", "CD", "BFG"],
 ["AF", "CD", "BEG"],... ]
  1. 我不希望任何组中的元素重复(相当于说:我希望每个不同的元素在所有组中针对每个不同的组合出现一次)。

    E.g. ["AB", "AD", "EFG"] is not a valid combination as it has the element A more than once accross all groups.

  2. 我不希望一个组内有不同的排列

    E.g. ["AB", "CD", "EFG"] should not be repeated in a form like ["BA", "DC", "EGF"].

  3. 此外,如果一个组合出现在任何 k-groups 中,我不希望在 k-groups 中出现相同的组合,如果 l-groups 是相同的(对于 l-groups 也是相同的)

    E.g. if["AB", "CD", "EFG"] appears, [ "CD", "AB", "EFG"] should not appear again.

明确地说,我只对这些组总是整齐/准确地适合要使用的元素的总组的情况感兴趣(g):

E.g. 2x2 + 1x3 == 7 == len(["A", "B", "C", "D", "E", "F", "G"]), 1x2 + 1x3 == 5 == len(["A", "B", "C", "D", "E"]).


我可以使用 Python's permutations function并在每个排列中将 knlm 组合在一起,但我会有对更多元素进行大量不必要的迭代。

最佳答案

编辑:编辑代码以满足更新的要求(规则 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 中找到.

关于python - 获取 K 组 N 成员和 L 组 M 成员的组合列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45644674/

相关文章:

python - (Python--numpy) 如何在不循环的情况下调整 numpy 数组的大小和切片?

c++ - 计算多个数字的几何平均值的有效方法

c# - 在加权图 C# 实现中查找最大权重团

javascript - 如何计算阈值(基础数学)

python - Python 中是否存在不能在字符串中进行类型转换的数据类型

python-2.7 - Python cv2 图像金字塔

python - django 应用程序中的导入策略

python - python pandas dataframe 保留前一个单元格值并复制到下一个单元格

python - AssertionError - 没有提供异常 - django

python - 如何将线程对象传递给 ThreadPoolExecutor?