omega-rosetta
aien-dev/omega-rosetta
Brought by drakestapleton
omega-rosetta / tasks / permutations-derangements / oracle.py
| 1 | # Independent reference for "Permutations/Derangements" (Python 3, standard library only). |
| 2 | # expected.txt is this program's stdout; omc never produced it. |
| 3 | # Cross-check, WolframLanguageEvaluator: Table[Subfactorial[n], {n, 0, 9}] and Subfactorial[20] |
| 4 | # -> {1, 0, 1, 2, 9, 44, 265, 1854, 14833, 133496} and 895014631192902121 |
| 5 | from itertools import permutations |
| 6 | from math import factorial |
| 7 | def subfact(n): |
| 8 | # inclusion-exclusion: sum over k of (-1)^k n!/k! |
| 9 | return sum((-1) ** k * factorial(n) // factorial(k) for k in range(n + 1)) |
| 10 | print("derangements of 0 1 2 3:") |
| 11 | for p in permutations(range(4)): |
| 12 | if all(p[i] != i for i in range(4)): |
| 13 | print(*p) |
| 14 | print("n counted !n") |
| 15 | for n in range(10): |
| 16 | counted = sum(1 for p in permutations(range(n)) if all(p[i] != i for i in range(n))) |
| 17 | print(f"{n} {counted:8} {subfact(n)}") |
| 18 | print("!20 =", subfact(20)) |