v9.1.1
Menu

2D Array Slicing

easyFREEIndexing & SlicingNumPy SlicingNumPy Foundations

Problem Statement

Extract portions of a 2D NumPy array using slicing.

Background

For 2D arrays:

  • arr[i, j] - element at row i, column j
  • arr[i, :] or arr[i] - entire row i
  • arr[:, j] - entire column j
  • arr[r1:r2, c1:c2] - submatrix

Your Task

Write a function slice_2d(arr) that returns a dictionary with:

  • "top_left": Top-left 2×2 submatrix (as list)
  • "bottom_row": Last row (as list)
  • "right_col": Rightmost column (as list)
  • "center": Center element (as int, for odd dimensions)

Example

Input
3×3 array [[1,2,3],[4,5,6],[7,8,9]]
Output
{'top_left': [[1, 2], [4, 5]], 'bottom_row': [7, 8, 9], 'right_col': [3, 6, 9], 'center': 5}
Reasoning
  • Input: arr is a 3×33 \times 3 grid of integers. Write aija_{ij} for the entry in row ii, column jj, counting from 0, so a00=1a_{00}=1 is the top-left corner and a22=9a_{22}=9 the bottom-right.
  • top_left: rows 0–1 crossed with columns 0–1 give the 2×22 \times 2 block [1245]\begin{bmatrix}1&2\\4&5\end{bmatrix}, reported as [[1, 2], [4, 5]], one inner list per row.
  • bottom_row: with R=3R=3 rows the last one is row R−1=2R-1=2: a20,a21,a22a_{20}, a_{21}, a_{22} gives [7, 8, 9].
  • right_col: the last column is column 2, read top to bottom: a02,a12,a22a_{02}, a_{12}, a_{22} gives [3, 6, 9]. Notice it is a flat list of three numbers, not three one-element rows.
  • center: the middle index is ⌊3/2⌋=1\lfloor 3/2 \rfloor = 1 in both directions, so the centre is the single number a11=5a_{11} = 5.
  • Notice that "last" and "centre" depend on the size while the top-left block never does: for the 5×55 \times 5 test the bottom row is row 4 and the centre is a22=13a_{22} = 13, yet top_left is still just the first two rows and columns.

Constraints

  • Array will be at least 3×3
  • For center, use shape//2 for both dimensions

More from NumPy Foundations

solution.py

Test results

Sign in to run your code against the test cases.