pythonlistintegerhighest

Returning second highest element of a list using just a for loop and Len() method


I need two different ways for getting the second highest value of an int from a list by just using one for loop and the Len() method. No other functions are allowed for my approach.


sorted(numbers)[-2]

This was my approach, but as you can see I used another function than just a for loop and Len()

How can I get the same result as with my code above just using the allowed functions.


Solution

  • You can use the following function -

    def second_highest(nums):
        first = second = float('-inf')
        for x in nums:
            if first < x:
                second, first = first, x
            elif second < x:
                second = x
        return second
    

    While traversing through the numbers -

    1. if we come across a number that is greater than the max number seen so far, update max number and second-max number
    2. else if we come across a number greater than second-max number but less than max number, update only the second-max number
    >>> second_highest([1, 2, 3, 7, 9, 15, 4, 8 ])
    9
    >>> second_highest([15, 2, 3, 7, 9, 15, 4, 8 ])
    15
    

    The above is assuming len(nums) > 2 and second_highest([2, 2, 1]) -> 2, if you want it to be 1 instead, you can replace second elif condition with elif second < x and first != x.