0
0
NumPydata~20 mins

np.argsort() for sort indices in NumPy - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Master of np.argsort()
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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)
A[0 1 2 3]
B[3 2 1 0]
C[1 3 2 0]
D[1 2 3 0]
Attempts:
2 left
💡 Hint
np.argsort() returns the indices that would sort the array in ascending order.
data_output
intermediate
1: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)
A(2, 3)
B(3, 2)
C(6,)
D(2,)
Attempts:
2 left
💡 Hint
np.argsort with axis=1 sorts each row and returns indices with the same shape as input.
🔧 Debug
advanced
2: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)
AValueError: operands could not be broadcast together
BTypeError: argsort() got an unexpected keyword argument 'axis'
CNo error, prints [0 1 2]
DAxisError: axis 1 is out of bounds for array of dimension 1
Attempts:
2 left
💡 Hint
Check the dimension of the array and the axis parameter.
🚀 Application
advanced
2: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)
A['Bob' 'Eve' 'Alice']
B['Bob' 'Alice' 'Eve']
C['Eve' 'Bob' 'Alice']
D['Alice' 'Eve' 'Bob']
Attempts:
2 left
💡 Hint
Use np.argsort on scores to get indices that sort scores, then index names with those indices.
🧠 Conceptual
expert
1:30remaining
Understanding np.argsort() with kind parameter
Which statement about the 'kind' parameter in np.argsort() is correct?
A'kind' is used to specify the data type of the output indices.
B'kind' specifies the sorting algorithm and can affect stability of the sort.
C'kind' controls the axis along which sorting is performed.
D'kind' determines whether the output is sorted ascending or descending.
Attempts:
2 left
💡 Hint
Think about sorting algorithms and their properties.