• 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«Sorting the list with a bubble method»

you work as a younger specialist in the digital archive. Your task & mdash; Create an assistant program for the cataloging of ancient artifacts. Each artifact has a unique numerical identifier (ID) and name.

rn

the program should be interactive and work in the cycle, expecting the commands from you.

rn

program commands:

rn
  • add & nbsp; & mdash; triggers the process of adding a new artifact. The program will request from you data in the & nbsp; "id: name" . You must make sure that the ID is an entire number. If the input format is incorrect (for example, there is no colon or ID is not a number), the program must report an error and request entry again until the correct data is entered.
  • rn
  • list & nbsp; & mdash; It displays on the screen the current list of all added artifacts in the order in which they were added.
  • rn
  • sort & nbsp; & mdash; Carries out the sorting of all artifacts by increasing their ID. For sorting, it is necessary to use & nbsp; bubble sorting algorithm . After the sorting, the program should inform about success.
  • rn
  • exit & nbsp; & mdash; completes the work of the program.
  • rn rn

    your goal & mdash; Write a program that correctly processes all the commands, controls the list of artifacts and correctly implements bubble sorting so that the senior archivist can easily navigate the catalog.

    Input format

    The user team (line). It can be one of: & nbsp; Add , & nbsp; List of , & nbsp; sort , & nbsp; output .

    If the command & nbsp; add , then the entry of data on artifact (line) in the & nbsp; id: name . ID should imagine in the form of a whole number.

    Output format

    The answers of the program to the commands, error messages, a sorted or unfinished list of artifacts (lines).

    Example

    Input

    Add
    30: Shield
    Add
    10: Sword
    Sort
    List
    Exit

    Output

    The artifact is successfully added.
    The artifact has been successfully added.
    The archive is successfully sorted by ID.
    --- Catalog of artifacts ---
    id: 10, name: sword
    id: 30, name
    -------------------- Programs. Goodbye!

    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
    # Создаем два пустых списка для хранения ID и названий артефактов.
    # Мы используем два списка, чтобы ID и названия с одинаковыми индексами соответствовали друг другу.
    artifact_ids = []
    artifact_names = []
    
    # Запускаем бесконечный цикл, который будет работать, пока пользователь не введет команду "выход".
    while True:
        # Запрашиваем у пользователя ввод команды.
        command = input()
    
        # Условие для обработки команды "добавить".
        if command == "добавить":
            # Внутренний цикл для проверки корректности ввода данных об артефакте.
            while True:
                # Запрашиваем данные в формате "ID:Название".
                data_input = input()
                
                # Проверяем, есть ли в строке разделитель ':'.
                if ':' in data_input:
                    # Разделяем строку на две части по первому вхождению ':'.
                    parts = data_input.split(':', 1)
                    id_str = parts[0]
                    name_str = parts[1]
                    
                    # Проверяем, состоит ли часть с ID только из цифр (и возможно знака минус).
                    if id_str.strip().isdigit():
                        # Если все проверки пройдены, преобразуем ID в целое число.
                        new_id = int(id_str)
                        # Добавляем ID и название в соответствующие списки.
                        artifact_ids.append(new_id)
                        artifact_names.append(name_str)
                        print("Артефакт успешно добавлен.")
                        # Прерываем внутренний цикл проверки, так как данные корректны.
                        break
                    else:
                        # Сообщение об ошибке, если ID не является числом.
                        print("Ошибка: ID должен быть целым числом. Попробуйте снова.")
                else:
                    # Сообщение об ошибке, если формат ввода неверный.
                    print("Ошибка: неверный формат. Используйте ID:Название. Попробуйте снова.")
    
        # Условие для обработки команды "список".
        elif command == "список":
            print("--- Каталог артефактов ---")
            # Проверяем, есть ли артефакты в каталоге.
            if not artifact_ids:
                print("Архив пуст.")
            else:
                # Используем цикл for для перебора всех артефактов и их вывода.
                # range(len(artifact_ids)) генерирует последовательность индексов от 0 до N-1.
                for i in range(len(artifact_ids)):
                    print(f"ID: {artifact_ids[i]}, Название: {artifact_names[i]}")
            print("--------------------------")
        
        # Условие для обработки команды "сортировать".
        elif command == "сортировать":
            # Получаем количество элементов для сортировки.
            n = len(artifact_ids)
            # Внешний цикл пузырьковой сортировки.
            for i in range(n):
                # Внутренний цикл, который сравнивает и меняет местами соседние элементы.
                # С каждым проходом внешнего цикла самый большой элемент "всплывает" в конец,
                # поэтому внутренний цикл можно сокращать на 'i'.
                for j in range(0, n-i-1):
                    # Если текущий ID больше следующего, меняем их местами.
                    if artifact_ids[j] > artifact_ids[j+1]:
                        # Меняем местами ID.
                        artifact_ids[j], artifact_ids[j+1] = artifact_ids[j+1], artifact_ids[j]
                        # ВАЖНО: одновременно меняем местами и названия, чтобы сохранить соответствие.
                        artifact_names[j], artifact_names[j+1] = artifact_names[j+1], artifact_names[j]
            print("Архив успешно отсортирован по ID.")
    
        # Условие для обработки команды "выход".
        elif command == "выход":
            print("Завершение работы программы. До свидания!")
            # Прерываем главный цикл while, что приводит к завершению программы.
            break
    
        # Если введена неизвестная команда.
        else:
            print("Неизвестная команда. Пожалуйста, используйте одну из следующих: добавить, список, сортировать, выход.")

    🎉 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, я могу рассказать о функциях, методах, обьяснить то, что тебе не понятно, а так же о текущей задаче!