Retrieve the two highest item from a list containing 100,000 integers

后端 未结 15 787
心在旅途
心在旅途 2020-12-13 17:55

How can retrieve the two highest item from a list containing 100,000 integers without having to sort the entire list first?

15条回答
  •  既然无缘
    2020-12-13 18:16

    "2 highest" is impossible; only one item can be "highest". Perhaps you mean "highest 2". In any case, you need to say what to do when the list contains duplicates. What do you want from [8, 9, 10, 10]: (10, 9) or (10, 10)? If your response is (10, 10), please consider input of [8, 9, 10, 10, 10]. What are you going to do with the "highest two" when you've got them? Please edit your question to give this guidance.

    In the meantime, here's an answer that takes the first approach (two unique values):

    largest = max(inlist)
    second_largest = max(item for item in inlist if item < largest)
    

    You should add guards against fewer than 2 unique values in the list.

提交回复
热议问题