0
0
NumPydata~20 mins

Partial sorting with np.partition() in NumPy - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Partial Sorting Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of np.partition() on a 1D array
What is the output of the following code using np.partition() on a 1D array?
NumPy
import numpy as np
arr = np.array([7, 2, 5, 3, 9, 1])
result = np.partition(arr, 3)
print(result)
A[1 2 3 5 7 9]
B[2 1 3 5 7 9]
C[1 2 3 7 5 9]
D[2 1 3 5 9 7]
Attempts:
2 left
💡 Hint
Remember, np.partition rearranges so that the element at the kth position is in sorted order, and all smaller elements are before it, but the rest are unordered.
data_output
intermediate
1:30remaining
Number of elements less than pivot after np.partition()
After running np.partition(arr, 2) on arr = np.array([10, 4, 5, 8, 6, 11, 3]), how many elements are guaranteed to be less than or equal to the element at index 2 in the result?
NumPy
import numpy as np
arr = np.array([10, 4, 5, 8, 6, 11, 3])
result = np.partition(arr, 2)
print(result)
AAt least 2 elements
BExactly 3 elements
CAt least 3 elements
DExactly 2 elements
Attempts:
2 left
💡 Hint
The kth element after partition is in its sorted position, so all elements before it are smaller or equal.
🔧 Debug
advanced
1:30remaining
Identify the error in np.partition usage
What error does the following code raise?
NumPy
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
result = np.partition(arr, 10)
print(result)
AValueError: kth out of bounds
BTypeError: invalid type for kth
CIndexError: index 10 is out of bounds for axis 0 with size 5
DNo error, returns the sorted array
Attempts:
2 left
💡 Hint
Check if the kth index is valid for the array size.
🚀 Application
advanced
2:00remaining
Using np.partition() to find the 3 smallest values
Which option correctly extracts the 3 smallest values from arr = np.array([12, 3, 5, 7, 19, 1]) using np.partition()?
NumPy
import numpy as np
arr = np.array([12, 3, 5, 7, 19, 1])
Anp.partition(arr, 2)[:3]
Bnp.partition(arr, 3)[:3]
Cnp.partition(arr, 3)[3:]
Dnp.partition(arr, 2)[3:]
Attempts:
2 left
💡 Hint
Remember, kth index is zero-based, so to get 3 smallest elements, use k=2.
🧠 Conceptual
expert
2:30remaining
Behavior of np.partition() on 2D arrays
Given a 2D array arr = np.array([[9, 4, 7], [1, 3, 5]]), what does np.partition(arr, 1, axis=1) do?
NumPy
import numpy as np
arr = np.array([[9, 4, 7], [1, 3, 5]])
result = np.partition(arr, 1, axis=1)
print(result)
APartitions each column so the element at index 1 is in sorted position within that column
BPartitions each row so the element at index 1 is in sorted position within that row
CSorts the entire array along axis 1
DRaises an error because axis=1 is invalid for partition
Attempts:
2 left
💡 Hint
Check the meaning of axis=1 for a 2D array in numpy.