With several numeric columns, compute the correlation of every pair and point out the strongest one, the first step of looking for relationships worth studying.
What to build
A program that prints the correlation of every pair of columns and the strongest pair.
Requirements
- For every pair of columns, in header order (first with second, first with third, ..., second with third, ...), print
A-B: Rwith R to three decimals. - Then print
strongest: A-B (R), the pair with the largest absolute r; on a tie, the first such pair.
Input
Line 1: n. Line 2: the column names separated by commas. Then n rows of numbers separated by commas.
Output
One line per pair, then one more line.
Constraints
2 ≤ n ≤ 1000; 2 to 6 columns; no column has all values equal.
Example
Input:
6
hours,score,sleep
1,52,8
2,55,7
3,61,7
4,64,6
5,70,6
6,73,5
Output:
hours-score: 0.995
hours-sleep: -0.968
score-sleep: -0.940
strongest: hours-score (0.995)
Why it works
Each pair's r is computed from the same formula on two columns, and comparing absolute values treats strong negative relationships as just as interesting as strong positive ones.
Examples
6 hours,score,sleep 1,52,8 2,55,7 3,61,7 4,64,6 5,70,6 6,73,5
hours-score: 0.995 hours-sleep: -0.968 score-sleep: -0.940 strongest: hours-score (0.995)
3 a,b 1,2 2,4 3,6
a-b: 1.000 strongest: a-b (1.000)
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Store each column as a list, then loop over pairs with two nested loops, i below j.
Hint 2
Keep the pair with the largest abs(r); use a strict comparison so the first pair wins a tie.
Solution
Show one correct solution (try it yourself first)
n = int(input())
names = input().split(",")
rows = [list(map(float, input().split(","))) for _ in range(n)]
cols = [[r[i] for r in rows] for i in range(len(names))]
def corr(xs, ys):
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)
return sxy / (sxx * syy) ** 0.5
best = None
for i in range(len(names)):
for j in range(i + 1, len(names)):
r = corr(cols[i], cols[j])
print(f"{names[i]}-{names[j]}: {r:.3f}")
if best is None or abs(r) > abs(best[0]):
best = (r, f"{names[i]}-{names[j]}")
print(f"strongest: {best[1]} ({best[0]:.3f})")