Many models need every feature on the same scale. Compute (X − X.mean(axis=0)) / X.std(axis=0) for a small data matrix.
What to build
A program that standardises every column of a matrix.
Requirements
- Print
meansfollowed by the column means, each to two decimals, separated by spaces. - Then print each row of the standardised matrix, values to two decimals separated by spaces.
- Use the population standard deviation. Where a column's standard deviation is 0, print 0.00 for its values (NumPy would give nan with a warning).
Input
Line 1: r and c. Then r lines of c numbers.
Output
1 + r lines.
Constraints
2 ≤ r ≤ 100; 1 ≤ c ≤ 10.
Example
Input:
3 2
1 10
2 20
3 30
Output:
means 2.00 20.00
-1.22 -1.22
0.00 0.00
1.22 1.22
Why it works
Subtracting the column mean centres each feature at 0 and dividing by its standard deviation sets its spread to 1, which is what broadcasting the two axis-0 reductions across the rows does.
Examples
Example 1 · Input
3 2 1 10 2 20 3 30
Expected output
means 2.00 20.00 -1.22 -1.22 0.00 0.00 1.22 1.22
Example 2 · Input
2 1 0 4
Expected output
means 2.00 -1.00 1.00
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Work column by column: zip(*rows) gives the columns.
Hint 2
Use the population standard deviation (ddof=0), NumPy's default.
Hint 3
Rebuild the rows from the standardised columns with zip again.
Solution
Show one correct solution (try it yourself first)
r, c = map(int, input().split())
rows = [[float(x) for x in input().split()] for _ in range(r)]
cols = [list(col) for col in zip(*rows)]
means = [sum(col) / r for col in cols]
stds = [(sum((x - m) ** 2 for x in col) / r) ** 0.5 for col, m in zip(cols, means)]
print("means", " ".join(f"{m:.2f}" for m in means))
for row in rows:
print(" ".join(f"{(x - m) / s:.2f}" if s else "0.00" for x, m, s in zip(row, means, stds)))