np.flip(img, axis) mirrors an image. Model all three cases.
What to build
A program that flips a small greyscale image.
Requirements
- For
0, reverse the rows (np.flipud); for1, reverse each row (np.fliplr); forboth, do both. - Print the result in NumPy's integer format (
[[...]], numbers right-aligned to the widest, single spaces).
Input
Line 1: 0, 1 or both. Line 2: h and w. Then h rows of w whole numbers.
Output
h lines.
Constraints
1 ≤ h, w ≤ 20; 0 ≤ pixel ≤ 255.
Example
Input:
1
2 3
1 2 3
4 5 6
Output:
[[3 2 1]
[6 5 4]]
Why it works
Reversing the outer list flips top to bottom and reversing each inner list flips left to right, which is what the slices img[::-1] and img[:, ::-1] do.
Examples
Example 1 · Input
1 2 3 1 2 3 4 5 6
Expected output
[[3 2 1] [6 5 4]]
Example 2 · Input
0 2 2 1 2 3 4
Expected output
[[3 4] [1 2]]
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Axis 0 reverses the order of the rows; axis 1 reverses each row.
Hint 2
Use the same printing helper as in earlier matrix exercises.
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) + "]"
axis = input()
h, w = map(int, input().split())
img = [[int(x) for x in input().split()] for _ in range(h)]
if axis in ("0", "both"):
img = img[::-1]
if axis in ("1", "both"):
img = [row[::-1] for row in img]
print(fmt2(img))