omega-rosetta
aien-dev/omega-rosetta
Brought by drakestapleton
omega-rosetta / tasks / ordered-partitions / oracle.py
| 1 | # Independent reference for "Ordered partitions" (Python 3, standard library only). |
| 2 | # expected.txt is this program's stdout; omc never produced it. |
| 3 | # Cross-check, WolframLanguageEvaluator: {4!/(2! 0! 2!), 4!/(1! 2! 1!)} -> {6, 12} |
| 4 | from itertools import permutations |
| 5 | from math import factorial |
| 6 | def partitions(*sizes): |
| 7 | # every arrangement of 1..n cut into consecutive runs of the given sizes, keeping one per distinct |
| 8 | # result; sorted by the blocks as lists gives the lexicographic order |
| 9 | n = sum(sizes) |
| 10 | seen = set() |
| 11 | for p in permutations(range(1, n + 1)): |
| 12 | blocks, k = [], 0 |
| 13 | for s in sizes: |
| 14 | blocks.append(tuple(sorted(p[k:k + s]))) |
| 15 | k += s |
| 16 | seen.add(tuple(blocks)) |
| 17 | return sorted(seen) |
| 18 | for sizes in ((2, 0, 2), (1, 2, 1)): |
| 19 | print("partitions(" + ", ".join(map(str, sizes)) + ")") |
| 20 | ps = partitions(*sizes) |
| 21 | total = factorial(sum(sizes)) |
| 22 | for s in sizes: |
| 23 | total //= factorial(s) |
| 24 | assert len(ps) == total |
| 25 | for blocks in ps: |
| 26 | print("(" + ", ".join("{" + ", ".join(map(str, b)) + "}" for b in blocks) + ")") |