In: Computer Science
2. Define a function max_n(arr, n) that takes in an array and an integer as arguments. Your function will then return the n largest values from that array as an array containing n elements. It is safe to assume that arr will have at least n elements. The resulting array should have the largest number on the end and the smallest number at the beginning.
For Example:
max_n(np.array([1,2,3,4,5]), 3) returns np.array([3,4,5])
max_n(np.array([10,9,8,7,6,5]), 4) returns np.array([7,8,9,10])
max_n(np.array([1,1,1]), 2) returns np.array([1,1])
#Python program to compute n largest elements in an array
# importing numpy package
import numpy as np
# np.argsort(arr) returns the indicies which will sort
numpy.array in ascending order
#np.argsort(arr)[-n:] returns the last n elements of the indices
list
def max_n(arr,n):
largernelements=arr[np.argsort(arr)[-n:]]
return largernelements
#calling function max_n() with array
elements
print("The largest n elements are
",max_n(np.array([1,2,3,4,5]),3) )
print("\nThe largest n elements are
",max_n(np.array([10,9,8,7,6,5]), 4))
Screenshot code:
Output: