A report should not just print r; it should say what it means. Compute Pearson's r and describe it in words.
What to build
A program that prints r and a description of the correlation.
Requirements
- Print
r Rto 3 decimal places. - Then print
strongwhen the absolute value of r is at least 0.7,moderatewhen at least 0.3, otherwiseweak, followed by a space andpositiveornegative. - When r is exactly 0, print
no linear relationshipinstead.
Input
The first line is n; each of the next n lines has x and y.
Output
Two lines.
Constraints
2 ≤ n ≤ 1000; the x values are not all equal, and neither are the y values.
Example
Input:
6
1 52
2 55
3 61
4 64
5 70
6 73
Output:
r 0.995
strong positive
Why it works
r is the sum of products of deviations scaled by both spreads, so it is free of units and always between −1 and 1, which makes fixed strength bands meaningful.
Examples
Example 1 · Input
6 1 52 2 55 3 61 4 64 5 70 6 73
Expected output
r 0.995 strong positive
Example 2 · Input
4 1 4 2 3 3 2 4 1
Expected output
r -1.000 strong negative
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Compute the means, then sxy, sxx and syy, then r = sxy ÷ √(sxx × syy).
Hint 2
Use the size of r for strong, moderate or weak, and its sign for the direction.
Solution
Show one correct solution (try it yourself first)
n = int(input())
pts = [tuple(map(float, input().split())) for _ in range(n)]
mx = sum(x for x, _ in pts) / n
my = sum(y for _, y in pts) / n
sxy = sum((x - mx) * (y - my) for x, y in pts)
sxx = sum((x - mx) ** 2 for x, _ in pts)
syy = sum((y - my) ** 2 for _, y in pts)
r = sxy / (sxx * syy) ** 0.5
print(f"r {r:.3f}")
if r == 0:
print("no linear relationship")
else:
size = abs(r)
word = "strong" if size >= 0.7 else "moderate" if size >= 0.3 else "weak"
print(word, "positive" if r > 0 else "negative")