1

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]
David542
  • 104,438
  • 178
  • 489
  • 842

3 Answers3

13
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

Boa
  • 2,609
  • 1
  • 23
  • 38
5

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]
Brionius
  • 13,858
  • 3
  • 38
  • 49
  • This is not the most efficient way to find the max n elements, since sorting the entire list may not be necessary if all you need is the top few values. – Daniel Jan 07 '19 at 00:21
1

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).

Community
  • 1
  • 1