Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How efficient is Python's max function

The function max() which returns the maximum element from a list . . . what is its running time (in Python 3) in terms of Big O notation?

like image 718
kamikaze_pilot Avatar asked Mar 28 '11 02:03

kamikaze_pilot


2 Answers

It's O(n), since it must check every element. If you want better performance for max, you can use the heapq module. However, you have to negate each value, since heapq provides a min heap. Inserting an element into a heap is O(log n).

like image 150
Matthew Flaschen Avatar answered Oct 11 '22 16:10

Matthew Flaschen


Of course it is O(n) unless you are using a different datastructure supporting the max of a value collection due to some implementation invariant.

like image 44
Andreas Jung Avatar answered Oct 11 '22 17:10

Andreas Jung