在Python中;获得n
成员的k
组和{
例如,给定元素列表:
g = ["A", "B", "C", "D", "E", "F", "G"]
我想要的是有一个所有组合的列表li
,例如2(=k
)组(=n
)和1(=l
)组的3(=m
):
我不希望元素在任何组中出现任何重复(相当于说:我希望每个不同的元素在每个不同组合的所有组中出现一次)。在
E.g.
["AB", "AD", "EFG"]
is not a valid combination as it has the elementA
more than once accross all groups.
我不想在一个组内有不同的排列
E.g.
["AB", "CD", "EFG"]
should not be repeated in a form like["BA", "DC", "EGF"]
.
另外,如果一个组合出现在k-groups
中的任何一个中,如果{l-groups
)我不希望在k-群中出现相同的组合。在
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并在每个排列中组合成n
的k
组和{
编辑:编辑代码以满足更新的需求(规则3)。在
代码:
输出:
^{pr2}$细节和细节可以在demonstration中找到。在
这个问题并不像它第一次出现的那样简单:从词汇表上看,每个组都必须是一个组合,并且您需要这些组的所有互斥排列。在
我认为这需要你编写一个递归生成器,使用字母表和大小列表。类似下面的代码(恐怕我还没有测试过…)公司名称:
编辑:在澄清之后,我添加了一行应该完成解决方案…
这个怎么样,它使用了几个itertools和{a2}。无论如何,我想itertools.组合是您要使用的:
对于您的示例列表,这将产生105结果
^{pr2}$也许你不想要一个依赖于字符串元素的答案
同样值得注意的是,万一性能出现问题
相关问题 更多 >
编程相关推荐