Every array is described by its shape, its number of dimensions and its size. Work them out from the data.
What to build
A program that describes an array the way NumPy's attributes would.
Requirements
- The first line is
1dor2d. For1d, one line of numbers follows; for2d, a line with the number of rows r follows, then r lines of numbers. - Print
ndim: D,shape: Sandsize: N, with the shape written as NumPy writes it:(5,)for 1-D and(2, 3)for 2-D. - If the rows of a 2-D array have different lengths, print only
ValueError: inhomogeneous shape.
Input
As described.
Output
Three lines, or the error.
Constraints
1 ≤ r ≤ 20; each row has 1 to 20 numbers.
Example
Input:
1d
4 8 15 16 23
Output:
ndim: 1
shape: (5,)
size: 5
Why it works
An array needs every row the same length, because its shape describes one regular block; the size is the product of the shape.
Examples
Example 1 · Input
1d 4 8 15 16 23
Expected output
ndim: 1 shape: (5,) size: 5
Example 2 · Input
2d 2 1 2 3 4 5 6
Expected output
ndim: 2 shape: (2, 3) size: 6
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
All rows must have the same length; otherwise NumPy cannot make a regular array.
Hint 2
A 1-D shape is written with a trailing comma: (5,).
Solution
Show one correct solution (try it yourself first)
kind = input()
if kind == "1d":
values = input().split()
print("ndim: 1")
print(f"shape: ({len(values)},)")
print(f"size: {len(values)}")
else:
r = int(input())
rows = [input().split() for _ in range(r)]
lengths = {len(row) for row in rows}
if len(lengths) != 1:
print("ValueError: inhomogeneous shape")
else:
c = len(rows[0])
print("ndim: 2")
print(f"shape: ({r}, {c})")
print(f"size: {r * c}")