• 1
    Input and Output Data
    • Tasks
  • 2
    Conditions
    • Tasks
  • 3
    For Loop
    • Tasks
  • 4
    Strings
    • Tasks
  • 5
    While Loop
    • Tasks
  • 6
    Lists
    • Tasks
  • 7
    Two-Dimensional Arrays
    • Tasks
  • 8
    Dictionaries
    • Tasks
  • 9
    Sets
    • Tasks
  • 10
    Functions and Recursion
    • Tasks
  • к

Lesson 5. While cycle

Difficulty level:

Task«Selection of the root of the number»

💻 Python

on the distant planet XB-103, a research robot geologist collects samples of minerals from the conveyor tape. Each type of mineral has its own unique numerical identifier (ID). The robot control system should work as efficiently as possible, therefore, to optimize the storage of the robot, it is necessary to transfer only one number to the central computer at the end of the shift: what was the maximum length of the continuous series of samples of the same type. The shift of the robot ends when a special calibration sample with ID is 0.

rn

you are given a sequence of numerical minerals of minerals. The sequence always ends with the number 0, which means the end of the shift and is not the ID of the mineral. Determine the largest number of the same IDs in a row in this sequence.

Input format

Entire natural numbers are introduced, each from a new line. The sequence ends with the number 0.

Output format

One number & mdash; The maximum length of the continuous sequence of the same elements.

Example

Input

1
7
7
7
2
2
9
0

Output

3

Hint

There will be no clue here, decide for yourself!

main.py
Test 1
Test 2
Test 3
Test 4
Test 5
Test 6
Test 7
Test 8
Test 9
Test 10
Developer’s solution
# Инициализируем переменные для подсчета
# max_len - хранит максимальную найденную длину серии
# current_len - хранит длину текущей серии одинаковых чисел
# prev_n - хранит предыдущее число для сравнения с текущим

max_len = 0
current_len = 0
# Используем -1 как начальное значение, так как ID минералов - натуральные числа
prev_n = -1 

# Запускаем бесконечный цикл, который прервется при вводе 0
while True:
    # Считываем очередной ID и преобразуем его в целое число
    n = int(input())

    # Условие выхода из цикла - конец смены
    if n == 0:
        break

    # Сравниваем текущий ID с предыдущим
    if n == prev_n:
        # Если они равны, увеличиваем счетчик текущей серии
        current_len += 1
    else:
        # Если числа не равны, значит серия прервалась.
        # Сначала проверяем, не была ли закончившаяся серия самой длинной
        if current_len > max_len:
            max_len = current_len
        
        # Начинаем новую серию с текущего числа. Ее длина равна 1.
        current_len = 1
        # Обновляем "предыдущее" число
        prev_n = n

# После завершения цикла нужно выполнить еще одну проверку.
# Это необходимо для случая, когда самая длинная серия оказалась в самом конце
# последовательности, прямо перед нулем.
if current_len > max_len:
    max_len = current_len

# Выводим результат
print(max_len)

🎉 Congratulations! 🎉

You did an excellent job with the task! It was a challenging problem, but you found the correct solution. You are one step closer to mastering programming! Keep up the good work, because every stage you pass makes you even stronger.

AD

Advertisement

red-snake blue-snake green-snake

Running your code...

AI Helper

Hi! I am your programming assistant. Ask me anything about Python — I can explain functions, methods, and help you understand the current task!