Loading the problem
Before you start
Compute the probability of exactly k successes in n independent trials,
each succeeding with probability p.
P(k) = C(n, k) * p^k * (1 - p)^(n - k)
where C(n, k) = n! / (k! * (n - k)!) counts the orderings.
Return 0.0 when k is negative or larger than n.
Use math.comb for the binomial coefficient. Computing factorials separately
overflows fast, and for large n the intermediate values are enormous even
when the answer is tiny.
def binomial_probability(n, k, p):
Input
binomial_probability(n=5, k=2, p=0.5)
Output
0.3125
Reasoning
C(5, 2) = 10 orderings, each with probability 0.5^2 * 0.5^3 = 1/32. So the answer is 10 / 32 = 0.3125.
0.0 when k < 0 or k > n.math.comb for the coefficient.Check runs the visible cases against a fresh kernel. Submit runs the hidden ones too.
⇧↵run cell