The second maximum. The sequence consists of distinct positive integers and ends with the number 0. Determine the value of the second largest element in this sequence. It is guaranteed that the sequence has at least two elements.
|
largest = second_largest = float('-inf') while True: num = int(input()) if num == 0: break if num > largest: second_largest = largest largest = num elif num > second_largest: second_largest = num print(second_largest) |
Explanation of the Code
- Initialize Variables:
largest = second_largest = float('-inf')
- Initialize
largest
and second_largest
to negative infinity (float('-inf')
) to ensure any input number will be larger.
- Reading Input and Finding the Largest and Second Largest Numbers:
while True:
num = int(input())
if num == 0:
break
if num > largest:
second_largest = largest
largest = num
elif num > second_largest:
second_largest = num
- Use a
while True
loop to continuously read input.
- Convert the input to an integer using
int()
.
- If the integer is 0, break the loop.
- If the integer is greater than
largest
, update second_largest
to largest
and update largest
to this integer.
- If the integer is greater than
second_largest
but not greater than largest
, update second_largest
to this integer.
- Printing the Second Largest Number:
- Print the value of
second_largest
after exiting the loop.