Challenge - 5 Problems
Master of np.argsort()
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of np.argsort() on a 1D array
What is the output of the following code?
import numpy as np arr = np.array([40, 10, 30, 20]) result = np.argsort(arr) print(result)
NumPy
import numpy as np arr = np.array([40, 10, 30, 20]) result = np.argsort(arr) print(result)
Attempts:
2 left
💡 Hint
np.argsort() returns the indices that would sort the array in ascending order.
✗ Incorrect
The smallest element is 10 at index 1, then 20 at index 3, then 30 at index 2, and finally 40 at index 0. So the sorted indices are [1, 3, 2, 0].
❓ data_output
intermediate1:30remaining
Number of items in argsort result for 2D array
Given this 2D array, how many elements does np.argsort(arr, axis=1) return?
import numpy as np arr = np.array([[3, 1, 2], [6, 4, 5]]) result = np.argsort(arr, axis=1) print(result.shape)
NumPy
import numpy as np arr = np.array([[3, 1, 2], [6, 4, 5]]) result = np.argsort(arr, axis=1) print(result.shape)
Attempts:
2 left
💡 Hint
np.argsort with axis=1 sorts each row and returns indices with the same shape as input.
✗ Incorrect
The input array has shape (2, 3). Sorting along axis=1 returns indices for each row, so the output shape is also (2, 3).
🔧 Debug
advanced2:00remaining
Identify the error in argsort usage
What error does this code raise?
import numpy as np arr = np.array([1, 2, 3]) result = np.argsort(arr, axis=1) print(result)
NumPy
import numpy as np arr = np.array([1, 2, 3]) result = np.argsort(arr, axis=1) print(result)
Attempts:
2 left
💡 Hint
Check the dimension of the array and the axis parameter.
✗ Incorrect
The array is 1D, so axis=1 is invalid. This causes an AxisError.
🚀 Application
advanced2:30remaining
Using np.argsort() to sort one array by another
You have two arrays:
import numpy as np names = np.array(['Bob', 'Alice', 'Eve']) scores = np.array([85, 95, 90])How do you get the names sorted by their scores in ascending order?
NumPy
import numpy as np names = np.array(['Bob', 'Alice', 'Eve']) scores = np.array([85, 95, 90]) sorted_names = names[np.argsort(scores)] print(sorted_names)
Attempts:
2 left
💡 Hint
Use np.argsort on scores to get indices that sort scores, then index names with those indices.
✗ Incorrect
np.argsort(scores) returns indices [0, 2, 1] which sorts scores ascending. Indexing names with this gives ['Bob', 'Eve', 'Alice'].
🧠 Conceptual
expert1:30remaining
Understanding np.argsort() with kind parameter
Which statement about the 'kind' parameter in np.argsort() is correct?
Attempts:
2 left
💡 Hint
Think about sorting algorithms and their properties.
✗ Incorrect
The 'kind' parameter lets you choose the sorting algorithm (e.g., 'quicksort', 'mergesort'). Some algorithms are stable, others are not.