Basic Indexing
Problem Statement
Access elements from a NumPy array using basic indexing.
Background
NumPy supports powerful indexing:
- arr[i] - single element
- arr[i, j] - element at row i, column j (for 2D)
- Negative indices count from end
Your Task
Write a function get_elements(arr) that returns a dictionary with:
- "first": First element (as int)
- "last": Last element (as int)
- "middle": Middle element (use len//2 for index, as int)
Output Format
Return a dictionary with exactly these three keys.
Example:
[10, 20, 30, 40, 50]
{'first': 10, 'last': 50, 'middle': 30}Index 0 for first, -1 for last, len//2 for middle
Constraints:
- Use standard indexing arr[i]
- Use negative indexing for last element
- Array will have at least 1 element
More from NumPy Foundations
Background Knowledge
NumPy arrays are the fundamental data structure for numerical computing in Python, enabling efficient vectorized operations on multi-dimensional data without explicit loops. Basic indexing allows direct access to specific elements using integer positions: arr[i] retrieves the element at index i (0-based), while negative indices like arr[-1] count from the end for intuitive access to last elements. For 1D arrays like the sample [10, 20, 30, 40, 50], arr is the first element (10), arr[-1] is the last (50), and the middle uses integer division len(arr) // 2 to find index 2 (30).
This contrasts with slicing (arr[start:stop]), which returns a view (not a copy) of a contiguous subarray, sharing memory with the original—modifications affect both. Indexing, however, typically returns a copy for single elements, isolating changes. Understanding array length via len(arr) or arr.shape is key, as it determines valid indices (0 to len(arr)-1). These concepts build efficiency: NumPy avoids Python lists' overhead for large datasets.
Algorithm/Approach
The task requires extracting three scalar elements from a 1D NumPy array and packaging them into a dictionary. Use direct integer indexing:
- First: index 0
- Last: index -1 (handles any length efficiently)
- Middle: len(arr) // 2 (floor division ensures integer index, works for odd/even lengths)
Convert elements to int using astype(int) or int() since NumPy returns array scalars. Return {"first": val1, "last": val2, "middle": val3}. This is O(1) time per access, leveraging NumPy's constant-time indexing.
Step-by-Step Strategy
- Access input array: Function receives arr (1D NumPy array).
- Compute indices:
- first_idx = 0
- last_idx = -1
- middle_idx = len(arr) // 2
- Extract elements: first = int(arr[first_idx]), similarly for others.
- Build dictionary: return {"first": first, "last": last, "middle": middle}
- Test edge cases: Verify with len(arr) == 1 (all indices yield same element) or even lengths.
# Example usage (not solution)
arr = np.array([10, 20, 30, 40, 50])
print(arr, arr[-1], arr[len(arr)//2]) # 10 50 30
Common Pitfalls
- Assuming list behavior: NumPy arr returns a 0D array scalar, not Python int—always cast with int(arr) for dictionary values.
- Index errors: No bounds checking needed for 0/-1/middle (valid for len >= 1), but empty arrays crash len(arr)//2; assume non-empty per problem.
- Slicing confusion: Don't use arr[:1] (returns array); stick to single indexing for scalars.
- Data types: If arr has floats, int() truncates—problem expects int output.
- 2D assumption: Problem is 1D; arr[i,j] would fail.
Time & Space Complexity
- Time: O(1) – Three constant-time indexing operations; len(arr) is O(1).
- Space: O(1) – Dictionary stores 3 integers; no new arrays created (scalars only). No scaling with input size n=\text{len(arr)}.