Before NumPy reshapes, it checks that the new shape fits and fills in a -1. Do the same check.
What to build
A program that resolves a requested shape for an array of a given size.
Requirements
- If the shape contains more than one -1, print
error: only one -1 allowed. - If the shape fits, print the final shape as a Python tuple, such as
(2, 3)or(5,). - Otherwise print
error: cannot reshape size N into S, where S is the requested shape written as a tuple.
Input
Line 1: the array size N. Line 2: the requested dimensions, separated by spaces.
Output
One line.
Constraints
1 ≤ N ≤ 10⁶; 1 to 4 dimensions; each is −1 or between 1 and 10⁶.
Example
Input:
6
2 3
Output:
(2, 3)
Why it works
reshape never adds or drops elements, so the product of the dimensions must equal the size; a -1 is found by dividing the size by the product of the known dimensions, which must divide it exactly.
Examples
6 2 3
(2, 3)
12 -1 4
(3, 4)
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Multiply the known dimensions; the -1 is the size divided by that product.
Hint 2
Check that the division leaves no remainder.
Hint 3
A one-dimensional shape prints with a trailing comma, like (5,).
Solution
Show one correct solution (try it yourself first)
def tup(dims):
inner = ", ".join(map(str, dims))
return "(" + inner + ("," if len(dims) == 1 else "") + ")"
n = int(input())
dims = [int(x) for x in input().split()]
if dims.count(-1) > 1:
print("error: only one -1 allowed")
else:
known = 1
for d in dims:
if d != -1:
known *= d
if -1 in dims and n % known == 0:
print(tup([n // known if d == -1 else d for d in dims]))
elif -1 not in dims and known == n:
print(tup(dims))
else:
print(f"error: cannot reshape size {n} into {tup(dims)}")