• 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
  • к

Занятие 5. While cycle

Difficulty level:

Task«Finding an average value in the list»

you work in a company that produces futuristic gadgets. Your new product & mdash; Bio-tracker "Vita Puls", which every day measures the "indicator of the life energy" of the user. At the end of the week, the device generates the final report in the form of one line. Your task & mdash; Write a program that analyzes this report.

rn

the program must extract from the line the user name and its indicators in the week. Then, using & nbsp; the & nbsp; While , it should calculate the average value of only & nbsp; positive & nbsp; indicators. A positive indicator means a good, energetic day. Negative indicators (stress, fatigue) and zero (neutral day) should not be taken into account when calculating the average.

rn

you need to process the input line, convert the numerical data from the string type (for this you can use Cycle & nbsp; for ), and then using the cycle & nbsp; While Find the amount and number of positive indicators for calculating the average.

Input format

line (string), which always has the following view: & nbsp; "name: [user name]; indicators: number through a gap]" . For example, & nbsp; Name: Alexey; Indicators: 10 -5 22 0 -12 18 7 .

Output format

The line (string) containing the user name and the average value of its positive indicators. If there were no positive reasons for a week, you need to display a special message.

Example

Input

Name: Elena; Indicators: 15 -4 25 0 10 -8 5

Output

Elena, the average indicator of your life energy for the week: 13.75

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
# Получаем на вход одну строку с данными от био-трекера
input_string = input()

# Разделяем строку на две части по символу ';'
# parts будет списком, например: ['Имя: Елена', ' Показатели: 15 -4 25 0 10 -8 5']
parts = input_string.split(';')

# Из первой части извлекаем имя
# Сначала разделяем 'Имя: Елена' по ':', получаем ['Имя', ' Елена']
# Берем второй элемент ' Елена' и убираем пробелы по краям с помощью strip()
user_name = parts[0].split(':')[1].strip()

# Из второй части извлекаем строку с показателями
# Аналогично получаем ' 15 -4 25 0 10 -8 5' и убираем пробелы
scores_string = parts[1].split(':')[1].strip()

# Разделяем строку с показателями по пробелу, чтобы получить список строк
# ['15', '-4', '25', '0', '10', '-8', '5']
str_numbers = scores_string.split()

# Создаем пустой список для хранения чисел
numbers = []
# Используем цикл for для преобразования каждой строки в списке в целое число
for s_num in str_numbers:
    numbers.append(int(s_num))

# Инициализируем переменные для цикла while
sum_of_positives = 0  # Сумма положительных чисел
count_of_positives = 0  # Количество положительных чисел
index = 0  # Индекс для перебора списка
list_length = len(numbers) # Длина списка, чтобы знать, когда остановиться

# Основной цикл while для подсчета среднего значения
while index < list_length:
    # Получаем текущее число из списка по индексу
    current_number = numbers[index]
    
    # Проверяем, является ли число строго положительным
    if current_number > 0:
        # Если да, добавляем его к сумме
        sum_of_positives += current_number
        # и увеличиваем счетчик положительных чисел
        count_of_positives += 1
    
    # Переходим к следующему элементу списка
    index += 1

# После цикла проверяем, были ли найдены положительные числа
if count_of_positives > 0:
    # Если да, вычисляем среднее значение
    average = sum_of_positives / count_of_positives
    # Выводим результат в заданном формате
    print(f"{user_name}, средний показатель вашей жизненной энергии за неделю: {average}")
else:
    # Если положительных чисел не было, выводим другое сообщение
    print(f"{user_name}, на этой неделе не было дней с положительными показателями.")

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

Помощник ИИ

Привет! Я твой помощник по программированию. Задавай любые вопросы по Python, я могу рассказать о функциях, методах, обьяснить то, что тебе не понятно, а так же о текущей задаче!