Python - Find second smallest number

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

    Yes, except that code relies on a small quirk (that raises an exception in Python 3): the fact that None compares as smaller than a number.

    Another value that works is float("-inf"), which is a number that is smaller than any other number.

    If you use that instead of None, and just change -inf to +inf and > to <, there's no reason it wouldn't work.

    Edit: another possibility would be to simply write -x in all the comparisons on x, e.g. do if -x <= m1: et cetera.

提交回复
热议问题