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

Занятие 4. Lines

Difficulty level:

Task«Memes»

four friends & mdash; Roma (ITSHNIK), Maxim (chemist), Danik (designer) and Vlad (versatile person) & mdash; Created a common chat to exchange memes. In order not to distract each other from work with inappropriate jokes, they decided to write a bot, which will automatically determine the topic of the meme and send it only to the interested person. Your task & mdash; Write a nucleus for this bot.

rn

sorting rules:
you get to the input; line & mdash; This is the text of the meme. The bot must analyze it and determine the category by the availability of certain letters:

rn
    rn
  1. it-meme: & nbsp; if The line has all the letters 'b', 'u', 'g' (in any order and quantity). Recipient & mdash; & nbsp; roma .
  2. rn
  3. chemical Mem: & nbsp; if the line has all the letters 'b', 'o', 'o', 'm' (that is, the letter 'o' should meet at least twice). Recipient & mdash; & nbsp; maxim .
  4. rn
  5. designer Mem: & nbsp; if the line has all the letters 'e', ​​'d', 'i', 't', 's'. Recipient & mdash; & nbsp; danik .
  6. rn
  7. other: & nbsp; if the meme does not fit any of the above categories. Recipient & mdash; & nbsp; vlad .
  8. rn rn

    key rule (resolution Conflicts):
    the meme can fit several categories at the same time. In this case, it must be sent to those whose category "ended" earlier. The category is considered "completed" at the moment when the last of the letters necessary for it is found in the line & nbsp; . The bot must choose a category with the least completion index.

    rn

    you need to write a program that accepts one line (meme) and display the recipient's name.

    Input format

    One line, which is a 'meme' (type: string).

    Output format

    Recipient's name (type: string).

    Example

    Input

    submergedits

    Output

    Roma

    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
from collections import Counter

def find_completion_index(meme, required_letters):
    """
    Находит индекс, на котором категория считается "завершенной".
    Возвращает индекс или очень большое число, если категория не подходит.
    """
    # Создаем счетчик необходимых букв (например, для 'boom' -> {'b': 1, 'o': 2, 'm': 1})
    required_counts = Counter(required_letters)
    current_counts = Counter()
    
    # Проверяем, выполнены ли все условия
    def are_requirements_met():
        for char, count in required_counts.items():
            if current_counts[char] < count:
                return False
        return True

    # Идем по строке и считаем буквы
    for i, char in enumerate(meme):
        if char in required_counts:
            current_counts[char] += 1
            # Как только все буквы найдены, возвращаем текущий индекс
            if are_requirements_met():
                return i
    
    # Если цикл закончился, а буквы не найдены, возвращаем "бесконечность"
    return float('inf')

# Получаем текст мема
meme_text = input()

# Создаем список кандидатов с их условиями
candidates = [
    ('Roma', 'bug'),
    ('Maxim', 'boom'),
    ('Danik', 'edits')
]

# Находим "индекс завершения" для каждого кандидата
results = []
for name, letters in candidates:
    index = find_completion_index(meme_text, letters)
    results.append((index, name))

# Находим победителя. Функция min() для кортежей (индекс, имя)
# автоматически выберет тот, у которого первый элемент (индекс) наименьший.
winner_index, winner_name = min(results)

# Если минимальный индекс остался "бесконечным", значит, никто не подошел
if winner_index == float('inf'):
    print("Vlad")
else:
    print(winner_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, я могу рассказать о функциях, методах, обьяснить то, что тебе не понятно, а так же о текущей задаче!