有没有办法用 Python 计算一个集合的所有合法分区?
Is there a way to compute all the legit partitions of a set with Python?
Wiki给出了这个definition的一个分区集
In mathematics, a partition of a set is a grouping of the set's elements into non-empty subsets, in such a way that every element is included in exactly one subset.
还有这个例子
集合{1,2,3}有这五个分区
{ {1}, {2}, {3} }, sometimes written 1|2|3.
{ {1, 2}, {3} }, or 12|3.
{ {1, 3}, {2} }, or 13|2.
{ {1}, {2, 3} }, or 1|23.
{ {1, 2, 3} }, or 123
有没有办法用 Python 计算集合的所有合法分区?
from sympy.combinatorics.partitions import Partition
a = Partition([1, 2, 3])
a.members
我得到了
(1, 2, 3)
这显然是不正确的。
如果您使用的是 Sympy,那么您需要 sympy.utilities.iterables.multiset_partitions:
>>> from sympy.utilities.iterables import multiset_partitions
>>> for p in multiset_partitions([1, 2, 3]):
... print(p)
...
[[1, 2, 3]]
[[1, 2], [3]]
[[1, 3], [2]]
[[1], [2, 3]]
[[1], [2], [3]]
Wiki给出了这个definition的一个分区集
In mathematics, a partition of a set is a grouping of the set's elements into non-empty subsets, in such a way that every element is included in exactly one subset.
还有这个例子
集合{1,2,3}有这五个分区
{ {1}, {2}, {3} }, sometimes written 1|2|3.
{ {1, 2}, {3} }, or 12|3.
{ {1, 3}, {2} }, or 13|2.
{ {1}, {2, 3} }, or 1|23.
{ {1, 2, 3} }, or 123
有没有办法用 Python 计算集合的所有合法分区?
from sympy.combinatorics.partitions import Partition
a = Partition([1, 2, 3])
a.members
我得到了
(1, 2, 3)
这显然是不正确的。
如果您使用的是 Sympy,那么您需要 sympy.utilities.iterables.multiset_partitions:
>>> from sympy.utilities.iterables import multiset_partitions
>>> for p in multiset_partitions([1, 2, 3]):
... print(p)
...
[[1, 2, 3]]
[[1, 2], [3]]
[[1, 3], [2]]
[[1], [2, 3]]
[[1], [2], [3]]