Turn each row of counts into percentages of its own total, the classic use of keepdims, and check which column leads in each row.
What to build
A program that converts the rows of a table to percentages.
Requirements
- Print
totals (keepdims): shape (r, 1), then each row's percentages, 100 × value / row total, each to 1 decimal place, separated by spaces (nanfor every value of a row whose total is 0). - Then print
leaders: ..., the column with the largest percentage in each row (the first on ties), or-for a row whose total is 0.
Input
Line 1: r and c. Then r lines of c whole numbers, not negative.
Output
r + 2 lines.
Constraints
1 ≤ r, c ≤ 10; values ≤ 10^6.
Example
Input:
2 3
1 1 2
0 3 1
Output:
totals (keepdims): shape (2, 1)
25.0 25.0 50.0
0.0 75.0 25.0
leaders: 2 1
Why it works
Summing along axis 1 with keepdims gives an (r, 1) column that broadcasts across each row, so one division turns every row into fractions of its own total.
Examples
Example 1 · Input
2 3 1 1 2 0 3 1
Expected output
totals (keepdims): shape (2, 1) 25.0 25.0 50.0 0.0 75.0 25.0 leaders: 2 1
Example 2 · Input
2 2 0 0 5 5
Expected output
totals (keepdims): shape (2, 1) nan nan 50.0 50.0 leaders: - 0
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Each row's total is a column of shape (r, 1): divide every element of the row by its own total.
Hint 2
A row whose total is 0 gives nan for every element, as 0 / 0 does in NumPy.
Solution
Show one correct solution (try it yourself first)
r, c = map(int, input().split())
m = [[int(x) for x in input().split()] for _ in range(r)]
totals = [[sum(row)] for row in m]
print(f"totals (keepdims): shape ({len(totals)}, 1)")
leaders = []
for row, (t,) in zip(m, totals):
if t == 0:
print(" ".join("nan" for _ in row))
leaders.append("-")
else:
pct = [100 * x / t for x in row]
print(" ".join(f"{p:.1f}" for p in pct))
leaders.append(str(pct.index(max(pct))))
print("leaders:", " ".join(leaders))