Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

More pythonic way to find first two greatest value in a list in python

Tags:

python

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?

like image 949
chao787 Avatar asked Jun 11 '12 07:06

chao787


3 Answers

Most Pythonic way is to use nlargest:

import heapq
values = heapq.nlargest(2, my_list)
like image 198
interjay Avatar answered Nov 14 '22 23:11

interjay


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
like image 34
Joel Cornett Avatar answered Nov 14 '22 22:11

Joel Cornett


mylist = [100 , 2000 , 1 , 5]
mylist.sort()
biggest = mylist[-2:]
like image 24
FakeDIY Avatar answered Nov 14 '22 22:11

FakeDIY