Apply the broadcasting rule to pairs of shapes and print the result shape or NumPy's error.
What to build
A program that broadcasts pairs of shapes.
Requirements
- Shapes are written as sizes separated by commas, such as
2,3or3. For each pair print(r1, r2, ...)as Python prints a tuple (a 1-D shape as(n,)). - If they cannot be broadcast print
ValueError: operands could not be broadcast together with shapes A B, with each shape written with no spaces, as(2,3)and(2,).
Input
Line 1: n. Then n lines, each two shapes separated by a space.
Output
n lines.
Constraints
1 ≤ n ≤ 30; up to 5 dimensions; sizes 1 to 1000.
Example
Input:
3
2,3 3
3,1 1,4
2,3 2
Output:
(2, 3)
(3, 4)
ValueError: operands could not be broadcast together with shapes (2,3) (2,)
Why it works
Shapes line up from the right, and each pair of sizes must be equal or contain a 1 that can be stretched; anything else has no element-by-element meaning.
Examples
Example 1 · Input
3 2,3 3 3,1 1,4 2,3 2
Expected output
(2, 3) (3, 4) ValueError: operands could not be broadcast together with shapes (2,3) (2,)
Example 2 · Input
2 5 5 4,1,5 3,1
Expected output
(5,) (4, 3, 5)
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Pad the shorter shape with 1s on the left, then compare pairs.
Hint 2
NumPy's error message writes shapes without spaces, such as (2,3) and (2,).
Solution
Show one correct solution (try it yourself first)
def parse(text):
return tuple(int(x) for x in text.split(","))
def compact(shape):
return "(" + ",".join(map(str, shape)) + ("," if len(shape) == 1 else "") + ")"
n = int(input())
for _ in range(n):
a, b = (parse(t) for t in input().split())
size = max(len(a), len(b))
pa = (1,) * (size - len(a)) + a
pb = (1,) * (size - len(b)) + b
if any(x != y and x != 1 and y != 1 for x, y in zip(pa, pb)):
print(f"ValueError: operands could not be broadcast together with shapes {compact(a)} {compact(b)}")
else:
print(tuple(max(x, y) for x, y in zip(pa, pb)))