Data science: Pearson's correlation

Two columns of the same rows: compute how closely they follow a straight line.

What to build

A program that prints Pearson's correlation of two columns.

Requirements

  • Print r = R with R to two decimals.

Input

Two lines with the same number of values: the x column, then the y column.

Output

One line.

Constraints

2 to 1000 values per line; neither column has all values equal.

Example

Input:

1 2 3 4 5
2 4 6 8 10

Output:

r = 1.00

Why it works

Dividing the sum of products of deviations by both spreads removes the units, so r is always between −1 and 1 whatever the columns measure.

Examples

Example 1 · Input
1 2 3 4 5
2 4 6 8 10
Expected output
r = 1.00
Example 2 · Input
1 2 3
3 2 1
Expected output
r = -1.00

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

Compute the two means first.

Hint 2

r = Σ(x − x̄)(y − ȳ) ÷ √(Σ(x − x̄)² × Σ(y − ȳ)²).

Solution

Show one correct solution (try it yourself first)
xs = list(map(float, input().split()))
ys = list(map(float, input().split()))
mx, my = sum(xs) / len(xs), sum(ys) / len(ys)
sxy = sum((x - mx) * (y - my) for x, y in zip(xs, ys))
sxx = sum((x - mx) ** 2 for x in xs)
syy = sum((y - my) ** 2 for y in ys)
print(f"r = {sxy / (sxx * syy) ** 0.5:.2f}")

Lesson: Relationships between variables →