Are there any other ways than sort() to find the second smallest integer in this row:
10 12 2 5 15
Are there any other ways than sort() to find the second smallest integer in this row:
10 12 2 5 15
you can use heapq.nsmalles
:
>>> import heapq
>>> l=[10, 12, 2, 5 ,15]
>>> print(heapq.nsmallest(2, l)) [1]
5
The most important feature of a heap is that heap[0]
is always the smallest item. More‐
over, subsequent items can be easily found using the heapq.heappop()
method, which
pops off the first item and replaces it with the next smallest item (an operation that
requires O(log N) operations where N is the size of the heap)
The nlargest()
and nsmallest()
functions are most appropriate if you are trying to
find a relatively small number of items. If you are simply trying to find the single smallest
or largest item (N=1), it is faster to use min()
and max()
. Similarly, if N is about the
same size as the collection itself, it is usually faster to sort it first and take a slice (i.e.,
use sorted(items)[:N]
or sorted(items)[-N:]
). It should be noted that the actual
implementation of nlargest()
and nsmallest()
is adaptive in how it operates and will
carry out some of these opti`mizations on your behalf (e.g., using sorting if N is close to
the same size as the input).
(reference : python cookbook 3rd edition)