pythonmathsympyset-theory

Is there a way to compute all the legit partitions of a set with Python?


Wiki gives this definition of a partition of a set

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.

And this example

The set { 1, 2, 3 } has these five partitions

{ {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

Is there a way to compute all the legit partitions of a set with Python?

I've tried the partitions in sympy

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

and I got

(1, 2, 3)

which is apparently incorrect.


Solution

  • If you're using Sympy, then you want 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]]