├── README.md
├── python_basics_2.1.md
├── python_basics_2.2.md
├── python_basics_2.3.md
├── python_basics_2.4.md
├── python_basics_3.1.md
├── python_basics_3.2.md
├── python_basics_3.3.md
├── python_basics_3.4.md
├── python_basics_3.5.md
├── python_basics_4.1.md
├── python_basics_4.2.md
├── python_basics_4.3.md
├── python_basics_5.1.md
├── python_basics_5.2.md
├── python_basics_5.3.md
├── python_basics_6.1.md
├── python_basics_6.2.md
└── python_basics_6.3.md
/README.md:
--------------------------------------------------------------------------------
1 | # Yandex handbook "Python Basics" keys
2 | 
3 |
4 | Ответы, решения, ключи к задачам глав хэндбука "Основы Python" от Яндекса. Решены все 260 задач.
5 |
6 | Answers, solutions, keys to the tasks of the chapters of the handbook "Python Basics" from Yandex.
7 |
8 |
9 | ### Раскрывающиеся списки заданий со ссылками на их решение по каждой главе:
10 |
11 | 2.1.
12 | Ввод и вывод данных. Операции с числами, строками. Форматирование
13 |
14 | [Решения 2.1](https://github.com/Pavellver/Yandex_handbook_answers/blob/main/python_basics_2.1.md)
15 | ```
16 | A. Привет, Яндекс!
17 | B. Привет, всем!
18 | C. Излишняя автоматизация
19 | D. Сдача
20 | E. Магазин
21 | F. Чек
22 | G. Делу — время, потехе — час
23 | H. Наказание
24 | I. Деловая колбаса
25 | J. Детский сад — штаны на лямках
26 | K. Автоматизация игры
27 | L. Интересное сложение
28 | M. Дед Мороз и конфеты
29 | N. Шарики и ручки
30 | O. В ожидании доставки
31 | P. Доставка
32 | Q. Ошибка кассового аппарата
33 | R. Сдача 10
34 | S. Украшение чека
35 | T. Мухи отдельно, котлеты отдельно
36 | ```
37 |
38 |
39 | 2.2.
40 | Условный оператор
41 |
42 | [Решения 2.2](https://github.com/Pavellver/Yandex_handbook_answers/blob/main/python_basics_2.2.md)
43 |
44 | ```
45 | A. Просто здравствуй, просто как дела
46 | B. Кто быстрее?
47 | C. Кто быстрее на этот раз?
48 | D. Список победителей
49 | E. Яблоки
50 | F. Сила прокрастинации
51 | G. А роза упала на лапу Азора
52 | H. Зайка — 1
53 | I. Первому игроку приготовиться
54 | J. Лучшая защита — шифрование
55 | K. Красота спасёт мир
56 | L. Музыкальный инструмент
57 | M. Властелин Чисел: Братство общей цифры
58 | N. Властелин Чисел: Две Башни
59 | O. Властелин Чисел: Возвращение Цезаря
60 | P. Легенды велогонок возвращаются: кто быстрее?
61 | Q. Корень зла
62 | R. Территория зла
63 | S. Автоматизация безопасности
64 | T. Зайка — 2
65 | ```
66 |
67 |
68 | 2.3.
69 | Циклы
70 |
71 | [Решения 2.3](https://github.com/Pavellver/Yandex_handbook_answers/blob/main/python_basics_2.3.md)
72 | ```
73 | A. Раз, два, три! Ёлочка, гори!
74 | B. Зайка — 3
75 | C. Считалочка
76 | D. Считалочка 2.0
77 | E. Внимание! Акция!
78 | F. НОД
79 | G. НОК
80 | H. Излишняя автоматизация 2.0
81 | I. Факториал
82 | J. Маршрут построен
83 | K. Цифровая сумма
84 | L. Сильная цифра
85 | M. Первому игроку приготовиться 2.0
86 | N. Простая задача
87 | O. Зайка - 4
88 | P. А роза упала на лапу Азора 2.0
89 | Q. Чётная чистота
90 | R. Простая задача 2.0
91 | S. Игра в «Угадайку»
92 | T. Хайпанём немножечко!
93 | ```
94 |
95 |
96 | 2.4.
97 | Вложенные циклы
98 |
99 | [Решения 2.4](https://github.com/Pavellver/Yandex_handbook_answers/blob/main/python_basics_2.4.md)
100 | ```
101 | A. Таблица умножения
102 | B. Не таблица умножения
103 | C. Новогоднее настроение
104 | D. Суммарная сумма
105 | E. Зайка — 5
106 | F. НОД 2.0
107 | G. На старт! Внимание! Марш!
108 | H. Максимальная сумма
109 | I. Большое число
110 | J. Мы делили апельсин
111 | K. Простая задача 3.0
112 | L. Числовой прямоугольник
113 | M. Числовой прямоугольник 2.0
114 | N. Числовая змейка
115 | O. Числовая змейка 2.0
116 | P. Редизайн таблицы умножения
117 | Q. А роза упала на лапу Азора 3.0
118 | R. Новогоднее настроение 2.0
119 | S. Числовой квадрат
120 | T. Математическая выгода
121 | ```
122 |
123 |
124 | 3.1.
125 | Строки, кортежи, списки
126 |
127 | [Решения 3.1](https://github.com/Pavellver/Yandex_handbook_answers/blob/main/python_basics_3.1.md)
128 | ```
129 | A. Азбука
130 | B. Кручу-верчу
131 | C. Анонс новости
132 | D. Очистка данных
133 | E. А роза упала на лапу Азора 4.0
134 | F. Зайка — 6
135 | G. А и Б сидели на трубе
136 | H. Зайка — 7
137 | I. Без комментариев
138 | J. Частотный анализ на минималках
139 | K. Найдётся всё
140 | L. Меню питания
141 | M. Массовое возведение в степень
142 | N. Массовое возведение в степень 2.0
143 | O. НОД 3.0
144 | P. Анонс новости 2.0
145 | Q. А роза упала на лапу Азора 5.0
146 | R. RLE
147 | S. Польский калькулятор
148 | T. Польский калькулятор — 2
149 | ```
150 |
151 |
152 | 3.2.
153 | Множества, словари
154 |
155 | [Решения 3.2](https://github.com/Pavellver/Yandex_handbook_answers/blob/main/python_basics_3.2.md)
156 | ```
157 | A. Символическая выжимка
158 | B. Символическая разница
159 | C. Зайка — 8
160 | D. Кашееды
161 | E. Кашееды — 2
162 | F. Кашееды — 3
163 | G. Азбука Морзе
164 | H. Кашееды — 4
165 | I. Зайка — 9
166 | J. Транслитерация
167 | K. Однофамильцы
168 | L. Однофамильцы — 2
169 | M. Дайте чего-нибудь новенького!
170 | N. Это будет шедевр!
171 | O. Двоичная статистика!
172 | P. Зайка — 10
173 | Q. Друзья друзей
174 | R. Карта сокровищ
175 | S. Частная собственность
176 | T. Простая задача 4.0
177 | ```
178 |
179 |
180 | 3.3.
181 | Списочные выражения. Модель памяти для типов языка Python
182 |
183 | [Решения 3.3](https://github.com/Pavellver/Yandex_handbook_answers/blob/main/python_basics_3.3.md)
184 | ```
185 | A. Список квадратов
186 | B. Таблица умножения 2.0
187 | C. Длины всех слов
188 | D. Множество нечетных чисел
189 | E. Множество всех полных квадратов
190 | F. Буквенная статистика
191 | G. Делители
192 | H. Аббревиатура
193 | I. Преобразование в строку
194 | J. RLE наоборот
195 | ```
196 |
197 |
198 | 3.4.
199 | Встроенные возможности по работе с коллекциями
200 |
201 | [Решения 3.4](https://github.com/Pavellver/Yandex_handbook_answers/blob/main/python_basics_3.4.md)
202 | ```
203 | A. Автоматизация списка
204 | B. Сборы на прогулку
205 | C. Рациональная считалочка
206 | D. Словарная ёлка
207 | E. Список покупок
208 | F. Колода карт
209 | G. Игровая сетка
210 | H. Меню питания 2.0
211 | I. Таблица умножения 3.0
212 | J. Мы делили апельсин 2.0
213 | K. Числовой прямоугольник 3.0
214 | L. Список покупок 2.0
215 | M. Расстановка спортсменов
216 | N. Спортивные гадания
217 | O. Список покупок 3.0
218 | P. Расклад таков...
219 | Q. А есть ещё варианты?
220 | R. Таблица истинности
221 | S. Таблица истинности 2
222 | T. Таблицы истинности 3 (Таблица истинности 3)
223 | ```
224 |
225 |
226 | 3.5.
227 | Потоковый ввод/вывод. Работа с текстовыми файлами. JSON
228 |
229 | [Решения 3.5](https://github.com/Pavellver/Yandex_handbook_answers/blob/main/python_basics_3.5.md)
230 | ```
231 | A. A+B+...
232 | B. Средний рост
233 | C. Без комментариев 2.0
234 | D. Найдётся всё 2.0
235 | E. А роза упала на лапу Азора 6.0
236 | F. Транслитерация 2.0
237 | G. Файловая статистика
238 | H. Файловая разница
239 | I. Файловая чистка
240 | J. Хвост
241 | K. Файловая статистика 2.0
242 | L. Разделяй и властвуй
243 | M. Обновление данных
244 | N. Слияние данных
245 | O. Поставь себя на моё место
246 | P. Найдётся всё 3.0
247 | Q. Прятки
248 | R. Сколько вешать в байтах?
249 | S. Это будет наш секрет
250 | T. Файловая сумма
251 | ```
252 |
253 |
254 | 4.1.
255 | Функции. Области видимости. Передача параметров в функции
256 |
257 | [Решения 4.1](https://github.com/Pavellver/Yandex_handbook_answers/blob/main/python_basics_4.1.md)
258 | ```
259 | A. Функциональное приветствие
260 | B. Функциональный НОД
261 | C. Длина числа
262 | D. Имя of the month
263 | E. Числовая строка
264 | F. Модернизация системы вывода
265 | G. Шахматный «обед»
266 | H. А роза упала на лапу Азора 7.0
267 | I. Простая задача 5.0
268 | J. Слияние
269 | ```
270 |
271 |
272 | 4.2.
273 | Позиционные и именованные аргументы. Функции высших порядков. Лямбда-функции
274 |
275 | [Решения 4.2](https://github.com/Pavellver/Yandex_handbook_answers/blob/main/python_basics_4.2.md)
276 | ```
277 | A. Генератор списков
278 | B. Генератор матриц
279 | C. Функциональный нод 2.0
280 | D. Имя of the month 2.0
281 | E. Подготовка данных
282 | F. Кофейня
283 | G. В эфире рубрика «Эксперименты»
284 | H. Длинная сортировка
285 | I. Чётная фильтрация
286 | J. Ключевой секрет
287 | ```
288 |
289 |
290 | 4.3.
291 | Рекурсия. Декораторы. Генераторы
292 |
293 | [Решения 4.3](https://github.com/Pavellver/Yandex_handbook_answers/blob/main/python_basics_4.3.md)
294 | ```
295 | A. Рекурсивный сумматор
296 | B. Рекурсивный сумматор цифр
297 | C. Многочлен N-ой степени
298 | D. Декор результата
299 | E. Накопление результата
300 | F. Сортировка слиянием
301 | G. Однотипность не порок
302 | H. Генератор Фибоначчи
303 | I. Циклический генератор
304 | J. "Выпрямление" списка
305 | ```
306 |
307 |
308 | 5.1.
309 | Объектная модель Python. Классы, поля и методы
310 |
311 | [Решения 5.1](https://github.com/Pavellver/Yandex_handbook_answers/blob/main/python_basics_5.1.md)
312 | ```
313 | A. Классная точка
314 | B. Классная точка 2.0
315 | C. Не нажимай красную кнопку!
316 | D. Работа не волк
317 | E. Классный прямоугольник
318 | F. Классный прямоугольник 2.0
319 | G. Классный прямоугольник 3.0
320 | H. Шашки
321 | I. Очередь
322 | J. Стек
323 | ```
324 |
325 |
326 | 5.2.
327 | Волшебные методы, переопределение методов. Наследование
328 |
329 | [Решения 5.2](https://github.com/Pavellver/Yandex_handbook_answers/blob/main/python_basics_5.2.md)
330 | ```
331 | A. Классная точка 3.0
332 | B. Классная точка 4.0
333 | C. Классная точка 5.0
334 | D. Дроби v0.1
335 | E. Дроби v0.2
336 | F. Дроби v0.3
337 | G. Дроби v0.4
338 | H. Дроби v0.5
339 | I. Дроби v0.6
340 | J. Дроби v0.7
341 | ```
342 |
343 |
344 | 5.3.
345 | Модель исключений Python. Try, except, else, finally. Модули
346 |
347 | [Решения 5.3](https://github.com/Pavellver/Yandex_handbook_answers/blob/main/python_basics_5.3.md)
348 | ```
349 | A. Обработка ошибок
350 | C. Ломать — не строить 2
351 | D. Контроль параметров
352 | E. Слияние с проверкой
353 | F. Корень зла 2
354 | G. Валидация имени
355 | H. Валидация имени пользователя
356 | I. Валидация пользователя
357 | J. Валидация пароля
358 | ```
359 |
360 |
361 | 6.1.
362 | Модули math и numpy
363 |
364 | [Решения 6.1](https://github.com/Pavellver/Yandex_handbook_answers/blob/main/python_basics_6.1.md)
365 | ```
366 | A. Математика — круто, но это не точно
367 | B. Потоковый НОД
368 | C. Есть варианты?
369 | D. Среднее не арифметическое
370 | E. Шаг навстречу
371 | F. Матрица умножения
372 | G. Шахматная подготовка
373 | H. Числовая змейка 3.0
374 | I. Вращение
375 | J. Лесенка
376 | ```
377 |
378 |
379 | 6.2.
380 | Модуль pandas
381 |
382 | [Решения 6.2](https://github.com/Pavellver/Yandex_handbook_answers/blob/main/python_basics_6.2.md)
383 | ```
384 | A. Длины всех слов - 2
385 | B. Длины всех слов по чётности
386 | C. Чек - 2
387 | D. Акция
388 | E. Длинные слова
389 | F. Отчёт успеваемости
390 | G. Отчёт неуспеваемости
391 | H. Обновление журнала
392 | I. Бесконечный морской бой
393 | J. Экстремум функции
394 | ```
395 |
396 |
397 | 6.3.
398 | Модуль requests
399 |
400 | [Решения 6.3](https://github.com/Pavellver/Yandex_handbook_answers/blob/main/python_basics_6.3.md)
401 | ```
402 | A. Проверка системы
403 | B. Суммирование ответов
404 | C. Суммирование ответов 2
405 | D. Конкретное значение
406 | E. Суммирование ответов 3
407 | F. Список пользователей
408 | G. Рассылка сообщений
409 | H. Регистрация нового пользователя
410 | I. Изменение данных
411 | J. Удаление данных
412 | ```
413 |
414 |
--------------------------------------------------------------------------------
/python_basics_2.1.md:
--------------------------------------------------------------------------------
1 | # Yandex handbook "Python Basics" answers
2 |
3 | 2.1. Ввод и вывод данных. Операции с числами, строками. Форматирование
4 |
5 | A. Привет, Яндекс!
6 | ```python
7 | print("Привет, Яндекс!")
8 | ```
9 | B. Привет, всем!
10 | ```python
11 | print("Как Вас зовут?")
12 | print("Привет,", input())
13 | ```
14 | C. Излишняя автоматизация
15 | ```python
16 | print((input() + '\n') * 3)
17 | ```
18 | D. Сдача
19 | ```python
20 | print(int(int(input()) - 2.5 * 38))
21 | ```
22 | E. Магазин
23 | ```python
24 | price = int(input())
25 | weight = int(input())
26 | money = int(input())
27 | print(money - price * weight)
28 | ```
29 | F. Чек
30 | ```python
31 | item = input()
32 | price = int(input())
33 | weight = int(input())
34 | money = int(input())
35 | print('Чек', f'{item} - {weight}кг - {price}руб/кг', sep='\n')
36 | print(f'Итого: {int(price * weight)}руб')
37 | print(f'Внесено: {money}руб')
38 | print(f'Сдача: {int(money - price * weight)}руб')
39 | ```
40 | G. Делу — время, потехе — час
41 | ```python
42 | print(('Купи слона!' + '\n') * int(input()))
43 | ```
44 | H. Наказание
45 | ```python
46 | number = int(input())
47 | punish = input()
48 | print((f'Я больше никогда не буду писать "{punish}"!\n') * number)
49 | ```
50 | I. Деловая колбаса
51 | ```python
52 | print(int(input()) * int(input()) // 2)
53 | ```
54 | J. Детский сад — штаны на лямках
55 | ```python
56 | name = input()
57 | locker = input()
58 | print(f'Группа №{locker[0]}.')
59 | print(f'{locker[2]}. {name}.')
60 | print(f'Шкафчик: {locker}.')
61 | print(f'Кроватка: {locker[1]}.')
62 | ```
63 | K. Автоматизация игры
64 | ```python
65 | number = input()
66 | print(f'{number[1]}{number[0]}{number[3]}{number[2]}')
67 | ```
68 | L. Интересное сложение
69 | ```python
70 | num1 = list(map(int, input().rjust(3, '0')))
71 | num2 = list(map(int, input().rjust(3, '0')))
72 | num_0 = str((num1[0] + num2[0]) % 10)
73 | num_1 = str((num1[1] + num2[1]) % 10)
74 | num_2 = str((num1[2] + num2[2]) % 10)
75 | print((num_0 + num_1 + num_2).lstrip('0'))
76 | ```
77 | M. Дед Мороз и конфеты
78 | ```python
79 | children = int(input())
80 | candies = int(input())
81 | print(candies // children)
82 | print(candies % children)
83 | ```
84 | N. Шарики и ручки
85 | ```python
86 | red = int(input())
87 | green = int(input())
88 | blue = int(input())
89 | print(red + blue + 1)
90 | ```
91 | O. В ожидании доставки
92 | ```python
93 | hours = int(input())
94 | minutes = int(input())
95 | delivery_time = int(input())
96 | new_minutes = str((minutes + delivery_time) % 60)
97 | new_hours = str((hours + (minutes + delivery_time) // 60) % 24)
98 | print(f'{new_hours.rjust(2, "0")}:{new_minutes.rjust(2, "0")}')
99 | ```
100 | P. Доставка
101 | ```python
102 | stock = int(input())
103 | market = int(input())
104 | speed = int(input())
105 | time = abs(market - stock) / speed
106 | print(f'{time:.2f}')
107 | ```
108 | Q. Ошибка кассового аппарата
109 | ```python
110 | earnings = int(input())
111 | last = int(input(), 2)
112 | print(earnings + last)
113 | ```
114 | R. Сдача 10
115 | ```python
116 | cost = int(input(), 2)
117 | bill = int(input())
118 | print(bill - cost)
119 | ```
120 | S. Украшение чека
121 | ```python
122 | item, price, weight, money = input(), int(input()), int(input()), int(input())
123 | headings = ['Товар:', 'Цена:', 'Итого:', 'Внесено:', 'Сдача:']
124 | values = [item, f'{weight}кг * {price}руб/кг', f'{weight * price}руб', f'{money}руб', f'{money - weight * price}руб']
125 | print('Чек'.center(35, '='))
126 | for i in range(len(headings)):
127 | print(f"{headings[i] : <10}{values[i] : >25}")
128 | print('=' * 35)
129 | ```
130 | T. Мухи отдельно, котлеты отдельно
131 | ```python
132 | weight, price, price_1, price_2 = int(input()), int(input()), int(input()), int(input())
133 | weight_1 = int((price - price_2) * weight / (price_1 - price_2))
134 | weight_2 = weight - weight_1
135 | print(weight_1, weight_2)
136 | ```
137 |
--------------------------------------------------------------------------------
/python_basics_2.2.md:
--------------------------------------------------------------------------------
1 | # Yandex handbook "Python Basics" answers
2 |
3 | 2.2. Условный оператор
4 |
5 | A. Просто здравствуй, просто как дела
6 | ```python
7 | name, status = input(), input()
8 | print('Как Вас зовут?', f'Здравствуйте, {name}!', 'Как дела?', sep='\n')
9 | if status == 'хорошо':
10 | print('Я за вас рада!')
11 | else:
12 | print('Всё наладится!')
13 | ```
14 | B. Кто быстрее?
15 | ```python
16 | petya_speed, vasya_speed = int(input()), int(input())
17 | if petya_speed > vasya_speed:
18 | print('Петя')
19 | else:
20 | print('Вася')
21 | ```
22 | C. Кто быстрее на этот раз?
23 | ```python
24 | petya_speed, vasya_speed, tolya_speed = int(input()), int(input()), int(input())
25 | winner_speed = max(petya_speed, vasya_speed, tolya_speed)
26 | if winner_speed == petya_speed:
27 | print('Петя')
28 | elif winner_speed == tolya_speed:
29 | print('Толя')
30 | else:
31 | print('Вася')
32 | ```
33 | D. Список победителей
34 | ```python
35 | petya_speed, vasya_speed, tolya_speed = int(input()), int(input()), int(input())
36 | winner_speed = max(petya_speed, vasya_speed, tolya_speed)
37 | loser_speed = min(petya_speed, vasya_speed, tolya_speed)
38 | if winner_speed == petya_speed:
39 | winner = 'Петя'
40 | if loser_speed == tolya_speed:
41 | loser, second = 'Толя', 'Вася'
42 | else:
43 | loser, second = 'Вася', 'Толя'
44 | elif winner_speed == tolya_speed:
45 | winner = 'Толя'
46 | if loser_speed == petya_speed:
47 | loser, second = 'Петя', 'Вася'
48 | else:
49 | loser, second = 'Вася', 'Петя'
50 | else:
51 | winner = 'Вася'
52 | if loser_speed == tolya_speed:
53 | loser, second = 'Толя', 'Петя'
54 | else:
55 | loser, second = 'Петя', 'Толя'
56 | for place in range(1, 4):
57 | print(f'{place}. {(winner, second, loser)[place-1]}')
58 | ```
59 | E. Яблоки
60 | ```python
61 | petya_apples, vasya_apples = int(input()), int(input())
62 | if vasya_apples + 3 > petya_apples:
63 | print('Вася')
64 | else:
65 | print('Петя')
66 | ```
67 | F. Сила прокрастинации
68 | ```python
69 | year = int(input())
70 | if year % 4 or not year % 100 and year % 400:
71 | print('NO')
72 | else:
73 | print('YES')
74 | ```
75 | G. А роза упала на лапу Азора
76 | ```python
77 | number = input()
78 | print('YES') if number == number[::-1] else print('NO')
79 | ```
80 | H. Зайка — 1
81 | ```python
82 | forest = input()
83 | print('YES') if 'зайка' in forest else print('NO')
84 | ```
85 | I. Первому игроку приготовиться
86 | ```python
87 | names = input(), input(), input()
88 | print(min(names))
89 | ```
90 | J. Лучшая защита — шифрование
91 | ```python
92 | number = input()
93 | first = int(number[0]) + int(number[1])
94 | second = int(number[1]) + int(number[2])
95 | print(str(first) + str(second)) if first > second else print(str(second) + str(first))
96 | ```
97 | K. Красота спасёт мир
98 | ```python
99 | number = list(map(int, input()))
100 | first = max(number) + min(number)
101 | print('YES') if first == 2 * (sum(number) - first) else print('NO')
102 | ```
103 | L. Музыкальный инструмент
104 | ```python
105 | sides = int(input()), int(input()), int(input())
106 | print('YES') if 2 * max(sides) < sum(sides) else print('NO')
107 | ```
108 | M. Властелин Чисел: Братство общей цифры
109 | ```python
110 | elf, dwarf, human = input(), input(), input()
111 | if elf[0] == dwarf[0] == human[0]:
112 | print(elf[0])
113 | elif elf[1] == dwarf[1] == human[1]:
114 | print(elf[1])
115 | ```
116 | N. Властелин Чисел: Две Башни
117 | ```python
118 | number = list(map(int, input()))
119 | second = str(max(number)) + str(max(sorted(number)[:-1]))
120 | if number.count(0) == 1:
121 | first = str(min(sorted(number)[1:])) + str(min(number))
122 | elif number.count(0) == 2:
123 | first = second
124 | else:
125 | first = str(min(number)) + str(min(sorted(number)[1:]))
126 | second = str(max(number)) + str(max(sorted(number)[:-1]))
127 | print(first, second)
128 | ```
129 | O. Властелин Чисел: Возвращение Цезаря
130 | ```python
131 | number = list(map(int, (input() + input())))
132 | print(str(max(number)) + str((sum(number) - max(number) - min(number)) % 10) + str(min(number)))
133 | ```
134 | P. Легенды велогонок возвращаются: кто быстрее?
135 | ```python
136 | petya_speed, vasya_speed, tolya_speed = int(input()), int(input()), int(input())
137 | winner_speed = max(petya_speed, vasya_speed, tolya_speed)
138 | loser_speed = min(petya_speed, vasya_speed, tolya_speed)
139 | if winner_speed == petya_speed:
140 | winner = 'Петя'
141 | if loser_speed == tolya_speed:
142 | loser, second = 'Толя', 'Вася'
143 | else:
144 | loser, second = 'Вася', 'Толя'
145 | elif winner_speed == tolya_speed:
146 | winner = 'Толя'
147 | if loser_speed == petya_speed:
148 | loser, second = 'Петя', 'Вася'
149 | else:
150 | loser, second = 'Вася', 'Петя'
151 | else:
152 | winner = 'Вася'
153 | if loser_speed == tolya_speed:
154 | loser, second = 'Толя', 'Петя'
155 | else:
156 | loser, second = 'Петя', 'Толя'
157 | print(f'{"": ^8}{winner: ^8}{"": ^8}')
158 | print(f'{second: ^8}{"": ^8}{"": ^8}')
159 | print(f'{"": ^8}{"": ^8}{loser: ^8}')
160 | print(f'{"II": ^8}{"I": ^8}{"III": ^8}')
161 | ```
162 | Q. Корень зла
163 | ```python
164 | a, b, c = float(input()), float(input()), float(input())
165 | if not a and not b and not c:
166 | print('Infinite solutions')
167 | elif not a and not b and c or b ** 2 < 4 * a * c:
168 | print('No solution')
169 | elif b ** 2 == 4 * a * c:
170 | print(f'{-b / (2 * a):.2f}')
171 | elif not a:
172 | print(f'{-c / b:.2f}')
173 | else:
174 | roots = [(-b - (b ** 2 - 4 * a * c) ** 0.5) / (2 * a), (-b + (b ** 2 - 4 * a * c) ** 0.5) / (2 * a)]
175 | roots.sort()
176 | print(f'{roots[0]:.2f} {roots[1]:.2f}')
177 | ```
178 | R. Территория зла
179 | ```python
180 | sides = [int(input()), int(input()), int(input())]
181 | sides.sort()
182 | if sides[2] ** 2 == sides[0] ** 2 + sides[1] ** 2:
183 | print('100%')
184 | elif sides[2] ** 2 > sides[0] ** 2 + sides[1] ** 2:
185 | print('велика')
186 | else:
187 | print('крайне мала')
188 | ```
189 | S. Автоматизация безопасности
190 | ```python
191 | x, y = float(input()), float(input())
192 | if (x ** 2 + y ** 2) ** 0.5 > 10:
193 | print('Вы вышли в море и рискуете быть съеденным акулой!')
194 | elif x >= 0 and y >= 0 and (x ** 2 + y ** 2) ** 0.5 <= 5:
195 | print('Опасность! Покиньте зону как можно скорее!')
196 | elif -4 <= x < 0 and 5 >= y >= 0:
197 | print('Опасность! Покиньте зону как можно скорее!')
198 | elif -7 <= x < -4 and 5 >= y >= 0 and 5 * x - 3 * y > -35:
199 | print('Опасность! Покиньте зону как можно скорее!')
200 | elif 0.25 * x ** 2 + 0.5 * x - 8.75 <= y <= 0:
201 | print('Опасность! Покиньте зону как можно скорее!')
202 | else:
203 | print('Зона безопасна. Продолжайте работу.')
204 | ```
205 | T. Зайка — 2
206 | ```python
207 | places = [input(), input(), input()]
208 | places.sort()
209 | for place in places:
210 | if 'зайка' in place:
211 | print(place, len(place))
212 | break
213 | ```
214 |
--------------------------------------------------------------------------------
/python_basics_2.3.md:
--------------------------------------------------------------------------------
1 | # Yandex handbook "Python Basics" answers
2 |
3 | 2.3. Циклы
4 |
5 | A. Раз, два, три! Ёлочка, гори!
6 | ```python
7 | while input() != 'Три!':
8 | print('Режим ожидания...')
9 | print('Ёлочка, гори!')
10 | ```
11 | B. Зайка — 3
12 | ```python
13 | counter = 0
14 | while (x := input()) != 'Приехали!':
15 | if 'зайка' in x:
16 | counter += 1
17 | print(counter)
18 | ```
19 | C. Считалочка
20 | ```python
21 | a, b = int(input()), int(input())
22 | for i in range(a, b + 1):
23 | print(i, end=' ')
24 | ```
25 | D. Считалочка 2.0
26 | ```python
27 | a, b = int(input()), int(input())
28 | if a < b:
29 | for i in range(a, b + 1):
30 | print(i, end=' ')
31 | else:
32 | for i in range(a, b - 1, -1):
33 | print(i, end=' ')
34 | ```
35 | E. Внимание! Акция!
36 | ```python
37 | counter = 0
38 | while (x := input()) != '0':
39 | if float(x) >= 500:
40 | counter += 0.9 * float(x)
41 | else:
42 | counter += float(x)
43 | print(counter)
44 | ```
45 | F. НОД
46 | ```python
47 | a, b = int(input()), int(input())
48 | while b:
49 | a, b = b, a % b
50 | print(a)
51 | ```
52 | G. НОК
53 | ```python
54 | a, b = c, d = int(input()), int(input())
55 | while b:
56 | a, b = b, a % b
57 | print(c * d // a)
58 | ```
59 | H. Излишняя автоматизация 2.0
60 | ```python
61 | line, number = input(), int(input())
62 | for _ in range(number):
63 | print(line)
64 | ```
65 | I. Факториал
66 | ```python
67 | a = int(input())
68 | factorial = 1
69 | for i in range(1, a + 1):
70 | factorial *= i
71 | print(factorial)
72 | ```
73 | J. Маршрут построен
74 | ```python
75 | x, y = 0, 0
76 | while (direction := input()) != 'СТОП':
77 | n = int(input())
78 | if direction == 'ВОСТОК':
79 | x += n
80 | elif direction == 'ЗАПАД':
81 | x -= n
82 | elif direction == 'СЕВЕР':
83 | y += n
84 | elif direction == 'ЮГ':
85 | y -= n
86 | print(y, x, sep='\n')
87 | ```
88 | K. Цифровая сумма
89 | ```python
90 | print(sum(map(int, input())))
91 | ```
92 | L. Сильная цифра
93 | ```python
94 | print(max(map(int, input())))
95 | ```
96 | M. Первому игроку приготовиться 2.0
97 | ```python
98 | n, first = int(input()), input()
99 | for _ in range(n - 1):
100 | first = min(first, input())
101 | print(first)
102 | ```
103 | N. Простая задача
104 | ```python
105 | n = int(input())
106 | i, result = 2, 'YES'
107 | if n > 1:
108 | while n % i:
109 | if i > n ** 0.5:
110 | break
111 | i += 1
112 | else:
113 | result = 'NO'
114 | else:
115 | result = 'NO'
116 | print(result)
117 | ```
118 | O. Зайка - 4
119 | ```python
120 | counter = 0
121 | for _ in range(int(input())):
122 | if 'зайка' in input():
123 | counter += 1
124 | print(counter)
125 | ```
126 | P. А роза упала на лапу Азора 2.0
127 | ```python
128 | print('YES') if (x := input()) == x[::-1] else print('NO')
129 | ```
130 | Q. Чётная чистота
131 | ```python
132 | print(''.join(filter(lambda x: int(x) % 2, input())))
133 | ```
134 | R. Простая задача 2.0
135 | ```python
136 | n, result, i = int(input()), [], 1
137 | if n < 2:
138 | print(n)
139 | while n > 1:
140 | i += 1
141 | if not n % i:
142 | result.append(str(i))
143 | n //= i
144 | i = 1
145 | else:
146 | print(' * '.join(result))
147 | ```
148 | S. Игра в «Угадайку»
149 | ```python
150 | begin, end = 1, 1001
151 | print((begin + end) // 2)
152 | while (x := input()) != 'Угадал!':
153 | if x == 'Меньше':
154 | end = (begin + end) // 2
155 | print((begin + end) // 2)
156 | elif x == 'Больше':
157 | begin = (begin + end) // 2
158 | print((begin + end) // 2)
159 | print('=' * 35)
160 | ```
161 | T. Хайпанём немножечко!
162 | ```python
163 | result, hn1 = -1, 0
164 | for i in range(int(input())):
165 | b = int(input())
166 | h, r, m = b % 256, (b // 256) % 256, b // 256 ** 2
167 | t = ((m + r + hn1) * 37) % 256
168 | if t != h or h > 99:
169 | result = i
170 | break
171 | hn1 = h
172 | print(result)
173 | ```
174 |
--------------------------------------------------------------------------------
/python_basics_2.4.md:
--------------------------------------------------------------------------------
1 | # Yandex handbook "Python Basics" answers
2 |
3 | 2.4. Вложенные циклы
4 |
5 | A. Таблица умножения
6 | ```python
7 | for i in range(1, (x := int(input())) + 1):
8 | for j in range(1, x + 1):
9 | if j < x:
10 | print(i * j, end=' ')
11 | else:
12 | print(i * j)
13 | ```
14 | B. Не таблица умножения
15 | ```python
16 | for i in range(1, (x := int(input())) + 1):
17 | for j in range(1, x + 1):
18 | print(f'{j} * {i} = {i * j}')
19 | ```
20 | C. Новогоднее настроение
21 | ```python
22 | for z in range(1, x := int(input()) + 1):
23 | if z in (sum(range(i)) for i in range(x)):
24 | print(z)
25 | else:
26 | print(z, end=' ')
27 | ```
28 | D. Суммарная сумма
29 | ```python
30 | summ = 0
31 | for _ in range(int(input())):
32 | summ += sum(map(int, list(input())))
33 | print(summ)
34 | ```
35 | E. Зайка — 5
36 | ```python
37 | counter, temp = 0, 0
38 | for _ in range(int(input())):
39 | while (x := input()) != 'ВСЁ':
40 | if x == 'зайка':
41 | temp += 1
42 | if temp:
43 | counter += 1
44 | temp = 0
45 | print(counter)
46 | ```
47 | F. НОД 2.0
48 | ```python
49 | n, a = int(input()), int(input())
50 | for _ in range(n - 1):
51 | b = int(input())
52 | while b:
53 | a, b = b, a % b
54 | print(a)
55 | ```
56 | G. На старт! Внимание! Марш!
57 | ```python
58 | for i in range(int(input())):
59 | for j in range(3 + i, 0, -1):
60 | print(f'До старта {j} секунд(ы)')
61 | print(f'Старт {i + 1}!!!')
62 | ```
63 | H. Максимальная сумма
64 | ```python
65 | name, summ = '', 0
66 | for _ in range(int(input())):
67 | temp_name, temp_summ = input(), sum(map(int, input()))
68 | if temp_summ >= summ:
69 | name, summ = temp_name, temp_summ
70 | print(name)
71 | ```
72 | I. Большое число
73 | ```python
74 | number = ''
75 | for _ in range(int(input())):
76 | number += max(input())
77 | print(number)
78 | ```
79 | J. Мы делили апельсин
80 | ```python
81 | for i in range(1, (n := int(input())) - 1):
82 | if i == 1:
83 | print('А Б В')
84 | for j in range(1, n - i):
85 | print(f'{i} {j} {n - i - j}')
86 | ```
87 | K. Простая задача 3.0
88 | ```python
89 | counter = 0
90 | for i in range(int(input())):
91 | j = 2
92 | if (n := int(input())) > 1:
93 | counter += 1
94 | if n == 2:
95 | counter += 1
96 | while n % j:
97 | if j > n ** 0.5:
98 | break
99 | j += 1
100 | else:
101 | counter -= 1
102 | print(counter)
103 | ```
104 | L. Числовой прямоугольник
105 | ```python
106 | n, k = int(input()), int(input())
107 | width = len(str(n * k))
108 | for i in range(1, n + 1):
109 | for j in range(k * (i - 1) + 1, k * i + 1):
110 | if j == k * i:
111 | print(str(j).rjust(width, ' '))
112 | else:
113 | print(str(j).rjust(width, ' '), end=' ')
114 | ```
115 | M. Числовой прямоугольник 2.0
116 | ```python
117 | n, k = int(input()), int(input())
118 | width = len(str(n * k))
119 | for i in range(1, n + 1):
120 | for j in range(i, i + n * (k - 1) + 1, n):
121 | if j == i + n * (k - 1):
122 | print(str(j).rjust(width, ' '))
123 | else:
124 | print(str(j).rjust(width, ' '), end=' ')
125 | ```
126 | N. Числовая змейка
127 | ```python
128 | n, k = int(input()), int(input())
129 | width = len(str(n * k))
130 | for i in range(1, n + 1):
131 | if i % 2:
132 | for j in range(k * (i - 1) + 1, k * i + 1):
133 | if j == k * i:
134 | print(str(j).rjust(width, ' '))
135 | else:
136 | print(str(j).rjust(width, ' '), end=' ')
137 | else:
138 | for j in range(k * i, k * (i - 1), -1):
139 | if j == k * (i - 1) + 1:
140 | print(str(j).rjust(width, ' '))
141 | else:
142 | print(str(j).rjust(width, ' '), end=' ')
143 | ```
144 | O. Числовая змейка 2.0
145 | ```python
146 | n, k = int(input()), int(input())
147 | width = len(str(n * k))
148 | for i in range(1, n + 1):
149 | for j in range(k):
150 | if not j % 2 and j != k - 1:
151 | print(str(i + 2 * n * (j // 2)).rjust(width, ' '), end=' ')
152 | elif not j % 2 and j == k - 1:
153 | print(str(i + 2 * n * (j // 2)).rjust(width, ' '))
154 | elif j % 2 and j != k - 1:
155 | print(str(2 * n * (j // 2 + 1) - (i - 1)).rjust(width, ' '), end=' ')
156 | else:
157 | print(str(2 * n * (j // 2 + 1) - (i - 1)).rjust(width, ' '))
158 | ```
159 | P. Редизайн таблицы умножения
160 | ```python
161 | a, b = int(input()), int(input())
162 | for i in range(1, a + 1):
163 | for j in range(1, a + 1):
164 | if j != a:
165 | print(f'{(str(i * j) + " " if b % 2 else str(i * j)).center(b)}|', end='')
166 | else:
167 | print(f'{(str(i * j) + " " if b % 2 else str(i * j)).center(b)}')
168 | if i * j != a * a:
169 | print(f'{"-"* ((b + 1) * a - 1)}')
170 | ```
171 | Q. А роза упала на лапу Азора 3.0
172 | ```python
173 | counter = 0
174 | for _ in range(int(input())):
175 | if (n := input()) == n[::-1]:
176 | counter += 1
177 | print(counter)
178 | ```
179 | R. Новогоднее настроение 2.0
180 | ```python
181 | g, lengths = '', [0]
182 | for j in range(1, (x := int(input())) + 1):
183 | g += str(j) + ' '
184 | if j in (sum(range(i)) for i in range(j + 2)):
185 | lengths.append(len(g) - 1)
186 | g = ''
187 | lengths.append(len(g) - 1)
188 | d = 1
189 | for z in range(1, x + 1):
190 | if z - 1 in (sum(range(i)) for i in range(z + 2)):
191 | print(f"{' ' * ((max(lengths) - lengths[d]) // 2)}{z}", end=' ' if z != 1 else '\n')
192 | d += 1
193 | else:
194 | print(z, end='\n' if z in (sum(range(i)) for i in range(z + 2)) else ' ')
195 | ```
196 | S. Числовой квадрат
197 | ```python
198 | for i in range(n := int(input())):
199 | for j in range(n):
200 | d = str(min(i, j, n - i - 1, n - j - 1) + 1)
201 | print(d.rjust(len(str((n + 1) // 2)), ' '), end=' ' if j < n - 1 else '\n')
202 | print('=' * 35)
203 | ```
204 | T. Математическая выгода
205 | ```python
206 | def convert_from_base_to_base(num, from_base=10, to_base=10):
207 | n = int(num, from_base) if isinstance(num, str) else num
208 | alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
209 | result = ""
210 | while n > 0:
211 | n, m = divmod(n, to_base)
212 | result += alphabet[m]
213 | return result[::-1]
214 |
215 |
216 | number = input()
217 | max_benefit, best_base = 0, 0
218 | for base in range(2, 11):
219 | if (digits_sum := sum(map(int, convert_from_base_to_base(number, 10, base)))) > max_benefit:
220 | best_base = base
221 | max_benefit = digits_sum
222 | print(best_base)
223 | ```
224 |
--------------------------------------------------------------------------------
/python_basics_3.1.md:
--------------------------------------------------------------------------------
1 | # Yandex handbook "Python Basics" answers
2 |
3 | 3.1. Строки, кортежи, списки
4 |
5 | A. Азбука
6 | ```python
7 | for _ in range(int(input())):
8 | if (word := input())[0] not in 'абв':
9 | print('NO')
10 | break
11 | else:
12 | print('YES')
13 | ```
14 | B. Кручу-верчу
15 | ```python
16 | for i in input():
17 | print(i)
18 | ```
19 | C. Анонс новости
20 | ```python
21 | length = int(input())
22 | for _ in range(int(input())):
23 | line = input()
24 | print(line[:length - 3].ljust(length, ".") if len(line) > length else line)
25 | ```
26 | D. Очистка данных
27 | ```python
28 | while (n := input()):
29 | if not n.endswith('@@@'):
30 | if n.startswith('##'):
31 | print(n[2:])
32 | else:
33 | print(n)
34 | ```
35 | E. А роза упала на лапу Азора 4.0
36 | ```python
37 | print('YES' if (line := input()) == line[::-1] else 'NO')
38 | ```
39 | F. Зайка — 6
40 | ```python
41 | counter = 0
42 | for _ in range(int(input())):
43 | counter += input().count("зайка")
44 | print(counter)
45 | ```
46 | G. А и Б сидели на трубе
47 | ```python
48 | print(sum(map(int, input().split())))
49 | ```
50 | H. Зайка — 7
51 | ```python
52 | for _ in range(int(input())):
53 | if "зайка" in (place := input()):
54 | print(place.index("зайка") + 1)
55 | else:
56 | print("Заек нет =(")
57 | ```
58 | I. Без комментариев
59 | ```python
60 | while (n := input()):
61 | if not n.startswith('#'):
62 | print(n[:(n.index('#') if '#' in n else len(n))])
63 | ```
64 | J. Частотный анализ на минималках
65 | ```python
66 | data = []
67 | while (n := input()) != 'ФИНИШ':
68 | data.extend(n.lower().split())
69 | max_count, data = 0, ''.join(data)
70 | for symbol in set(data):
71 | max_count = max(max_count, data.count(symbol))
72 | print(min([i for i in set(data) if data.count(i) == max_count]))
73 | ```
74 | K. Найдётся всё
75 | ```python
76 | headings = []
77 | for _ in range(int(input())):
78 | headings.append(input())
79 | word = input()
80 | for heading in headings:
81 | if word.lower() in heading.lower():
82 | print(heading)
83 | ```
84 | L. Меню питания
85 | ```python
86 | order = ('Манная', 'Гречневая', 'Пшённая', 'Овсяная', 'Рисовая')
87 | for i in range(int(input())):
88 | print(order[i % len(order)])
89 | ```
90 | M. Массовое возведение в степень
91 | ```python
92 | data = []
93 | for _ in range(int(input())):
94 | data.append(int(input()))
95 | number = int(input())
96 | for i in data:
97 | print(i ** number)
98 | ```
99 | N. Массовое возведение в степень 2.0
100 | ```python
101 | data = list(map(int, input().split()))
102 | number = int(input())
103 | for i in data:
104 | print(i ** number, end=' ')
105 | ```
106 | O. НОД 3.0
107 | ```python
108 | numbers = list(map(int, input().split()))
109 | a = numbers[0]
110 | while len(numbers) > 1:
111 | b = numbers[1]
112 | while b:
113 | a, b = b, a % b
114 | numbers.pop(1)
115 | print(a)
116 | ```
117 | P. Анонс новости 2.0
118 | ```python
119 | length, line = int(input()), []
120 | for _ in range(int(input())):
121 | line.append(input())
122 | for i in line:
123 | if length > 3:
124 | print(i[:length - 3] + "..." if len(i) >= length - 3 else (i + "..." if length == 4 else i))
125 | length -= len(i)
126 | ```
127 | Q. А роза упала на лапу Азора 5.0
128 | ```python
129 | line = ''.join(input().lower().split())
130 | print('YES' if line == line[::-1] else 'NO')
131 | ```
132 | R. RLE
133 | ```python
134 | line = input()
135 | temp_line, repeat = line[0], 1
136 | for i in line[1:]:
137 | if i == temp_line:
138 | repeat += 1
139 | else:
140 | print(temp_line, repeat)
141 | temp_line, repeat = i, 1
142 | print(temp_line, repeat)
143 | ```
144 | S. Польский калькулятор
145 | ```python
146 | data = list(input().split())
147 | result = [int(data[0])]
148 | for i in data[1:]:
149 | if i.isdigit():
150 | result.append(int(i))
151 | else:
152 | a = result.pop()
153 | exec("result[-1] " + i + "= a")
154 | print(result[0])
155 | ```
156 | T. Польский калькулятор — 2
157 | ```python
158 | def factorial(n):
159 | return n * factorial(n - 1) if n > 1 else 1
160 |
161 |
162 | data = list(input().split())
163 | result = [int(data[0])]
164 | for i in data[1:]:
165 | if i.isdigit():
166 | result.append(int(i))
167 | elif i == "/":
168 | a = result.pop()
169 | result[-1] //= a
170 | elif i == "~":
171 | result[-1] = -result[-1]
172 | elif i == "#":
173 | result.append(result[-1])
174 | elif i == "!":
175 | result[-1] = factorial(result[-1])
176 | elif i == "@":
177 | result.append(result.pop(-3))
178 | else:
179 | a = result.pop()
180 | exec("result[-1] " + i + "= a")
181 | print(result[0])
182 | ```
183 |
--------------------------------------------------------------------------------
/python_basics_3.2.md:
--------------------------------------------------------------------------------
1 | # Yandex handbook "Python Basics" answers
2 |
3 | 3.2. Множества, словари
4 |
5 | A. Символическая выжимка
6 | ```python
7 | print(''.join(set(input())))
8 | ```
9 | B. Символическая разница
10 | ```python
11 | print(''.join(set(input()).intersection(set(input()))))
12 | ```
13 | C. Зайка — 8
14 | ```python
15 | objects = []
16 | for _ in range(int(input())):
17 | objects.extend(input().split())
18 | print('\n'.join(set(objects)))
19 | ```
20 | D. Кашееды
21 | ```python
22 | a, b = int(input()), int(input())
23 | semolina, oatmeal = set(), set()
24 | for _ in range(a):
25 | semolina.add(input())
26 | for _ in range(b):
27 | oatmeal.add(input())
28 | both = len(semolina & oatmeal)
29 | print(both if both else 'Таких нет')
30 | ```
31 | E. Кашееды — 2
32 | ```python
33 | a, b = int(input()), int(input())
34 | porridges = []
35 | for _ in range(a + b):
36 | porridges.append(input())
37 | both = len([i for i in porridges if porridges.count(i) == 1])
38 | print(both if both else 'Таких нет')
39 | ```
40 | F. Кашееды — 3
41 | ```python
42 | a, b = int(input()), int(input())
43 | porridges = []
44 | for _ in range(a + b):
45 | if (x := input()) not in porridges:
46 | porridges.append(x)
47 | else:
48 | porridges.remove(x)
49 | if len(porridges):
50 | for kid in sorted(porridges):
51 | print(kid)
52 | else:
53 | print('Таких нет')
54 | ```
55 | G. Азбука Морзе
56 | ```python
57 | MORSE = {
58 | 'A': '.-', 'B': '-...', 'C': '-.-.',
59 | 'D': '-..', 'E': '.', 'F': '..-.',
60 | 'G': '--.', 'H': '....', 'I': '..',
61 | 'J': '.---', 'K': '-.-', 'L': '.-..',
62 | 'M': '--', 'N': '-.', 'O': '---',
63 | 'P': '.--.', 'Q': '--.-', 'R': '.-.',
64 | 'S': '...', 'T': '-', 'U': '..-',
65 | 'V': '...-', 'W': '.--', 'X': '-..-',
66 | 'Y': '-.--', 'Z': '--..',
67 | '0': '-----', '1': '.----', '2': '..---',
68 | '3': '...--', '4': '....-', '5': '.....',
69 | '6': '-....', '7': '--...', '8': '---..',
70 | '9': '----.', ' ': ' ',
71 | }
72 | line = input()
73 | for letter in line:
74 | print(MORSE[letter.upper()], end=' ' if letter != ' ' else '\n')
75 | ```
76 | H. Кашееды — 4
77 | ```python
78 | a, kids = int(input()), []
79 | for _ in range(a):
80 | kids.extend([input().split()])
81 | kids.sort()
82 | key, counter = input(), 0
83 | for kid in kids:
84 | if key in kid[1:]:
85 | print(kid[0])
86 | counter += 1
87 | if not counter:
88 | print('Таких нет')
89 | ```
90 | I. Зайка — 9
91 | ```python
92 | d = {}
93 | while x := input().split():
94 | for i in x:
95 | if i not in d:
96 | d[i] = 1
97 | else:
98 | d[i] += 1
99 | for j in d:
100 | print(j, d[j])
101 | ```
102 | J. Транслитерация
103 | ```python
104 | LITER = {
105 | 'А': 'A', 'Б': 'B', 'В': 'V',
106 | 'Г': 'G', 'Д': 'D', 'Е': 'E',
107 | 'Ё': 'E', 'Ж': 'ZH', 'З': 'Z',
108 | 'И': 'I', 'Й': 'I', 'К': 'K',
109 | 'Л': 'L', 'М': 'M', 'Н': 'N',
110 | 'О': 'O', 'П': 'P', 'Р': 'R',
111 | 'С': 'S', 'Т': 'T', 'У': 'U',
112 | 'Ф': 'F', 'Х': 'KH', 'Ц': 'TC',
113 | 'Ч': 'CH', 'Ш': 'SH', 'Щ': 'SHCH',
114 | 'Ы': 'Y', 'Э': 'E', 'Ю': 'IU',
115 | 'Я': 'IA', 'Ь': '', 'Ъ': '',
116 | }
117 | for i in (x := input()):
118 | if i.upper() in LITER:
119 | print(LITER[i.upper()].lower().capitalize() if i == i.upper() else LITER[i.upper()].lower(), end='')
120 | else:
121 | print(i, end='')
122 | ```
123 | K. Однофамильцы
124 | ```python
125 | people = []
126 | for _ in range(int(input())):
127 | people.append(input())
128 | print(len([i for i in people if people.count(i) > 1]))
129 | ```
130 | L. Однофамильцы — 2
131 | ```python
132 | people = []
133 | for _ in range(int(input())):
134 | people.append(input())
135 | people = [i + ' - ' + str(people.count(i)) for i in set(people) if people.count(i) > 1]
136 | if people:
137 | for x in sorted(people):
138 | print(x)
139 | else:
140 | print('Однофамильцев нет')
141 | ```
142 | M. Дайте чего-нибудь новенького!
143 | ```python
144 | menu, new_menu = set(), set()
145 | for _ in range(int(input())):
146 | menu.add(input())
147 | for _ in range(int(input())):
148 | for j in range(int(input())):
149 | new_menu.add(input())
150 | diff = sorted(menu - new_menu)
151 | if diff:
152 | for dish in diff:
153 | print(dish)
154 | else:
155 | print('Готовить нечего')
156 | ```
157 | N. Это будет шедевр!
158 | ```python
159 | ingredients, dishes = [], set()
160 | for _ in range(int(input())):
161 | ingredients.append(input())
162 | for _ in range(int(input())):
163 | dishes.add(x := input())
164 | for i in range(int(input())):
165 | if input() not in ingredients:
166 | dishes.discard(x)
167 | if dishes:
168 | for dish in sorted(dishes):
169 | print(dish)
170 | else:
171 | print('Готовить нечего')
172 | ```
173 | O. Двоичная статистика!
174 | ```python
175 | data = []
176 | for i in list(map(lambda x: bin(int(x))[2:], input().split())):
177 | data.append({"digits": len(i),
178 | "units": i.count('1'),
179 | "zeros": i.count('0')})
180 | print(data)
181 | ```
182 | P. Зайка — 10
183 | ```python
184 | near = set()
185 | while x := input().split():
186 | for ind, i in enumerate(x):
187 | if i == 'зайка' and ind not in (0, len(x) - 1):
188 | near.add(x[ind - 1])
189 | near.add(x[ind + 1])
190 | elif i == 'зайка' and not ind:
191 | near.add(x[ind + 1])
192 | elif i == 'зайка' and ind == len(x) - 1:
193 | near.add(x[ind - 1])
194 | for item in near:
195 | print(item)
196 | ```
197 | Q. Друзья друзей
198 | ```python
199 | friends = {}
200 | while x := input().split():
201 | if x[0] not in friends:
202 | friends[x[0]] = {x[1]}
203 | else:
204 | friends[x[0]].add(x[1])
205 | if x[1] not in friends:
206 | friends[x[1]] = {x[0]}
207 | else:
208 | friends[x[1]].add(x[0])
209 | friends_2 = dict.fromkeys(friends, set())
210 | for friend in friends:
211 | for n in friends[friend]:
212 | friends_2[friend] = friends_2[friend].union(friends[n])
213 | friends_2[friend].discard(friend)
214 | for z in friends[friend]:
215 | friends_2[friend].discard(z)
216 | data = []
217 | for friend in friends_2:
218 | data.append(f'{friend}: {", ".join(sorted(friends_2[friend]))}')
219 | data.sort()
220 | for string in data:
221 | print(string)
222 | ```
223 | R. Карта сокровищ
224 | ```python
225 | d = {}
226 | for _ in range(int(input())):
227 | x = input().split()
228 | if not (z := f'{x[0][:-1]}-{x[1][:-1]}') in d:
229 | d[z] = 1
230 | else:
231 | d[z] += 1
232 | print(max(d.values()))
233 | ```
234 | S. Частная собственность
235 | ```python
236 | data = []
237 | for _ in range(int(input())):
238 | k = list(map(lambda x: x.rstrip(','), input().split()))
239 | data.extend(set(k[1:]))
240 | data = sorted(toy for toy in data if data.count(toy) == 1)
241 | for kid in data:
242 | print(kid)
243 | ```
244 | T. Простая задача 4.0
245 | ```python
246 | data = sorted(map(int, input().split('; ')))
247 | result = dict.fromkeys(data)
248 | for i in data:
249 | for j in data:
250 | a, b = i, j
251 | while b:
252 | a, b = b, a % b
253 | if a == 1:
254 | if result[i]:
255 | result[i].add(j)
256 | else:
257 | result[i] = {j}
258 | for number in result:
259 | if result[number]:
260 | print(f'{number} - {", ".join(map(str, sorted(result[number])))}')
261 | ```
262 |
--------------------------------------------------------------------------------
/python_basics_3.3.md:
--------------------------------------------------------------------------------
1 | # Yandex handbook "Python Basics" answers
2 |
3 | 3.3. Списочные выражения. Модель памяти для типов языка Python
4 |
5 | A. Список квадратов
6 | ```python
7 | [number ** 2 for number in range(a, b + 1)]
8 | ```
9 | B. Таблица умножения 2.0
10 | ```python
11 | [[i * j for i in range(1, n + 1)] for j in range(1, n + 1)]
12 | ```
13 | C. Длины всех слов
14 | ```python
15 | [len(word) for word in sentence.split()]
16 | ```
17 | D. Множество нечетных чисел
18 | ```python
19 | {number for number in numbers if number % 2}
20 | ```
21 | E. Множество всех полных квадратов
22 | ```python
23 | {number for number in numbers if number in [i ** 2 for i in range(1, int(max(numbers) ** 0.5 + 1))]}
24 | ```
25 | F. Буквенная статистика
26 | ```python
27 | {letter: text.lower().count(letter) for letter in text.lower() if letter.isalpha()}
28 | ```
29 | G. Делители
30 | ```python
31 | {number: [i for i in range(1, number + 1) if not number % i] for number in numbers}
32 | ```
33 | H. Аббревиатура
34 | ```python
35 | ''.join(word[0] for word in string.split()).upper()
36 | ```
37 | I. Преобразование в строку
38 | ```python
39 | ' - '.join(str(i) for i in sorted(set(numbers)))
40 | ```
41 | J. RLE наоборот
42 | ```python
43 | ''.join(i * j for i, j in rle)
44 | ```
45 |
--------------------------------------------------------------------------------
/python_basics_3.4.md:
--------------------------------------------------------------------------------
1 | # Yandex handbook "Python Basics" answers
2 |
3 | 3.4. Встроенные возможности по работе с коллекциями
4 |
5 | A. Автоматизация списка
6 | ```python
7 | for index, word in enumerate(input().split(), start=1):
8 | print(f'{index}. {word}')
9 | ```
10 | B. Сборы на прогулку
11 | ```python
12 | for kids in zip(a := input().split(', '), b := input().split(', ')):
13 | print(f'{kids[0]} - {kids[1]}')
14 | ```
15 | C. Рациональная считалочка
16 | ```python
17 | from itertools import count
18 |
19 | a, b, step = list(map(float, input().split()))
20 | for value in count(a, step):
21 | if value <= b:
22 | print(f'{value:.2f}')
23 | else:
24 | break
25 | ```
26 | D. Словарная ёлка
27 | ```python
28 | from itertools import accumulate
29 |
30 | for value in accumulate(map(lambda x: ' ' + x, input().split())):
31 | print(value[1:])
32 | ```
33 | E. Список покупок
34 | ```python
35 | items = set()
36 | for _ in range(3):
37 | items = items.union({item for item in input().split(', ')})
38 | for i, item in enumerate(sorted(items), start=1):
39 | print(f'{i}. {item}')
40 | ```
41 | F. Колода карт
42 | ```python
43 | from itertools import product
44 |
45 | nominal = [2, 3, 4, 5, 6, 7, 8, 9, 10, 'валет', 'дама', 'король', 'туз']
46 | suits = ['пик', 'треф', 'бубен', 'червей']
47 | suits.remove(input())
48 | for card in product(nominal, suits):
49 | print(card[0], card[1])
50 | ```
51 | G. Игровая сетка
52 | ```python
53 | from itertools import product
54 |
55 | players, games = [], []
56 | for _ in range(int(input())):
57 | players.append(input())
58 | for i in product(players, players):
59 | if i[0] != i[1] and [i[1], i[0]] not in games:
60 | games.append([i[0], i[1]])
61 | print(f'{i[0]} - {i[1]}')
62 | ```
63 | H. Меню питания 2.0
64 | ```python
65 | cereals = []
66 | for _ in range(int(input())):
67 | cereals.append(input())
68 | amount = int(input())
69 | cereals *= amount // len(cereals) + 1
70 | for i in range(amount):
71 | print(cereals[i])
72 | ```
73 | I. Таблица умножения 3.0
74 | ```python
75 | from itertools import product
76 |
77 | for i in (n := range(1, int(input()) + 1)):
78 | print(' '.join(map(lambda x: str(x[0] * x[1]), product(n, [i]))))
79 | ```
80 | J. Мы делили апельсин 2.0
81 | ```python
82 | for i in range(1, (n := int(input())) - 1):
83 | if i == 1:
84 | print('А Б В')
85 | for j in range(1, n - i):
86 | print(f'{i} {j} {n - i - j}')
87 | ```
88 | K. Числовой прямоугольник 3.0
89 | ```python
90 | from itertools import product
91 |
92 | n, m = int(input()), int(input())
93 | for i in range(n):
94 | line = product(range(1, m + 1), [i * m])
95 | print(' '.join(map(lambda x: str(sum(x)).rjust(len(str((n - 1 - i) * m + sum(x))), ' '), line)))
96 | ```
97 | L. Список покупок 2.0
98 | ```python
99 | items = []
100 | for _ in range(int(input())):
101 | items.extend([item for item in input().split(', ')])
102 | for i, item in enumerate(sorted(items), start=1):
103 | print(f'{i}. {item}')
104 | ```
105 | M. Расстановка спортсменов
106 | ```python
107 | from itertools import permutations
108 |
109 | items = []
110 | for _ in range(int(input())):
111 | items.append(input())
112 | for i in sorted(permutations(items)):
113 | print(', '.join(i))
114 | ```
115 | N. Спортивные гадания
116 | ```python
117 | from itertools import permutations
118 |
119 | items = []
120 | for _ in range(int(input())):
121 | items.append(input())
122 | for i in sorted(permutations(items, 3)):
123 | print(', '.join(i))
124 | ```
125 | O. Список покупок 3.0
126 | ```python
127 | from itertools import permutations
128 |
129 | items = []
130 | for _ in range(int(input())):
131 | items.extend([item for item in input().split(', ')])
132 | for item in sorted(permutations(items, 3)):
133 | print(' '.join(item))
134 | ```
135 | P. Расклад таков...
136 | ```python
137 | from itertools import product, permutations
138 |
139 | suits_ro = ["бубен", "пик", "треф", "червей"]
140 | suit, exception = input(), input()
141 | best_suit = [s for s in suits_ro if s.startswith(suit[0:3])][0]
142 | nominal = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "валет", "дама", "король", "туз"]
143 | nominal.remove(exception)
144 | comb = permutations(product(sorted(nominal), sorted(suits_ro)), 3)
145 | y = [', '.join(' '.join(j) for j in sorted(i)) for i in comb]
146 | triads = [i for i in y if best_suit in i][:10]
147 | for triad in triads:
148 | print(triad)
149 | ```
150 | Q. А есть ещё варианты?
151 | ```python
152 | from itertools import product, permutations
153 |
154 | suits_ro = sorted(["бубен", "пик", "треф", "червей"])
155 | suit, exception, situation = input(), input(), input()
156 | best_suit = [s for s in suits_ro if s.startswith(suit[0:3])][0]
157 | nominal = sorted(["2", "3", "4", "5", "6", "7", "8", "9", "10", "валет", "дама", "король", "туз"])
158 | nominal.remove(exception)
159 | comb = permutations(product(nominal, suits_ro), 3)
160 | y = sorted(set([', '.join(' '.join(j) for j in sorted(i)) for i in comb]))
161 | triads = [i for i in y if best_suit in i]
162 | for ind, triad in enumerate(triads):
163 | if triad == situation:
164 | print(triads[ind + 1])
165 | break
166 | ```
167 | R. Таблица истинности
168 | ```python
169 | x = input()
170 | print('a b c f')
171 | for i in range(8):
172 | values = list(bin(i)[2:].zfill(3))
173 | a, b, c = map(int, values)
174 | print(' '.join(values), int(eval(x)))
175 | ```
176 | S. Таблица истинности 2
177 | ```python
178 | x = input()
179 | args = sorted({i for i in x if i.isupper()})
180 | print(' '.join(args), 'F')
181 | for i in range(2 ** len(args)):
182 | values = list(bin(i)[2:].zfill(len(args)))
183 | exec(', '.join(args) + " = map(int, values)")
184 | print(' '.join(values), int(eval(x)))
185 | ```
186 | T. Таблицы истинности 3
187 | ```python
188 | from itertools import product
189 |
190 | OPERATORS = {
191 | 'not': 'not',
192 | 'and': 'and',
193 | 'or': 'or',
194 | '^': '!=',
195 | '->': '<=',
196 | '~': '==',
197 | }
198 |
199 | PRIORITY = {
200 | 'not': 0,
201 | 'and': 1,
202 | 'or': 2,
203 | '^': 3,
204 | '->': 4,
205 | '~': 5,
206 | '(': 6,
207 | }
208 |
209 |
210 | def postfix_expression(expression, variables):
211 | stack, result, lst = [], [], expression.split()
212 | for i in lst:
213 | if i in variables:
214 | result.append(i)
215 | elif i == '(':
216 | stack.append(i)
217 | elif i == ')':
218 | while stack[-1] != '(':
219 | result.append(OPERATORS[stack.pop()])
220 | stack.pop()
221 | elif i in OPERATORS.keys():
222 | while len(stack) and PRIORITY[i] >= PRIORITY[stack[-1]]:
223 | result.append(OPERATORS[stack.pop()])
224 | stack.append(i)
225 | for _ in range(len(stack)):
226 | result.append(OPERATORS[stack.pop()])
227 | return result
228 |
229 |
230 | def result_of_expression(postfix_exp, variables):
231 | stack = []
232 | for i in range(len(postfix_exp)):
233 | if postfix_exp[i] in variables.keys():
234 | stack.append(variables[postfix_exp[i]])
235 | else:
236 | if postfix_exp[i] == 'not':
237 | stack.append(not stack.pop())
238 | else:
239 | var2, var1 = stack.pop(), stack.pop()
240 | stack.append(eval(f'{var1} {postfix_exp[i]} {var2}'))
241 | return int(stack.pop())
242 |
243 |
244 | statement = input()
245 | var_all = sorted(set([i for i in statement if i.isupper()]))
246 | print(' '.join(var_all), 'F')
247 | table = product([0, 1], repeat=len(var_all))
248 | statement = statement.replace('(', '( ').replace(')', ' )')
249 | exp = postfix_expression(statement, var_all)
250 |
251 | for row in table:
252 | res = {}
253 | for k, v in zip(var_all, row):
254 | res[k] = v
255 | print(' '.join(str(x) for x in row), result_of_expression(exp, res))
256 | ```
257 |
--------------------------------------------------------------------------------
/python_basics_3.5.md:
--------------------------------------------------------------------------------
1 | # Yandex handbook "Python Basics" answers
2 |
3 | 3.5. Потоковый ввод/вывод. Работа с текстовыми файлами. JSON
4 |
5 | A. A+B+...
6 | ```python
7 | from sys import stdin
8 |
9 | print(sum(map(int, stdin.read().split())))
10 | ```
11 | B. Средний рост
12 | ```python
13 | from sys import stdin
14 |
15 | print(round(sum(x := [int(i.split()[2]) - int(i.split()[1]) for i in stdin.readlines()]) / len(x)))
16 | ```
17 | C. Без комментариев 2.0
18 | ```python
19 | from sys import stdin
20 |
21 | for i in stdin.readlines():
22 | if not i.startswith('#'):
23 | print(i[:i.find('#')])
24 | ```
25 | D. Найдётся всё 2.0
26 | ```python
27 | from sys import stdin
28 |
29 | for line in (x := [i.strip() for i in stdin])[:-1]:
30 | if x[-1].lower() in line.lower():
31 | print(line)
32 | ```
33 | E. А роза упала на лапу Азора 6.0
34 | ```python
35 | from sys import stdin
36 |
37 | data = [string.strip().split() for string in stdin]
38 | words = []
39 | for line in data:
40 | words.extend(line)
41 | for word in sorted(set(words)):
42 | if word.lower() == word.lower()[::-1]:
43 | print(word)
44 | ```
45 | F. Транслитерация 2.0
46 | ```python
47 | LITER = {
48 | 'А': 'A', 'Б': 'B', 'В': 'V',
49 | 'Г': 'G', 'Д': 'D', 'Е': 'E',
50 | 'Ё': 'E', 'Ж': 'ZH', 'З': 'Z',
51 | 'И': 'I', 'Й': 'I', 'К': 'K',
52 | 'Л': 'L', 'М': 'M', 'Н': 'N',
53 | 'О': 'O', 'П': 'P', 'Р': 'R',
54 | 'С': 'S', 'Т': 'T', 'У': 'U',
55 | 'Ф': 'F', 'Х': 'KH', 'Ц': 'TC',
56 | 'Ч': 'CH', 'Ш': 'SH', 'Щ': 'SHCH',
57 | 'Ы': 'Y', 'Э': 'E', 'Ю': 'IU',
58 | 'Я': 'IA', 'Ь': '', 'Ъ': '',
59 | }
60 |
61 | data, translit_data = '', ''
62 | with open("cyrillic.txt", encoding="UTF-8") as file_in:
63 | for line in file_in:
64 | data += line
65 |
66 | for i in data:
67 | if i.upper() in LITER:
68 | translit_data += LITER[i.upper()].lower().capitalize() if i == i.upper() else LITER[i.upper()].lower()
69 | else:
70 | translit_data += i
71 |
72 | with open("transliteration.txt", "w", encoding="UTF-8") as file_out:
73 | print(translit_data, file=file_out)
74 | ```
75 | G. Файловая статистика
76 | ```python
77 | name = input()
78 | numbers = []
79 | with open(name, 'r') as f:
80 | for line in f:
81 | numbers.extend([int(x) for x in line.split()])
82 | print(len(numbers))
83 | print(len(list(filter(lambda x: x > 0, numbers))))
84 | print(min(numbers))
85 | print(max(numbers))
86 | print(sum(numbers))
87 | print(round(sum(numbers) / len(numbers), 2))
88 | ```
89 | H. Файловая разница
90 | ```python
91 | files_in = input(), input()
92 | file_out = input()
93 | words = [set(), set()]
94 | for i in range(len(files_in)):
95 | with open(files_in[i], 'r') as file_in:
96 | for line in file_in:
97 | words[i].update({x for x in line.split()})
98 | with open(file_out, 'w') as file_out:
99 | for word in sorted(words[0].symmetric_difference(words[1])):
100 | print(word, file=file_out)
101 | ```
102 | I. Файловая чистка
103 | ```python
104 | first_file, second_file = input(), input()
105 | data = []
106 | with open(first_file, 'r') as f:
107 | for line in f:
108 | data.append(line.strip().replace('\t', '').split())
109 | data = [i for i in data if any(i)]
110 | with open(second_file, 'w') as g:
111 | for line in data:
112 | print(' '.join(line), file=g)
113 | ```
114 | J. Хвост
115 | ```python
116 | file_in, number = input(), int(input())
117 | data = []
118 | with open(file_in) as f:
119 | for line in f:
120 | data.append(line)
121 | for line in data[-number:]:
122 | print(line.strip())
123 | ```
124 | K. Файловая статистика 2.0
125 | ```python
126 | import json
127 |
128 | file_in, file_out = input(), input()
129 | numbers = []
130 | with open(file_in) as f:
131 | for line in f:
132 | numbers.extend([int(x) for x in line.split()])
133 | data = {
134 | "count": len(numbers),
135 | "positive_count": len(list(filter(lambda x: x > 0, numbers))),
136 | "min": min(numbers),
137 | "max": max(numbers),
138 | "sum": sum(numbers),
139 | "average": round(sum(numbers) / len(numbers), 2)
140 | }
141 | with open(file_out, "w", encoding="UTF-8") as g:
142 | json.dump(data, g, ensure_ascii=False, indent=4)
143 | ```
144 | L. Разделяй и властвуй
145 | ```python
146 | from sys import stdin
147 |
148 | files = [name.strip() for name in stdin]
149 | data = []
150 | with open(files[0]) as f:
151 | for line in f:
152 | data.append(line.split())
153 | D = dict(zip([1, 2, 3], ['>', '<', '==']))
154 | for n in range(1, len(files)):
155 | with open(files[n], 'w') as f:
156 | for line in data:
157 | for i in line:
158 | if eval('len(list(filter(lambda x: not int(x) % 2, i)))'
159 | + D[n] +
160 | 'len(list(filter(lambda x: int(x) % 2, i)))'):
161 | print(i, end=' ', file=f)
162 | print('\n', end='', file=f)
163 | ```
164 | M. Обновление данных
165 | ```python
166 | from sys import stdin
167 | import json
168 |
169 | data = [line.strip() for line in stdin]
170 | print(data)
171 | print({line.split(' == ')[0]: line.split(' == ')[1] for line in data[1:]})
172 | D = {line.split(' == ')[0]: line.split(' == ')[1] for line in data[1:]}
173 | with open(data[0], 'r', encoding="UTF-8") as f:
174 | records = json.load(f)
175 | records.update(D)
176 | if len(data) > 1:
177 | with open(data[0], 'w', encoding="UTF-8") as f:
178 | json.dump(records, f, ensure_ascii=False, indent=4, sort_keys=True)
179 | ```
180 | N. Слияние данных
181 | ```python
182 | import json
183 |
184 | file_1, file_2 = input(), input()
185 | with open(file_1, 'r') as f:
186 | data_1 = json.load(f)
187 | with open(file_2, 'r') as f:
188 | data_2 = json.load(f)
189 | data_1 = {i["name"]: {k: v for k, v in i.items() if k != "name"} for i in data_1}
190 | for d in data_2:
191 | if d["name"] in data_1:
192 | for key in d:
193 | if (key not in data_1[d["name"]] or d[key] > data_1[d["name"]][key]) and key != "name":
194 | data_1[d["name"]][key] = d[key]
195 | else:
196 | data_1[d["name"]] = {k: v for k, v in d.items() if k != "name"}
197 | with open(file_1, 'w') as g:
198 | json.dump(data_1, g, ensure_ascii=False, indent=4)
199 | ```
200 | O. Поставь себя на моё место
201 | ```python
202 | from sys import stdin
203 | import json
204 |
205 | answers = [i.strip() for i in stdin]
206 | with open("scoring.json", "r") as file_in:
207 | data = json.load(file_in)
208 | data = [{y["pattern"]: x["points"] // len(x["tests"]) for y in x["tests"]} for x in data]
209 | result, counter = 0, 0
210 | for i in data:
211 | for j in range(counter, len(i) + counter):
212 | if answers[j] in i:
213 | result += i[answers[j]]
214 | counter += 1
215 | print(result)
216 | ```
217 | P. Найдётся всё 3.0
218 | ```python
219 | from sys import stdin
220 |
221 | data = [line.strip() for line in stdin]
222 | query = data[0].lower()
223 | D = {}
224 | for file in data[1:]:
225 | with open(file, "r", encoding="UTF-8") as f:
226 | D[file] = f.read()
227 | if query in ' '.join(D[file].replace(' ', ' ').lower().split()):
228 | print(file)
229 | else:
230 | del D[file]
231 | if not D:
232 | print('404. Not Found')
233 | ```
234 | Q. Прятки
235 | ```python
236 | with open("secret.txt", 'r', encoding='UTF-8') as f:
237 | print(''.join([chr(ord(i) % 128) for i in f.read()]))
238 | ```
239 | R. Сколько вешать в байтах?
240 | ```python
241 | import os
242 |
243 | size = os.path.getsize(input())
244 | if size > 1024**3 - 1:
245 | size = int(size / 1024**3) + 1
246 | postfix = 'ГБ'
247 | elif size > 1024**2 - 1:
248 | size = int(size / 1024**2) + 1
249 | postfix = 'МБ'
250 | elif size > 1023:
251 | size = int(size / 1024) + 1
252 | postfix = 'КБ'
253 | else:
254 | postfix = 'Б'
255 | print(str(size) + postfix)
256 | ```
257 | S. Это будет наш секрет
258 | ```python
259 | shift = int(input())
260 | a = "abcdefghijklmnopqrstuvwxyz"
261 | with open("public.txt", "r", encoding="UTF-8") as file_in:
262 | data = file_in.read()
263 | data_out = [a[(a.find(i.lower()) + shift) % len(a)] if i.lower() in a else i for i in data]
264 | for ind, letter in enumerate(data):
265 | if letter.isupper():
266 | data_out[ind] = data_out[ind].upper()
267 | with open("private.txt", "w") as file_out:
268 | print(''.join(data_out), file=file_out)
269 | ```
270 | T. Файловая сумма
271 | ```python
272 | with open("numbers.num", "rb") as f:
273 | data = f.read()
274 | print(sum([int.from_bytes(data[i:i + 2], "big") for i in range(0, len(data), 2)]) % 2**16)
275 | ```
276 |
--------------------------------------------------------------------------------
/python_basics_4.1.md:
--------------------------------------------------------------------------------
1 | # Yandex handbook "Python Basics" answers
2 |
3 | 4.1. Функции. Области видимости. Передача параметров в функции
4 |
5 | A. Функциональное приветствие
6 | ```python
7 | def print_hello(name):
8 | print(f'Hello, {name}!')
9 | ```
10 | B. Функциональный НОД
11 | ```python
12 | def gcd(a, b):
13 | while b:
14 | a, b = b, a % b
15 | return a
16 | ```
17 | C. Длина числа
18 | ```python
19 | def number_length(number):
20 | return len(str(abs(number)))
21 | ```
22 | D. Имя of the month
23 | ```python
24 | def month(number, language):
25 | MONTH = {
26 | 'en': [
27 | 'January', 'February', 'March',
28 | 'April', 'May', 'June',
29 | 'July', 'August', 'September',
30 | 'October', 'November', 'December'
31 | ],
32 | 'ru': [
33 | 'Январь', 'Февраль', 'Март',
34 | 'Апрель', 'Май', 'Июнь',
35 | 'Июль', 'Август', 'Сентябрь',
36 | 'Октябрь', 'Ноябрь', 'Декабрь'
37 | ]
38 | }
39 | return MONTH[language][number - 1]
40 | ```
41 | E. Числовая строка
42 | ```python
43 | def split_numbers(line):
44 | return tuple(map(int, line.split()))
45 | ```
46 | F. Модернизация системы вывода
47 | ```python
48 | lst = []
49 |
50 |
51 | def modern_print(string):
52 | print(string) if string not in lst else None
53 | lst.append(string)
54 | ```
55 | G. Шахматный «обед»
56 | ```python
57 | def can_eat(horse, shape):
58 | return abs(horse[0] - shape[0]) + abs(horse[1] - shape[1]) == 3
59 | ```
60 | H. А роза упала на лапу Азора 7.0
61 | ```python
62 | def is_palindrome(n):
63 | return str(n) == str(n)[::-1] if isinstance(n, int) else n == n[::-1]
64 | ```
65 | I. Простая задача 5.0
66 | ```python
67 | def is_prime(n):
68 | for i in range(2, int(n**0.5) + 1):
69 | if not n % i:
70 | return False
71 | return n != 1
72 | ```
73 | J. Слияние
74 | ```python
75 | def merge(a, b):
76 | c = list(a) + list(b)
77 | n = len(c)
78 | for i in range(n):
79 | for j in range(0, n - i - 1):
80 | if c[j] > c[j + 1]:
81 | c[j], c[j + 1] = c[j + 1], c[j]
82 | return tuple(c)
83 | ```
84 |
--------------------------------------------------------------------------------
/python_basics_4.2.md:
--------------------------------------------------------------------------------
1 | # Yandex handbook "Python Basics" answers
2 |
3 | 4.2. Позиционные и именованные аргументы. Функции высших порядков. Лямбда-функции
4 |
5 | A. Генератор списков
6 | ```python
7 | def make_list(length, value=0):
8 | return [value] * length
9 | ```
10 | B. Генератор матриц
11 | ```python
12 | def make_matrix(size, value=0):
13 | if isinstance(size, int):
14 | return [[value for i in range(size)] for j in range(size)]
15 | else:
16 | return [[value for i in range(size[0])] for j in range(size[1])]
17 | ```
18 | C. Функциональный нод 2.0
19 | ```python
20 | def gcd(*args):
21 | a = list(args)
22 | while len(a) > 1:
23 | while a[1]:
24 | a[0], a[1] = a[1], a[0] % a[1]
25 | a.pop(1)
26 | return a[0]
27 | ```
28 | D. Имя of the month 2.0
29 | ```python
30 | def month(number, language='ru'):
31 | MONTH = {
32 | 'en': [
33 | 'January', 'February', 'March',
34 | 'April', 'May', 'June',
35 | 'July', 'August', 'September',
36 | 'October', 'November', 'December'
37 | ],
38 | 'ru': [
39 | 'Январь', 'Февраль', 'Март',
40 | 'Апрель', 'Май', 'Июнь',
41 | 'Июль', 'Август', 'Сентябрь',
42 | 'Октябрь', 'Ноябрь', 'Декабрь'
43 | ]
44 | }
45 | return MONTH[language][number - 1]
46 | ```
47 | E. Подготовка данных
48 | ```python
49 | def to_string(*args, **kwargs):
50 | return kwargs.get("sep", " ").join([str(i) for i in args]) + kwargs.get("end", "\n")
51 | ```
52 | F. Кофейня
53 | ```python
54 | def order(*args):
55 | temp = in_stock
56 | GRADES = {
57 | "Эспрессо": {"coffee": 1},
58 | "Капучино": {"coffee": 1,
59 | "milk": 3},
60 | "Макиато": {"coffee": 2,
61 | "milk": 1},
62 | "Кофе по-венски": {"coffee": 1,
63 | "cream": 2},
64 | "Латте Макиато": {"coffee": 1,
65 | "milk": 2,
66 | "cream": 1},
67 | "Кон Панна": {"coffee": 1,
68 | "cream": 1},
69 | }
70 | for grade in args:
71 | for ingr in GRADES[grade]:
72 | if GRADES[grade].get(ingr, 0) > in_stock[ingr]:
73 | break
74 | else:
75 | for ingr in GRADES[grade]:
76 | in_stock[ingr] -= GRADES[grade][ingr]
77 | return grade
78 | if in_stock == temp:
79 | return "К сожалению, не можем предложить Вам напиток"
80 | ```
81 | G. В эфире рубрика «Эксперименты»
82 | ```python
83 | numbers = tuple()
84 |
85 |
86 | def enter_results(*args):
87 | global numbers
88 | numbers += args
89 |
90 |
91 | def get_sum():
92 | return round(sum(numbers[::2]), 2), round(sum(numbers[1::2]), 2)
93 |
94 |
95 | def get_average():
96 | return round(2 * get_sum()[0] / len(numbers), 2), round(2 * get_sum()[1] / len(numbers), 2)
97 | ```
98 | H. Длинная сортировка
99 | ```python
100 | lambda x: (len(x), x.lower())
101 | ```
102 | I. Чётная фильтрация
103 | ```python
104 | lambda x: not sum(map(int, str(x))) % 2
105 | ```
106 | J. Ключевой секрет
107 | ```python
108 | def secret_replace(text, **kwargs):
109 | result = ''
110 | kwargs = {d: (v, 0) for d, v in kwargs.items()}
111 | for i in text:
112 | if i in kwargs:
113 | result += kwargs[i][0][kwargs[i][1] % len(kwargs[i][0])]
114 | kwargs[i] = kwargs[i][0], kwargs[i][1] + 1
115 | else:
116 | result += i
117 | return result
118 | ```
119 |
--------------------------------------------------------------------------------
/python_basics_4.3.md:
--------------------------------------------------------------------------------
1 | # Yandex handbook "Python Basics" answers
2 |
3 | 4.3. Рекурсия. Декораторы. Генераторы
4 |
5 | A. Рекурсивный сумматор
6 | ```python
7 | def recursive_sum(*args):
8 | if not args:
9 | return 0
10 | return args[0] + recursive_sum(*args[1:])
11 | ```
12 | B. Рекурсивный сумматор цифр
13 | ```python
14 | def recursive_digit_sum(n):
15 | return n % 10 + recursive_digit_sum(n // 10) if n else 0
16 | ```
17 | C. Многочлен N-ой степени
18 | ```python
19 | def make_equation(*args):
20 | if len(args) == 1:
21 | return str(args[0])
22 | line = ') * x ' + ('- ' if args[-1] < 0 else '+ ') + str(args[-1])
23 | return '(' + make_equation(*args[:-1]) + line
24 | ```
25 | D. Декор результата
26 | ```python
27 | def answer(func):
28 | def wrap(*args, **kwargs):
29 | return f'Результат функции: {func(*args, **kwargs)}'
30 | return wrap
31 | ```
32 | E. Накопление результата
33 | ```python
34 | def result_accumulator(func):
35 | result = []
36 |
37 | def wrap(*args, method="accumulate"):
38 | result.append(func(*args))
39 | if method == "drop":
40 | temp = result.copy()
41 | result.clear()
42 | return temp
43 | return wrap
44 | ```
45 | F. Сортировка слиянием
46 | ```python
47 | def merge_sort(arr):
48 | n = len(arr)
49 | if n <= 1:
50 | return arr
51 | else:
52 | middle = int(len(arr) / 2)
53 | left = merge_sort(arr[:middle])
54 | right = merge_sort(arr[middle:])
55 | return merge(left, right)
56 |
57 |
58 | def merge(left, right):
59 | result = []
60 | while len(left) > 0 and len(right) > 0:
61 | if left[0] <= right[0]:
62 | result.append(left[0])
63 | left = left[1:]
64 | else:
65 | result.append(right[0])
66 | right = right[1:]
67 | if len(left) > 0:
68 | result += left
69 | if len(right) > 0:
70 | result += right
71 | return result
72 | ```
73 | G. Однотипность не порок
74 | ```python
75 | def same_type(func):
76 | def wrapper(*args):
77 | if len({type(i) for i in args}) != 1:
78 | print("Обнаружены различные типы данных")
79 | return False
80 | return func(*args)
81 | return wrapper
82 | ```
83 | H. Генератор Фибоначчи
84 | ```python
85 | def fibonacci(n):
86 | n1, n2 = 0, 1
87 | for i in range(n):
88 | yield n1
89 | n1, n2 = n2, n1 + n2
90 | ```
91 | I. Циклический генератор
92 | ```python
93 | def cycle(line):
94 | while line:
95 | for i in line:
96 | yield i
97 | ```
98 | J. "Выпрямление" списка
99 | ```python
100 | def make_linear(arr):
101 | new_arr = []
102 | for i in arr:
103 | if isinstance(i, list):
104 | new_arr.extend(make_linear(i))
105 | else:
106 | new_arr.append(i)
107 | return new_arr
108 | ```
109 |
--------------------------------------------------------------------------------
/python_basics_5.1.md:
--------------------------------------------------------------------------------
1 | # Yandex handbook "Python Basics" answers
2 |
3 | 5.1. Объектная модель Python. Классы, поля и методы
4 |
5 | A. Классная точка
6 | ```python
7 | class Point:
8 | def __init__(self, x, y):
9 | self.x = x
10 | self.y = y
11 | ```
12 | B. Классная точка 2.0
13 | ```python
14 | class Point:
15 | def __init__(self, x, y):
16 | self.x = x
17 | self.y = y
18 |
19 | def move(self, shift_x, shift_y):
20 | self.x += shift_x
21 | self.y += shift_y
22 |
23 | def length(self, p):
24 | return round(((self.x - p.x)**2 + (self.y - p.y)**2)**0.5, 2)
25 | ```
26 | C. Не нажимай красную кнопку!
27 | ```python
28 | class RedButton:
29 | def __init__(self):
30 | self.counter = 0
31 |
32 | def click(self):
33 | print('Тревога!')
34 | self.counter += 1
35 |
36 | def count(self):
37 | return self.counter
38 | ```
39 | D. Работа не волк
40 | ```python
41 | class Programmer:
42 |
43 | def __init__(self, name, position="Junior"):
44 | self.name = name
45 | self.position = position
46 | self.worked = 0
47 | self.money = 0
48 | self.overrises = 0
49 |
50 | def work(self, time):
51 | P = {
52 | "Junior": 10,
53 | "Middle": 15,
54 | "Senior": 20,
55 | }
56 | self.worked += time
57 | self.money += time * (P[self.position] + self.overrises)
58 |
59 | def rise(self):
60 | if self.position == "Junior":
61 | self.position = "Middle"
62 | elif self.position == "Middle":
63 | self.position = "Senior"
64 | elif self.position == "Senior":
65 | self.overrises += 1
66 |
67 | def info(self):
68 | return f'{self.name} {self.worked}ч. {self.money}тгр.'
69 | ```
70 | E. Классный прямоугольник
71 | ```python
72 | class Rectangle:
73 | def __init__(self, *coords):
74 | self.coords = coords
75 | self.first_line = abs(self.coords[0][0] - self.coords[1][0])
76 | self.second_line = abs(self.coords[0][1] - self.coords[1][1])
77 |
78 | def perimeter(self):
79 | return round(2 * (self.first_line + self.second_line), 2)
80 |
81 | def area(self):
82 | return round(self.first_line * self.second_line, 2)
83 | ```
84 | F. Классный прямоугольник 2.0
85 | ```python
86 | class Rectangle:
87 | def __init__(self, *coords):
88 | self.coords = coords
89 | self.upper_left_x = round(min(self.coords[0][0], self.coords[1][0]), 2)
90 | self.upper_left_y = round(max(self.coords[0][1], self.coords[1][1]), 2)
91 | self.lower_right_x = round(max(self.coords[0][0], self.coords[1][0]), 2)
92 | self.lower_right_y = round(min(self.coords[0][1], self.coords[1][1]), 2)
93 | self.width = abs(self.coords[0][0] - self.coords[1][0])
94 | self.height = abs(self.coords[0][1] - self.coords[1][1])
95 |
96 | def perimeter(self):
97 | return round(2 * (self.width + self.height), 2)
98 |
99 | def area(self):
100 | return round(self.width * self.height, 2)
101 |
102 | def get_pos(self):
103 | return self.upper_left_x, self.upper_left_y
104 |
105 | def get_size(self):
106 | return round(self.width, 2), round(self.height, 2)
107 |
108 | def move(self, dx, dy):
109 | self.coords = (self.coords[0][0] + dx, self.coords[0][1] + dy), (self.coords[1][0] + dx, self.coords[1][1] + dy)
110 | self.__init__(*self.coords)
111 |
112 | def resize(self, width, height):
113 | self.coords = self.get_pos(), (self.upper_left_x + width, self.upper_left_y - height)
114 | self.__init__(*self.coords)
115 | ```
116 | G. Классный прямоугольник 3.0
117 | ```python
118 | class Rectangle:
119 | def __init__(self, coord1, coord2):
120 | self.left = min(coord1[0], coord2[0])
121 | self.top = max(coord1[1], coord2[1])
122 | self.right = max(coord1[0], coord2[0])
123 | self.bottom = min(coord1[1], coord2[1])
124 | self.w = round(abs(coord1[0] - coord2[0]), 2)
125 | self.h = round(abs(coord1[1] - coord2[1]), 2)
126 | self.x = min(coord1[0], coord2[0])
127 | self.y = max(coord1[1], coord2[1])
128 | self.flag = False
129 |
130 | def perimeter(self):
131 | return round(abs(self.left - self.right) * 2 + abs(self.top - self.bottom) * 2, 2)
132 |
133 | def area(self):
134 | return round(abs(self.left - self.right) * abs(self.top - self.bottom), 2)
135 |
136 | def get_pos(self):
137 | return self.left, self.top
138 |
139 | def get_size(self):
140 | if self.flag:
141 | return self.w, self.h
142 | return ((round(abs(self.left - self.right), 2), round(abs(self.top - self.bottom), 2)))
143 |
144 | def resize(self, width, height):
145 | self.flag = False
146 | self.right = round(self.left + width, 2)
147 | self.bottom = round(self.top + height, 2)
148 | self.w, self.h = width, height
149 |
150 | def turn(self):
151 | self.flag = False
152 | width, height = self.get_size()
153 | d = (width - height) / 2
154 | self.left = round(self.left + d, 2)
155 | self.right = round(self.right - d, 2)
156 | self.top = round(self.top + d, 2)
157 | self.bottom = round(self.bottom - d, 2)
158 | d = (self.w - self.h) / 2
159 | self.x = round(self.x + d, 2)
160 | self.y = round(self.y + d, 2)
161 | self.w, self.h = self.h, self.w
162 |
163 | def scale(self, factor):
164 | self.flag = False
165 | width, height = self.get_size()
166 | self.flag = False
167 | if abs(width - self.w) <= 0.01:
168 | width = self.w
169 | if abs(height - self.h) <= 0.02:
170 | height = self.h
171 | self.left = round(self.left - (factor * width - width) / 2, 2)
172 | self.top = round(self.top + (factor * height - height) / 2, 2)
173 | width = round(width * factor, 2)
174 | height = round(height * factor, 2)
175 | self.right = round(self.left + width, 2)
176 | self.bottom = round(self.top - height, 2)
177 | self.x = round(self.x - (factor * self.w - self.w) / 2, 2)
178 | self.y = round(self.y + (factor * self.h - self.h) / 2, 2)
179 | self.w = round(self.w * factor, 2)
180 | self.h = round(self.h * factor, 2)
181 | ```
182 | H. Шашки
183 | ```python
184 | class Checkers:
185 |
186 | def __init__(self):
187 | self.desk = {
188 | 'A': {
189 | '8': 'X',
190 | '7': 'B',
191 | '6': 'X',
192 | '5': 'X',
193 | '4': 'X',
194 | '3': 'W',
195 | '2': 'X',
196 | '1': 'W',
197 | },
198 | 'B': {
199 | '8': 'B',
200 | '7': 'X',
201 | '6': 'B',
202 | '5': 'X',
203 | '4': 'X',
204 | '3': 'X',
205 | '2': 'W',
206 | '1': 'X',
207 | },
208 | 'C': {
209 | '8': 'X',
210 | '7': 'B',
211 | '6': 'X',
212 | '5': 'X',
213 | '4': 'X',
214 | '3': 'W',
215 | '2': 'X',
216 | '1': 'W',
217 | },
218 | 'D': {
219 | '8': 'B',
220 | '7': 'X',
221 | '6': 'B',
222 | '5': 'X',
223 | '4': 'X',
224 | '3': 'X',
225 | '2': 'W',
226 | '1': 'X',
227 | },
228 | 'E': {
229 | '8': 'X',
230 | '7': 'B',
231 | '6': 'X',
232 | '5': 'X',
233 | '4': 'X',
234 | '3': 'W',
235 | '2': 'X',
236 | '1': 'W',
237 | },
238 | 'F': {
239 | '8': 'B',
240 | '7': 'X',
241 | '6': 'B',
242 | '5': 'X',
243 | '4': 'X',
244 | '3': 'X',
245 | '2': 'W',
246 | '1': 'X',
247 | },
248 | 'G': {
249 | '8': 'X',
250 | '7': 'B',
251 | '6': 'X',
252 | '5': 'X',
253 | '4': 'X',
254 | '3': 'W',
255 | '2': 'X',
256 | '1': 'W',
257 | },
258 | 'H': {
259 | '8': 'B',
260 | '7': 'X',
261 | '6': 'B',
262 | '5': 'X',
263 | '4': 'X',
264 | '3': 'X',
265 | '2': 'W',
266 | '1': 'X',
267 | },
268 | }
269 |
270 | def move(self, f, t):
271 | self.desk[f[0]][f[1]], self.desk[t[0]][t[1]] = self.desk[t[0]][t[1]], self.desk[f[0]][f[1]]
272 |
273 | def get_cell(self, p):
274 | return Cell(self.desk[p[0]][p[1]])
275 |
276 |
277 | class Cell:
278 |
279 | def __init__(self, coords):
280 | self.coords = coords
281 |
282 | def status(self):
283 | return self.coords
284 | ```
285 | I. Очередь
286 | ```python
287 | class Queue:
288 | a = []
289 |
290 | def push(self, item):
291 | self.a.append(item)
292 |
293 | def pop(self):
294 | return self.a.pop(0)
295 |
296 | def is_empty(self):
297 | return self.a == []
298 | ```
299 | J. Стек
300 | ```python
301 | class Stack:
302 | a = []
303 |
304 | def push(self, item):
305 | self.a.append(item)
306 |
307 | def pop(self):
308 | return self.a.pop()
309 |
310 | def is_empty(self):
311 | return self.a == []
312 | ```
313 |
--------------------------------------------------------------------------------
/python_basics_5.2.md:
--------------------------------------------------------------------------------
1 | # Yandex handbook "Python Basics" answers
2 |
3 | 5.2. Волшебные методы, переопределение методов. Наследование
4 |
5 | A. Классная точка 3.0
6 | ```python
7 | class Point:
8 | def __init__(self, x, y):
9 | self.x = x
10 | self.y = y
11 |
12 | def move(self, shift_x, shift_y):
13 | self.x += shift_x
14 | self.y += shift_y
15 |
16 | def length(self, p):
17 | return round(((self.x - p.x)**2 + (self.y - p.y)**2)**0.5, 2)
18 |
19 |
20 | class PatchedPoint(Point):
21 | def __init__(self, *args):
22 | if not args:
23 | self.x, self.y = 0, 0
24 | elif len(args) == 1:
25 | self.x, self.y = args[0]
26 | else:
27 | self.x, self.y = args
28 | ```
29 | B. Классная точка 4.0
30 | ```python
31 | class Point:
32 | def __init__(self, x, y):
33 | self.x = x
34 | self.y = y
35 |
36 | def move(self, shift_x, shift_y):
37 | self.x += shift_x
38 | self.y += shift_y
39 |
40 | def length(self, p):
41 | return round(((self.x - p.x)**2 + (self.y - p.y)**2)**0.5, 2)
42 |
43 |
44 | class PatchedPoint(Point):
45 |
46 | def __init__(self, *args):
47 | if not args:
48 | self.x, self.y = 0, 0
49 | elif len(args) == 1:
50 | self.x, self.y = args[0]
51 | else:
52 | self.x, self.y = args
53 |
54 | def __str__(self):
55 | return f"({self.x}, {self.y})"
56 |
57 | def __repr__(self):
58 | return f"PatchedPoint({self.x}, {self.y})"
59 | ```
60 | C. Классная точка 5.0
61 | ```python
62 | class Point:
63 | def __init__(self, x, y):
64 | self.x = x
65 | self.y = y
66 |
67 | def move(self, shift_x, shift_y):
68 | self.x += shift_x
69 | self.y += shift_y
70 |
71 | def length(self, p):
72 | return round(((self.x - p.x)**2 + (self.y - p.y)**2)**0.5, 2)
73 |
74 |
75 | class PatchedPoint(Point):
76 | def __init__(self, *args):
77 | if not args:
78 | self.x, self.y = 0, 0
79 | elif len(args) == 1:
80 | self.x, self.y = args[0]
81 | else:
82 | self.x, self.y = args
83 |
84 | def __str__(self):
85 | return f"({self.x}, {self.y})"
86 |
87 | def __repr__(self):
88 | return f"PatchedPoint({self.x}, {self.y})"
89 |
90 | def __add__(self, other):
91 | return PatchedPoint(self.x + other[0], self.y + other[1])
92 |
93 | def __iadd__(self, other):
94 | self.move(other[0], other[1])
95 | return self
96 | ```
97 | D. Дроби v0.1
98 | ```python
99 | class Fraction:
100 |
101 | def __simp(self, coords):
102 | a, b = coords[0], coords[1]
103 | while b:
104 | a, b = b, a % b
105 | return coords[0] // a, coords[1] // a
106 |
107 | def __init__(self, *args):
108 | if isinstance(args[0], str):
109 | self.n, self.d = self.__simp(tuple(map(int, args[0].split('/'))))
110 | else:
111 | self.n, self.d = self.__simp(args)
112 |
113 | def numerator(self, number=0):
114 | if number:
115 | self.n, self.d = self.__simp((number, self.d))
116 | return self.n
117 |
118 | def denominator(self, number=0):
119 | if number:
120 | self.n, self.d = self.__simp((self.n, number))
121 | return self.d
122 |
123 | def __str__(self):
124 | return f"{self.n}/{self.d}"
125 |
126 | def __repr__(self):
127 | return f"Fraction({self.n}, {self.d})"
128 | ```
129 | E. Дроби v0.2
130 | ```python
131 | class Fraction:
132 |
133 | def __simp(self, coords):
134 | a, b = coords[0], coords[1]
135 | while b:
136 | a, b = b, a % b
137 | return coords[0] // a, coords[1] // a
138 |
139 | def __init__(self, *args):
140 | if isinstance(args[0], str):
141 | self.n, self.d = self.__simp(tuple(map(int, args[0].split('/'))))
142 | else:
143 | self.n, self.d = self.__simp(args)
144 |
145 | def numerator(self, number=0):
146 | if number:
147 | if self.n > 0:
148 | self.n, self.d = self.__simp((abs(number), self.d))
149 | self.n = -self.n if number < 0 else self.n
150 | elif self.n < 0:
151 | self.n, self.d = self.__simp((abs(number), self.d))
152 | self.n = -self.n if number > 0 else self.n
153 | return abs(self.n)
154 |
155 | def denominator(self, number=0):
156 | if number:
157 | if self.n > 0:
158 | self.n, self.d = self.__simp((self.n, abs(number)))
159 | self.n = -self.n if number < 0 else self.n
160 | elif self.n < 0:
161 | self.n, self.d = self.__simp((abs(self.n), abs(number)))
162 | self.n = -self.n if number > 0 else self.n
163 | return self.d
164 |
165 | def __neg__(self):
166 | return Fraction(-self.n, self.d)
167 |
168 | def __str__(self):
169 | return f"{self.n}/{self.d}"
170 |
171 | def __repr__(self):
172 | return f"Fraction('{self.n}/{self.d}')"
173 | ```
174 | F. Дроби v0.3
175 | ```python
176 | class Fraction:
177 |
178 | def __simp(self, coords):
179 | a, b = coords[0], coords[1]
180 | while b:
181 | a, b = b, a % b
182 | return coords[0] // a, coords[1] // a
183 |
184 | def __init__(self, *args):
185 | if isinstance(args[0], str):
186 | self.n, self.d = self.__simp(tuple(map(int, args[0].split('/'))))
187 | else:
188 | self.n, self.d = self.__simp(args)
189 |
190 | def numerator(self, number=0):
191 | if number:
192 | if self.n > 0:
193 | self.n, self.d = self.__simp((abs(number), self.d))
194 | self.n = -self.n if number < 0 else self.n
195 | elif self.n < 0:
196 | self.n, self.d = self.__simp((abs(number), self.d))
197 | self.n = -self.n if number > 0 else self.n
198 | return abs(self.n)
199 |
200 | def denominator(self, number=0):
201 | if number:
202 | if self.n > 0:
203 | self.n, self.d = self.__simp((self.n, abs(number)))
204 | self.n = -self.n if number < 0 else self.n
205 | elif self.n < 0:
206 | self.n, self.d = self.__simp((abs(self.n), abs(number)))
207 | self.n = -self.n if number > 0 else self.n
208 | return self.d
209 |
210 | def __neg__(self):
211 | return Fraction(-self.n, self.d)
212 |
213 | def __add__(self, other):
214 | return Fraction(self.n * other.d + other.n * self.d, self.d * other.d)
215 |
216 | def __iadd__(self, other):
217 | self.n, self.d = self.__simp((self.n * other.d + other.n * self.d, self.d * other.d))
218 | return self
219 |
220 | def __sub__(self, other):
221 | return Fraction(self.n * other.d - other.n * self.d, self.d * other.d)
222 |
223 | def __isub__(self, other):
224 | self.n, self.d = self.__simp((self.n * other.d - other.n * self.d, self.d * other.d))
225 | return self
226 |
227 | def __str__(self):
228 | return f"{self.n}/{self.d}"
229 |
230 | def __repr__(self):
231 | return f"Fraction('{self.n}/{self.d}')"
232 | ```
233 | G. Дроби v0.4
234 | ```python
235 | class Fraction:
236 |
237 | def __simp(self, coords):
238 | a, b = coords[0], coords[1]
239 | while b:
240 | a, b = b, a % b
241 | return coords[0] // a, coords[1] // a
242 |
243 | def __init__(self, *args):
244 | if isinstance(args[0], str):
245 | self.n, self.d = self.__simp(tuple(map(int, args[0].split('/'))))
246 | else:
247 | self.n, self.d = self.__simp(args)
248 |
249 | def numerator(self, number=0):
250 | if number:
251 | if self.n > 0:
252 | self.n, self.d = self.__simp((abs(number), self.d))
253 | self.n = -self.n if number < 0 else self.n
254 | elif self.n < 0:
255 | self.n, self.d = self.__simp((abs(number), self.d))
256 | self.n = -self.n if number > 0 else self.n
257 | return abs(self.n)
258 |
259 | def denominator(self, number=0):
260 | if number:
261 | if self.n > 0:
262 | self.n, self.d = self.__simp((self.n, abs(number)))
263 | self.n = -self.n if number < 0 else self.n
264 | elif self.n < 0:
265 | self.n, self.d = self.__simp((abs(self.n), abs(number)))
266 | self.n = -self.n if number > 0 else self.n
267 | return self.d
268 |
269 | def __neg__(self):
270 | return Fraction(-self.n, self.d)
271 |
272 | def __add__(self, other):
273 | return Fraction(self.n * other.d + other.n * self.d, self.d * other.d)
274 |
275 | def __iadd__(self, other):
276 | self.n, self.d = self.__simp((self.n * other.d + other.n * self.d, self.d * other.d))
277 | return self
278 |
279 | def __sub__(self, other):
280 | return Fraction(self.n * other.d - other.n * self.d, self.d * other.d)
281 |
282 | def __isub__(self, other):
283 | self.n, self.d = self.__simp((self.n * other.d - other.n * self.d, self.d * other.d))
284 | return self
285 |
286 | def __mul__(self, other):
287 | return Fraction(self.n * other.n, self.d * other.d)
288 |
289 | def __imul__(self, other):
290 | self.n, self.d = self.__simp((self.n * other.n, self.d * other.d))
291 | return self
292 |
293 | def __truediv__(self, other):
294 | return Fraction(self.n * other.d, self.d * other.n)
295 |
296 | def __itruediv__(self, other):
297 | self.n, self.d = self.__simp((self.n * other.d, self.d * other.n))
298 | return self
299 |
300 | def reverse(self):
301 | self.n, self.d = self.__simp((self.d, self.n))
302 | return self
303 |
304 | def __str__(self):
305 | return f"{self.n}/{self.d}"
306 |
307 | def __repr__(self):
308 | return f"Fraction('{self.n}/{self.d}')"
309 | ```
310 | H. Дроби v0.5
311 | ```python
312 | class Fraction:
313 |
314 | def __simp(self, coords):
315 | a, b = coords[0], coords[1]
316 | while b:
317 | a, b = b, a % b
318 | return coords[0] // a, coords[1] // a
319 |
320 | def __init__(self, *args):
321 | if isinstance(args[0], str):
322 | self.n, self.d = self.__simp(tuple(map(int, args[0].split('/'))))
323 | else:
324 | self.n, self.d = self.__simp(args)
325 |
326 | def numerator(self, number=0):
327 | if number:
328 | if self.n > 0:
329 | self.n, self.d = self.__simp((abs(number), self.d))
330 | self.n = -self.n if number < 0 else self.n
331 | elif self.n < 0:
332 | self.n, self.d = self.__simp((abs(number), self.d))
333 | self.n = -self.n if number > 0 else self.n
334 | return abs(self.n)
335 |
336 | def denominator(self, number=0):
337 | if number:
338 | if self.n > 0:
339 | self.n, self.d = self.__simp((self.n, abs(number)))
340 | self.n = -self.n if number < 0 else self.n
341 | elif self.n < 0:
342 | self.n, self.d = self.__simp((abs(self.n), abs(number)))
343 | self.n = -self.n if number > 0 else self.n
344 | return self.d
345 |
346 | def __neg__(self):
347 | return Fraction(-self.n, self.d)
348 |
349 | def __add__(self, other):
350 | return Fraction(self.n * other.d + other.n * self.d, self.d * other.d)
351 |
352 | def __iadd__(self, other):
353 | self.n, self.d = self.__simp((self.n * other.d + other.n * self.d, self.d * other.d))
354 | return self
355 |
356 | def __sub__(self, other):
357 | return Fraction(self.n * other.d - other.n * self.d, self.d * other.d)
358 |
359 | def __isub__(self, other):
360 | self.n, self.d = self.__simp((self.n * other.d - other.n * self.d, self.d * other.d))
361 | return self
362 |
363 | def __mul__(self, other):
364 | return Fraction(self.n * other.n, self.d * other.d)
365 |
366 | def __imul__(self, other):
367 | self.n, self.d = self.__simp((self.n * other.n, self.d * other.d))
368 | return self
369 |
370 | def __truediv__(self, other):
371 | return Fraction(self.n * other.d, self.d * other.n)
372 |
373 | def __itruediv__(self, other):
374 | self.n, self.d = self.__simp((self.n * other.d, self.d * other.n))
375 | return self
376 |
377 | def reverse(self):
378 | self.n, self.d = self.__simp((self.d, self.n))
379 | return self
380 |
381 | def __gt__(self, other):
382 | return self.n / self.d > other.n / other.d
383 |
384 | def __ge__(self, other):
385 | return self.n / self.d >= other.n / other.d
386 |
387 | def __lt__(self, other):
388 | return self.n / self.d < other.n / other.d
389 |
390 | def __le__(self, other):
391 | return self.n / self.d <= other.n / other.d
392 |
393 | def __eq__(self, other):
394 | return self.n / self.d == other.n / other.d
395 |
396 | def __ne__(self, other):
397 | return self.n / self.d != other.n / other.d
398 |
399 | def __str__(self):
400 | return f"{self.n}/{self.d}"
401 |
402 | def __repr__(self):
403 | return f"Fraction('{self.n}/{self.d}')"
404 | ```
405 | I. Дроби v0.6
406 | ```python
407 | class Fraction:
408 |
409 | def __simp(self, coords):
410 | if len(coords) == 1:
411 | coords += (1,)
412 | a, b = coords[0], coords[1]
413 | while b:
414 | a, b = b, a % b
415 | return coords[0] // a, coords[1] // a
416 |
417 | def __init__(self, *args):
418 | if isinstance(args[0], str):
419 | self.n, self.d = self.__simp(tuple(map(int, args[0].split('/'))))
420 | else:
421 | self.n, self.d = self.__simp(args)
422 |
423 | def numerator(self, number=0):
424 | if number:
425 | if self.n > 0:
426 | self.n, self.d = self.__simp((abs(number), self.d))
427 | self.n = -self.n if number < 0 else self.n
428 | elif self.n < 0:
429 | self.n, self.d = self.__simp((abs(number), self.d))
430 | self.n = -self.n if number > 0 else self.n
431 | return abs(self.n)
432 |
433 | def denominator(self, number=0):
434 | if number:
435 | if self.n > 0:
436 | self.n, self.d = self.__simp((self.n, abs(number)))
437 | self.n = -self.n if number < 0 else self.n
438 | elif self.n < 0:
439 | self.n, self.d = self.__simp((abs(self.n), abs(number)))
440 | self.n = -self.n if number > 0 else self.n
441 | return self.d
442 |
443 | def __neg__(self):
444 | return Fraction(-self.n, self.d)
445 |
446 | def __add__(self, other):
447 | other = other if isinstance(other, Fraction) else Fraction(other)
448 | return Fraction(self.n * other.d + other.n * self.d, self.d * other.d)
449 |
450 | def __iadd__(self, other):
451 | other = other if isinstance(other, Fraction) else Fraction(other)
452 | self.n, self.d = self.__simp((self.n * other.d + other.n * self.d, self.d * other.d))
453 | return self
454 |
455 | def __sub__(self, other):
456 | other = other if isinstance(other, Fraction) else Fraction(other)
457 | return Fraction(self.n * other.d - other.n * self.d, self.d * other.d)
458 |
459 | def __isub__(self, other):
460 | other = other if isinstance(other, Fraction) else Fraction(other)
461 | self.n, self.d = self.__simp((self.n * other.d - other.n * self.d, self.d * other.d))
462 | return self
463 |
464 | def __mul__(self, other):
465 | other = other if isinstance(other, Fraction) else Fraction(other)
466 | return Fraction(self.n * other.n, self.d * other.d)
467 |
468 | def __imul__(self, other):
469 | other = other if isinstance(other, Fraction) else Fraction(other)
470 | self.n, self.d = self.__simp((self.n * other.n, self.d * other.d))
471 | return self
472 |
473 | def __truediv__(self, other):
474 | other = other if isinstance(other, Fraction) else Fraction(other)
475 | return Fraction(self.n * other.d, self.d * other.n)
476 |
477 | def __itruediv__(self, other):
478 | other = other if isinstance(other, Fraction) else Fraction(other)
479 | self.n, self.d = self.__simp((self.n * other.d, self.d * other.n))
480 | return self
481 |
482 | def reverse(self):
483 | self.n, self.d = self.__simp((self.d, self.n))
484 | return self
485 |
486 | def __gt__(self, other):
487 | other = other if isinstance(other, Fraction) else Fraction(other)
488 | return self.n / self.d > other.n / other.d
489 |
490 | def __ge__(self, other):
491 | other = other if isinstance(other, Fraction) else Fraction(other)
492 | return self.n / self.d >= other.n / other.d
493 |
494 | def __lt__(self, other):
495 | other = other if isinstance(other, Fraction) else Fraction(other)
496 | return self.n / self.d < other.n / other.d
497 |
498 | def __le__(self, other):
499 | other = other if isinstance(other, Fraction) else Fraction(other)
500 | return self.n / self.d <= other.n / other.d
501 |
502 | def __eq__(self, other):
503 | other = other if isinstance(other, Fraction) else Fraction(other)
504 | return self.n / self.d == other.n / other.d
505 |
506 | def __ne__(self, other):
507 | other = other if isinstance(other, Fraction) else Fraction(other)
508 | return self.n / self.d != other.n / other.d
509 |
510 | def __str__(self):
511 | return f"{self.n}/{self.d}"
512 |
513 | def __repr__(self):
514 | return f"Fraction('{self.n}/{self.d}')"
515 | ```
516 | J. Дроби v0.7
517 | ```python
518 | class Fraction:
519 |
520 | def __simp(self, coords):
521 | if len(coords) == 1:
522 | coords += (1,)
523 | a, b = coords[0], coords[1]
524 | while b:
525 | a, b = b, a % b
526 | return coords[0] // a, coords[1] // a
527 |
528 | def __init__(self, *args):
529 | if isinstance(args[0], str):
530 | self.n, self.d = self.__simp(tuple(map(int, args[0].split('/'))))
531 | else:
532 | self.n, self.d = self.__simp(args)
533 |
534 | def numerator(self, number=0):
535 | if number:
536 | if self.n > 0:
537 | self.n, self.d = self.__simp((abs(number), self.d))
538 | self.n = -self.n if number < 0 else self.n
539 | elif self.n < 0:
540 | self.n, self.d = self.__simp((abs(number), self.d))
541 | self.n = -self.n if number > 0 else self.n
542 | return abs(self.n)
543 |
544 | def denominator(self, number=0):
545 | if number:
546 | if self.n > 0:
547 | self.n, self.d = self.__simp((self.n, abs(number)))
548 | self.n = -self.n if number < 0 else self.n
549 | elif self.n < 0:
550 | self.n, self.d = self.__simp((abs(self.n), abs(number)))
551 | self.n = -self.n if number > 0 else self.n
552 | return self.d
553 |
554 | def __neg__(self):
555 | return Fraction(-self.n, self.d)
556 |
557 | def __add__(self, other):
558 | other = other if isinstance(other, Fraction) else Fraction(other)
559 | return Fraction(self.n * other.d + other.n * self.d, self.d * other.d)
560 |
561 | def __radd__(self, other):
562 | other = other if isinstance(other, Fraction) else Fraction(other)
563 | return Fraction(self.n * other.d + other.n * self.d, self.d * other.d)
564 |
565 | def __iadd__(self, other):
566 | other = other if isinstance(other, Fraction) else Fraction(other)
567 | self.n, self.d = self.__simp((self.n * other.d + other.n * self.d, self.d * other.d))
568 | return self
569 |
570 | def __sub__(self, other):
571 | other = other if isinstance(other, Fraction) else Fraction(other)
572 | return Fraction(self.n * other.d - other.n * self.d, self.d * other.d)
573 |
574 | def __rsub__(self, other):
575 | other = other if isinstance(other, Fraction) else Fraction(other)
576 | return Fraction(other.n * self.d - self.n * other.d, self.d * other.d)
577 |
578 | def __isub__(self, other):
579 | other = other if isinstance(other, Fraction) else Fraction(other)
580 | self.n, self.d = self.__simp((self.n * other.d - other.n * self.d, self.d * other.d))
581 | return self
582 |
583 | def __mul__(self, other):
584 | other = other if isinstance(other, Fraction) else Fraction(other)
585 | return Fraction(self.n * other.n, self.d * other.d)
586 |
587 | def __rmul__(self, other):
588 | other = other if isinstance(other, Fraction) else Fraction(other)
589 | return Fraction(self.n * other.n, self.d * other.d)
590 |
591 | def __imul__(self, other):
592 | other = other if isinstance(other, Fraction) else Fraction(other)
593 | self.n, self.d = self.__simp((self.n * other.n, self.d * other.d))
594 | return self
595 |
596 | def __truediv__(self, other):
597 | other = other if isinstance(other, Fraction) else Fraction(other)
598 | return Fraction(self.n * other.d, self.d * other.n)
599 |
600 | def __rtruediv__(self, other):
601 | other = other if isinstance(other, Fraction) else Fraction(other)
602 | return Fraction(self.d * other.n, self.n * other.d)
603 |
604 | def __itruediv__(self, other):
605 | other = other if isinstance(other, Fraction) else Fraction(other)
606 | self.n, self.d = self.__simp((self.n * other.d, self.d * other.n))
607 | return self
608 |
609 | def reverse(self):
610 | self.n, self.d = self.__simp((self.d, self.n))
611 | return self
612 |
613 | def __gt__(self, other):
614 | other = other if isinstance(other, Fraction) else Fraction(other)
615 | return self.n / self.d > other.n / other.d
616 |
617 | def __ge__(self, other):
618 | other = other if isinstance(other, Fraction) else Fraction(other)
619 | return self.n / self.d >= other.n / other.d
620 |
621 | def __lt__(self, other):
622 | other = other if isinstance(other, Fraction) else Fraction(other)
623 | return self.n / self.d < other.n / other.d
624 |
625 | def __le__(self, other):
626 | other = other if isinstance(other, Fraction) else Fraction(other)
627 | return self.n / self.d <= other.n / other.d
628 |
629 | def __eq__(self, other):
630 | other = other if isinstance(other, Fraction) else Fraction(other)
631 | return self.n / self.d == other.n / other.d
632 |
633 | def __ne__(self, other):
634 | other = other if isinstance(other, Fraction) else Fraction(other)
635 | return self.n / self.d != other.n / other.d
636 |
637 | def __str__(self):
638 | return f"{self.n}/{self.d}"
639 |
640 | def __repr__(self):
641 | return f"Fraction('{self.n}/{self.d}')"
642 | ```
643 |
--------------------------------------------------------------------------------
/python_basics_5.3.md:
--------------------------------------------------------------------------------
1 | # Yandex handbook "Python Basics" answers
2 |
3 | 5.3. Модель исключений Python. Try, except, else, finally. Модули
4 |
5 | A. Обработка ошибок
6 | ```python
7 | try:
8 | func()
9 | except Exception as error:
10 | print(type(error).__name__)
11 | else:
12 | print('No Exceptions')
13 | ```
14 | B. Ломать — не строить
15 | ```python
16 | try:
17 | func('2', None)
18 | except ValueError:
19 | print('Ура! Ошибка!')
20 | ```
21 | C. Ломать — не строить 2
22 | ```python
23 | class Broken:
24 | def __repr__(self):
25 | raise Exception
26 |
27 |
28 | try:
29 | a = Broken()
30 | func(a)
31 | except Exception:
32 | print('Ура! Ошибка!')
33 | ```
34 | D. Контроль параметров
35 | ```python
36 | def only_positive_even_sum(a, b):
37 | if not (isinstance(a, int) and isinstance(b, int)):
38 | raise TypeError
39 | if not (a > 0 and not a % 2) or not (b > 0 and not b % 2):
40 | raise ValueError
41 | return a + b
42 | ```
43 | E. Слияние с проверкой
44 | ```python
45 | def merge(a, b):
46 | try:
47 | iterator_1 = iter(a)
48 | iterator_2 = iter(b)
49 | except TypeError:
50 | raise StopIteration
51 | if not (all(isinstance(i, type(a[0])) for i in a) and all(isinstance(i, type(a[0])) for i in b)):
52 | raise TypeError
53 | if list(a) != sorted(a) or list(b) != sorted(b):
54 | raise ValueError
55 | c = list(a) + list(b)
56 | c.sort()
57 | return tuple(c)
58 | ```
59 | F. Корень зла 2
60 | ```python
61 | class InfiniteSolutionsError(Exception):
62 | pass
63 |
64 |
65 | class NoSolutionsError(Exception):
66 | pass
67 |
68 |
69 | def find_roots(a, b, c):
70 | if sum(1 for i in (a, b, c) if type(i) not in (int, float)):
71 | raise TypeError
72 | elif not a and not b and not c:
73 | raise InfiniteSolutionsError
74 | elif not a and not b and c or b ** 2 < 4 * a * c:
75 | raise NoSolutionsError
76 | elif b ** 2 == 4 * a * c:
77 | return -b / (2 * a), -b / (2 * a)
78 | elif not a:
79 | return -c / b
80 | else:
81 | roots = [(-b - (b ** 2 - 4 * a * c) ** 0.5) / (2 * a), (-b + (b ** 2 - 4 * a * c) ** 0.5) / (2 * a)]
82 | roots.sort()
83 | return roots[0], roots[1]
84 | ```
85 | G. Валидация имени
86 | ```python
87 | class CyrillicError(Exception):
88 | pass
89 |
90 |
91 | class CapitalError(Exception):
92 | pass
93 |
94 |
95 | def name_validation(name):
96 | if not isinstance(name, str):
97 | raise TypeError
98 | if sum(i.lower() not in 'абвгдеёжзийклмнопрстуфхцчшщьыъэюя' for i in name):
99 | raise CyrillicError
100 | if name != name.lower().capitalize():
101 | raise CapitalError
102 | return name
103 | ```
104 | H. Валидация имени пользователя
105 | ```python
106 | class BadCharacterError(Exception):
107 | pass
108 |
109 |
110 | class StartsWithDigitError(Exception):
111 | pass
112 |
113 |
114 | def username_validation(username):
115 | if not isinstance(username, str):
116 | raise TypeError
117 | if sum((i.lower() not in '0123456789_abcdefghijklmnopqrstuvwxyz') for i in username):
118 | raise BadCharacterError
119 | if username[0].isdigit():
120 | raise StartsWithDigitError
121 | return username
122 | ```
123 | I. Валидация пользователя
124 | ```python
125 | class BadCharacterError(Exception):
126 | pass
127 |
128 |
129 | class StartsWithDigitError(Exception):
130 | pass
131 |
132 |
133 | class CyrillicError(Exception):
134 | pass
135 |
136 |
137 | class CapitalError(Exception):
138 | pass
139 |
140 |
141 | def name_validation(name):
142 | if not isinstance(name, str):
143 | raise TypeError
144 | if sum(i.lower() not in 'абвгдеёжзийклмнопрстуфхцчшщьыъэюя' for i in name):
145 | raise CyrillicError
146 | if name != name.lower().capitalize():
147 | raise CapitalError
148 | return name
149 |
150 |
151 | def username_validation(username):
152 | if not isinstance(username, str):
153 | raise TypeError
154 | if sum((i.lower() not in '0123456789_abcdefghijklmnopqrstuvwxyz') for i in username):
155 | raise BadCharacterError
156 | if username[0].isdigit():
157 | raise StartsWithDigitError
158 | return username
159 |
160 |
161 | def user_validation(**kwargs):
162 | if [i for i in kwargs] != ['last_name', 'first_name', 'username'] or len(kwargs) != 3:
163 | raise KeyError
164 | if any(not isinstance(k, str) for k in kwargs.values()):
165 | raise TypeError
166 | kwargs['last_name'] = name_validation(kwargs['last_name'])
167 | kwargs['first_name'] = name_validation(kwargs['first_name'])
168 | kwargs['username'] = username_validation(kwargs['username'])
169 | return kwargs
170 | ```
171 | J. Валидация пароля
172 | ```python
173 | import hashlib
174 |
175 |
176 | class MinLengthError(Exception):
177 | pass
178 |
179 |
180 | class PossibleCharError(Exception):
181 | pass
182 |
183 |
184 | class NeedCharError(Exception):
185 | pass
186 |
187 |
188 | def password_validation(password, min_length=8,
189 | possible_chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',
190 | at_least_one=str.isdigit):
191 | if not isinstance(password, str):
192 | raise TypeError
193 | if len(password) < min_length:
194 | raise MinLengthError
195 | if any(i not in possible_chars for i in password):
196 | raise PossibleCharError
197 | if not any(map(at_least_one, password)):
198 | raise NeedCharError
199 | return hashlib.sha256(password.encode()).hexdigest()
200 | ```
201 |
--------------------------------------------------------------------------------
/python_basics_6.1.md:
--------------------------------------------------------------------------------
1 | # Yandex handbook "Python Basics" answers
2 |
3 | 6.1. Модули math и numpy
4 |
5 | A. Математика — круто, но это не точно
6 | ```python
7 | import math as m
8 |
9 | x = float(input())
10 | a = m.log(m.pow(x, 3 / 16), 32)
11 | b = m.pow(x, m.cos((m.pi * x) / (2 * m.e)))
12 | c = m.pow(m.sin(x / m.pi), 2)
13 | print(a + b - c)
14 | ```
15 | B. Потоковый НОД
16 | ```python
17 | from math import gcd
18 | from sys import stdin
19 |
20 | for i in stdin:
21 | print(gcd(*map(int, i.split())))
22 | ```
23 | C. Есть варианты?
24 | ```python
25 | from math import comb
26 |
27 | n, m = map(int, input().split())
28 | print(comb(n, m) * m // n, comb(n, m))
29 | ```
30 | D. Среднее не арифметическое
31 | ```python
32 | import math as m
33 |
34 | numbers = list(map(float, input().split()))
35 | print(m.pow(m.prod(numbers), 1 / len(numbers)))
36 | ```
37 | E. Шаг навстречу
38 | ```python
39 | from math import dist, cos, sin
40 |
41 | deca_x, deca_y = map(float, input().split())
42 | pola_r, pola_f = map(float, input().split())
43 | pola_x = pola_r * cos(pola_f)
44 | pola_y = pola_r * sin(pola_f)
45 | print(dist((deca_x, deca_y), (pola_x, pola_y)))
46 | ```
47 | F. Матрица умножения
48 | ```python
49 | import numpy as np
50 |
51 |
52 | def multiplication_matrix(n):
53 | matrix = np.arange(1, n + 1)
54 | return matrix * matrix[:, None]
55 | ```
56 | G. Шахматная подготовка
57 | ```python
58 | import numpy as np
59 |
60 |
61 | def make_board(num):
62 | matrix = np.indices((num, num)).sum(axis=0) % 2
63 | return np.array(np.rot90(matrix), dtype='int8')
64 | ```
65 | H. Числовая змейка 3.0
66 | ```python
67 | import numpy as np
68 |
69 |
70 | def snake(m, n, direction='H'):
71 | matrix = np.zeros((n, m), dtype=np.int16)
72 | num = 1
73 | if direction == 'H':
74 | for i in range(n):
75 | if not i % 2:
76 | matrix[i] = np.arange(num, num + m)
77 | else:
78 | matrix[i] = np.arange(num + m - 1, num - 1, -1)
79 | num += m
80 | else:
81 | for j in range(m):
82 | if not j % 2:
83 | matrix[:, j] = np.arange(num, num + n)
84 | else:
85 | matrix[:, j] = np.arange(num + n - 1, num - 1, -1)
86 | num += n
87 | return matrix
88 | ```
89 | I. Вращение
90 | ```python
91 | import numpy as np
92 |
93 |
94 | def rotate(matrix, angle):
95 | return np.rot90(matrix, (360 - angle) // 90)
96 | ```
97 | J. Лесенка
98 | ```python
99 | import numpy as np
100 |
101 |
102 | def stairs(vector):
103 | n = len(vector)
104 | matrix = np.zeros((n, n), dtype=int)
105 | for i in range(n):
106 | matrix[i] = np.roll(vector, i)
107 | return matrix
108 | ```
109 |
--------------------------------------------------------------------------------
/python_basics_6.2.md:
--------------------------------------------------------------------------------
1 | # Yandex handbook "Python Basics" answers
2 |
3 | 6.2. Модуль pandas
4 |
5 | A. Длины всех слов - 2
6 | ```python
7 | import pandas as pd
8 |
9 |
10 | def length_stats(text):
11 | text = ''.join(i for i in text if i.isalpha() or i == ' ')
12 | arr = sorted(set(text.lower().split()))
13 | s = pd.Series([len(i) for i in arr], index=arr)
14 | return s
15 | ```
16 | B. Длины всех слов по чётности
17 | ```python
18 | import pandas as pd
19 |
20 |
21 | def length_stats(text):
22 | text = ''.join(i for i in text if i.isalpha() or i == ' ')
23 | arr = sorted(set(text.lower().split()))
24 | arr_odd = [i for i in arr if len(i) % 2]
25 | arr_even = [i for i in arr if not len(i) % 2]
26 | odd = pd.Series([len(i) for i in arr_odd], index=arr_odd, dtype='int64')
27 | even = pd.Series([len(i) for i in arr_even], index=arr_even, dtype='int64')
28 | return odd, even
29 | ```
30 | C. Чек - 2
31 | ```python
32 | import pandas as pd
33 |
34 |
35 | def cheque(price_list, **kwargs):
36 | my_products = sorted(kwargs)
37 | product_dict = {
38 | 'product': my_products,
39 | 'price': [price_list[i] for i in my_products],
40 | 'number': [kwargs[i] for i in my_products]
41 | }
42 | product_dict['cost'] = [price_list[i] * product_dict['number'][ind] for ind, i in enumerate(my_products)]
43 | s = pd.DataFrame(product_dict)
44 | return s
45 | ```
46 | D. Акция
47 | ```python
48 | import pandas as pd
49 |
50 |
51 | def cheque(price_list, **kwargs):
52 | my_products = sorted(kwargs)
53 | product_dict = {
54 | 'product': my_products,
55 | 'price': [price_list[i] for i in my_products],
56 | 'number': [kwargs[i] for i in my_products]
57 | }
58 | product_dict['cost'] = [price_list[i] * product_dict['number'][ind] for ind, i in enumerate(my_products)]
59 | s = pd.DataFrame(product_dict)
60 | return s
61 |
62 |
63 | def discount(s):
64 | new_s = s.copy()
65 | for i in range(len(new_s.loc[:, 'cost'])):
66 | new_s.loc[i, 'cost'] /= 1 + (s.loc[:, 'number'][i] > 2)
67 | return new_s
68 | ```
69 | E. Длинные слова
70 | ```python
71 | def get_long(data, min_length=5):
72 | return data[data >= min_length]
73 | ```
74 | F. Отчёт успеваемости
75 | ```python
76 | def best(j):
77 | new_j = j.copy()
78 | return new_j[(new_j['maths'] > 3) & (new_j['physics'] > 3) & (new_j['computer science'] > 3)]
79 | ```
80 | G. Отчёт неуспеваемости
81 | ```python
82 | def need_to_work_better(j):
83 | new_j = j.copy()
84 | return new_j[(new_j['maths'] < 3) | (new_j['physics'] < 3) | (new_j['computer science'] < 3)]
85 | ```
86 | H. Обновление журнала
87 | ```python
88 | def update(journal):
89 | j = journal.copy()
90 | for i in range(len(j.loc[:, 'name'])):
91 | j.loc[:, 'average'] = (j['maths'] + j['physics'] + j['computer science']) / 3
92 | return j.sort_values(by=['average', 'name'], ascending=(False, True))
93 | ```
94 | I. Бесконечный морской бой
95 | ```python
96 | import pandas as pd
97 |
98 | a, b = map(int, input().split())
99 | c, d = map(int, input().split())
100 | data = pd.read_csv('data.csv')
101 | print(data[(a <= data['x']) & (data['x'] <= c) & (d <= data['y']) & (data['y'] <= b)])
102 | ```
103 | J. Экстремум функции
104 | ```python
105 | import numpy as np
106 | import pandas as pd
107 |
108 |
109 | def values(func, start, end, step):
110 | index = np.arange(start, end + step, step)
111 | return pd.Series(map(func, index), index=index, dtype='float64')
112 |
113 |
114 | def min_extremum(data):
115 | return min(data[data == min(data)].index)
116 |
117 |
118 | def max_extremum(data):
119 | return max(data[data == max(data)].index)
120 | ```
121 |
--------------------------------------------------------------------------------
/python_basics_6.3.md:
--------------------------------------------------------------------------------
1 | # Yandex handbook "Python Basics" answers
2 |
3 | 6.3. Модуль requests
4 |
5 | A. Проверка системы
6 | ```python
7 | from requests import get
8 |
9 | print(get('http://127.0.0.1:5000').text)
10 | ```
11 | B. Суммирование ответов
12 | ```python
13 | from requests import get
14 |
15 | address = 'http://' + input()
16 | summ = 0
17 | while data := int(get(address).text):
18 | summ += data
19 | print(summ)
20 | ```
21 | C. Суммирование ответов 2
22 | ```python
23 | from requests import get
24 |
25 | address = 'http://' + input()
26 | data = get(address).json()
27 | print(sum(i for i in data if type(i) == int))
28 | ```
29 | D. Конкретное значение
30 | ```python
31 | from requests import get
32 |
33 | address = 'http://' + input()
34 | key = input()
35 | data = get(address).json()
36 | print(data.get(key, 'No data'))
37 | ```
38 | E. Суммирование ответов 3
39 | ```python
40 | from requests import get
41 | from sys import stdin
42 |
43 | address = 'http://' + input()
44 | ways = [i.strip() for i in stdin]
45 | summ = 0
46 | for way in ways:
47 | summ += sum(get(address + way).json())
48 | print(summ)
49 | ```
50 | F. Список пользователей
51 | ```python
52 | from requests import get
53 |
54 | address = 'http://' + input() + '/users'
55 | data = get(address).json()
56 | names = []
57 | for i in data:
58 | names.append(f"{i['last_name']} {i['first_name']}")
59 | for name in sorted(names):
60 | print(name)
61 | ```
62 | G. Рассылка сообщений
63 | ```python
64 | from requests import get
65 | from sys import stdin
66 |
67 | address = 'http://' + input() + '/users/' + input()
68 | d = ''.join(i for i in stdin)
69 | data = {}
70 | try:
71 | data = get(address).json()
72 | except ValueError:
73 | print('Пользователь не найден')
74 | if data:
75 | for key in data:
76 | d = d.replace('{' + key + '}', str(data[key]))
77 | print(d)
78 | ```
79 | H. Регистрация нового пользователя
80 | ```python
81 | from requests import post
82 | from json import dumps
83 |
84 | address = 'http://' + input() + '/users'
85 | data = {}
86 | data["username"] = input()
87 | data["last_name"] = input()
88 | data["first_name"] = input()
89 | data["email"] = input()
90 | post(address, data=dumps(data))
91 | ```
92 | I. Изменение данных
93 | ```python
94 | from requests import put
95 | from json import dumps
96 | from sys import stdin
97 |
98 | address = 'http://' + input() + '/users/' + input()
99 | line = [i.strip().split('=') for i in stdin]
100 | data = {}
101 | for j in line:
102 | data[j[0]] = j[1]
103 | put(address, data=dumps(data))
104 | ```
105 | J. Удаление данных
106 | ```python
107 | from requests import delete
108 |
109 | address = 'http://' + input() + '/users/' + input()
110 | delete(address)
111 | ```
112 |
--------------------------------------------------------------------------------