0
0
NumPydata~5 mins

Partial sorting with np.partition() in NumPy - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does np.partition() do in numpy?

np.partition() rearranges elements in an array so that the element at the specified index is in its sorted position, and all smaller elements are before it, while all larger elements are after it. It does not fully sort the array.

Click to reveal answer
beginner
How is np.partition() different from np.sort()?

np.sort() fully sorts the entire array, while np.partition() only ensures that the element at the given index is in the correct position, with smaller elements before and larger after, but the order within those groups is not guaranteed.

Click to reveal answer
beginner
What is the main use case of np.partition()?

It is useful when you want to find the k-th smallest or largest elements quickly without sorting the entire array, such as finding medians or percentiles efficiently.

Click to reveal answer
intermediate
Example: What does np.partition([3, 1, 4, 1, 5], 2) return?

It returns an array where the element at index 2 is the third smallest element, and all elements before index 2 are smaller or equal, and all after are larger or equal. One possible output is [1, 1, 3, 5, 4]. The order of elements before and after index 2 is not sorted.

Click to reveal answer
intermediate
Can np.partition() be used on multi-dimensional arrays?

Yes, by specifying the axis parameter, you can partition along a specific axis of a multi-dimensional array.

Click to reveal answer
What does np.partition(arr, k) guarantee about the element at index k?
AIt is the k-th smallest element in the array
BThe array is fully sorted
CAll elements are larger than the element at index k
DThe array is reversed
Which numpy function fully sorts an array?
Anp.sort()
Bnp.argsort()
Cnp.partition()
Dnp.argpartition()
If you want to find the median quickly without full sorting, which function is best?
Anp.sort()
Bnp.cumsum()
Cnp.partition()
Dnp.argmax()
What happens to elements before the partition index after using np.partition()?
AThey are reversed
BThey are sorted in ascending order
CThey are all larger than the element at the partition index
DThey are all smaller or equal to the element at the partition index
Can np.partition() be used to find the top 3 largest elements?
ANo, it only finds smallest elements
BYes, by partitioning at the correct index
CYes, but only for 1D arrays
DNo, it only sorts fully
Explain how np.partition() works and when you would use it instead of full sorting.
Think about finding a specific element's position without sorting everything.
You got /5 concepts.
    Describe the difference between np.partition() and np.sort() with an example.
    Consider what happens to the array after each function.
    You got /5 concepts.