I found this code on this site to find the second largest number:
def second_largest(numbers):
m1, m2 = None, None
for x in numbers:
if x >
The function can indeed be modified to find the second smallest:
def second_smallest(numbers):
m1, m2 = float('inf'), float('inf')
for x in numbers:
if x <= m1:
m1, m2 = x, m1
elif x < m2:
m2 = x
return m2
The old version relied on a Python 2 implementation detail that None
is always sorted before anything else (so it tests as 'smaller'); I replaced that with using float('inf')
as the sentinel, as infinity always tests as larger than any other number. Ideally the original function should have used float('-inf')
instead of None
there, to not be tied to an implementation detail other Python implementations may not share.
Demo:
>>> def second_smallest(numbers):
... m1, m2 = float('inf'), float('inf')
... for x in numbers:
... if x <= m1:
... m1, m2 = x, m1
... elif x < m2:
... m2 = x
... return m2
...
>>> print second_smallest([1, 2, 3, 4])
2
Outside of the function you found, it's almost just as efficient to use the heapq.nsmallest() function to return the two smallest values from an iterable, and from those two pick the second (or last) value:
from heapq import nsmallest
def second_smallest(numbers):
return nsmallest(2, numbers)[-1]
Like the above implementation, this is a O(N) solution; keeping the heap variant each step takes logK time, but K is a constant here (2)! Whatever you do, do not use sorting; that takes O(NlogN) time.