At a party n guests leave their hats, and the hats are given back at random. How many of the n! ways return no guest his own hat? Inclusion-exclusion counts these derangements: all permutations, minus those fixing at least one item, adjusted for overlaps.
What to build
A program that counts the derangements of n items and the permutations of n items.
Requirements
- Read n.
- Print
derangements:and the number of permutations of n items in which no item stays in its own position. - Print
permutations:and n!.
Input
One whole number n.
Output
Two lines.
Constraints
0 ≤ n ≤ 20.
Example
Input:
3
Output:
derangements: 2
permutations: 6
Why it works
Let A_i be the permutations that fix item i. By inclusion-exclusion the permutations fixing at least one item number C(n,1)(n−1)! − C(n,2)(n−2)! + ..., and subtracting that from n! gives D(n) = Σ (−1)^k n!/k!. The ratio D(n)/n! gets close to 1/e, so about 37 percent of random shuffles leave no card in place.
Examples
3
derangements: 2 permutations: 6
4
derangements: 9 permutations: 24
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
A derangement is a permutation in which no item stays in its own place.
Hint 2
Inclusion-exclusion: D(n) = the sum over k from 0 to n of (-1)**k * n! / k!.
Hint 3
Use integer division: n! // k! is exact, because k! divides n!.
Solution
Show one correct solution (try it yourself first)
n = int(input())
def fact(k):
r = 1
for i in range(2, k + 1):
r *= i
return r
d = sum((-1) ** k * (fact(n) // fact(k)) for k in range(n + 1))
print("derangements:", d)
print("permutations:", fact(n))
▶ Open this solution in the compiler, then press Visualize to watch it run step by step