In: Computer Science
Design and write an efficient Python function (with tester code) for finding the 10 largest elements in a sequence of size n, where n >= 50. In your tester function, write code that generates at least 50 random numbers and stores them in an array, then calls your function on that array (and prints the resulting 10 largest elements). This function must be as efficient as possible. Marks will be deducted for a slow function, even if it actually answers the question. What is the running time of your algorithm? Justify your answer.
We can find 10 largest elements by using the following function we traverse the list and update the final list which contains the 10 maximum numbers
def maxelements(ls):
ans = []
for i in range(10):
maxi = -float('inf')#setting the maxi value to be negative
infinity
max_index=0
for j in range(len(ls)):
if ls[j] > maxi:
maxi = ls[j];
max_index=j
del ls[max_index]
ans.append(maxi)
print(ans)
The output and screenshot of code is given below for indentation purposes.