分区列表的集合或所有可能的子组

时间:2015-04-21 03:57:35

标签: arrays python-3.x set partitioning

假设我有一个[1,2,3,4]列表我想生成这个集合的所有子集,它覆盖所有成员一次,结果应该有15个列表,顺序不重要,而不是t提供所有可能的子组:

>>>>[[1,2,3,4]]
[[1][2][3][4]]
[[1,2],[3][4]]
[[1,2],[3,4]]
[[1][2],[3,4]]
[[1,3],[2][4]]
[[1,3],[2,4]]
[[1][3],[2,4]]
[[1],[2,3][4]]
[[1,4],[2,3]]
[[1][2,3,4]]
[[2][1,3,4]]
[[3][1,2,4]]
[[4][1,2,3]]

这是一个设置分区问题或partitions of a set讨论here,但是回复让我感到困惑,因为它只是建议回忆一下排列,但我不知道怎么做! another response也不包括[1,3] 同时我应该为高数字解决这个问题,结果应该提供Bell Number 对不起,我对python很新,感到很困惑。谁能为我清楚?

2 个答案:

答案 0 :(得分:1)

而不是做所有排列并删除重复项,这是我最初的想法,然后你可以使用这个递归函数,我发现herehere

def partitions(set_):
    if not set_:
        yield []
        return
    for i in range(int(2**len(set_)/2)):
        parts = [set(), set()]
        for item in set_:
            parts[i&1].add(item)
            i >>= 1
        for b in partitions(parts[1]):
            yield [parts[0]]+b

l = [1, 2, 3, 4]
for p in reversed(sorted(partitions(l))):
    print(p)
print('The Bell number is', len(list(partitions(l))))

打印:

[{1, 2, 3, 4}]
[{1, 2, 4}, {3}]
[{1, 4}, {2, 3}]
[{1, 4}, {3}, {2}]
[{2, 4}, {1, 3}]
[{2, 4}, {3}, {1}]
[{1, 3, 4}, {2}]
[{2, 3, 4}, {1}]
[{3, 4}, {1, 2}]
[{3, 4}, {2}, {1}]
[{4}, {1, 2, 3}]
[{4}, {1, 3}, {2}]
[{4}, {2, 3}, {1}]
[{4}, {3}, {1, 2}]
[{4}, {3}, {2}, {1}]
The Bell number is 15

答案 1 :(得分:-1)

from itertools import combinations

s = [1, 2, 3, 4]
for combs in (combinations(s, r) for r in range(len(s)+1))  :
    for comb in combs:
        print list(comb)

<强>输出

[]
[1]
[2]
[3]
[4]
[1, 2]
[1, 3]
[1, 4]
[2, 3]
[2, 4]
[3, 4]
[1, 2, 3]
[1, 2, 4]
[1, 3, 4]
[2, 3, 4]
[1, 2, 3, 4]