Challenge - 5 Problems
Unravel Index Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of np.unravel_index with a single flat index
What is the output of the following code snippet?
NumPy
import numpy as np index = 5 shape = (3, 4) result = np.unravel_index(index, shape) print(result)
Attempts:
2 left
💡 Hint
Remember that unravel_index converts a flat index to a tuple of coordinates in the given shape.
✗ Incorrect
The flat index 5 corresponds to row 1, column 1 in a 3x4 array because 3 rows * 4 columns means indices go row-wise: 0 to 11. Index 5 is at position (1, 1).
❓ data_output
intermediate2:00remaining
Shape of output from np.unravel_index with multiple indices
Given multiple flat indices, what is the shape of the output from np.unravel_index?
NumPy
import numpy as np indices = [3, 7, 11] shape = (3, 4) result = np.unravel_index(indices, shape) print(result)
Attempts:
2 left
💡 Hint
Check the documentation: unravel_index returns a tuple with one array per dimension.
✗ Incorrect
For shape (3,4), unravel_index returns a tuple with 2 arrays (one per dimension). Each array has length equal to the number of indices (3 here).
🔧 Debug
advanced2:00remaining
Identify the error in using np.unravel_index with an invalid shape
What error does the following code raise?
NumPy
import numpy as np index = 10 shape = (3, 3) result = np.unravel_index(index, shape) print(result)
Attempts:
2 left
💡 Hint
Check if the flat index is valid for the given shape size.
✗ Incorrect
The shape (3,3) means total size 9. Index 10 is out of bounds, so numpy raises IndexError.
🚀 Application
advanced2:00remaining
Using np.unravel_index to find coordinates of max value in a 3D array
You have a 3D numpy array. How can you find the coordinates of the maximum value using np.unravel_index?
NumPy
import numpy as np arr = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]) max_index = arr.argmax() coords = np.unravel_index(max_index, arr.shape) print(coords)
Attempts:
2 left
💡 Hint
The maximum value is 8. Find its position in the 3D array.
✗ Incorrect
The max value 8 is at position (1, 1, 1) in the array. argmax returns flat index 7, unravel_index converts it to (1,1,1).
🧠 Conceptual
expert2:00remaining
Understanding np.unravel_index output for high-dimensional arrays
For a 4D array with shape (2, 3, 4, 5), what is the length of the tuple returned by np.unravel_index for a single flat index?
Attempts:
2 left
💡 Hint
The tuple length equals the number of dimensions in the shape.
✗ Incorrect
np.unravel_index returns a tuple with one element per dimension of the shape. For shape (2,3,4,5), it returns 4 arrays.