Python - Find second smallest number

前端 未结 16 1226
长发绾君心
长发绾君心 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:16

    Here we want to keep an invariant while we scan the list of numbers, for every sublist it must be

    m1<=m2<={all other elements}

    the minimum length of a list for which the question (2nd smallest) is sensible is 2, so we establish the invariant examining the first and the second element of the list (no need for magic numbers), next we iterate on all the remaining numbers, maintaining our invariant.

    def second_smaller(numbers):
        # if len(numbers)<2: return None or otherwise raise an exception
    
        m1, m2 = numbers[:2]
        if m2

    Addendum

    BTW, the same reasoning should be applied to the second_largest function mentioned by the OP

提交回复
热议问题