Chapter 76 · Solutions
z-Tests — Worked Solutions ✅
Five challenges, each verified in code.
⚙️ Setup¶
In [1]:
import numpy as np, pandas as pd
from scipy import stats
from statsmodels.stats.proportion import proportions_ztest
BASE="https://raw.githubusercontent.com/johnfisher-ai/Statistics-Data-Science-AI-Visual-Book/main/data/"
rng=np.random.default_rng(760)
CHALLENGE 1
One-proportion z-test
In 1,000 trials you see 470 successes. Test H0: p = 0.5 (two-sided).
In [2]:
z,p=proportions_ztest(470,1000,value=0.5,prop_var=0.5)
print(f"z={z:.2f}, p={p:.4f}")
z=-1.90, p=0.0578
CHALLENGE 2
Two-proportion z-test
Group A: 90/500. Group B: 130/520. Test H0: pA = pB.
In [3]:
z,p=proportions_ztest([130,90],[520,500])
print(f"z={z:.2f}, p={p:.4f}")
z=2.72, p=0.0066
CHALLENGE 3
Large-sample z-test for a mean
A sample of 500 has mean 51 and sd 10. Test H0: mu = 50 (two-sided).
In [4]:
xbar,s,n,mu0=51,10,500,50; se=s/np.sqrt(n); z=(xbar-mu0)/se
print(f"z={z:.2f}, p={2*(1-stats.norm.cdf(abs(z))):.4f}")
z=2.24, p=0.0253
CHALLENGE 4
Check the validity condition
For n=40 and p0=0.05, is the normal (z) approximation valid? Explain with the success-failure rule.
In [5]:
n,p0=40,0.05; print(f"n*p0={n*p0}, n*(1-p0)={n*(1-p0)}")
print("n*p0 = 2 < 10 -> normal approximation NOT valid; use an exact binomial test instead")
n*p0=2.0, n*(1-p0)=38.0 n*p0 = 2 < 10 -> normal approximation NOT valid; use an exact binomial test instead
CHALLENGE 5
Real data: approval poll
Load z-tests--approval_poll.xlsx and run the one-proportion z-test of H0: p = 0.60.
In [6]:
try: poll = pd.read_excel("../../data/z-tests--approval_poll.xlsx", sheet_name="Poll")
except FileNotFoundError: poll = pd.read_excel(BASE+"z-tests--approval_poll.xlsx", sheet_name="Poll")
a=poll.approve; z,p=proportions_ztest(a.sum(), len(a), value=0.60, prop_var=0.60)
print(f"phat={a.mean():.3f}, z={z:.2f}, p={p:.4f}")
phat=0.643, z=2.49, p=0.0126
Statistics, Data Science and AI: A Visual Handbook · © 2026 John Fisher