NumPy: Concatenate two matrices

np.concatenate joins arrays along an axis, but only when every other dimension matches. Model it, with the check.

What to build

A program that concatenates two integer matrices along axis 0 or axis 1.

Requirements

  • If the matrices cannot be joined, print error: sizes differ along axis K, where K is the other axis (1 when joining along 0, 0 when joining along 1).
  • Otherwise print shape (R, C) and then the result in NumPy's format, as in the transpose exercise.

Input

Line 1: the axis, 0 or 1. Then matrix A: a line r c and r rows. Then matrix B in the same form.

Output

One line, or 1 + R lines.

Constraints

1 ≤ r, c ≤ 10 for each matrix; |x| ≤ 10⁵.

Example

Input:

0
2 2
1 2
3 4
1 2
5 6

Output:

shape (3, 2)
[[1 2]
 [3 4]
 [5 6]]

Why it works

Joining along one axis lines the arrays up on the other, so that other dimension must be identical, which is the condition NumPy checks before it builds the result.

Examples

Example 1 · Input
0
2 2
1 2
3 4
1 2
5 6
Expected output
shape (3, 2)
[[1 2]
 [3 4]
 [5 6]]
Example 2 · Input
1
2 2
1 2
3 4
2 1
9
10
Expected output
shape (2, 3)
[[ 1  2  9]
 [ 3  4 10]]

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

Hints

Hint 1

Along axis 0 the column counts must match; along axis 1 the row counts must match.

Hint 2

Along axis 1, join row i of A with row i of B.

Solution

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


def read():
    r, c = map(int, input().split())
    return [[int(x) for x in input().split()] for _ in range(r)]


axis = int(input())
a, b = read(), read()
if axis == 0 and len(a[0]) != len(b[0]):
    print("error: sizes differ along axis 1")
elif axis == 1 and len(a) != len(b):
    print("error: sizes differ along axis 0")
else:
    out = a + b if axis == 0 else [ra + rb for ra, rb in zip(a, b)]
    print(f"shape ({len(out)}, {len(out[0])})")
    print(fmt2(out))

Lesson: Reshaping and stacking →