Finding the n Largest Values

Write a NumPy program to get the n largest values of an array. Return the n largest values.

Example 1:

Input: np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]), 3 
Output: array([ 8, 9, 10])

Example 2:

Input: np.array([10, 20, 30, 40, 50, 60, 70, 80, 90, 100]), 5 
Output: array([ 60, 70, 80, 90, 100])

You can use np.partition() and slicing functions to get the n largest values of an array.

import numpy as np

def find_largest(array, n):
    return np.partition(array, -n)[-n:]

print(find_largest(np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]), 3))
print(find_largest(np.array([10, 20, 30, 40, 50, 60, 70, 80, 90, 100]), 5))

 

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!