0
0
NumPydata~10 mins

np.searchsorted() for insertion points in NumPy - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to find the insertion index for value 5 in a sorted array.

NumPy
import numpy as np
arr = np.array([1, 3, 7, 9])
index = np.searchsorted(arr, [1])
print(index)
Drag options to blanks, or click blank then click option'
A5
B4
C5.0
D'5'
Attempts:
3 left
💡 Hint
Common Mistakes
Passing the wrong value like 4 or 5.0
Passing the value as a string '5'
2fill in blank
medium

Complete the code to find the insertion index for value 2 in a sorted array using side='right'.

NumPy
import numpy as np
arr = np.array([1, 2, 2, 3])
index = np.searchsorted(arr, [1], side='right')
print(index)
Drag options to blanks, or click blank then click option'
A3
B1
C2
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Using side='left' instead of 'right'
Choosing index 2 which is before the second 2
3fill in blank
hard

Fix the error in the code to correctly find insertion indices for multiple values.

NumPy
import numpy as np
arr = np.array([1, 3, 5, 7])
values = np.array([2, 4, 6])
indices = np.searchsorted(arr, [1])
print(indices)
Drag options to blanks, or click blank then click option'
Avalues
B[2, 4, 6]
Carr
Dnp.array([1, 2, 3])
Attempts:
3 left
💡 Hint
Common Mistakes
Passing the original array instead of the values array
Passing a list instead of a numpy array
4fill in blank
hard

Fill both blanks to create a dictionary of values and their insertion indices for values > 3.

NumPy
import numpy as np
arr = np.array([1, 3, 5, 7, 9])
values = np.array([2, 4, 6, 8])
result = {v: np.searchsorted(arr, v[1]) for v in values if v [2] 3}
print(result)
Drag options to blanks, or click blank then click option'
A, side='right'
B>
C<
D, side='left'
Attempts:
3 left
💡 Hint
Common Mistakes
Using side='left' instead of side='right'
Using < instead of > in the condition
5fill in blank
hard

Fill all three blanks to create a dictionary of uppercase keys and insertion indices for values less than 7.

NumPy
import numpy as np
arr = np.array([1, 3, 5, 7, 9])
values = np.array([2, 4, 6, 8])
result = { [1]: np.searchsorted(arr, v[2]) for v in values if v [3] 7}
print(result)
Drag options to blanks, or click blank then click option'
Astr(v).upper()
B, side='left'
C<
Dv
Attempts:
3 left
💡 Hint
Common Mistakes
Using the value itself as key instead of uppercase
Using side='right' instead of side='left'
Using > instead of < in the condition