Reduce a matrix three ways: everything, down the columns and along the rows.
What to build
A program that prints sum(), sum(axis=0) and sum(axis=1).
Requirements
- Print
sum: S, thenaxis 0: ...andaxis 1: ...in NumPy's 1-D format (brackets, numbers right-aligned to the widest, single spaces).
Input
Line 1: r and c. Then r lines of c whole numbers.
Output
Three lines.
Constraints
1 ≤ r, c ≤ 10; |x| ≤ 10^5.
Example
Input:
2 3
1 2 3
4 5 6
Output:
sum: 21
axis 0: [5 7 9]
axis 1: [ 6 15]
Why it works
axis 0 collapses the rows, leaving one total per column, and axis 1 collapses the columns, leaving one total per row.
Examples
Example 1 · Input
2 3 1 2 3 4 5 6
Expected output
sum: 21 axis 0: [5 7 9] axis 1: [ 6 15]
Example 2 · Input
1 1 -4
Expected output
sum: -4 axis 0: [-4] axis 1: [-4]
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
zip(*rows) gives the columns.
Hint 2
Print the axis results in NumPy's 1-D format.
Solution
Show one correct solution (try it yourself first)
def fmt(values):
w = max(len(str(v)) for v in values)
return "[" + " ".join(str(v).rjust(w) for v in values) + "]"
r, c = map(int, input().split())
m = [[int(x) for x in input().split()] for _ in range(r)]
print("sum:", sum(sum(row) for row in m))
print("axis 0:", fmt([sum(col) for col in zip(*m)]))
print("axis 1:", fmt([sum(row) for row in m]))