Решение 1. Числа кратные 3 или 5
numbers = [16, 18, 1, 6, 3, 2, 6, 2, 14, 3, 20, 15, 19, 4, 18, 15, 15, 4, 20, 18]
result = {number for number in numbers if number % 3 == 0 or number % 5 == 0}
print(result)Дубликаты автоматически исчезают.
Решение 2. Общие ключи
dict1 = {"a": 1, "b": 2, "c": 3}
dict2 = {"b": 5, "d": 7, "a": 8}
common_keys = sorted(set(dict1) & set(dict2))
print("Общие ключи:", common_keys if common_keys else "-")set(dict) содержит ключи словаря.
Решение 3. Строки с длиной
words = ["apple", "banana", "cherry", "date"]
result = {word: len(word) for word in words}
print(result)Ключ - строка, значение - len(word).
Решение 4. Подмножество словаря
dict1 = {"a": 1, "b": 2}
dict2 = {"a": 1, "b": 2, "c": 3}
if all(item in dict2.items() for item in dict1.items()):
print("Первый словарь является подмножеством второго.")
else:
print("Первый словарь не является подмножеством второго.")Проверяются пары, не только ключи.
Решение 5. Удаление пустых значений
data = {"a": None, "b": 2, "c": "", "d": [], "e": [1, 2]}
result = {key: value for key, value in data.items() if value}
print(result)if value удаляет None, пустую строку и пустой список.
Решение 6. Потерянные страницы книги
book = {1: "Начало истории", 2: None, 3: "Глава 1", 4: None, 5: "Глава 2"}
for page, content in book.items():
if content is None:
book[page] = "Страница потеряна"
print(book)Решение следует тексту задания, а не ошибочному примеру вывода в источнике.
Решение 7. База оценок студентов
grades = {
"anna": [5, 4, 3, 5],
"bennet": [3, 2, 4],
"john": [5, 5, 5],
}
result = {}
for student, marks in grades.items():
result[student] = {
"оценки": marks,
"средний балл": sum(marks) / len(marks),
}
print(result)Среднее считается как сумма оценок, делённая на количество.
Решение 8. Рецепты по ингредиентам
recipes = {
("flour", "egg", "milk"): "Pancakes",
("egg", "milk", "butter"): "Omelette",
("flour", "sugar", "butter"): "Cookies",
("flour", "egg", "butter", "sugar"): "Cake",
("milk", "flour", "egg"): "Waffles",
("butter", "milk", "egg"): "Scrambled Eggs",
("flour", "milk", "sugar", "butter"): "Sweet Bread",
}
recipes_by_ingredients = {}
for ingredients, recipe in recipes.items():
key = frozenset(ingredients)
recipes_by_ingredients.setdefault(key, []).append(recipe)
available = frozenset("milk egg butter flour".split())
result = []
for ingredients, recipe_names in recipes_by_ingredients.items():
if ingredients <= available:
result.extend(recipe_names)
print(result if result else "Нет рецептов")frozenset убирает зависимость от порядка ингредиентов.
Решение 9. Одинаковые предметы
students = {
"Alice": ["Math", "Physics"],
"Bob": ["Math", "Physics"],
"Charlie": ["Chemistry", "Biology"],
"David": ["Math", "Physics"],
"Eve": ["Chemistry", "Biology"],
}
groups = {}
for student, subjects in students.items():
groups.setdefault(frozenset(subjects), []).append(student)
for subjects, names in groups.items():
print(f"Группа с предметами: {', '.join(sorted(subjects))}: {names}")Одинаковые наборы предметов попадают в одну группу.
Решение 10. Перевод и расширение словаря
english_words = {
"Butterfly": "Бабочка",
"Training": "Обучение",
"Restaurant": "Ресторан",
"Programming": "Программирование",
}
requests = [("Butterfly", ""), ("Travel", "Путешествие")]
for word, new_translation in requests:
if word in english_words:
print("Перевод:", english_words[word])
elif new_translation:
english_words[word] = new_translation
print(f'Слово "{word}" добавлено в словарь.')
else:
print("Перевод отсутствует.")
print(english_words)В интерактивной версии requests заменяются на input().