The index of the maximum of a sequence. A sequence consists of integer numbers and ends with the number 0. Determine the index of the largest element in the sequence. If the largest element is not unique, print the index of the first occurrence.
|
largest = float('-inf') index_of_largest = -1 index = 0 while True: num = int(input()) if num == 0: break if num > largest: largest = num index_of_largest = index index += 1 print(index_of_largest+1) |
Explanation of the Code
- Initialize Variables:
largest = float('-inf')
index_of_largest = -1
index = 0
- Initialize
largest
to negative infinity (float('-inf')
) to ensure any input number will be larger.
- Initialize
index_of_largest
to -1 to keep track of the index of the largest element.
- Initialize
index
to 0 to keep track of the current index in the sequence.
- Reading Input and Finding the Largest Number:
while True:
num = int(input())
if num == 0:
break
if num > largest:
largest = num
index_of_largest = index
index += 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 update index_of_largest
to the current index
.
- Increment
index
by 1.
- Printing the Index of the Largest Number:
- Print the value of
index_of_largest
after exiting the loop.