Python - Find second smallest number

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

    I am writing the code which is using recursion to find the second smallest element in a list.

    def small(l):
     small.counter+=1;
     min=l[0];
    
     emp=[]
    
     for i in range(len(l)):
        if l[i]<min:
            min=l[i]
    
     for i in range(len(l)):
        if min==l[i]:
         emp.append(i)
    
     if small.counter==2:
        print "The Second smallest element is:"+str(min)
     else:
       for j in range(0,len(emp)):
    
         l.remove(min)
    
       small(l)
    small.counter = 0
    
    list=[-1-1-1-1-1-1-1-1-1,1,1,1,1,1]
    small(list)
    

    You can test it with various input integers.

    0 讨论(0)
  • 2020-11-28 11:30
    a = [6,5,4,4,2,1,10,1,2,48]
    s = set(a) # used to convert any of the list/tuple to the distinct element and sorted sequence of elements
    # Note: above statement will convert list into sets 
    print sorted(s)[1] 
    
    0 讨论(0)
  • 2020-11-28 11:33
    l = [41,9000,123,1337]
    
    # second smallest
    sorted(l)[1]
    123
    
    
    # second biggest
    sorted(l)[-2]
    1337
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题