Module 4 · Lesson 3
Sorting
np.sort(arr)returns a sorted copy;arr.sort()sorts in place and returnsNone.np.argsort(arr)doesn’t sort anything — it returns the indices that would sort the array. This is the tool you reach for when you need to sort one array “by” another (e.g. sort names by score).- Both accept
axison 2-D arrays, sorting each row/column independently (each row sorted on its own does not sort the matrix as a whole).
arr = np.array([3, 1, 4, 1, 5])
print("np.sort (copy): ", np.sort(arr), "| original untouched:", arr)
order = np.argsort(arr)
print("argsort indices: ", order)
print("names sorted by score, using argsort as a key:")
names = np.array(["c", "a", "d", "b", "e"])
scores = np.array([30, 90, 10, 90, 50])
print(names[np.argsort(scores)])
Output:
np.sort (copy): [1 1 3 4 5] | original untouched: [3 1 4 1 5]
argsort indices: [1 3 0 2 4]
names sorted by score, using argsort as a key:
['d' 'c' 'e' 'a' 'b']
3.1
Rank the runners
Write top_n_names(names, times, n) that returns the n names (as a NumPy
array of strings) belonging to the smallest n values in times —
i.e. the fastest n runners — ordered from fastest to slowest. names
and times are same-length 1-D arrays.
💡 Hint
np.argsort(times) gives ascending order (fastest first, since lower time is better); slice the first n of names[order].
✅ Solution
def top_n_names(names, times, n):
order = np.argsort(times)
return names[order][:n]
3.2
Sort each row independently
Write sort_rows_desc(grid) that returns a copy of grid with each row
sorted in descending order (columns no longer correspond to anything
meaningful across rows — that's expected).
💡 Hint
Sort ascending along axis=1 with np.sort, then reverse each row with [:, ::-1].
✅ Solution
def sort_rows_desc(grid):
return np.sort(grid, axis=1)[:, ::-1]