Skip to content
DeepForgeby svx
All problems
EasyProbabilitypr-145

Hat-Check No-Match Probability

Problem

Probability that in a random permutation of n hats no one gets their own hat back:

P = sum from k = 0 to n of (-1)^k / k!

which converges to 1 / e. Return 0.0 for negative n.

Hint

This is the derangement probability, the inclusion-exclusion complement of all match patterns.

Test cases

case 1
in: [0]
expected: 1
case 2
in: [1]
expected: 0
case 3
in: [3]
expected: 0.33333333333333337
case 4
in: [10]
expected: 0.3678794642857144
Starter codePython
import math


def hat_check_no_match_probability(n):
    # Your code here
    pass

4 test cases · run your code against them in the editor