NumPy: Broadcast many shapes and find what stretches

np.broadcast_shapes takes any number of shapes. Model it, and report which axes of each input are stretched.

What to build

A program that broadcasts several shapes together.

Requirements

  • Print result: (r1, r2, ...) as Python prints a tuple, then for each input SHAPE: stretched along axes A, B listing the result's axis numbers (from 0) where that input, padded with 1s on the left, has size 1 and the result is larger, or SHAPE: not stretched. SHAPE is the input as written.
  • If the shapes cannot all be broadcast together, print only ValueError: shape mismatch on axis K, where K is the first result axis (from 0) whose sizes conflict.

Input

Line 1: n. Then n shapes, sizes separated by commas.

Output

As described.

Constraints

2 ≤ n ≤ 5; up to 5 dimensions; sizes 1 to 100.

Example

Input:

2
3,1
1,4

Output:

result: (3, 4)
3,1: stretched along axes 1
1,4: stretched along axes 0

Why it works

Every input is padded on the left with 1s to the same length; along each axis all sizes must be 1 or one shared value, and an input is stretched exactly where it has a 1 and the result does not.

Examples

Example 1 · Input
2
3,1
1,4
Expected output
result: (3, 4)
3,1: stretched along axes 1
1,4: stretched along axes 0
Example 2 · Input
3
2,3
3
2,1
Expected output
result: (2, 3)
2,3: not stretched
3: stretched along axes 0
2,1: stretched along axes 1

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

Pad every shape on the left to the longest length, then check each axis across all shapes.

Hint 2

An input stretches along an axis where its size is 1 and the result's size is bigger.

Solution

Show one correct solution (try it yourself first)
n = int(input())
texts = [input().strip() for _ in range(n)]
shapes = [tuple(int(x) for x in t.split(",")) for t in texts]
size = max(len(s) for s in shapes)
padded = [(1,) * (size - len(s)) + s for s in shapes]
result = []
for axis in range(size):
    sizes = {p[axis] for p in padded} - {1}
    if len(sizes) > 1:
        print(f"ValueError: shape mismatch on axis {axis}")
        break
    result.append(sizes.pop() if sizes else 1)
else:
    print("result:", tuple(result))
    for text, p in zip(texts, padded):
        axes = [str(i) for i in range(size) if p[i] == 1 and result[i] > 1]
        print(f"{text}: stretched along axes {', '.join(axes)}" if axes else f"{text}: not stretched")

Lesson: Broadcasting →