Compute several reductions along a chosen axis, as m.min(axis=k) and friends do.
What to build
A program that summarises a matrix along an axis.
Requirements
- The axis is
0,1ornone. Printmin,max,mean(each value to 2 decimal places) andargmax, each asNAME: ...: for an axis, the values separated by spaces; fornone, one value, with argmax a position in the flattened matrix.
Input
Line 1: r c axis. Then r lines of c whole numbers.
Output
Four lines.
Constraints
1 ≤ r, c ≤ 10; |x| ≤ 10^5.
Example
Input:
2 3 0
1 9 3
4 5 6
Output:
min: 1 5 3
max: 4 9 6
mean: 2.50 7.00 4.50
argmax: 1 0 1
Why it works
Each reduction runs along the chosen axis and returns one value per remaining position; with no axis it runs over the flattened array, which is why argmax then gives a flat position.
Examples
Example 1 · Input
2 3 0 1 9 3 4 5 6
Expected output
min: 1 5 3 max: 4 9 6 mean: 2.50 7.00 4.50 argmax: 1 0 1
Example 2 · Input
2 3 none 1 9 3 4 5 6
Expected output
min: 1 max: 9 mean: 4.67 argmax: 1
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
For axis 0 work on the columns, for axis 1 on the rows, and for none on all the values.
Hint 2
argmax takes the first position of the largest value.
Solution
Show one correct solution (try it yourself first)
r, c, axis = input().split()
m = [[int(x) for x in input().split()] for _ in range(int(r))]
if axis == "0":
groups = [list(col) for col in zip(*m)]
elif axis == "1":
groups = m
else:
groups = [[x for row in m for x in row]]
print("min:", " ".join(str(min(g)) for g in groups))
print("max:", " ".join(str(max(g)) for g in groups))
print("mean:", " ".join(f"{sum(g) / len(g):.2f}" for g in groups))
print("argmax:", " ".join(str(g.index(max(g))) for g in groups))