v9.1.1
Menu

Array Reshaping

easyFREEReshaping & StackingNumPy ReshapingNumPy Foundations

Problem Statement

Reshape arrays into different dimensions.

Background

NumPy reshape operations:

  • arr.reshape(m, n) - reshape to m×n
  • arr.reshape(-1) - flatten
  • arr.reshape(-1, 1) - column vector
  • arr.T or arr.transpose() - transpose

Your Task

Write a function reshape_array(arr, rows, cols) that reshapes a 1D array.

Output Format

Return a dictionary with:

  • "reshaped": Array reshaped to (rows, cols) as list
  • "transposed": Transposed (cols, rows) as list
  • "flattened": Flattened back to 1D as list
  • "column_vec": As column vector (n, 1) as list

Example

Input
arr = [1,2,3,4,5,6], rows = 2, cols = 3
Output
{'reshaped': [[1, 2, 3], [4, 5, 6]], 'transposed': [[1, 4], [2, 5], [3, 6]], 'flattened': [1, 2, 3, 4, 5, 6], 'column_vec': [[1], [2], [3], [4], [5], [6]]}
Reasoning
  • Input: arr is a 1D array of n=6n = 6 numbers, 1 through 6, and rows = 2, cols = 3 ask for a 2×32 \times 3 grid. The grid size must match: 2×3=6=n2 \times 3 = 6 = n.
  • reshaped: the six values fill the grid row by row, giving [[1, 2, 3], [4, 5, 6]]. Counting from 0, entry aija_{ij} is element i⋅cols+ji \cdot \text{cols} + j of the original, so a12a_{12} is element 1⋅3+2=51 \cdot 3 + 2 = 5, the value 6.
  • transposed: ATA^T is 3×23 \times 2 with (AT)ij=aji(A^T)_{ij} = a_{ji}, so the columns of AA become rows: [[1, 4], [2, 5], [3, 6]].
  • flattened: reading the grid row by row recovers the original 1D order [1, 2, 3, 4, 5, 6].
  • column_vec: the same 6 values stacked as a 6×16 \times 1 matrix, one value per row, so each entry is a one-element list.
  • Notice that every view holds the same six numbers; only the shape changes.

Constraints

  • Array size must equal rows * cols
  • Use -1 for automatic dimension calculation

More from NumPy Foundations

solution.py

Test results

Sign in to run your code against the test cases.