""" Урок 29. Практикум 7 — весь код примеров одним файлом. Источник: subjects/python-fundamentals/course/lessons/29-practice-7/examples.html Файл собран автоматически (tools/build_lesson_examples.py): правьте страницу урока. Запуск: python lesson-29.py """ # ==================================================================== # Пример 1. Безопасный поиск через index() # ==================================================================== # 01_safe_index.py products = ["Bread", "Butter", "Cheese", "Milk", "Eggs"] target = "Milk" if target in products: print(products.index(target) + 1) else: print(f"Товар {target} отсутствует") # 4 missing = "Juice" if missing in products: print(products.index(missing) + 1) else: print(f"Товар {missing} отсутствует") # Товар Juice отсутствует try: products.index("Juice") except ValueError as error: print("ValueError:", error) # ValueError: 'Juice' is not in list # ==================================================================== # Пример 2. Уникальные слова без учёта регистра # ==================================================================== # 02_unique_words.py text = "Python is a great language. Python is popular and Python is powerful." words = [word.strip(".").lower() for word in text.split()] unique_sorted = sorted(set(words)) print("Всего слов:", len(words), "уникальных:", len(unique_sorted)) print(unique_sorted) # Всего слов: 12 уникальных: 8 # ['a', 'and', 'great', 'is', 'language', 'popular', 'powerful', 'python'] # ==================================================================== # Пример 3. Элемент по критерию: max(key=len) # ==================================================================== # 03_max_key.py sentence = "Programming in Python is both fun and educational" words = sentence.split() longest = max(words, key=len) print("Самое длинное слово:", longest, "длина:", len(longest)) # Самое длинное слово: Programming длина: 11 # ==================================================================== # Пример 4. Перегруппировка списка с сохранением порядка # ==================================================================== # 04_stable_partition.py numbers = [4, 7, 1, 6, 3, 8, 2] big = [n for n in numbers if n >= 5] small = [n for n in numbers if n < 5] print("Было:", numbers) print("Стало:", big + small) # Было: [4, 7, 1, 6, 3, 8, 2] # Стало: [7, 6, 8, 4, 1, 3, 2] # ==================================================================== # Пример 5. Уникальные суммы пар чисел # ==================================================================== # 05_pair_sums.py values = [3, 5, 9, 3] pair_sums = set() for i in range(len(values)): for j in range(i + 1, len(values)): pair_sums.add(values[i] + values[j]) print(sorted(pair_sums, reverse=True)) # [14, 12, 8, 6] # ==================================================================== # Пример 6. Удаление элементов из списка — только с конца # ==================================================================== # 06_delete_from_end.py transactions = [(100, -50, -30), (-200, 100, 50), (-50, -50)] print("Суммы:", [sum(t) for t in transactions]) # Суммы: [20, -50, -100] correct = transactions.copy() for index in range(len(correct) - 1, -1, -1): if sum(correct[index]) < 0: del correct[index] print("После очистки:", correct) # После очистки: [(100, -50, -30)] # ==================================================================== # Пример 7. Список внутри кортежа остаётся изменяемым # ==================================================================== # 07_mutable_in_tuple.py employees = [ ("Alice", ["Review documents", "Call clients"]), ("Bob", ["Check emails"]), ] name, tasks = employees[0] tasks.append("Prepare presentation") print(employees) # [('Alice', ['Review documents', 'Call clients', 'Prepare presentation']), ('Bob', ['Check emails'])] try: employees[0][0] = "Carol" except TypeError as error: print("TypeError:", error) # TypeError: 'tuple' object does not support item assignment # ==================================================================== # Пример 8. Проверка подпоследовательности указателем # ==================================================================== # 08_subsequence.py digits = ["3", "6", "3", "2", "9", "3", "9", "4", "3", "9", "0"] sequence = "943" position = 0 for digit in digits: if position < len(sequence) and digit == sequence[position]: position += 1 print("Последовательность найдена:", position == len(sequence)) # Последовательность найдена: True sequence2 = "900" # в digits только один символ "0" (в самом конце) — второй "0" найти негде position2 = 0 for digit in digits: if position2 < len(sequence2) and digit == sequence2[position2]: position2 += 1 print("Последовательность найдена:", position2 == len(sequence2)) # Последовательность найдена: False # ==================================================================== # Пример 9. Коды символов: ord(), chr() и сдвиг # ==================================================================== # 09_ascii_cipher.py shift = 3 message = "Python" encoded = [ord(char) + shift for char in message] print("Коды со сдвигом:", encoded) # Коды со сдвигом: [83, 124, 119, 107, 114, 113] decoded = "".join(chr(code - shift) for code in encoded) print("Расшифровано:", decoded) # Расшифровано: Python