v9.1.1
Menu

Sort and Search

easyPROMiscNumPy UtilitiesNumpy

Problem Statement

Sort NumPy arrays and find elements.

Background

  • np.sort(arr): Returns sorted copy
  • np.argsort(arr): Returns indices that would sort the array
  • np.where(condition): Find indices where condition is True
  • np.argmax(), np.argmin(): Index of max/min element

Your Task

Write a function sort_and_search(arr) that returns a dictionary with:

  • "sorted": Sorted array as list
  • "argsort": Indices that would sort the array, as a list
  • "argmax": Index of maximum value, as a plain integer
  • "argmin": Index of minimum value (first occurrence), as a plain integer

Output Format

Return a dictionary with exactly these four keys.

Example

Input
[3, 1, 4, 1, 5, 9, 2, 6]
Output
{'sorted': [1, 1, 2, 3, 4, 5, 6, 9], 'argsort': [1, 3, 6, 0, 2, 4, 7, 5], 'argmax': 5, 'argmin': 1}
Reasoning
  • Input: arr is a 1D array of 8 values, indexed 00 to 77: a=(3,1,4,1,5,9,2,6)a = (3, 1, 4, 1, 5, 9, 2, 6).
  • Sorted: the same 8 values in ascending order, [1, 1, 2, 3, 4, 5, 6, 9]. Both 1s stay.
  • Argsort: instead of values, list the positions they came from, in sorted order. The smallest value 1 sits at positions 1 and 3, then 2 is at 6, 3 at 0, 4 at 2, 5 at 4, 6 at 7 and 9 at 5, giving [1, 3, 6, 0, 2, 4, 7, 5]. Reading aa at those positions gives the sorted list.
  • Argmax / argmin: the largest value, 9, is at position 5, and the smallest, 1, first appears at position 1, so argmax is 5 and argmin is 1.
  • Notice that with ties, position 1 beats position 3 for the minimum: it is the first occurrence that counts. Here the maximum 9 is unique, so the last entry of argsort is the argmax position 5, and in this sample its first entry, 1, is also the argmin position.

Constraints

  • Use np.sort(), np.argsort(), np.argmax(), np.argmin()
  • Array will have at least 1 element

Learn this in

More from Numpy

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.