编辑:经过澄清,我添加了一行应该完成解决方案...
这个怎么样,它使用了几个itertools和flatten recipe。无论如何,我认为你想要使用itertools.combinations:
from itertools import combinations, chain, product
def flatten(listOfLists):
"Flatten one level of nesting"
return chain.from_iterable(listOfLists)
lico = lambda li,x: list( combinations(li,x) )
def get_funky_groups( elements, k,n,l,m ):
kn = lico( lico(elements,n),k)
lm = lico( lico( elements,m), l)
results = [map( lambda x: "".join(x), flatten(r)) for r in product(kn, lm)]
return [ r for r in results if len(set( flatten( r))) == len(g) ]
针对您的示例列表,这将产生105个结果。
In [3]: g = ["A", "B", "C", "D", "E", "F", "G"]
In [4]: results = get_funky_groups(g, 2,2,1,3)
In [5]: results[:10]
Out[5]:
[['AB', 'CD', 'EFG'],
['AB', 'CE', 'DFG'],
['AB', 'CF', 'DEG'],
['AB', 'CG', 'DEF'],
['AB', 'DE', 'CFG'],
['AB', 'DF', 'CEG'],
['AB', 'DG', 'CEF'],
['AB', 'EF', 'CDG'],
['AB', 'EG', 'CDF'],
['AB', 'FG', 'CDE']]
In [6]: len( results)
Out[6]: 105
In [7]: g = ["A", "B", "C", "D", "E"]
In [8]: results = get_funky_groups(g, 1,2,1,3)
In [9]: results
Out[9]:
[['AB', 'CDE'],
['AC', 'BDE'],
['AD', 'BCE'],
['AE', 'BCD'],
['BC', 'ADE'],
['BD', 'ACE'],
['BE', 'ACD'],
['CD', 'ABE'],
['CE', 'ABD'],
['DE', 'ABC']]
也许你不想要一个基于字符串元素的答案。
def get_funky_groups_anyhashable( elements, k,n,l,m ):
kn = lico( lico(elements,n),k)
lm = lico( lico( elements,m), l)
results = [ list(flatten(r)) for r in product(kn, lm)]
return [ r for r in results if len(set( flatten( r))) == len(g) ]
In [103]: g = ["A1", "B2", 232, "D0", 32]
In [104]: get_funky_groups_anyhashable(g, 1,2,1,3)
Out[104]:
[[('A1', 'B2'), (232, 'D0', 32)],
[('A1', 232), ('B2', 'D0', 32)],
[('A1', 'D0'), ('B2', 232, 32)],
[('A1', 32), ('B2', 232, 'D0')],
[('B2', 232), ('A1', 'D0', 32)],
[('B2', 'D0'), ('A1', 232, 32)],
[('B2', 32), ('A1', 232, 'D0')],
[(232, 'D0'), ('A1', 'B2', 32)],
[(232, 32), ('A1', 'B2', 'D0')],
[('D0', 32), ('A1', 'B2', 232)]]
值得注意的是,如果性能成为问题。
In [132]: lico( combinations( g,2),1) == lico( lico( g,2),1 )
Out[132]: True
["AB", "BC", "EFE"]
是合法的吗? - Prune["AB", "BC", "EFG"]
这样的一些示例中已经重复了 B 和 C。 - Prune["AB", "CD", "EFG"]
和["CD", "AB", "EFG"]
两者都得到还是只需要其中一个? - rici