A coin is flipped n times and lands heads k times. Run the exact two-sided test of "the coin is fair".
What to build
A program that prints the upper tail, the two-sided p-value and the decision at the 5% level.
Requirements
- Print
upper tail U, the probability of k or more heads, to 4 decimal places. - Print
two-sided p Pto 4 decimal places: twice the smaller of P(X ≥ k) and P(X ≤ k), capped at 1. - Print
reject H0when the p-value is below 0.05, otherwisekeep H0.
Input
One line: n and k.
Output
Three lines.
Constraints
1 ≤ n ≤ 200; 0 ≤ k ≤ n.
Example
Input:
20 16
Output:
upper tail 0.0059
two-sided p 0.0118
reject H0
Why it works
Under H₀ the number of heads is binomial with p = 0.5. Results at least as extreme on either side are counted by doubling the smaller tail, which is exact because the fair binomial is symmetric.
Examples
Example 1 · Input
20 16
Expected output
upper tail 0.0059 two-sided p 0.0118 reject H0
Example 2 · Input
10 5
Expected output
upper tail 0.6230 two-sided p 1.0000 keep H0
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
P(X = k) = C(n, k) ÷ 2ⁿ for a fair coin; math.comb gives C(n, k).
Hint 2
Work out both tails, P(X ≥ k) and P(X ≤ k).
Hint 3
The two-sided p-value is twice the smaller tail, but never more than 1.
Solution
Show one correct solution (try it yourself first)
from math import comb
n, k = map(int, input().split())
upper = sum(comb(n, i) for i in range(k, n + 1)) / 2 ** n
lower = sum(comb(n, i) for i in range(0, k + 1)) / 2 ** n
p = min(1.0, 2 * min(upper, lower))
print(f"upper tail {upper:.4f}")
print(f"two-sided p {p:.4f}")
print("reject H0" if p < 0.05 else "keep H0")