0
0
NumPydata~20 mins

np.unravel_index() for multi-dim positions in NumPy - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Unravel Index Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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)
A(1, 2)
B(0, 5)
C(2, 1)
D(1, 1)
Attempts:
2 left
💡 Hint
Remember that unravel_index converts a flat index to a tuple of coordinates in the given shape.
data_output
intermediate
2: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)
AA tuple of 2 arrays, each of shape (3,)
BA tuple of 3 arrays, each of shape (2,)
CA single array of shape (3, 2)
DA list of 3 tuples, each of length 2
Attempts:
2 left
💡 Hint
Check the documentation: unravel_index returns a tuple with one array per dimension.
🔧 Debug
advanced
2: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)
AValueError: shape must be a tuple of positive integers
BIndexError: index 10 is out of bounds for array with size 9
CTypeError: index must be an integer or array of integers
DNo error, output is (3, 1)
Attempts:
2 left
💡 Hint
Check if the flat index is valid for the given shape size.
🚀 Application
advanced
2: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)
A(1, 1, 1)
B(0, 1, 1)
C(1, 0, 1)
D(0, 0, 1)
Attempts:
2 left
💡 Hint
The maximum value is 8. Find its position in the 3D array.
🧠 Conceptual
expert
2: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?
A5
B1
C4
D20
Attempts:
2 left
💡 Hint
The tuple length equals the number of dimensions in the shape.