img[r0:r1:s, c0:c1:s] crops an image and keeps every s-th pixel in both directions. Model it.
What to build
A program that crops and downsamples an image with slices.
Requirements
- Take rows r0 to r1 − 1 and columns c0 to c1 − 1, keeping every s-th row and column starting from r0 and c0.
- Print
shape (R, C)and then the result in NumPy's integer format.
Input
Line 1: h and w. Then h rows of w pixels. Last line: r0 r1 c0 c1 s.
Output
1 + R lines.
Constraints
1 ≤ h, w ≤ 20; 0 ≤ r0 < h; 0 ≤ c0 < w; r1 > r0 and c1 > c0 (they may be past the edge); 1 ≤ s ≤ 10.
Example
Input:
4 4
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
0 4 0 4 2
Output:
shape (2, 2)
[[ 1 3]
[ 9 11]]
Why it works
A slice with a step selects every s-th index between its start and stop and clamps a stop past the edge, so the same slice applied to the rows and then to each row gives the 2-D crop with downsampling.
Examples
4 4 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 0 4 0 4 2
shape (2, 2) [[ 1 3] [ 9 11]]
3 3 1 2 3 4 5 6 7 8 9 1 3 1 3 1
shape (2, 2) [[5 6] [8 9]]
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Python slices behave like NumPy's: img[r0:r1:s] then row[c0:c1:s].
Hint 2
Slices clamp out-of-range ends, so 1:10 on 4 columns means 1:4.
Solution
Show one correct solution (try it yourself first)
def fmt2(m):
w = max(len(str(v)) for row in m for v in row)
rows = ["[" + " ".join(str(v).rjust(w) for v in row) + "]" for row in m]
return "[" + "\n ".join(rows) + "]"
h, w = map(int, input().split())
img = [[int(x) for x in input().split()] for _ in range(h)]
r0, r1, c0, c1, s = map(int, input().split())
out = [row[c0:c1:s] for row in img[r0:r1:s]]
print(f"shape ({len(out)}, {len(out[0])})")
print(fmt2(out))