![](/img/trans.png)
[英]Is there a way to compute all the legit partitions of a set with Python?
[英]get all the partitions of the set python with itertools
如何获取一个集合的所有分区?
例如,我有数组[1, 2, 3]
。 我需要得到[[1], [2], [3]], [[1], [2, 3]], [[2], [1,3]], [[3], [1, 2]], [[1, 2, 3]]
。
现在,我写了这段代码:
def neclusters(S, K):
for splits in itertools.combinations(range(len(S)), K):
yield np.split(S, 1 + np.array(splits))
但该代码不返回[[2],[1,3]]
。
我可以采用原始集合的所有排列并在它们上运行此代码。 但这可以变得更容易吗?
我写这篇文章很有趣:
def partition(a_list):
yield [[x] for x in a_list]
for i in range(1, len(a_list) + 1):
_l = a_list[:]
yield [_l.pop(i-1), _l]
yield a_list
my_list = [1, 2, 3]
print list(partition(my_list))
#or
for p in partition(my_list):
print p
a = [1, 2, 3]
b = list()
for l in range(len(a)+1): b.append([c for c in combinations(a, l)])
print(b)
检查一下
我在https://stackoverflow.com/a/30134039/17419428 中找到了这个问题的答案,由alexis提供(请不要在这里复制)
当前标记为解决方案的答案,这是,具有丹尼斯指出的问题。 它不会从partition(list(range(4)))
生成[[0, 1], [2, 3]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.