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.
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 -
>>> 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
.