These days I design some algorithms in python, but find first two greatest value in python is too ugly and inefficient.
How to implement it in a efficient or a pythonic way?
Most Pythonic way is to use nlargest
:
import heapq
values = heapq.nlargest(2, my_list)
I've found this to be consistently faster (about 2x for a list of 1,000,000 items) than heapq.nlargest
:
def two_largest(sequence):
first = second = 0
for item in sequence:
if item > second:
if item > first:
first, second = item, first
else:
second = item
return first, second
(function modified at the suggestion of MatthieuW)
Here are the results of my testing (timeit
was taking forever, so I used time.time()
):
>>> from random import shuffle
>>> from time import time
>>> seq = range(1000000)
>>> shuffle(seq)
>>> def time_it(func, *args, **kwargs):
... t0 = time()
... func(*args, **kwargs)
... return time() - t0
...
>>> #here I define the above function, two_largest().
>>> from heapq import nlargest
>>> time_it(nlargest, 2, seq)
0.258958101273
>>> time_it(two_largest, seq)
0.145977973938
mylist = [100 , 2000 , 1 , 5]
mylist.sort()
biggest = mylist[-2:]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With