Python - Find second smallest number

前端 未结 16 1164
长发绾君心
长发绾君心 2020-11-28 10:35

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 >         


        
16条回答
  •  一整个雨季
    2020-11-28 11:22

    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.

提交回复
热议问题