NumPy: Add a row, a column or a number

Broadcasting lets a matrix combine with a row, a column or a single number. Model matrix + operand.

What to build

A program that adds broadcast operands to a matrix.

Requirements

  • Each operand is scalar V, row V1 V2 ... (shape (c,)) or col V1 V2 ... (shape (r, 1)). Print matrix + operand in NumPy's 2-D format (one width for the whole result).
  • If the operand does not fit, print ValueError: operands could not be broadcast together with shapes (r,c) S, with S (k,) for a row and (k,1) for a column. Print a blank line between results.

Input

Line 1: r and c. Then r lines of c whole numbers. Then q, then q operands.

Output

The results, separated by blank lines.

Constraints

1 ≤ r, c ≤ 6; 1 ≤ q ≤ 10; |values| ≤ 1000.

Example

Input:

2 3
1 2 3
4 5 6
2
row 10 20 30
col 100 200

Output:

[[11 22 33]
 [14 25 36]]

[[101 102 103]
 [204 205 206]]

Why it works

A row of shape (c,) lines up with the last axis and is stretched down the rows; a column of shape (r, 1) has its 1 stretched across the columns; any other length has no matching axis.

Examples

Example 1 · Input
2 3
1 2 3
4 5 6
2
row 10 20 30
col 100 200
Expected output
[[11 22 33]
 [14 25 36]]

[[101 102 103]
 [204 205 206]]
Example 2 · Input
2 2
1 2
3 4
2
row 1 2 3
scalar -1
Expected output
ValueError: operands could not be broadcast together with shapes (2,2) (3,)

[[0 1]
 [2 3]]

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

Hints

Hint 1

A row lines up with the columns; a column with the rows.

Hint 2

A row's length must equal the number of columns, and a column's the number of rows.

Solution

Show one correct solution (try it yourself first)
def fmt2(rows):
    w = max(len(str(v)) for row in rows for v in row)
    return "[" + "\n ".join("[" + " ".join(str(v).rjust(w) for v in row) + "]" for row in rows) + "]"

r, c = map(int, input().split())
m = [[int(x) for x in input().split()] for _ in range(r)]
q = int(input())
out = []
for _ in range(q):
    parts = input().split()
    kind, vals = parts[0], [int(x) for x in parts[1:]]
    if kind == "scalar":
        out.append(fmt2([[x + vals[0] for x in row] for row in m]))
    elif kind == "row":
        if len(vals) != c:
            out.append(f"ValueError: operands could not be broadcast together with shapes ({r},{c}) ({len(vals)},)")
        else:
            out.append(fmt2([[x + v for x, v in zip(row, vals)] for row in m]))
    else:
        if len(vals) != r:
            out.append(f"ValueError: operands could not be broadcast together with shapes ({r},{c}) ({len(vals)},1)")
        else:
            out.append(fmt2([[x + v for x in row] for row, v in zip(m, vals)]))
print("\n\n".join(out))

Lesson: Broadcasting →