这可行,尽管它可能超级无效(我将它们全部排序以避免重复计算):
def clusters(l, K): if l: prev = None for t in clusters(l[1:], K): tup = sorted(t) if tup != prev: prev = tup for i in xrange(K): yield tup[:i] + [[l[0]] + tup[i],] + tup[i+1:] else: yield [[] for _ in xrange(K)]
它还返回空簇,因此您可能希望将其包装起来以便仅获取非空簇:
def neclusters(l, K): for c in clusters(l, K): if all(x for x in c): yield c
计数只是为了检查:
def kamongn(n, k): res = 1 for x in xrange(n-k, n): res *= x + 1 for x in xrange(k): res /= x + 1 return resdef Stirling(n, k): res = 0 for j in xrange(k + 1): res += (-1)**(k-j) * kamongn(k, j) * j ** n for x in xrange(k): res /= x + 1 return res>>> sum(1 for _ in neclusters([2,3,5,7,11,13], K=3)) == Stirling(len([2,3,5,7,11,13]), k=3)True
有用 !
输出:
>>> clust = neclusters([2,3,5,7,11,13], K=3)>>> [clust.next() for _ in xrange(5)][[[2, 3, 5, 7], [11], [13]], [[3, 5, 7], [2, 11], [13]], [[3, 5, 7], [11], [2, 13]], [[2, 3, 11], [5, 7], [13]], [[3, 11], [2, 5, 7], [13]]]
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)