Model NumPy's filled-array creators, including eye with a shifted diagonal, and print them the way NumPy does.
What to build
A program that builds arrays from commands and prints them.
Requirements
- Commands:
zeros R C,ones R C,full R C Vandeye N K(an N by N matrix with ones on the diagonal shifted by K: column - row = K). - Print each array as NumPy prints a 2-D integer array: every number right-aligned to the widest in that array, the first row starting
[[, the others[, the last ending]]. Print a blank line between arrays.
Input
Line 1: n. Then n commands.
Output
The arrays, separated by blank lines.
Constraints
1 ≤ n ≤ 10; 1 ≤ R, C, N ≤ 8; |K| < N; |V| ≤ 1000.
Example
Input:
2
zeros 2 3
eye 3 0
Output:
[[0 0 0]
[0 0 0]]
[[1 0 0]
[0 1 0]
[0 0 1]]
Why it works
Every creator is a grid with a rule for each position, and the printing rule is the same for all of them, so one formatter serves every command.
Examples
Example 1 · Input
2 zeros 2 3 eye 3 0
Expected output
[[0 0 0] [0 0 0]] [[1 0 0] [0 1 0] [0 0 1]]
Example 2 · Input
1 eye 3 1
Expected output
[[0 1 0] [0 0 1] [0 0 0]]
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Build each array as a list of rows, then print it with one width for the whole array.
Hint 2
In eye with an offset k, the ones sit where column - row = k.
Solution
Show one correct solution (try it yourself first)
def show(rows):
width = max(len(str(v)) for row in rows for v in row)
lines = ["[" + " ".join(str(v).rjust(width) for v in row) + "]" for row in rows]
return "[" + "\n ".join(lines) + "]"
n = int(input())
out = []
for _ in range(n):
parts = input().split()
name, nums = parts[0], [int(x) for x in parts[1:]]
if name == "eye":
size, k = nums
rows = [[1 if c - r == k else 0 for c in range(size)] for r in range(size)]
else:
value = {"zeros": 0, "ones": 1}.get(name, nums[2] if len(nums) > 2 else 0)
rows = [[value] * nums[1] for _ in range(nums[0])]
out.append(show(rows))
print("\n\n".join(out))