How to find second largest number in a list?

前端 未结 14 1885
遇见更好的自我
遇见更好的自我 2020-12-06 15:38

So I have to find the second largest number from list. I am doing it through simple loops.

My approach is to divide a list into two parts and then find the largest n

相关标签:
14条回答
  • 2020-12-06 15:55
    alist = [-45,0,3,10,90,5,-2,4,18,45,100,1,-266,706]
    largest = 0
    second_largest = 0
    for large in alist:
      if second_largest < large:
        second_largest = large
    
      if largest < large:
        temp = second_largest
        second_largest = largest
        largest = temp
    
    print "First Highest:- %s" %largest
    print "Second Highest:- %s" %second_largest
    
    0 讨论(0)
  • 2020-12-06 15:59

    Here is my program, irrespective of complexity

    if __name__ == '__main__':
        alist=[-45,0,3,10,90,5,-2,4,18,45,100,1,-266,706]
        alist1 = [ ]
        [alist1.append(x) for x in alist if x not in alist1]
        alist1.sort()
        print alist1[-2]
    
    0 讨论(0)
  • 2020-12-06 16:01
    alist=[10, 0,3,10,90,5,-2,4,18,45,707, 100,1,-266,706, 1]
    print(max(alist))
    second_largest=alist[0]
    for i in range(len(alist)):
        if (alist[i]>second_largest and alist[i]!=max(alist)):
            second_largest=alist[i]
    print(second_largest)
    
    0 讨论(0)
  • 2020-12-06 16:03

    Try this:

    alist=[10, 0,3,10,90,5,-2,4,18,45,707, 100,1,-266,706, 1]
    largest = alist[0]
    second_largest = alist[0]
    for i in range(len(alist)):
        if alist[i] > second_largest:
            second_largest = alist[i]
        if alist[i] > largest:
            tmp = second_largest
            second_largest = largest
            largest = tmp      
    
    print(largest, second_largest)
    
    0 讨论(0)
  • 2020-12-06 16:03

    O(n) solution

    alist=[-45,0,3,10,90,5,-2,4,18,45,100,1,-266,706]
    m = alist[:2] #m will hold 2 values, fill it with the first two values of alist
    for num in alist:
        m = sorted(m + [num],reverse=True)[:2] #appends num to m and sorts it, takes only top 2
    m[1] #the second highest element.
    

    EDIT: changed to work with negative numbers. Basic description as follows

    First I set m to be the first two elements of alist. As I iterate through alist I will be adding one value to the end of m, then sorting the three elements and throwing away the smallest one. This ensures that at the end m will contain the top two largest elements.

    0 讨论(0)
  • 2020-12-06 16:03
    alist=[-45,0,3,10,90,5,-2,4,18,45,100,1,-266,706]
    sorted_list = sorted(set(alist))
    sorted_list.pop()
    print(max(sorted_list))
    
    0 讨论(0)
提交回复
热议问题