2D Array Indexing
Problem Statement
Access elements and slices from a 2D NumPy array.
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
Your Task
Write a function index_2d(arr) that returns a dictionary with:
- "element_0_0": Element at position (0, 0)
- "element_1_2": Element at position (1, 2)
- "row_0": First row as list
- "col_1": Second column as list
Output Format
Return a dictionary with exactly these four keys.
Example:
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
{'element_0_0': 1, 'element_1_2': 6, 'row_0': [1, 2, 3], 'col_1': [2, 5, 8]}Use [row, col] for elements, [row, :] for rows, [:, col] for columns
Constraints:
- Input will be a 2D array with at least 2 rows and 3 columns
- Use arr[i, j] syntax for elements
1. Background Knowledge
NumPy arrays are the foundational data structure for numerical computing in Python, enabling array programmingβa paradigm that treats entire arrays as single objects for efficient operations. A 2D NumPy array (ndarray with ndim=2) represents a matrix with shape (rows, cols), where indexing follows zero-based row-major order: arr[i, j] accesses element at row i, column j.
Key indexing syntax (directly from problem background):
- arr[i, j] β Single element (requires exact i, j coordinates)
- arr[i] or arr[i, :] β Entire row i (colon : means "all")
- arr[:, j] β Entire column j
NumPy slicing returns views (not copies) by default, enabling zero-copy access for efficiency (O(1) time). Arrays must have compatible shapes per constraints (β₯2 rows, β₯3 columns).
Prerequisites:
- Import: import numpy as np
- Array creation: np.array([[1,2,3], [4,5,6]])
- Dictionary output: Python dict with exact keys as strings
2. Algorithm Approach
This is a direct indexing problem requiring four constant-time lookups:
- Point queries: arr[0,0], arr[1,2] β O(1) each
- Row slice: arr[0, :] β O(1) view, convert to list()
- Column slice: arr[:, 1] β O(1) view, convert to list()
No iteration or search neededβpure array programming with vectorized indexing. Total algorithm: dictionary construction from four O(1) operations.
Input: arr β β^(mΓn), mβ₯2, nβ₯3
Output: {str: scalar|list} mapping
Time: O(1) dominant (slicing) + O(n) for list conversion
3. Step-by-Step Strategy
def index_2d(arr):
result = {} # 1. Initialize empty dict
# 2. Element access: exact [row, col] syntax (O(1))
result["element_0_0"] = arr[0, 0] # (0,0) β top-left
result["element_1_2"] = arr[1, 2] # (1,2) β row1, col2
Continue the full explanation
You're reading the free preview. Unlock the complete walkthrough, the code editor, test runner and reference solution with Premium.
Editor locked
The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.