v9.1.1
Menu

Concatenate Arrays

easyFREEMiscNumPy ManipulationNumpy

Problem Statement

Combine multiple NumPy arrays along different axes.

Background

  • np.concatenate([arr1, arr2], axis=0): Stack vertically (default)
  • np.concatenate([arr1, arr2], axis=1): Stack horizontally
  • np.vstack(): Vertical stack
  • np.hstack(): Horizontal stack

Your Task

Write a function concat_arrays(arr1, arr2) that returns a dictionary with:

  • "vstack": Vertically stacked array as nested list
  • "hstack": Horizontally stacked array as nested list
  • "vstack_shape": Shape of vstack result as list
  • "hstack_shape": Shape of hstack result as list

Output Format

Return a dictionary with exactly these four keys.

Example

Input
arr1 = [[1, 2], [3, 4]], arr2 = [[5, 6], [7, 8]]
Output
{'vstack': [[1, 2], [3, 4], [5, 6], [7, 8]], 'hstack': [[1, 2, 5, 6], [3, 4, 7, 8]], 'vstack_shape': [4, 2], 'hstack_shape': [2, 4]}
Reasoning
  • Inputs: arr1 and arr2 are 2×22 \times 2 integer matrices: arr1 has rows (1,2)(1, 2) and (3,4)(3, 4); arr2 has rows (5,6)(5, 6) and (7,8)(7, 8).
  • Vertical stacking puts arr2 underneath arr1. Rows stay whole and are listed in order, so the result has 2+2=42 + 2 = 4 rows and still 22 columns: [[1, 2], [3, 4], [5, 6], [7, 8]], with shape [4, 2].
  • Horizontal stacking puts arr2 to the right of arr1. Row ii of the result is row ii of arr1 followed by row ii of arr2: (1,2) ∥ (5,6)=(1,2,5,6)(1, 2) \,\|\, (5, 6) = (1, 2, 5, 6) and (3,4) ∥ (7,8)=(3,4,7,8)(3, 4) \,\|\, (7, 8) = (3, 4, 7, 8). That gives 22 rows and 2+2=42 + 2 = 4 columns, shape [2, 4].
  • Output: a dictionary with the two matrices as plain nested lists and the two shapes as lists of the form [rows, columns].
  • Notice that vertical stacking needs equal column counts and horizontal stacking needs equal row counts. With 1×31 \times 3 inputs the shapes would be 2×32 \times 3 and 1×61 \times 6.

Constraints

  • Use np.vstack() and np.hstack()
  • Both arrays will have compatible shapes

More from Numpy

solution.py

Test results

Sign in to run your code against the test cases.