0
0
NumPydata~20 mins

np.searchsorted() for insertion points in NumPy - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Searchsorted Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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)
A0
B2
C1
D3
Attempts:
2 left
💡 Hint
Think about where 4 fits in the sorted array [1, 3, 5, 7].
data_output
intermediate
2: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)
A[4 4]
B[3 4]
C[4 3]
D[3 3]
Attempts:
2 left
💡 Hint
With side='right', insertion happens after existing equal values.
🔧 Debug
advanced
2: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')
AValueError
BTypeError
CSyntaxError
DNo error, returns array
Attempts:
2 left
💡 Hint
Check if 'side' parameter accepts 'middle'.
🧠 Conceptual
advanced
2:00remaining
Effect of sorted vs unsorted input array
What happens if you use np.searchsorted() on an unsorted array?
AIt returns the indices of the closest values regardless of order.
BIt automatically sorts the array before searching, so results are correct.
CIt raises a RuntimeError because the array is not sorted.
DIt returns insertion indices assuming the array is sorted, leading to incorrect results.
Attempts:
2 left
💡 Hint
Think about the assumption np.searchsorted makes about the input array.
🚀 Application
expert
3: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])
Aindices = [np.searchsorted(arr, v) for v in vals]
Bindices = np.array([arr.searchsorted(v) for v in vals])
Cindices = np.searchsorted(arr, vals)
Dindices = np.searchsorted(vals, arr)
Attempts:
2 left
💡 Hint
np.searchsorted can take an array of values to search at once.