A placement cell recorded, for n students, the hours spent on aptitude practice (x) and the aptitude test score (y). Compute the Pearson correlation coefficient r between x and y, rounded to 4 decimals.
If either list has zero variance (all values equal), r is undefined: print undefined.
Use only the standard library.
Constraints
- 2 ≤ n ≤ 5000
- −10^4 ≤ each value ≤ 10^4
Input and output
- Input
- First line: n. Second line: n integers x. Third line: n integers y.
- Output
- One line: r with 4 decimals, or `undefined`.
Examples
Input 1
5
1 2 3 4 5
2 4 5 4 5Output
0.7746Σx = 15, Σy = 20, Σxy = 66, Σx² = 55, Σy² = 86. r = (330 − 300)/√(50 × 30) = 30/38.73 ≈ 0.7746.
Input 2
3
1 2 3
7 7 7Output
undefinedy is constant, so r is undefined.
Show hints
- r = cov(x, y) / (σx · σy).
- With integer sums: r = (nΣxy − ΣxΣy) / √((nΣx² − (Σx)²)(nΣy² − (Σy)²)). The numerator and both brackets are exact integers in Python.
Show the explanation
Formula. With Sx = Σx, Sy = Σy, Sxy = Σxy, Sxx = Σx² and Syy = Σy²:
r = (n·Sxy − Sx·Sy) / √((n·Sxx − Sx²)(n·Syy − Sy²))
Every term is an exact integer in Python, because Python ints never overflow. Only the final division and square root use floating point. This avoids rounding drift. It also gives exactly 0.0000 (not -0.0000) when the numerator is 0.
If either bracket in the denominator is 0, that variable is constant and r is undefined. Print undefined rather than dividing by zero.
Interpreting r
- r is always between −1 and +1. Its sign gives the direction of the relationship and its size gives how close the points are to a straight line.
- r measures linear association only. y = x² over a range symmetric around 0 gives r ≈ 0 even though y depends completely on x. Plot the data.
- A single outlier can create or hide a strong r. Spearman's rank correlation (Pearson applied to the ranks) is more robust.
- Correlation is not causation. A third factor, such as general motivation, can drive both practice hours and scores.
In libraries: statistics.correlation(x, y) (Python 3.10+), numpy.corrcoef or df.corr().
Original UniCircle question. Last reviewed 22 Oct 2026.
