How to find second largest number in a list?

前端 未结 14 1886
遇见更好的自我
遇见更好的自我 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 16:06

    Without giving away code, I will give you my approach to solving this problem.

    1.) Take your list, and sort it from least to greatest. There is a python function to handle this

    2.) Split your list into two sections

    3.) Compare the two sections, take the half with the largest numbers, repeat #2

    4.) When either half contains only two numbers, take the first number from that list

    The challenge is you will have to decide what to do if the list cannot be evenly split. Obviously, in the real world, you would sort the list and return the second from last value, but if you must do it by performing a binary split, this is how I would do it :)

    0 讨论(0)
  • 2020-12-06 16:06
     list1=[1,10,2,3,5,7,1,-32,90,99,99]
     max=0
     secmax=0
     for i in list1:
        if i>max:
           max=i
     for i in list1:
        if i>secmax and max!=i:
          secmax=i
     print(secmax)
    
    0 讨论(0)
提交回复
热议问题