【问题标题】:Is there a way to compute all the legit partitions of a set with Python?有没有办法用 Python 计算一个集合的所有合法分区?
【发布时间】:2019-08-08 05:52:15
【问题描述】:

Wiki 给出了这个集合的分区的definition

在数学中,集合的分区是将集合的元素分组为非空子集,这样每个元素都包含在一个子集中。

还有这个例子

集合{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 计算一个集合的所有合法分区?

我试过the partitions in sympy

from sympy.combinatorics.partitions import Partition
a = Partition([1, 2, 3])
a.members

我得到了

(1, 2, 3)

这显然是不正确的。

【问题讨论】:

    标签: python math sympy set-theory


    【解决方案1】:

    如果您使用 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]]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-22
      • 1970-01-01
      • 2021-12-15
      • 1970-01-01
      • 2015-12-17
      • 2019-06-09
      • 2020-06-23
      • 1970-01-01
      相关资源
      最近更新 更多