Hardy-Weinberg Equilibrium Test

Intermediate Computational Biology Population Genetics Chi-Square Statistics Allele Frequency
Significance:

The Hardy-Weinberg principle states that in a large, randomly mating population with
no selection, migration or mutation, genotype frequencies stay constant across generations. Testing a
locus against it is the standard quality-control filter in every genome-wide association study — a
marker that deviates sharply is usually a genotyping artefact rather than a real biological signal, and
GWAS pipelines routinely discard variants failing this test.

Statement

You are given the observed counts of three genotypes at a biallelic locus: homozygous
for the major allele (AA), heterozygous (Aa), and homozygous for the minor allele (aa).

  1. Compute the major allele frequency p and minor allele frequency q.
  2. Compute the expected counts under Hardy-Weinberg equilibrium: p^2 * N, 2pq * N, q^2 * N.
  3. Compute the chi-square statistic: the sum over the three genotypes of
    (observed - expected)^2 / expected.

Print p on the first line to four decimal places, and the chi-square statistic on the second line to
four decimal places. Skip any genotype whose expected count is zero when summing the statistic.

Input — read from standard input
Variable Type Description
n_AA
line 1
int Observed count of homozygous major genotype
0 <= n_AA <= 100000
n_Aa
line 1
int Observed count of heterozygous genotype
0 <= n_Aa <= 100000
n_aa
line 1
int Observed count of homozygous minor genotype
0 <= n_aa <= 100000

These variables are already read for you in the starter code on the right.

Output

str major allele frequency p to four decimals on line 1, chi-square statistic to four decimals on line 2

Sample Cases
Sample 1
Input
25 50 25
Expected Output
0.5000
0.0000
Perfect Hardy-Weinberg proportions, so the chi-square statistic is zero.
Sample 2
Input
100 0 100
Expected Output
0.5000
200.0000
No heterozygotes at all — a strong deviation from equilibrium.

Submit also runs your code against 5 hidden test cases. Hidden inputs are never shown — if one fails you'll get its number and a description of the mismatch, not the data.

Constraints
  • The three counts are given on one line, separated by single spaces
  • Total sample size N = n_AA + n_Aa + n_aa >= 1
  • p = (2*n_AA + n_Aa) / (2*N) and q = 1 - p
  • Genotypes with an expected count of exactly zero are excluded from the chi-square sum
Further Reading
  • Each individual carries two alleles, so the denominator when computing p is 2N, not N.
  • Compute expected counts as floats — rounding them to integers first will change the statistic.
  • Guard the division: when p or q is 0, one expected count is 0 and that term must be skipped.

My Notes
Log in to save personal notes.
Console output will appear here when you click Run Code or Submit...
Expected: n_AA (int), n_Aa (int), n_aa (int)
Next Problem
CPM Normalisation of a Count Matrix