Finding all partitions of a set
Starting with myList = {a, b, c, d, e, f}
, here are a few solutions, in increasing order of generality:
1.
Internal`PartitionRagged[myList, #] & /@ IntegerPartitions[Length[myList]]
{{{a, b, c, d, e, f}}, {{a, b, c, d, e}, {f}}, {{a, b, c, d}, {e, f}},
{{a, b, c, d}, {e}, {f}}, {{a, b, c}, {d, e, f}}, {{a, b, c}, {d, e}, {f}},
{{a, b, c}, {d}, {e}, {f}}, {{a, b}, {c, d}, {e, f}},
{{a, b}, {c, d}, {e}, {f}}, {{a, b}, {c}, {d}, {e}, {f}},
{{a}, {b}, {c}, {d}, {e}, {f}}}
2.
Internal`PartitionRagged[myList, #] & /@
Apply[Join, Permutations /@ IntegerPartitions[Length[myList]]]
{{{a, b, c, d, e, f}}, {{a, b, c, d, e}, {f}}, {{a}, {b, c, d, e, f}},
{{a, b, c, d}, {e, f}}, {{a, b}, {c, d, e, f}}, {{a, b, c, d}, {e}, {f}},
{{a}, {b, c, d, e}, {f}}, {{a}, {b}, {c, d, e, f}}, {{a, b, c}, {d, e, f}},
{{a, b, c}, {d, e}, {f}}, {{a, b, c}, {d}, {e, f}}, {{a, b}, {c, d, e}, {f}},
{{a, b}, {c}, {d, e, f}}, {{a}, {b, c, d}, {e, f}}, {{a}, {b, c}, {d, e, f}},
{{a, b, c}, {d}, {e}, {f}}, {{a}, {b, c, d}, {e}, {f}}, {{a}, {b}, {c, d, e}, {f}},
{{a}, {b}, {c}, {d, e, f}}, {{a, b}, {c, d}, {e, f}},
{{a, b}, {c, d}, {e}, {f}}, {{a, b}, {c}, {d, e}, {f}},
{{a, b}, {c}, {d}, {e, f}}, {{a}, {b, c}, {d, e}, {f}},
{{a}, {b, c}, {d}, {e, f}}, {{a}, {b}, {c, d}, {e, f}},
{{a, b}, {c}, {d}, {e}, {f}}, {{a}, {b, c}, {d}, {e}, {f}},
{{a}, {b}, {c, d}, {e}, {f}}, {{a}, {b}, {c}, {d, e}, {f}},
{{a}, {b}, {c}, {d}, {e, f}}, {{a}, {b}, {c}, {d}, {e}, {f}}}
3.
Needs["Combinatorica`"];
Short[SetPartitions[myList], 5]
{{{a, b, c, d, e, f}}, {{a}, {b, c, d, e, f}}, {{a, b}, {c, d, e, f}},
{{a, c, d, e, f}, {b}}, {{a, b, c}, {d, e, f}}, {{a, d, e, f}, {b, c}},
{{a, b, d, e, f}, {c}}, {{a, c}, {b, d, e, f}}, {{a, b, c, d}, {e, f}},
{{a, e, f}, {b, c, d}}, <<184>>, {{a}, {b, d}, {c}, {e}, {f}},
{{a}, {b, e}, {c}, {d}, {f}}, {{a}, {b, f}, {c}, {d}, {e}},
{{a, b}, {c}, {d}, {e}, {f}}, {{a, c}, {b}, {d}, {e}, {f}},
{{a, d}, {b}, {c}, {e}, {f}}, {{a, e}, {b}, {c}, {d}, {f}},
{{a, f}, {b}, {c}, {d}, {e}}, {{a}, {b}, {c}, {d}, {e}, {f}}}
The output of SetPartitions[]
was rather long, so I had to use Short[]
. Execute SetPartitions[myList]
if you want to see everything.
Based on BellList
from Robert M. Dickau:
partition[{x_}] := {{{x}}}
partition[{r__, x_}] :=
Join @@ (ReplaceList[#,
{{b___, {S__}, a___} :> {b, {S, x}, a},
{S__} :> {S, {x}}}
] & /@ partition[{r}])
This is faster than SetPartitions
on shorter sets:
Needs["Combinatorica`"];
myList = {a, b, c, d, e, f};
partition[myList] ~Do~ {500} // Timing // First
SetPartitions[myList] ~Do~ {500} // Timing // First
0.405
0.843
Related:
- Subsets of a list