I know how to get a single max:
m = max([1,2])
2
How would I get the max n
elements? For example:
m = max([1,2,3,4,5], n=2)
[4,5]
import heapq
input_list = [1,2,3,4,5]
number_of_elements = 3
heapq.nlargest(number_of_elements, input_list)
For more info, here are the heap queue algorithm docs
Here's one way to implement it - sort the list, then slice the first n
elements.
def maxN(elements, n):
return sorted(elements, reverse=True)[:n]
If you want to beat the performance of a sorting algo you need to use a select algorithm (like QuickSelect)
see : quickSelect HW in Python
This reduces the average complexity from O(n log n) (in quicksort) to O(n) (in quickselect).