The number of elements equal to the maximum. A sequence consists of integer numbers and ends with the number 0. Determine how many elements in this sequence are equal to its largest element.
|
largest = float('-inf') count_largest = 0 while True: num = int(input()) if num == 0: break if num > largest: largest = num count_largest = 1 elif num == largest: count_largest += 1 print(count_largest) |
Explanation of the Code
- Initialize Variables:
largest = float('-inf')
count_largest = 0
- Initialize
largest
to negative infinity (float('-inf')
) to ensure any input number will be larger.
- Initialize
count_largest
to 0 to keep track of the number of elements equal to the largest element.
- Reading Input and Counting Elements Equal to Largest:
while True:
num = int(input())
if num == 0:
break
if num > largest:
largest = num
count_largest = 1
elif num == largest:
count_largest += 1
- 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 largest
to this integer and reset count_largest
to 1.
- If the integer is equal to
largest
, increment count_largest
by 1.
- Printing the Count of Elements Equal to Largest:
- Print the value of
count_largest
after exiting the loop.