一个集合或一个列表的所有可能子组的划分
partition of a set or all possible subgroups of a list
假设我有一个 [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 which is discussed here, but the response made me confused as it just suggests recalling permutations, but I don't know how! and another response also doesn't include [1,3]
同时我应该为高数字解决这个问题,结果应该提供 Bell Number
抱歉,我是 python 的新手,因此感到困惑。谁能帮我弄清楚?
与其进行所有排列并删除重复项,这是我最初的想法,不如使用我发现的这个递归函数 here and here:
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,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 which is discussed here, but the response made me confused as it just suggests recalling permutations, but I don't know how! and another response also doesn't include [1,3] 同时我应该为高数字解决这个问题,结果应该提供 Bell Number 抱歉,我是 python 的新手,因此感到困惑。谁能帮我弄清楚?
与其进行所有排列并删除重复项,这是我最初的想法,不如使用我发现的这个递归函数 here and here:
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