Challenge - 5 Problems
Searchsorted Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Find insertion index with np.searchsorted()
What is the output of this code snippet using
np.searchsorted()?NumPy
import numpy as np arr = np.array([1, 3, 5, 7]) index = np.searchsorted(arr, 4) print(index)
Attempts:
2 left
💡 Hint
Think about where 4 fits in the sorted array [1, 3, 5, 7].
✗ Incorrect
The number 4 should be inserted between 3 and 5, which is at index 2.
❓ data_output
intermediate2:00remaining
Multiple insertion points with side='right'
Given the array and values below, what is the output of
np.searchsorted() with side='right'?NumPy
import numpy as np arr = np.array([2, 4, 4, 4, 6]) values = np.array([4, 5]) indices = np.searchsorted(arr, values, side='right') print(indices)
Attempts:
2 left
💡 Hint
With side='right', insertion happens after existing equal values.
✗ Incorrect
For value 4, insertion is after the last 4 at index 3, so index 4. For 5, it fits before 6 at index 4.
🔧 Debug
advanced2:00remaining
Identify the error in np.searchsorted usage
What error does this code raise?
NumPy
import numpy as np arr = np.array([1, 2, 3]) index = np.searchsorted(arr, [2, 3], side='middle')
Attempts:
2 left
💡 Hint
Check if 'side' parameter accepts 'middle'.
✗ Incorrect
The 'side' parameter only accepts 'left' or 'right'. Using 'middle' raises a ValueError.
🧠 Conceptual
advanced2:00remaining
Effect of sorted vs unsorted input array
What happens if you use
np.searchsorted() on an unsorted array?Attempts:
2 left
💡 Hint
Think about the assumption np.searchsorted makes about the input array.
✗ Incorrect
np.searchsorted assumes the input array is sorted. If not, the insertion indices will not be correct.
🚀 Application
expert3:00remaining
Find insertion indices for multiple values in a large array
You have a large sorted array
arr and a list of values vals. Which code snippet efficiently finds the insertion indices for all values in vals?NumPy
import numpy as np arr = np.arange(0, 1000000, 2) vals = np.array([3, 500000, 999999])
Attempts:
2 left
💡 Hint
np.searchsorted can take an array of values to search at once.
✗ Incorrect
Option C uses vectorized np.searchsorted which is efficient. Option C works but is slower due to Python loop. Option C is invalid syntax. Option C reverses arguments.