Challenge - 5 Problems
Multi-dimensional Fancy Indexing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of multi-dimensional fancy indexing with arrays
What is the output of the following code snippet using NumPy fancy indexing?
NumPy
import numpy as np arr = np.array([[10, 20, 30], [40, 50, 60], [70, 80, 90]]) rows = np.array([0, 1, 2]) cols = np.array([2, 1, 0]) result = arr[rows, cols] print(result)
Attempts:
2 left
💡 Hint
Remember that arr[rows, cols] selects elements at positions (rows[i], cols[i]) for each i.
✗ Incorrect
The code selects elements at positions (0,2), (1,1), and (2,0) from the array, which are 30, 50, and 70 respectively.
❓ data_output
intermediate2:00remaining
Shape of result from multi-dimensional fancy indexing
Given the code below, what is the shape of the resulting array 'result'?
NumPy
import numpy as np arr = np.arange(27).reshape(3,3,3) rows = np.array([0, 1]) cols = np.array([1, 2]) result = arr[rows, cols] print(result.shape)
Attempts:
2 left
💡 Hint
Check how fancy indexing with two arrays affects the shape when indexing a 3D array.
✗ Incorrect
The indexing arr[rows, cols] selects elements at (0,1) and (1,2), each is a 1D array of length 3, so the result shape is (2,3).
🔧 Debug
advanced2:00remaining
Identify the error in multi-dimensional fancy indexing
What error does the following code raise when executed?
NumPy
import numpy as np arr = np.array([[1, 2], [3, 4]]) rows = np.array([0, 1, 2]) cols = np.array([1, 0, 1]) result = arr[rows, cols] print(result)
Attempts:
2 left
💡 Hint
Check the size of the array and the indices used for rows.
✗ Incorrect
The array has shape (2,2), so index 2 for rows is out of bounds causing IndexError.
🚀 Application
advanced2:00remaining
Extract diagonal elements using multi-dimensional fancy indexing
Which option correctly extracts the diagonal elements from a 2D NumPy array 'arr' using fancy indexing?
NumPy
import numpy as np arr = np.array([[5, 6, 7], [8, 9, 10], [11, 12, 13]])
Attempts:
2 left
💡 Hint
Diagonal elements have the same row and column indices.
✗ Incorrect
Using arr[np.arange(3), np.arange(3)] selects elements where row and column indices are equal, which are the diagonal elements.
🧠 Conceptual
expert2:30remaining
Effect of broadcasting in multi-dimensional fancy indexing
Given the code below, what is the shape of 'result' and why?
NumPy
import numpy as np arr = np.arange(24).reshape(4,6) rows = np.array([[0], [1], [2]]) cols = np.array([1, 3, 5]) result = arr[rows, cols] print(result.shape)
Attempts:
2 left
💡 Hint
Consider how NumPy broadcasts arrays of shapes (3,1) and (3,) for indexing.
✗ Incorrect
rows has shape (3,1) and cols has shape (3,), which broadcast to (3,3). The result shape matches this broadcasted shape.