[Python] Get the second largest number in a list in linear time

Discussão em 'Python' iniciado por Stack, Junho 15, 2025.

  1. Stack

    Stack Membro Participativo

    I'm obtaining the second largest number from a list:

    >>> numbers = [20,67,3,2.6,7,74,2.8,90.8,52.8,4,3,2,5,7]
    >>> numbers.remove(max(numbers))
    >>> max(numbers)
    74


    Except that the easy list processing runs through the list twice: to find the largest and then the 2nd largest. It's also destructive - I need two copies of the data if I wanted to keep the original:

    >>> numbers = [20,67,3,2.6,7,74,2.8,90.8,52.8,4,3,2,5,7]
    >>> if numbers[0]>numbers[1]):
    ... m, m2 = numbers[0], numbers[1]
    ... else:
    ... m, m2 = numbers[1], numbers[0]
    ...
    >>> for x in numbers[2:]:
    ... if x>m2:
    ... if x>m:
    ... m2, m = m, x
    ... else:
    ... m2 = x
    ...
    >>> m2
    74


    Which runs through the list just once, but isn't terse and clear like the previous solution.

    Is there a way to have both? The clarity of the first version, but the single run through of the second?

    Continue reading...

Compartilhe esta Página