Challenge - 5 Problems
Sorting Master with np.sort()
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of np.sort() on a 1D array
What is the output of this code?
import numpy as np arr = np.array([3, 1, 4, 1, 5]) sorted_arr = np.sort(arr) print(sorted_arr)
NumPy
import numpy as np arr = np.array([3, 1, 4, 1, 5]) sorted_arr = np.sort(arr) print(sorted_arr)
Attempts:
2 left
💡 Hint
np.sort() returns a sorted copy of the array in ascending order.
✗ Incorrect
np.sort() sorts the array elements in ascending order and returns a new array. The original array remains unchanged.
❓ data_output
intermediate2:00remaining
Sorting a 2D array along axis 0
Given this 2D array, what is the output of np.sort(arr, axis=0)?
import numpy as np arr = np.array([[3, 2], [1, 4]]) sorted_arr = np.sort(arr, axis=0) print(sorted_arr)
NumPy
import numpy as np arr = np.array([[3, 2], [1, 4]]) sorted_arr = np.sort(arr, axis=0) print(sorted_arr)
Attempts:
2 left
💡 Hint
Sorting along axis 0 sorts each column independently.
✗ Incorrect
Sorting along axis 0 sorts each column separately, so the smallest values in each column come first.
🔧 Debug
advanced2:00remaining
Identify the error in using np.sort()
What error does this code raise?
import numpy as np arr = np.array([3, 1, 4]) sorted_arr = np.sort(arr, axis=1) print(sorted_arr)
NumPy
import numpy as np arr = np.array([3, 1, 4]) sorted_arr = np.sort(arr, axis=1) print(sorted_arr)
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.sort() to sort structured arrays
Given this structured array, what is the output of np.sort(arr, order='age')?
import numpy as np
arr = np.array([(1, 'Alice', 25), (2, 'Bob', 20), (3, 'Carol', 30)],
dtype=[('id', 'i4'), ('name', 'U10'), ('age', 'i4')])
sorted_arr = np.sort(arr, order='age')
print(sorted_arr['name'])NumPy
import numpy as np arr = np.array([(1, 'Alice', 25), (2, 'Bob', 20), (3, 'Carol', 30)], dtype=[('id', 'i4'), ('name', 'U10'), ('age', 'i4')]) sorted_arr = np.sort(arr, order='age') print(sorted_arr['name'])
Attempts:
2 left
💡 Hint
Sorting by 'age' orders the records by the age field ascending.
✗ Incorrect
np.sort with order='age' sorts the structured array by the age field ascending, so Bob (20), Alice (25), Carol (30).
🧠 Conceptual
expert1:30remaining
Effect of np.sort() on original array
Which statement about np.sort() is true?
Attempts:
2 left
💡 Hint
Think about whether np.sort() changes the original array or not.
✗ Incorrect
np.sort() returns a new sorted array and leaves the original array unchanged. To sort in place, use arr.sort().