├── 2 ├── 2.1 │ ├── 1.py │ ├── 10.py │ ├── 11.py │ ├── 12.py │ ├── 13.py │ ├── 14.py │ ├── 15.py │ ├── 16.py │ ├── 17.py │ ├── 18.py │ ├── 19.py │ ├── 2.py │ ├── 20.py │ ├── 3.py │ ├── 4.py │ ├── 5.py │ ├── 6.py │ ├── 7.py │ ├── 8.py │ ├── 9.py │ └── solutions.md ├── 2.2 │ ├── 1.py │ ├── 10.py │ ├── 11.py │ ├── 12.py │ ├── 13.py │ ├── 14.py │ ├── 15.py │ ├── 16.py │ ├── 17.py │ ├── 18.py │ ├── 19.py │ ├── 2.py │ ├── 20.py │ ├── 3.py │ ├── 4.py │ ├── 5.py │ ├── 6.py │ ├── 7.py │ ├── 8.py │ ├── 9.py │ └── solutions.md ├── 2.3 │ ├── 1.py │ ├── 10.py │ ├── 11.py │ ├── 12.py │ ├── 13.py │ ├── 14.py │ ├── 15.py │ ├── 16.py │ ├── 17.py │ ├── 18.py │ ├── 19.py │ ├── 2.py │ ├── 20.py │ ├── 3.py │ ├── 4.py │ ├── 5.py │ ├── 6.py │ ├── 7.py │ ├── 8.py │ ├── 9.py │ └── solutions.md └── 2.4 │ ├── 1.py │ ├── 10.py │ ├── 11.py │ ├── 12.py │ ├── 13.py │ ├── 14.py │ ├── 15.py │ ├── 16.py │ ├── 17.py │ ├── 18.py │ ├── 19.py │ ├── 2.py │ ├── 20.py │ ├── 3.py │ ├── 4.py │ ├── 5.py │ ├── 6.py │ ├── 7.py │ ├── 8.py │ ├── 9.py │ └── solutions.md ├── 3 ├── 3.1 │ ├── 1.py │ ├── 10.py │ ├── 11.py │ ├── 12.py │ ├── 13.py │ ├── 14.py │ ├── 15.py │ ├── 16.py │ ├── 17.py │ ├── 18.py │ ├── 19.py │ ├── 2.py │ ├── 20.py │ ├── 3.py │ ├── 4.py │ ├── 5.py │ ├── 6.py │ ├── 7.py │ ├── 8.py │ ├── 9.py │ └── solutions.md ├── 3.2 │ ├── 1.py │ ├── 10.py │ ├── 11.py │ ├── 12.py │ ├── 13.py │ ├── 14.py │ ├── 15.py │ ├── 16.py │ ├── 17.py │ ├── 18.py │ ├── 19.py │ ├── 2.py │ ├── 20.py │ ├── 3.py │ ├── 4.py │ ├── 5.py │ ├── 6.py │ ├── 7.py │ ├── 8.py │ ├── 9.py │ └── solutions.md ├── 3.3 │ ├── 1.py │ ├── 10.py │ ├── 2.py │ ├── 3.py │ ├── 4.py │ ├── 5.py │ ├── 6.py │ ├── 7.py │ ├── 8.py │ ├── 9.py │ └── solutions.md ├── 3.4 │ ├── 1.py │ ├── 10.py │ ├── 11.py │ ├── 12.py │ ├── 13.py │ ├── 14.py │ ├── 15.py │ ├── 16.py │ ├── 17.py │ ├── 18.py │ ├── 19.py │ ├── 2.py │ ├── 20.py │ ├── 3.py │ ├── 4.py │ ├── 5.py │ ├── 6.py │ ├── 7.py │ ├── 8.py │ ├── 9.py │ └── solutions.md └── 3.5 │ ├── 1.py │ ├── 10.py │ ├── 11.py │ ├── 12.py │ ├── 13.py │ ├── 14.py │ ├── 15.py │ ├── 16.py │ ├── 17.py │ ├── 18.py │ ├── 19.py │ ├── 2.py │ ├── 20.py │ ├── 3.py │ ├── 4.py │ ├── 5.py │ ├── 6.py │ ├── 7.py │ ├── 8.py │ ├── 9.py │ └── solutions.md ├── 4 ├── 4.1 │ ├── 1.py │ ├── 10.py │ ├── 2.py │ ├── 3.py │ ├── 4.py │ ├── 5.py │ ├── 6.py │ ├── 7.py │ ├── 8.py │ ├── 9.py │ └── solutions.md ├── 4.2 │ ├── 1.py │ ├── 10.py │ ├── 2.py │ ├── 3.py │ ├── 4.py │ ├── 5.py │ ├── 6.py │ ├── 7.py │ ├── 8.py │ ├── 9.py │ └── solutions.md └── 4.3 │ ├── 1.py │ ├── 10.py │ ├── 2.py │ ├── 3.py │ ├── 4.py │ ├── 5.py │ ├── 6.py │ ├── 7.py │ ├── 8.py │ ├── 9.py │ └── solutions.md ├── 5 ├── 5.1 │ ├── 1.py │ ├── 10.py │ ├── 2.py │ ├── 3.py │ ├── 4.py │ ├── 5.py │ ├── 6.py │ ├── 7.py │ ├── 8.py │ ├── 9.py │ └── solutions.md ├── 5.2 │ ├── 1.py │ ├── 10.py │ ├── 2.py │ ├── 3.py │ ├── 4.py │ ├── 5.py │ ├── 6.py │ ├── 7.py │ ├── 8.py │ ├── 9.py │ └── solutions.md └── 5.3 │ ├── 1.py │ ├── 10.py │ ├── 2.py │ ├── 3.py │ ├── 4.py │ ├── 5.py │ ├── 6.py │ ├── 7.py │ ├── 8.py │ ├── 9.py │ └── solutions.md ├── 6 ├── 6.1 │ ├── 1.py │ ├── 10.py │ ├── 2.py │ ├── 3.py │ ├── 4.py │ ├── 5.py │ ├── 6.py │ ├── 7.py │ ├── 8.py │ ├── 9.py │ └── solutions.md ├── 6.2 │ ├── 1.py │ ├── 10.py │ ├── 2.py │ ├── 3.py │ ├── 4.py │ ├── 5.py │ ├── 6.py │ ├── 7.py │ ├── 8.py │ ├── 9.py │ └── solutions.md └── 6.3 │ ├── 1.py │ ├── 10.py │ ├── 2.py │ ├── 3.py │ ├── 4.py │ ├── 5.py │ ├── 6.py │ ├── 7.py │ ├── 8.py │ ├── 9.py │ └── solutions.md ├── .gitignore ├── LICENSE ├── README.md ├── poetry.lock └── pyproject.toml /.gitignore: -------------------------------------------------------------------------------- 1 | .venv 2 | .idea 3 | __pycache__/ 4 | -------------------------------------------------------------------------------- /2/2.1/1.py: -------------------------------------------------------------------------------- 1 | # Привет, Яндекс! 2 | def main() -> None: 3 | print("Привет, Яндекс!") 4 | 5 | 6 | if __name__ == "__main__": 7 | main() 8 | -------------------------------------------------------------------------------- /2/2.1/10.py: -------------------------------------------------------------------------------- 1 | # Детский сад — штаны на лямках 2 | def main() -> None: 3 | name, number = [input() for _ in range(2)] 4 | print(f"Группа №{number[0]}.") 5 | print(f"{number[2]}. {name}.") 6 | print(f"Шкафчик: {number}.") 7 | print(f"Кроватка: {number[1]}.") 8 | 9 | 10 | if __name__ == "__main__": 11 | main() 12 | -------------------------------------------------------------------------------- /2/2.1/11.py: -------------------------------------------------------------------------------- 1 | # Автоматизация игры 2 | def main() -> None: 3 | num = input() 4 | print(num[1] + num[0] + num[3] + num[2]) 5 | 6 | 7 | if __name__ == "__main__": 8 | main() 9 | -------------------------------------------------------------------------------- /2/2.1/12.py: -------------------------------------------------------------------------------- 1 | # Интересное сложение 2 | def main() -> None: 3 | num1, num2 = [int(input()) for _ in range(2)] 4 | ind2 = (num1 // 100 + num2 // 100) % 10 5 | ind1 = ((num1 // 10) % 10 + (num2 // 10) % 10) % 10 6 | ind0 = (num1 % 10 + num2 % 10) % 10 7 | print(f"{ind2 * 100 + ind1 * 10 + ind0}") 8 | 9 | 10 | if __name__ == "__main__": 11 | main() 12 | -------------------------------------------------------------------------------- /2/2.1/13.py: -------------------------------------------------------------------------------- 1 | # Дед Мороз и конфеты 2 | def main() -> None: 3 | candies, in_bag = [int(input()) for _ in range(2)] 4 | print(in_bag // candies, in_bag % candies, sep="\n") 5 | 6 | 7 | if __name__ == "__main__": 8 | main() 9 | -------------------------------------------------------------------------------- /2/2.1/14.py: -------------------------------------------------------------------------------- 1 | # Шарики и ручки 2 | def main() -> None: 3 | red, _, blue = [int(input()) for _ in range(3)] 4 | print(red + blue + 1) 5 | 6 | 7 | if __name__ == "__main__": 8 | main() 9 | -------------------------------------------------------------------------------- /2/2.1/15.py: -------------------------------------------------------------------------------- 1 | # В ожидании доставки 2 | def main() -> None: 3 | n, m, t = [int(input()) for _ in range(3)] 4 | hours = t // 60 5 | m += t % 60 6 | n = (n + hours + m // 60) % 24 7 | m %= 60 8 | print(f"{n if n >= 10 else f'0{n}'}:{m if m >= 10 else f'0{m}'}") 9 | 10 | 11 | if __name__ == "__main__": 12 | main() 13 | -------------------------------------------------------------------------------- /2/2.1/16.py: -------------------------------------------------------------------------------- 1 | # Доставка 2 | def main() -> None: 3 | print(f"{((-int(input()) + int(input())) / int(input())):.2f}") 4 | 5 | 6 | if __name__ == "__main__": 7 | main() 8 | -------------------------------------------------------------------------------- /2/2.1/17.py: -------------------------------------------------------------------------------- 1 | # Ошибка кассового аппарата 2 | def main() -> None: 3 | print(int(input()) + int(input(), 2)) 4 | 5 | 6 | if __name__ == "__main__": 7 | main() 8 | -------------------------------------------------------------------------------- /2/2.1/18.py: -------------------------------------------------------------------------------- 1 | # Сдача 10 2 | def main() -> None: 3 | print(-int(input(), 2) + int(input())) 4 | 5 | 6 | if __name__ == "__main__": 7 | main() 8 | -------------------------------------------------------------------------------- /2/2.1/19.py: -------------------------------------------------------------------------------- 1 | # Украшение чека 2 | def main() -> None: 3 | name = input() 4 | coast, weight, money = [int(input()) for _ in range(3)] 5 | print("=" * 16 + "Чек" + "=" * 16) 6 | print("Товар:" + f"{name:>29}") 7 | print("Цена:" + f"{f"{weight}кг * {coast}руб/кг":>30}") 8 | print("Итого:" + f"{f"{weight * coast}руб":>29}") 9 | print("Внесено:" + f"{f"{money}руб":>27}") 10 | print("Сдача:" + f"{f"{money - weight * coast}руб":>29}") 11 | print("=" * 35) 12 | 13 | 14 | if __name__ == "__main__": 15 | main() 16 | -------------------------------------------------------------------------------- /2/2.1/2.py: -------------------------------------------------------------------------------- 1 | # Привет, всем! 2 | def main() -> None: 3 | print(f"Привет, {input("Как Вас зовут?\n")}") 4 | 5 | 6 | if __name__ == "__main__": 7 | main() 8 | -------------------------------------------------------------------------------- /2/2.1/20.py: -------------------------------------------------------------------------------- 1 | # Мухи отдельно, котлеты отдельно 2 | def main() -> None: 3 | n, m, k1, k2 = [int(input()) for _ in range(4)] 4 | batch1 = (m * n - n * k2) // (k1 - k2) 5 | batch2 = n - batch1 6 | print(batch1, batch2) 7 | 8 | 9 | if __name__ == "__main__": 10 | main() 11 | -------------------------------------------------------------------------------- /2/2.1/3.py: -------------------------------------------------------------------------------- 1 | # Излишняя автоматизация 2 | def main() -> None: 3 | string = input() 4 | print(*[string for _ in range(3)], sep="\n") 5 | 6 | 7 | if __name__ == "__main__": 8 | main() 9 | -------------------------------------------------------------------------------- /2/2.1/4.py: -------------------------------------------------------------------------------- 1 | # Сдача 2 | def main() -> None: 3 | print(int(float(input()) - 2.5 * 38)) 4 | 5 | 6 | if __name__ == "__main__": 7 | main() 8 | -------------------------------------------------------------------------------- /2/2.1/5.py: -------------------------------------------------------------------------------- 1 | # Магазин 2 | def main() -> None: 3 | print(-int(input()) * int(input()) + int(input())) 4 | 5 | 6 | if __name__ == "__main__": 7 | main() 8 | -------------------------------------------------------------------------------- /2/2.1/6.py: -------------------------------------------------------------------------------- 1 | # Чек 2 | def main() -> None: 3 | name = input() 4 | coast, weight, money = [int(input()) for _ in range(3)] 5 | print("Чек") 6 | print(f"{name} - {weight}кг - {coast}руб/кг") 7 | print(f"Итого: {weight * coast}руб") 8 | print(f"Внесено: {money}руб") 9 | print(f"Сдача: {money - weight * coast}руб") 10 | 11 | 12 | if __name__ == "__main__": 13 | main() 14 | -------------------------------------------------------------------------------- /2/2.1/7.py: -------------------------------------------------------------------------------- 1 | # Делу — время, потехе — час 2 | def main() -> None: 3 | print(*["Купи слона!" for _ in range(int(input()))], sep="\n") 4 | 5 | 6 | if __name__ == "__main__": 7 | main() 8 | -------------------------------------------------------------------------------- /2/2.1/8.py: -------------------------------------------------------------------------------- 1 | # Наказание 2 | def main() -> None: 3 | n, message = int(input()), input() 4 | print(*[f"Я больше никогда не буду писать \"{message}\"!" for _ in range(n)], sep="\n") 5 | 6 | 7 | if __name__ == "__main__": 8 | main() 9 | -------------------------------------------------------------------------------- /2/2.1/9.py: -------------------------------------------------------------------------------- 1 | # Деловая колбаса 2 | def main() -> None: 3 | print(int(input()) * int(input()) // 2) 4 | 5 | 6 | if __name__ == "__main__": 7 | main() 8 | -------------------------------------------------------------------------------- /2/2.1/solutions.md: -------------------------------------------------------------------------------- 1 | # Ввод и вывод данных. Операции с числами, строками. Форматирование 2 | 3 | ### Привет, Яндекс! 4 | 5 | ```python 6 | def main() -> None: 7 | print("Привет, Яндекс!") 8 | 9 | 10 | if __name__ == "__main__": 11 | main() 12 | ``` 13 | 14 | ### Привет, всем! 15 | 16 | ```python 17 | def main() -> None: 18 | print(f"Привет, {input("Как Вас зовут?\n")}") 19 | 20 | 21 | if __name__ == "__main__": 22 | main() 23 | ``` 24 | 25 | ### Излишняя автоматизация 26 | 27 | ```python 28 | def main() -> None: 29 | string = input() 30 | print(*[string for _ in range(3)], sep="\n") 31 | 32 | 33 | if __name__ == "__main__": 34 | main() 35 | ``` 36 | 37 | ### Сдача 38 | 39 | ```python 40 | def main() -> None: 41 | print(int(float(input()) - 2.5 * 38)) 42 | 43 | 44 | if __name__ == "__main__": 45 | main() 46 | ``` 47 | 48 | ### Магазин 49 | 50 | ```python 51 | def main() -> None: 52 | print(-int(input()) * int(input()) + int(input())) 53 | 54 | 55 | if __name__ == "__main__": 56 | main() 57 | ``` 58 | 59 | ### Чек 60 | 61 | ```python 62 | def main() -> None: 63 | name = input() 64 | coast, weight, money = [int(input()) for _ in range(3)] 65 | print("Чек") 66 | print(f"{name} - {weight}кг - {coast}руб/кг") 67 | print(f"Итого: {weight * coast}руб") 68 | print(f"Внесено: {money}руб") 69 | print(f"Сдача: {money - weight * coast}руб") 70 | 71 | 72 | if __name__ == "__main__": 73 | main() 74 | ``` 75 | 76 | ### Делу — время, потехе — час 77 | 78 | ```python 79 | def main() -> None: 80 | print(*["Купи слона!" for _ in range(int(input()))], sep="\n") 81 | 82 | 83 | if __name__ == "__main__": 84 | main() 85 | ``` 86 | 87 | ### Наказание 88 | 89 | ```python 90 | def main() -> None: 91 | n, message = int(input()), input() 92 | print(*[f"Я больше никогда не буду писать \"{message}\"!" for _ in range(n)], sep="\n") 93 | 94 | 95 | if __name__ == "__main__": 96 | main() 97 | ``` 98 | 99 | ### Деловая колбаса 100 | 101 | ```python 102 | def main() -> None: 103 | print(int(input()) * int(input()) // 2) 104 | 105 | 106 | if __name__ == "__main__": 107 | main() 108 | ``` 109 | 110 | ### Детский сад — штаны на лямках 111 | 112 | ```python 113 | def main() -> None: 114 | name, number = [input() for _ in range(2)] 115 | print(f"Группа №{number[0]}.") 116 | print(f"{number[2]}. {name}.") 117 | print(f"Шкафчик: {number}.") 118 | print(f"Кроватка: {number[1]}.") 119 | 120 | 121 | if __name__ == "__main__": 122 | main() 123 | ``` 124 | 125 | ### Автоматизация игры 126 | 127 | ```python 128 | def main() -> None: 129 | num = input() 130 | print(num[1] + num[0] + num[3] + num[2]) 131 | 132 | 133 | if __name__ == "__main__": 134 | main() 135 | ``` 136 | 137 | ### Интересное сложение 138 | 139 | ```python 140 | def main() -> None: 141 | num1, num2 = [int(input()) for _ in range(2)] 142 | ind2 = (num1 // 100 + num2 // 100) % 10 143 | ind1 = ((num1 // 10) % 10 + (num2 // 10) % 10) % 10 144 | ind0 = (num1 % 10 + num2 % 10) % 10 145 | print(f"{ind2 * 100 + ind1 * 10 + ind0}") 146 | 147 | 148 | if __name__ == "__main__": 149 | main() 150 | ``` 151 | 152 | ### Дед Мороз и конфеты 153 | 154 | ```python 155 | def main() -> None: 156 | candies, in_bag = [int(input()) for _ in range(2)] 157 | print(in_bag // candies, in_bag % candies, sep="\n") 158 | 159 | 160 | if __name__ == "__main__": 161 | main() 162 | ``` 163 | 164 | ### Шарики и ручки 165 | 166 | ```python 167 | def main() -> None: 168 | red, _, blue = [int(input()) for _ in range(3)] 169 | print(red + blue + 1) 170 | 171 | 172 | if __name__ == "__main__": 173 | main() 174 | ``` 175 | 176 | ### В ожидании доставки 177 | 178 | ```python 179 | def main() -> None: 180 | n, m, t = [int(input()) for _ in range(3)] 181 | hours = t // 60 182 | m += t % 60 183 | n = (n + hours + m // 60) % 24 184 | m %= 60 185 | print(f"{n if n >= 10 else f'0{n}'}:{m if m >= 10 else f'0{m}'}") 186 | 187 | 188 | if __name__ == "__main__": 189 | main() 190 | ``` 191 | 192 | ### Доставка 193 | 194 | ```python 195 | def main() -> None: 196 | print(f"{((-int(input()) + int(input())) / int(input())):.2f}") 197 | 198 | 199 | if __name__ == "__main__": 200 | main() 201 | 202 | ``` 203 | 204 | ### Ошибка кассового аппарата 205 | 206 | ```python 207 | def main() -> None: 208 | print(int(input()) + int(input(), 2)) 209 | 210 | 211 | if __name__ == "__main__": 212 | main() 213 | ``` 214 | 215 | ### Сдача 10 216 | 217 | ```python 218 | def main() -> None: 219 | print(-int(input(), 2) + int(input())) 220 | 221 | 222 | if __name__ == "__main__": 223 | main() 224 | ``` 225 | 226 | ### Украшение чека 227 | 228 | ```python 229 | def main() -> None: 230 | name = input() 231 | coast, weight, money = [int(input()) for _ in range(3)] 232 | print("=" * 16 + "Чек" + "=" * 16) 233 | print("Товар:" + f"{name:>29}") 234 | print("Цена:" + f"{f"{weight}кг * {coast}руб/кг":>30}") 235 | print("Итого:" + f"{f"{weight * coast}руб":>29}") 236 | print("Внесено:" + f"{f"{money}руб":>27}") 237 | print("Сдача:" + f"{f"{money - weight * coast}руб":>29}") 238 | print("=" * 35) 239 | 240 | 241 | if __name__ == "__main__": 242 | main() 243 | ``` 244 | 245 | ### Мухи отдельно, котлеты отдельно 246 | 247 | ```python 248 | def main() -> None: 249 | n, m, k1, k2 = [int(input()) for _ in range(4)] 250 | batch1 = (m * n - n * k2) // (k1 - k2) 251 | batch2 = n - batch1 252 | print(batch1, batch2) 253 | 254 | 255 | if __name__ == "__main__": 256 | main() 257 | ``` 258 | -------------------------------------------------------------------------------- /2/2.2/1.py: -------------------------------------------------------------------------------- 1 | # Просто здравствуй, просто как дела 2 | def main() -> None: 3 | print(f"Здравствуйте, {input("Как Вас зовут?\n")}!") 4 | print("Я за вас рада!" if input("Как дела?\n") == "хорошо" else "Всё наладится!") 5 | 6 | 7 | if __name__ == "__main__": 8 | main() 9 | -------------------------------------------------------------------------------- /2/2.2/10.py: -------------------------------------------------------------------------------- 1 | # Лучшая защита — шифрование 2 | def main() -> None: 3 | number = int(input()) 4 | ind1 = number % 10 + (number // 10) % 10 5 | ind0 = number // 100 + (number // 10) % 10 6 | print(f"{ind1}{ind0}" if ind1 >= ind0 else f"{ind0}{ind1}") 7 | 8 | 9 | if __name__ == "__main__": 10 | main() 11 | -------------------------------------------------------------------------------- /2/2.2/11.py: -------------------------------------------------------------------------------- 1 | # Красота спасёт мир 2 | def main() -> None: 3 | n = sorted([int(x) for x in input()]) 4 | print("YES" if n[2] + n[0] == n[1] * 2 else "NO") 5 | 6 | 7 | if __name__ == "__main__": 8 | main() 9 | -------------------------------------------------------------------------------- /2/2.2/12.py: -------------------------------------------------------------------------------- 1 | # Музыкальный инструмент 2 | def main() -> None: 3 | side1, side2, side3 = [int(input()) for _ in range(3)] 4 | print("YES" if (side1 < side2 + side3) and (side2 < side1 + side3) and (side3 < side1 + side2) else "NO") 5 | 6 | 7 | if __name__ == "__main__": 8 | main() 9 | -------------------------------------------------------------------------------- /2/2.2/13.py: -------------------------------------------------------------------------------- 1 | # Властелин Чисел: Братство общей цифры 2 | def main() -> None: 3 | num1, num2, num3 = [int(input()) for _ in range(3)] 4 | print(num1 // 10 if (num1 // 10) == (num2 // 10) == (num3 // 10) else num1 % 10) 5 | 6 | 7 | if __name__ == "__main__": 8 | main() 9 | -------------------------------------------------------------------------------- /2/2.2/14.py: -------------------------------------------------------------------------------- 1 | # Властелин Чисел: Две Башни 2 | def main() -> None: 3 | number = input() 4 | raw_combinations = [number[i] + number[j] for i in range(len(number)) for j in range(len(number)) if i != j] 5 | combinations = sorted([int(i) for i in raw_combinations if i[0] != '0']) 6 | print(combinations[0], combinations[-1]) 7 | 8 | 9 | if __name__ == "__main__": 10 | main() 11 | -------------------------------------------------------------------------------- /2/2.2/15.py: -------------------------------------------------------------------------------- 1 | # Властелин Чисел: Возвращение Цезаря 2 | def main() -> None: 3 | num1, num2 = input(), input() 4 | combinations = sorted([int(x) for x in (num1[0], num1[1], num2[0], num2[1])]) 5 | print(f"{combinations[-1]}{(sum(combinations) - combinations[-1] - combinations[0]) % 10}{combinations[0]}") 6 | 7 | 8 | if __name__ == "__main__": 9 | main() 10 | -------------------------------------------------------------------------------- /2/2.2/16.py: -------------------------------------------------------------------------------- 1 | # Легенды велогонок возвращаются: кто быстрее? 2 | def main() -> None: 3 | rating = {"Петя": int(input()), "Вася": int(input()), "Толя": int(input())} 4 | sorted_rating = sorted(rating.items(), key=lambda x: x[1])[::-1] 5 | 6 | print(f"{f"{sorted_rating[0][0]}":^24}") 7 | print(f"{f"{sorted_rating[1][0]}":^8}") 8 | print(" " * 16 + f"{f"{sorted_rating[2][0]}":^8}") 9 | print(f"{"II":^8}" + f"{"I":^8}" + f"{"III":^8}") 10 | 11 | 12 | if __name__ == "__main__": 13 | main() 14 | -------------------------------------------------------------------------------- /2/2.2/17.py: -------------------------------------------------------------------------------- 1 | # Корень зла 2 | def main() -> None: 3 | a, b, c = [float(input()) for _ in range(3)] 4 | 5 | if a == b == c == 0: 6 | print("Infinite solutions") 7 | elif (a == b == 0 and c != 0) or b ** 2 < 4 * a * c: 8 | print("No solution") 9 | elif b ** 2 == 4 * a * c: 10 | print(f"{-b / (2 * a):.2f}") 11 | elif a == 0: 12 | print(f"{-c / b:.2f}") 13 | else: 14 | solutions = sorted([(-b - (b ** 2 - 4 * a * c) ** 0.5) / (2 * a), (-b + (b ** 2 - 4 * a * c) ** 0.5) / (2 * a)]) 15 | print(f"{solutions[0]:.2f} {solutions[1]:.2f}") 16 | 17 | 18 | if __name__ == "__main__": 19 | main() 20 | -------------------------------------------------------------------------------- /2/2.2/18.py: -------------------------------------------------------------------------------- 1 | # Территория зла 2 | def main() -> None: 3 | side1, side2, c = [int(input()) for _ in range(3)] 4 | if (side1 ** 2 == side2 ** 2 + c ** 2) or (side2 ** 2 == side1 ** 2 + c ** 2) or (c ** 2 == side1 ** 2 + side2 ** 2): 5 | print("100%") 6 | elif (side1 ** 2 > side2 ** 2 + c ** 2) or (side2 ** 2 > side1 ** 2 + c ** 2) or (c ** 2 > side1 ** 2 + side2 ** 2): 7 | print("велика") 8 | else: 9 | print("крайне мала") 10 | 11 | 12 | if __name__ == "__main__": 13 | main() 14 | -------------------------------------------------------------------------------- /2/2.2/19.py: -------------------------------------------------------------------------------- 1 | # Автоматизация безопасности 2 | def main() -> None: 3 | x, y = [float(input()) for _ in range(2)] 4 | 5 | rectangle = y <= 5 6 | circle = x ** 2 + y ** 2 <= 25 7 | parable = y >= 0.25 * (x + 1) ** 2 - 9 8 | triangle = y <= (5 / 3) * x + (35 / 3) 9 | 10 | if rectangle and circle and parable and triangle: 11 | print("Опасность! Покиньте зону как можно скорее!") 12 | elif x ** 2 + y ** 2 >= 100: 13 | print("Вы вышли в море и рискуете быть съеденным акулой!") 14 | else: 15 | print("Зона безопасна. Продолжайте работу.") 16 | 17 | 18 | if __name__ == "__main__": 19 | main() 20 | -------------------------------------------------------------------------------- /2/2.2/2.py: -------------------------------------------------------------------------------- 1 | # Кто быстрее? 2 | def main() -> None: 3 | print("Петя" if int(input()) > int(input()) else "Вася") 4 | 5 | 6 | if __name__ == "__main__": 7 | main() 8 | -------------------------------------------------------------------------------- /2/2.2/20.py: -------------------------------------------------------------------------------- 1 | # Зайка — 2 2 | def main() -> None: 3 | result = min([i for i in ([input() for _ in range(3)]) if "зайка" in i]) 4 | print(result, len(result)) 5 | 6 | 7 | if __name__ == "__main__": 8 | main() 9 | -------------------------------------------------------------------------------- /2/2.2/3.py: -------------------------------------------------------------------------------- 1 | # Кто быстрее на этот раз? 2 | def main() -> None: 3 | rating = {"Петя": int(input()), "Вася": int(input()), "Толя": int(input())} 4 | sorted_rating = sorted(rating.items(), key=lambda x: x[1])[::-1] 5 | print(sorted_rating[0][0]) 6 | 7 | 8 | if __name__ == "__main__": 9 | main() 10 | -------------------------------------------------------------------------------- /2/2.2/4.py: -------------------------------------------------------------------------------- 1 | # Список победителей 2 | def main() -> None: 3 | rating = {"Петя": int(input()), "Вася": int(input()), "Толя": int(input())} 4 | sorted_rating = sorted(rating.items(), key=lambda x: x[1])[::-1] 5 | print(*[f"{i + 1}. {sorted_rating[i][0]}" for i in range(3)], sep="\n") 6 | 7 | 8 | if __name__ == "__main__": 9 | main() 10 | -------------------------------------------------------------------------------- /2/2.2/5.py: -------------------------------------------------------------------------------- 1 | # Яблоки 2 | def main() -> None: 3 | print("Петя" if 7 - 3 + 2 + int(input()) > 6 + 3 + 5 - 2 + int(input()) else "Вася") 4 | 5 | 6 | if __name__ == "__main__": 7 | main() 8 | -------------------------------------------------------------------------------- /2/2.2/6.py: -------------------------------------------------------------------------------- 1 | # Сила прокрастинации 2 | def main() -> None: 3 | year = int(input()) 4 | print("YES" if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0 else "NO") 5 | 6 | 7 | if __name__ == "__main__": 8 | main() 9 | -------------------------------------------------------------------------------- /2/2.2/7.py: -------------------------------------------------------------------------------- 1 | # А роза упала на лапу Азора 2 | def main() -> None: 3 | print("YES" if (number := input()) == number[::-1] else "NO") 4 | 5 | 6 | if __name__ == "__main__": 7 | main() 8 | -------------------------------------------------------------------------------- /2/2.2/8.py: -------------------------------------------------------------------------------- 1 | # Зайка — 1 2 | def main() -> None: 3 | print("YES" if "зайка" in input() else "NO") 4 | 5 | 6 | if __name__ == "__main__": 7 | main() 8 | -------------------------------------------------------------------------------- /2/2.2/9.py: -------------------------------------------------------------------------------- 1 | # Первому игроку приготовиться 2 | def main() -> None: 3 | print(min(input(), input(), input())) 4 | 5 | 6 | if __name__ == "__main__": 7 | main() 8 | -------------------------------------------------------------------------------- /2/2.2/solutions.md: -------------------------------------------------------------------------------- 1 | # Условный оператор 2 | 3 | ### Просто здравствуй, просто как дела 4 | 5 | ```python 6 | def main() -> None: 7 | print(f"Здравствуйте, {input("Как Вас зовут?\n")}!") 8 | print("Я за вас рада!" if input("Как дела?\n") == "хорошо" else "Всё наладится!") 9 | 10 | 11 | if __name__ == "__main__": 12 | main() 13 | ``` 14 | 15 | ### Кто быстрее? 16 | 17 | ```python 18 | def main() -> None: 19 | print("Петя" if int(input()) > int(input()) else "Вася") 20 | 21 | 22 | if __name__ == "__main__": 23 | main() 24 | ``` 25 | 26 | ### Кто быстрее на этот раз? 27 | 28 | ```python 29 | def main() -> None: 30 | rating = {"Петя": int(input()), "Вася": int(input()), "Толя": int(input())} 31 | sorted_rating = sorted(rating.items(), key=lambda x: x[1])[::-1] 32 | print(sorted_rating[0][0]) 33 | 34 | 35 | if __name__ == "__main__": 36 | main() 37 | ``` 38 | 39 | ### Список победителей 40 | 41 | ```python 42 | def main() -> None: 43 | rating = {"Петя": int(input()), "Вася": int(input()), "Толя": int(input())} 44 | sorted_rating = sorted(rating.items(), key=lambda x: x[1])[::-1] 45 | print(*[f"{i + 1}. {sorted_rating[i][0]}" for i in range(3)], sep="\n") 46 | 47 | 48 | if __name__ == "__main__": 49 | main() 50 | ``` 51 | 52 | ### Яблоки 53 | 54 | ```python 55 | def main() -> None: 56 | print("Петя" if 7 - 3 + 2 + int(input()) > 6 + 3 + 5 - 2 + int(input()) else "Вася") 57 | 58 | 59 | if __name__ == "__main__": 60 | main() 61 | ``` 62 | 63 | ### Сила прокрастинации 64 | 65 | ```python 66 | def main() -> None: 67 | year = int(input()) 68 | print("YES" if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0 else "NO") 69 | 70 | 71 | if __name__ == "__main__": 72 | main() 73 | ``` 74 | 75 | ### А роза упала на лапу Азора 76 | 77 | ```python 78 | def main() -> None: 79 | print("YES" if (number := input()) == number[::-1] else "NO") 80 | 81 | 82 | if __name__ == "__main__": 83 | main() 84 | ``` 85 | 86 | ### Зайка — 1 87 | 88 | ```python 89 | def main() -> None: 90 | print("YES" if "зайка" in input() else "NO") 91 | 92 | 93 | if __name__ == "__main__": 94 | main() 95 | ``` 96 | 97 | ### Первому игроку приготовиться 98 | 99 | ```python 100 | def main() -> None: 101 | print(min(input(), input(), input())) 102 | 103 | 104 | if __name__ == "__main__": 105 | main() 106 | ``` 107 | 108 | ### Лучшая защита — шифрование 109 | 110 | ```python 111 | def main() -> None: 112 | number = int(input()) 113 | ind1 = number % 10 + (number // 10) % 10 114 | ind0 = number // 100 + (number // 10) % 10 115 | print(f"{ind1}{ind0}" if ind1 >= ind0 else f"{ind0}{ind1}") 116 | 117 | 118 | if __name__ == "__main__": 119 | main() 120 | ``` 121 | 122 | ### Красота спасёт мир 123 | 124 | ```python 125 | def main() -> None: 126 | n = sorted([int(x) for x in input()]) 127 | print("YES" if n[2] + n[0] == n[1] * 2 else "NO") 128 | 129 | 130 | if __name__ == "__main__": 131 | main() 132 | ``` 133 | 134 | ### Музыкальный инструмент 135 | 136 | ```python 137 | def main() -> None: 138 | side1, side2, side3 = [int(input()) for _ in range(3)] 139 | print("YES" if (side1 < side2 + side3) and (side2 < side1 + side3) and (side3 < side1 + side2) else "NO") 140 | 141 | 142 | if __name__ == "__main__": 143 | main() 144 | ``` 145 | 146 | ### Властелин Чисел: Братство общей цифры 147 | 148 | ```python 149 | def main() -> None: 150 | num1, num2, num3 = [int(input()) for _ in range(3)] 151 | print(num1 // 10 if (num1 // 10) == (num2 // 10) == (num3 // 10) else num1 % 10) 152 | 153 | 154 | if __name__ == "__main__": 155 | main() 156 | ``` 157 | 158 | ### Властелин Чисел: Две Башни 159 | 160 | ```python 161 | def main() -> None: 162 | number = input() 163 | raw_combinations = [number[i] + number[j] for i in range(len(number)) for j in range(len(number)) if i != j] 164 | combinations = sorted([int(i) for i in raw_combinations if i[0] != '0']) 165 | print(combinations[0], combinations[-1]) 166 | 167 | 168 | if __name__ == "__main__": 169 | main() 170 | ``` 171 | 172 | ### Властелин Чисел: Возвращение Цезаря 173 | 174 | ```python 175 | def main() -> None: 176 | num1, num2 = input(), input() 177 | combinations = sorted([int(x) for x in (num1[0], num1[1], num2[0], num2[1])]) 178 | print(f"{combinations[-1]}{(sum(combinations) - combinations[-1] - combinations[0]) % 10}{combinations[0]}") 179 | 180 | 181 | if __name__ == "__main__": 182 | main() 183 | ``` 184 | 185 | ### Легенды велогонок возвращаются: кто быстрее? 186 | 187 | ```python 188 | def main() -> None: 189 | rating = {"Петя": int(input()), "Вася": int(input()), "Толя": int(input())} 190 | sorted_rating = sorted(rating.items(), key=lambda x: x[1])[::-1] 191 | 192 | print(f"{f"{sorted_rating[0][0]}":^24}") 193 | print(f"{f"{sorted_rating[1][0]}":^8}") 194 | print(" " * 16 + f"{f"{sorted_rating[2][0]}":^8}") 195 | print(f"{"II":^8}" + f"{"I":^8}" + f"{"III":^8}") 196 | 197 | 198 | if __name__ == "__main__": 199 | main() 200 | ``` 201 | 202 | ### Корень зла 203 | 204 | ```python 205 | def main() -> None: 206 | a, b, c = [float(input()) for _ in range(3)] 207 | 208 | if a == b == c == 0: 209 | print("Infinite solutions") 210 | elif (a == b == 0 and c != 0) or b ** 2 < 4 * a * c: 211 | print("No solution") 212 | elif b ** 2 == 4 * a * c: 213 | print(f"{-b / (2 * a):.2f}") 214 | elif a == 0: 215 | print(f"{-c / b:.2f}") 216 | else: 217 | solutions = sorted([(-b - (b ** 2 - 4 * a * c) ** 0.5) / (2 * a), (-b + (b ** 2 - 4 * a * c) ** 0.5) / (2 * a)]) 218 | print(f"{solutions[0]:.2f} {solutions[1]:.2f}") 219 | 220 | 221 | if __name__ == "__main__": 222 | main() 223 | ``` 224 | 225 | ### Территория зла 226 | 227 | ```python 228 | def main() -> None: 229 | side1, side2, c = [int(input()) for _ in range(3)] 230 | if (side1 ** 2 == side2 ** 2 + c ** 2) or (side2 ** 2 == side1 ** 2 + c ** 2) or ( 231 | c ** 2 == side1 ** 2 + side2 ** 2): 232 | print("100%") 233 | elif (side1 ** 2 > side2 ** 2 + c ** 2) or (side2 ** 2 > side1 ** 2 + c ** 2) or (c ** 2 > side1 ** 2 + side2 ** 2): 234 | print("велика") 235 | else: 236 | print("крайне мала") 237 | 238 | 239 | if __name__ == "__main__": 240 | main() 241 | ``` 242 | 243 | ### Автоматизация безопасности 244 | 245 | ```python 246 | def main() -> None: 247 | x, y = [float(input()) for _ in range(2)] 248 | 249 | rectangle = y <= 5 250 | circle = x ** 2 + y ** 2 <= 25 251 | parable = y >= 0.25 * (x + 1) ** 2 - 9 252 | triangle = y <= (5 / 3) * x + (35 / 3) 253 | 254 | if rectangle and circle and parable and triangle: 255 | print("Опасность! Покиньте зону как можно скорее!") 256 | elif x ** 2 + y ** 2 >= 100: 257 | print("Вы вышли в море и рискуете быть съеденным акулой!") 258 | else: 259 | print("Зона безопасна. Продолжайте работу.") 260 | 261 | 262 | if __name__ == "__main__": 263 | main() 264 | ``` 265 | 266 | ### Зайка — 2 267 | 268 | ```python 269 | def main() -> None: 270 | result = min([i for i in ([input() for _ in range(3)]) if "зайка" in i]) 271 | print(result, len(result)) 272 | 273 | 274 | if __name__ == "__main__": 275 | main() 276 | ``` -------------------------------------------------------------------------------- /2/2.3/1.py: -------------------------------------------------------------------------------- 1 | # Раз, два, три! Ёлочка, гори! 2 | def main() -> None: 3 | while input() != "Три!": 4 | print("Режим ожидания...") 5 | print("Ёлочка, гори!") 6 | 7 | 8 | if __name__ == "__main__": 9 | main() 10 | -------------------------------------------------------------------------------- /2/2.3/10.py: -------------------------------------------------------------------------------- 1 | # Маршрут построен 2 | def main() -> None: 3 | x = y = 0 4 | x_dir = {"ВОСТОК": 1, "ЗАПАД": -1} 5 | y_dir = {"СЕВЕР": 1, "ЮГ": -1} 6 | 7 | while (direction := input()) != "СТОП": 8 | value = int(input()) 9 | (x, y) = (x + value * x_dir[direction], y) if direction in x_dir else (x, y + value * y_dir[direction]) 10 | print(y, x, sep="\n") 11 | 12 | 13 | if __name__ == "__main__": 14 | main() 15 | -------------------------------------------------------------------------------- /2/2.3/11.py: -------------------------------------------------------------------------------- 1 | # Цифровая сумма 2 | def main() -> None: 3 | print(sum([int(i) for i in input()])) 4 | 5 | 6 | if __name__ == "__main__": 7 | main() 8 | -------------------------------------------------------------------------------- /2/2.3/12.py: -------------------------------------------------------------------------------- 1 | # Сильная цифра 2 | def main() -> None: 3 | print(max([int(i) for i in input()])) 4 | 5 | 6 | if __name__ == "__main__": 7 | main() 8 | -------------------------------------------------------------------------------- /2/2.3/13.py: -------------------------------------------------------------------------------- 1 | # Первому игроку приготовиться 2.0 2 | def main() -> None: 3 | print(min([input() for _ in range(int(input()))])) 4 | 5 | 6 | if __name__ == "__main__": 7 | main() 8 | -------------------------------------------------------------------------------- /2/2.3/14.py: -------------------------------------------------------------------------------- 1 | # Простая задача 2 | def is_prime(num: int) -> bool: 3 | return num > 1 and all(num % i != 0 for i in range(2, int(num ** 0.5) + 1)) 4 | 5 | 6 | def main() -> None: 7 | print("YES" if is_prime(int(input())) else "NO") 8 | 9 | 10 | if __name__ == "__main__": 11 | main() 12 | -------------------------------------------------------------------------------- /2/2.3/15.py: -------------------------------------------------------------------------------- 1 | # Зайка - 4 2 | def main() -> None: 3 | print(sum([1 for _ in range(int(input())) if "зайка" in input()])) 4 | 5 | 6 | if __name__ == "__main__": 7 | main() 8 | -------------------------------------------------------------------------------- /2/2.3/16.py: -------------------------------------------------------------------------------- 1 | # А роза упала на лапу Азора 2.0 2 | def main() -> None: 3 | print("YES" if (number := input()) == number[::-1] else "NO") 4 | 5 | 6 | if __name__ == "__main__": 7 | main() 8 | -------------------------------------------------------------------------------- /2/2.3/17.py: -------------------------------------------------------------------------------- 1 | # Чётная чистота 2 | def main() -> None: 3 | print(*[int(i) for i in input() if int(i) % 2 != 0], sep="") 4 | 5 | 6 | if __name__ == "__main__": 7 | main() 8 | -------------------------------------------------------------------------------- /2/2.3/18.py: -------------------------------------------------------------------------------- 1 | # Простая задача 2.0 2 | def main() -> None: 3 | number, multipliers, divider = int(input()), [], 2 4 | print(number) if number < 2 else ... 5 | 6 | while number > 1: 7 | if number % divider == 0: 8 | multipliers.append(divider) 9 | number //= divider 10 | else: 11 | divider += 1 12 | 13 | print(*multipliers, sep=" * ") 14 | 15 | 16 | if __name__ == "__main__": 17 | main() 18 | -------------------------------------------------------------------------------- /2/2.3/19.py: -------------------------------------------------------------------------------- 1 | # Игра в «Угадайку» 2 | def main() -> None: 3 | number, half = 500, 250 4 | print(number) 5 | while (string := input()) != "Угадал!": 6 | number += half if string == "Больше" else -half if string == "Меньше" else 0 7 | half = (half + 1) // 2 if half >= 2 else ... 8 | print(number) 9 | 10 | 11 | if __name__ == "__main__": 12 | main() 13 | -------------------------------------------------------------------------------- /2/2.3/2.py: -------------------------------------------------------------------------------- 1 | # Зайка — 3 2 | def main() -> None: 3 | count = 0 4 | while (string := input()) != "Приехали!": 5 | count += 1 if "зайка" in string else ... 6 | print(count) 7 | 8 | 9 | if __name__ == "__main__": 10 | main() 11 | -------------------------------------------------------------------------------- /2/2.3/20.py: -------------------------------------------------------------------------------- 1 | # Хайпанём немножечко! 2 | def main() -> None: 3 | result, hn = -1, 0 4 | for i in range(int(input())): 5 | b = int(input()) 6 | h = b % 256 7 | r = (b // 256) % 256 8 | m = b // (256 ** 2) 9 | temp = 37 * (hn + r + m) % 256 10 | if temp != h or h >= 100: 11 | result = i 12 | break 13 | hn = h 14 | print(result) 15 | 16 | 17 | if __name__ == "__main__": 18 | main() 19 | -------------------------------------------------------------------------------- /2/2.3/3.py: -------------------------------------------------------------------------------- 1 | # Считалочка 2 | def main() -> None: 3 | print(*[i for i in range(int(input()), int(input()) + 1)], end=" ") 4 | 5 | 6 | if __name__ == "__main__": 7 | main() 8 | -------------------------------------------------------------------------------- /2/2.3/4.py: -------------------------------------------------------------------------------- 1 | # Считалочка 2.0 2 | def main() -> None: 3 | start, end = [int(input()) for _ in range(2)] 4 | step = 1 if start < end else -1 5 | print(*[i for i in range(start, end + step, step)], end=" ") 6 | 7 | 8 | if __name__ == "__main__": 9 | main() 10 | -------------------------------------------------------------------------------- /2/2.3/5.py: -------------------------------------------------------------------------------- 1 | # Внимание! Акция! 2 | def main() -> None: 3 | discount = full_coast = 0 4 | while (s := float(input())) != 0: 5 | discount += s * (s >= 500) 6 | full_coast += s * (s < 500) 7 | print(full_coast + discount * 9 / 10) 8 | 9 | 10 | if __name__ == "__main__": 11 | main() 12 | -------------------------------------------------------------------------------- /2/2.3/6.py: -------------------------------------------------------------------------------- 1 | # НОД 2 | def main() -> None: 3 | num1, num2 = [int(input()) for _ in range(2)] 4 | while num1 != 0 and num2 != 0: 5 | num1, num2 = (num1 % num2, num2) if num1 > num2 else (num1, num2 % num1) 6 | print(num1 + num2) 7 | 8 | 9 | if __name__ == "__main__": 10 | main() 11 | -------------------------------------------------------------------------------- /2/2.3/7.py: -------------------------------------------------------------------------------- 1 | # НОК 2 | def GCD(num1: int, num2: int) -> int: 3 | while num1 != 0 and num2 != 0: 4 | num1, num2 = (num1 % num2, num2) if num1 > num2 else (num1, num2 % num1) 5 | return num1 + num2 6 | 7 | 8 | def main() -> None: 9 | num1, num2 = [int(input()) for _ in range(2)] 10 | print(num1 * num2 // GCD(num1, num2)) 11 | 12 | 13 | if __name__ == "__main__": 14 | main() 15 | -------------------------------------------------------------------------------- /2/2.3/8.py: -------------------------------------------------------------------------------- 1 | # Излишняя автоматизация 2.0 2 | def main() -> None: 3 | string = input() 4 | for _ in range(int(input())): 5 | print(string) 6 | 7 | 8 | if __name__ == "__main__": 9 | main() 10 | -------------------------------------------------------------------------------- /2/2.3/9.py: -------------------------------------------------------------------------------- 1 | # Факториал 2 | def f(n: int) -> int: 3 | return n * f(n - 1) if n > 1 else 1 4 | 5 | 6 | def main() -> None: 7 | print(f(int(input()))) 8 | 9 | 10 | if __name__ == "__main__": 11 | main() 12 | -------------------------------------------------------------------------------- /2/2.3/solutions.md: -------------------------------------------------------------------------------- 1 | # Циклы 2 | 3 | ### Раз, два, три! Ёлочка, гори! 4 | 5 | ```python 6 | def main() -> None: 7 | while input() != "Три!": 8 | print("Режим ожидания...") 9 | print("Ёлочка, гори!") 10 | 11 | 12 | if __name__ == "__main__": 13 | main() 14 | ``` 15 | 16 | ### Зайка — 3 17 | 18 | ```python 19 | def main() -> None: 20 | count = 0 21 | while (string := input()) != "Приехали!": 22 | count += 1 if "зайка" in string else ... 23 | print(count) 24 | 25 | 26 | if __name__ == "__main__": 27 | main() 28 | ``` 29 | 30 | ### Считалочка 31 | 32 | ```python 33 | def main() -> None: 34 | print(*[i for i in range(int(input()), int(input()) + 1)], end=" ") 35 | 36 | 37 | if __name__ == "__main__": 38 | main() 39 | ``` 40 | 41 | ### Считалочка 2.0 42 | 43 | ```python 44 | def main() -> None: 45 | start, end = [int(input()) for _ in range(2)] 46 | step = 1 if start < end else -1 47 | print(*[i for i in range(start, end + step, step)], end=" ") 48 | 49 | 50 | if __name__ == "__main__": 51 | main() 52 | ``` 53 | 54 | ### Внимание! Акция! 55 | 56 | ```python 57 | def main() -> None: 58 | discount = full_coast = 0 59 | while (s := float(input())) != 0: 60 | discount += s * (s >= 500) 61 | full_coast += s * (s < 500) 62 | print(full_coast + discount * 9 / 10) 63 | 64 | 65 | if __name__ == "__main__": 66 | main() 67 | ``` 68 | 69 | ### НОД 70 | 71 | ```python 72 | def main() -> None: 73 | num1, num2 = [int(input()) for _ in range(2)] 74 | while num1 != 0 and num2 != 0: 75 | num1, num2 = (num1 % num2, num2) if num1 > num2 else (num1, num2 % num1) 76 | print(num1 + num2) 77 | 78 | 79 | if __name__ == "__main__": 80 | main() 81 | ``` 82 | 83 | ### НОК 84 | 85 | ```python 86 | def GCD(num1: int, num2: int) -> int: 87 | while num1 != 0 and num2 != 0: 88 | num1, num2 = (num1 % num2, num2) if num1 > num2 else (num1, num2 % num1) 89 | return num1 + num2 90 | 91 | 92 | def main() -> None: 93 | num1, num2 = [int(input()) for _ in range(2)] 94 | print(num1 * num2 // GCD(num1, num2)) 95 | 96 | 97 | if __name__ == "__main__": 98 | main() 99 | ``` 100 | 101 | ### Излишняя автоматизация 2.0 102 | 103 | ```python 104 | def main() -> None: 105 | string = input() 106 | for _ in range(int(input())): 107 | print(string) 108 | 109 | 110 | if __name__ == "__main__": 111 | main() 112 | ``` 113 | 114 | ### Факториал 115 | 116 | ```python 117 | def f(n: int) -> int: 118 | return n * f(n - 1) if n > 1 else 1 119 | 120 | 121 | def main() -> None: 122 | print(f(int(input()))) 123 | 124 | 125 | if __name__ == "__main__": 126 | main() 127 | ``` 128 | 129 | ### Маршрут построен 130 | 131 | ```python 132 | def main() -> None: 133 | x = y = 0 134 | x_dir = {"ВОСТОК": 1, "ЗАПАД": -1} 135 | y_dir = {"СЕВЕР": 1, "ЮГ": -1} 136 | 137 | while (direction := input()) != "СТОП": 138 | value = int(input()) 139 | (x, y) = (x + value * x_dir[direction], y) if direction in x_dir else (x, y + value * y_dir[direction]) 140 | print(y, x, sep="\n") 141 | 142 | 143 | if __name__ == "__main__": 144 | main() 145 | ``` 146 | 147 | ### Цифровая сумма 148 | 149 | ```python 150 | def main() -> None: 151 | print(sum([int(i) for i in input()])) 152 | 153 | 154 | if __name__ == "__main__": 155 | main() 156 | ``` 157 | 158 | ### Сильная цифра 159 | 160 | ```python 161 | def main() -> None: 162 | print(max([int(i) for i in input()])) 163 | 164 | 165 | if __name__ == "__main__": 166 | main() 167 | ``` 168 | 169 | ### Первому игроку приготовиться 2.0 170 | 171 | ```python 172 | def main() -> None: 173 | print(min([input() for _ in range(int(input()))])) 174 | 175 | 176 | if __name__ == "__main__": 177 | main() 178 | ``` 179 | 180 | ### Простая задача 181 | 182 | ```python 183 | def is_prime(num: int) -> bool: 184 | return num > 1 and all(num % i != 0 for i in range(2, int(num ** 0.5) + 1)) 185 | 186 | 187 | def main() -> None: 188 | print("YES" if is_prime(int(input())) else "NO") 189 | 190 | 191 | if __name__ == "__main__": 192 | main() 193 | ``` 194 | 195 | ### Зайка - 4 196 | 197 | ```python 198 | def main() -> None: 199 | print(sum([1 for _ in range(int(input())) if "зайка" in input()])) 200 | 201 | 202 | if __name__ == "__main__": 203 | main() 204 | ``` 205 | 206 | ### А роза упала на лапу Азора 2.0 207 | 208 | ```python 209 | def main() -> None: 210 | print("YES" if (number := input()) == number[::-1] else "NO") 211 | 212 | 213 | if __name__ == "__main__": 214 | main() 215 | ``` 216 | 217 | ### Чётная чистота 218 | 219 | ```python 220 | def main() -> None: 221 | print(*[int(i) for i in input() if int(i) % 2 != 0], sep="") 222 | 223 | 224 | if __name__ == "__main__": 225 | main() 226 | ``` 227 | 228 | ### Простая задача 2.0 229 | 230 | ```python 231 | def main() -> None: 232 | number, multipliers, divider = int(input()), [], 2 233 | print(number) if number < 2 else ... 234 | 235 | while number > 1: 236 | if number % divider == 0: 237 | multipliers.append(divider) 238 | number //= divider 239 | else: 240 | divider += 1 241 | 242 | print(*multipliers, sep=" * ") 243 | 244 | 245 | if __name__ == "__main__": 246 | main() 247 | ``` 248 | 249 | ### Игра в «Угадайку» 250 | 251 | ```python 252 | def main() -> None: 253 | number, half = 500, 250 254 | print(number) 255 | while (string := input()) != "Угадал!": 256 | number += half if string == "Больше" else -half if string == "Меньше" else 0 257 | half = (half + 1) // 2 if half >= 2 else ... 258 | print(number) 259 | 260 | 261 | if __name__ == "__main__": 262 | main() 263 | ``` 264 | 265 | ### Хайпанём немножечко! 266 | 267 | ```python 268 | def main() -> None: 269 | result, hn = -1, 0 270 | for i in range(int(input())): 271 | b = int(input()) 272 | h = b % 256 273 | r = (b // 256) % 256 274 | m = b // (256 ** 2) 275 | temp = 37 * (hn + r + m) % 256 276 | if temp != h or h >= 100: 277 | result = i 278 | break 279 | hn = h 280 | print(result) 281 | 282 | 283 | if __name__ == "__main__": 284 | main() 285 | ``` -------------------------------------------------------------------------------- /2/2.4/1.py: -------------------------------------------------------------------------------- 1 | # Таблица умножения 2 | def main() -> None: 3 | for i in range(1, (n := int(input())) + 1): 4 | print(" ".join(str(i * j) for j in range(1, n + 1))) 5 | 6 | 7 | if __name__ == "__main__": 8 | main() 9 | -------------------------------------------------------------------------------- /2/2.4/10.py: -------------------------------------------------------------------------------- 1 | # Мы делили апельсин 2 | def main() -> None: 3 | print("А Б В") 4 | for i in range(1, (n := int(input())) + 1): 5 | print('\n'.join(f"{i} {j} {n - i - j}" for j in range(1, n - i))) 6 | 7 | 8 | if __name__ == "__main__": 9 | main() 10 | -------------------------------------------------------------------------------- /2/2.4/11.py: -------------------------------------------------------------------------------- 1 | # Простая задача 3.0 2 | def is_prime(num: int) -> bool: 3 | return num > 1 and all(num % i != 0 for i in range(2, int(num ** 0.5) + 1)) 4 | 5 | 6 | def main() -> None: 7 | print(sum([is_prime(int(input())) for _ in range(int(input()))])) 8 | 9 | 10 | if __name__ == "__main__": 11 | main() 12 | -------------------------------------------------------------------------------- /2/2.4/12.py: -------------------------------------------------------------------------------- 1 | # Числовой прямоугольник 2 | def main() -> None: 3 | n, m = [int(input()) for _ in range(2)] 4 | width = len(str(n * m)) 5 | for i in range(1, n * m + 1): 6 | print(f"{i:>{width}} ", end=" " * (i % m == 0) + "\n" * (i % m == 0 and i != n * m)) 7 | 8 | 9 | if __name__ == "__main__": 10 | main() 11 | -------------------------------------------------------------------------------- /2/2.4/13.py: -------------------------------------------------------------------------------- 1 | # Числовой прямоугольник 2.0 2 | def main() -> None: 3 | n, m = [int(input()) for _ in range(2)] 4 | width = len(str(n * m)) 5 | for i in range(n): 6 | print(" ".join(f"{i + 1 + j * n:>{width}}" for j in range(m))) 7 | 8 | 9 | if __name__ == "__main__": 10 | main() 11 | -------------------------------------------------------------------------------- /2/2.4/14.py: -------------------------------------------------------------------------------- 1 | # Числовая змейка 2 | def main() -> None: 3 | n, m = [int(input()) for _ in range(2)] 4 | width = len(str(n * m)) 5 | for i in range(n): 6 | print(" ".join(f"{i * m + (j + 1 if i % 2 == 0 else m - j):>{width}}" for j in range(m))) 7 | 8 | 9 | if __name__ == "__main__": 10 | main() 11 | -------------------------------------------------------------------------------- /2/2.4/15.py: -------------------------------------------------------------------------------- 1 | # Числовая змейка 2.0 2 | def main() -> None: 3 | n, m = [int(input()) for _ in range(2)] 4 | width = len(str(n * m)) 5 | for i in range(n): 6 | print(" ".join(f"{j * n + (i + 1 if j % 2 == 0 else n - i):>{width}}" for j in range(m))) 7 | 8 | 9 | if __name__ == "__main__": 10 | main() 11 | -------------------------------------------------------------------------------- /2/2.4/16.py: -------------------------------------------------------------------------------- 1 | # Редизайн таблицы умножения 2 | def main() -> None: 3 | n, m = [int(input()) for _ in range(2)] 4 | string = m * n + (n - 1) 5 | if n != 1: 6 | for i in range(1, n + 1): 7 | for j in range(1, n + 1): 8 | k = str(i * j) 9 | result = f'{k: ^{m}}' 10 | print(result, '|', sep="", end="") if j != n else print(result, end="") 11 | print() 12 | if i != n: 13 | print('-' * string) 14 | else: 15 | print(f"{1: ^{m}}") 16 | 17 | 18 | if __name__ == "__main__": 19 | main() 20 | -------------------------------------------------------------------------------- /2/2.4/17.py: -------------------------------------------------------------------------------- 1 | # А роза упала на лапу Азора 3.0 2 | def main() -> None: 3 | print(sum([(string := input()) == string[::-1] for _ in range(int(input()))])) 4 | 5 | 6 | if __name__ == "__main__": 7 | main() 8 | -------------------------------------------------------------------------------- /2/2.4/18.py: -------------------------------------------------------------------------------- 1 | # Новогоднее настроение 2.0 2 | def main() -> None: 3 | n = int(input()) 4 | max_length, number, line = 0, 0, 1 5 | while number < n: 6 | length = " ".join(str(i) for i in range(number + 1, min(number + line + 1, n + 1))) 7 | max_length = max(len(length), max_length) 8 | number += line 9 | line += 1 10 | number, line = 0, 1 11 | while number < n: 12 | answer = " ".join(str(i) for i in range(number + 1, min(number + line + 1, n + 1))) 13 | print(f"{answer:^{max_length}}") 14 | number += line 15 | line += 1 16 | 17 | 18 | if __name__ == "__main__": 19 | main() 20 | -------------------------------------------------------------------------------- /2/2.4/19.py: -------------------------------------------------------------------------------- 1 | # Числовой квадрат 2 | def main() -> None: 3 | n = int(input()) 4 | width = len(str(n // 2 + 1)) 5 | for i in range(n): 6 | print(" ".join(f"{min(i + 1, n - i, j + 1, n - j):>{width}}" for j in range(n))) 7 | 8 | 9 | if __name__ == "__main__": 10 | main() 11 | -------------------------------------------------------------------------------- /2/2.4/2.py: -------------------------------------------------------------------------------- 1 | # Не таблица умножения 2 | def main() -> None: 3 | for i in range(1, (n := int(input())) + 1): 4 | print("\n".join(f"{j} * {i} = {i * j}" for j in range(1, n + 1))) 5 | 6 | 7 | if __name__ == "__main__": 8 | main() 9 | -------------------------------------------------------------------------------- /2/2.4/20.py: -------------------------------------------------------------------------------- 1 | # Математическая выгода 2 | def main() -> None: 3 | n = int(input()) 4 | max_i = max_num = 0 5 | for i in range(2, 11): 6 | num, s = n, [] 7 | while num > 0: 8 | s, num = [num % i] + s, num // i 9 | if max_num < sum(s): 10 | max_num, max_i = sum(s), i 11 | print(max_i) 12 | 13 | 14 | if __name__ == "__main__": 15 | main() 16 | -------------------------------------------------------------------------------- /2/2.4/3.py: -------------------------------------------------------------------------------- 1 | # Новогоднее настроение 2 | def main() -> None: 3 | number = 1 4 | for i in range(1, (n := int(input())) + 1): 5 | for j in range(i): 6 | if number - 1 < n: 7 | print(number, end=" ") 8 | number += 1 9 | print() 10 | 11 | 12 | if __name__ == "__main__": 13 | main() 14 | -------------------------------------------------------------------------------- /2/2.4/4.py: -------------------------------------------------------------------------------- 1 | # Суммарная сумма 2 | def main() -> None: 3 | print(sum([int(i) for x in [input() for _ in range(int(input()))] for i in x])) 4 | 5 | 6 | if __name__ == "__main__": 7 | main() 8 | -------------------------------------------------------------------------------- /2/2.4/5.py: -------------------------------------------------------------------------------- 1 | # Зайка — 5 2 | def find() -> int: 3 | founded = 0 4 | while (string := input()) != "ВСЁ": 5 | if string == "зайка": 6 | founded = 1 7 | return founded 8 | 9 | 10 | def main() -> None: 11 | print(sum([find() for _ in range(int(input()))])) 12 | 13 | 14 | if __name__ == "__main__": 15 | main() 16 | -------------------------------------------------------------------------------- /2/2.4/6.py: -------------------------------------------------------------------------------- 1 | # НОД 2.0 2 | def GCD(num1: int, num2: int) -> int: 3 | while num1 != 0 and num2 != 0: 4 | num1, num2 = (num1 % num2, num2) if num1 > num2 else (num1, num2 % num1) 5 | return num1 + num2 6 | 7 | 8 | def main() -> None: 9 | numbers = [int(input()) for _ in range(int(input()))] 10 | gcd = 0 11 | for i in range(len(numbers)): 12 | gcd = GCD(gcd, numbers[i]) 13 | print(gcd) 14 | 15 | 16 | if __name__ == "__main__": 17 | main() 18 | -------------------------------------------------------------------------------- /2/2.4/7.py: -------------------------------------------------------------------------------- 1 | # На старт! Внимание! Марш! 2 | def main() -> None: 3 | for i in range(int(input())): 4 | print('\n'.join(f"До старта {j} секунд(ы)" for j in range(3 + i, 0, -1))) 5 | print(f"Старт {i + 1}!!!") 6 | 7 | 8 | if __name__ == "__main__": 9 | main() 10 | -------------------------------------------------------------------------------- /2/2.4/8.py: -------------------------------------------------------------------------------- 1 | # Максимальная сумма 2 | def main() -> None: 3 | rating = {} 4 | for _ in range(int(input())): 5 | name = input() 6 | rating[name] = sum([int(x) for x in input()]) 7 | sorted_rating = sorted(rating.items(), key=lambda x: x[1])[::-1] 8 | print(sorted_rating[0][0]) 9 | 10 | 11 | if __name__ == "__main__": 12 | main() 13 | -------------------------------------------------------------------------------- /2/2.4/9.py: -------------------------------------------------------------------------------- 1 | # Большое число 2 | def main() -> None: 3 | print(*[max(int(i) for i in x) for x in [input() for _ in range(int(input()))]], sep="") 4 | 5 | 6 | if __name__ == "__main__": 7 | main() 8 | -------------------------------------------------------------------------------- /2/2.4/solutions.md: -------------------------------------------------------------------------------- 1 | # Вложенные циклы 2 | 3 | ### Таблица умножения 4 | 5 | ```python 6 | def main() -> None: 7 | for i in range(1, (n := int(input())) + 1): 8 | print(" ".join(str(i * j) for j in range(1, n + 1))) 9 | 10 | 11 | if __name__ == "__main__": 12 | main() 13 | ``` 14 | 15 | ### Не таблица умножения 16 | 17 | ```python 18 | def main() -> None: 19 | for i in range(1, (n := int(input())) + 1): 20 | print("\n".join(f"{j} * {i} = {i * j}" for j in range(1, n + 1))) 21 | 22 | 23 | if __name__ == "__main__": 24 | main() 25 | ``` 26 | 27 | ### Новогоднее настроение 28 | 29 | ```python 30 | def main() -> None: 31 | number = 1 32 | for i in range(1, (n := int(input())) + 1): 33 | for j in range(i): 34 | if number - 1 < n: 35 | print(number, end=" ") 36 | number += 1 37 | print() 38 | 39 | 40 | if __name__ == "__main__": 41 | main() 42 | ``` 43 | 44 | ### Суммарная сумма 45 | 46 | ```python 47 | def main() -> None: 48 | print(sum([int(i) for x in [input() for _ in range(int(input()))] for i in x])) 49 | 50 | 51 | if __name__ == "__main__": 52 | main() 53 | ``` 54 | 55 | ### Зайка — 5 56 | 57 | ```python 58 | def find() -> int: 59 | founded = 0 60 | while (string := input()) != "ВСЁ": 61 | if string == "зайка": 62 | founded = 1 63 | return founded 64 | 65 | 66 | def main() -> None: 67 | print(sum([find() for _ in range(int(input()))])) 68 | 69 | 70 | if __name__ == "__main__": 71 | main() 72 | ``` 73 | 74 | ### НОД 2.0 75 | 76 | ```python 77 | def GCD(num1: int, num2: int) -> int: 78 | while num1 != 0 and num2 != 0: 79 | num1, num2 = (num1 % num2, num2) if num1 > num2 else (num1, num2 % num1) 80 | return num1 + num2 81 | 82 | 83 | def main() -> None: 84 | numbers = [int(input()) for _ in range(int(input()))] 85 | gcd = 0 86 | for i in range(len(numbers)): 87 | gcd = GCD(gcd, numbers[i]) 88 | print(gcd) 89 | 90 | 91 | if __name__ == "__main__": 92 | main() 93 | ``` 94 | 95 | ### На старт! Внимание! Марш! 96 | 97 | ```python 98 | def main() -> None: 99 | for i in range(int(input())): 100 | print('\n'.join(f"До старта {j} секунд(ы)" for j in range(3 + i, 0, -1))) 101 | print(f"Старт {i + 1}!!!") 102 | 103 | 104 | if __name__ == "__main__": 105 | main() 106 | ``` 107 | 108 | ### Максимальная сумма 109 | 110 | ```python 111 | def main() -> None: 112 | rating = {} 113 | for _ in range(int(input())): 114 | name = input() 115 | rating[name] = sum([int(x) for x in input()]) 116 | sorted_rating = sorted(rating.items(), key=lambda x: x[1])[::-1] 117 | print(sorted_rating[0][0]) 118 | 119 | 120 | if __name__ == "__main__": 121 | main() 122 | ``` 123 | 124 | ### Большое число 125 | 126 | ```python 127 | def main() -> None: 128 | print(*[max(int(i) for i in x) for x in [input() for _ in range(int(input()))]], sep="") 129 | 130 | 131 | if __name__ == "__main__": 132 | main() 133 | ``` 134 | 135 | ### Мы делили апельсин 136 | 137 | ```python 138 | def main() -> None: 139 | print("А Б В") 140 | for i in range(1, (n := int(input())) + 1): 141 | print('\n'.join(f"{i} {j} {n - i - j}" for j in range(1, n - i))) 142 | 143 | 144 | if __name__ == "__main__": 145 | main() 146 | ``` 147 | 148 | ### Простая задача 3.0 149 | 150 | ```python 151 | def is_prime(num: int) -> bool: 152 | return num > 1 and all(num % i != 0 for i in range(2, int(num ** 0.5) + 1)) 153 | 154 | 155 | def main() -> None: 156 | print(sum([is_prime(int(input())) for _ in range(int(input()))])) 157 | 158 | 159 | if __name__ == "__main__": 160 | main() 161 | ``` 162 | 163 | ### Числовой прямоугольник 164 | 165 | ```python 166 | def main() -> None: 167 | n, m = [int(input()) for _ in range(2)] 168 | width = len(str(n * m)) 169 | for i in range(1, n * m + 1): 170 | print(f"{i:>{width}} ", end=" " * (i % m == 0) + "\n" * (i % m == 0 and i != n * m)) 171 | 172 | 173 | if __name__ == "__main__": 174 | main() 175 | ``` 176 | 177 | ### Числовой прямоугольник 2.0 178 | 179 | ```python 180 | def main() -> None: 181 | n, m = [int(input()) for _ in range(2)] 182 | width = len(str(n * m)) 183 | for i in range(n): 184 | print(" ".join(f"{i + 1 + j * n:>{width}}" for j in range(m))) 185 | 186 | 187 | if __name__ == "__main__": 188 | main() 189 | ``` 190 | 191 | ### Числовая змейка 192 | 193 | ```python 194 | def main() -> None: 195 | n, m = [int(input()) for _ in range(2)] 196 | width = len(str(n * m)) 197 | for i in range(n): 198 | print(" ".join(f"{i * m + (j + 1 if i % 2 == 0 else m - j):>{width}}" for j in range(m))) 199 | 200 | 201 | if __name__ == "__main__": 202 | main() 203 | ``` 204 | 205 | ### Числовая змейка 2.0 206 | 207 | ```python 208 | def main() -> None: 209 | n, m = [int(input()) for _ in range(2)] 210 | width = len(str(n * m)) 211 | for i in range(n): 212 | print(" ".join(f"{j * n + (i + 1 if j % 2 == 0 else n - i):>{width}}" for j in range(m))) 213 | 214 | 215 | if __name__ == "__main__": 216 | main() 217 | ``` 218 | 219 | ### Редизайн таблицы умножения 220 | 221 | ```python 222 | def main() -> None: 223 | n, m = [int(input()) for _ in range(2)] 224 | string = m * n + (n - 1) 225 | if n != 1: 226 | for i in range(1, n + 1): 227 | for j in range(1, n + 1): 228 | k = str(i * j) 229 | result = f'{k: ^{m}}' 230 | print(result, '|', sep="", end="") if j != n else print(result, end="") 231 | print() 232 | if i != n: 233 | print('-' * string) 234 | else: 235 | print(f"{1: ^{m}}") 236 | 237 | 238 | if __name__ == "__main__": 239 | main() 240 | ``` 241 | 242 | ### А роза упала на лапу Азора 3.0 243 | 244 | ```python 245 | def main() -> None: 246 | print(sum([(string := input()) == string[::-1] for _ in range(int(input()))])) 247 | 248 | 249 | if __name__ == "__main__": 250 | main() 251 | ``` 252 | 253 | ### Новогоднее настроение 2.0 254 | 255 | ```python 256 | def main() -> None: 257 | n = int(input()) 258 | max_length, number, line = 0, 0, 1 259 | while number < n: 260 | length = " ".join(str(i) for i in range(number + 1, min(number + line + 1, n + 1))) 261 | max_length = max(len(length), max_length) 262 | number += line 263 | line += 1 264 | number, line = 0, 1 265 | while number < n: 266 | answer = " ".join(str(i) for i in range(number + 1, min(number + line + 1, n + 1))) 267 | print(f"{answer:^{max_length}}") 268 | number += line 269 | line += 1 270 | 271 | 272 | if __name__ == "__main__": 273 | main() 274 | ``` 275 | 276 | ### Числовой квадрат 277 | 278 | ```python 279 | def main() -> None: 280 | n = int(input()) 281 | width = len(str(n // 2 + 1)) 282 | for i in range(n): 283 | print(" ".join(f"{min(i + 1, n - i, j + 1, n - j):>{width}}" for j in range(n))) 284 | 285 | 286 | if __name__ == "__main__": 287 | main() 288 | ``` 289 | 290 | ### Математическая выгода 291 | 292 | ```python 293 | def main() -> None: 294 | n = int(input()) 295 | max_i = max_num = 0 296 | for i in range(2, 11): 297 | num, s = n, [] 298 | while num > 0: 299 | s, num = [num % i] + s, num // i 300 | if max_num < sum(s): 301 | max_num, max_i = sum(s), i 302 | print(max_i) 303 | 304 | 305 | if __name__ == "__main__": 306 | main() 307 | ``` -------------------------------------------------------------------------------- /3/3.1/1.py: -------------------------------------------------------------------------------- 1 | # Азбука 2 | def main() -> None: 3 | print("YES" if all(input()[0].upper() in "АБВ" for _ in range(int(input()))) else "NO") 4 | 5 | 6 | if __name__ == "__main__": 7 | main() 8 | -------------------------------------------------------------------------------- /3/3.1/10.py: -------------------------------------------------------------------------------- 1 | # Частотный анализ на минималках 2 | def main() -> None: 3 | res = "" 4 | while (s := input()) != 'ФИНИШ': 5 | res += s 6 | line = str(res).lower().replace(" ", "") 7 | count, letter = 0, "" 8 | for char in set(line): 9 | if line.count(char) > count: 10 | letter, count = char, line.count(char) 11 | print(letter) 12 | 13 | 14 | if __name__ == "__main__": 15 | main() 16 | -------------------------------------------------------------------------------- /3/3.1/11.py: -------------------------------------------------------------------------------- 1 | # Найдётся всё 2 | def main() -> None: 3 | headings, request = [input() for _ in range(int(input()))], input() 4 | print(*[i for i in headings if request.lower() in i.lower()], sep='\n') 5 | 6 | 7 | if __name__ == "__main__": 8 | main() 9 | -------------------------------------------------------------------------------- /3/3.1/12.py: -------------------------------------------------------------------------------- 1 | # Меню питания 2 | def main() -> None: 3 | print(*[["Манная", "Гречневая", "Пшённая", "Овсяная", "Рисовая"][i % 5] for i in range(int(input()))], sep="\n") 4 | 5 | 6 | if __name__ == "__main__": 7 | main() 8 | -------------------------------------------------------------------------------- /3/3.1/13.py: -------------------------------------------------------------------------------- 1 | # Массовое возведение в степень 2 | def main() -> None: 3 | numbers, power = [int(input()) for _ in range(int(input()))], int(input()) 4 | print(*[i ** power for i in numbers], sep="\n") 5 | 6 | 7 | if __name__ == "__main__": 8 | main() 9 | -------------------------------------------------------------------------------- /3/3.1/14.py: -------------------------------------------------------------------------------- 1 | # Массовое возведение в степень 2.0 2 | def main() -> None: 3 | numbers, power = list(map(int, input().split())), int(input()) 4 | print(*[i ** power for i in numbers]) 5 | 6 | 7 | if __name__ == "__main__": 8 | main() 9 | -------------------------------------------------------------------------------- /3/3.1/15.py: -------------------------------------------------------------------------------- 1 | # НОД 3.0 2 | def GCD(num1: int, num2: int) -> int: 3 | while num1 != 0 and num2 != 0: 4 | num1, num2 = (num1 % num2, num2) if num1 > num2 else (num1, num2 % num1) 5 | return num1 + num2 6 | 7 | 8 | def main() -> None: 9 | numbers = list(map(int, input().split())) 10 | gcd = 0 11 | for i in range(len(numbers)): 12 | gcd = GCD(gcd, numbers[i]) 13 | print(gcd) 14 | 15 | 16 | if __name__ == "__main__": 17 | main() 18 | -------------------------------------------------------------------------------- /3/3.1/16.py: -------------------------------------------------------------------------------- 1 | # Анонс новости 2.0 2 | def main() -> None: 3 | length, strings = int(input()), [input() for _ in range(int(input()))] 4 | total = length 5 | for i in strings: 6 | if total <= 3: 7 | break 8 | print(i[:total:] if (total - len(i)) > 3 else i[:total - 3:] + "...") 9 | total -= len(i) 10 | 11 | 12 | if __name__ == "__main__": 13 | main() 14 | -------------------------------------------------------------------------------- /3/3.1/17.py: -------------------------------------------------------------------------------- 1 | # А роза упала на лапу Азора 5.0 2 | def main() -> None: 3 | print("YES" if (string := input().replace(" ", "").lower()) == string[::-1] else "NO") 4 | 5 | 6 | if __name__ == "__main__": 7 | main() 8 | -------------------------------------------------------------------------------- /3/3.1/18.py: -------------------------------------------------------------------------------- 1 | # RLE 2 | def main() -> None: 3 | line = input() 4 | letter, count = line[0], 1 5 | for i in line[1:]: 6 | if i == letter: 7 | count += 1 8 | else: 9 | print(letter, count) 10 | letter, count = i, 1 11 | print(letter, count) 12 | 13 | 14 | if __name__ == "__main__": 15 | main() 16 | -------------------------------------------------------------------------------- /3/3.1/19.py: -------------------------------------------------------------------------------- 1 | # Польский калькулятор 2 | def main() -> None: 3 | elements, result = list(input().split()), [] 4 | for i in elements: 5 | if i.isdigit(): 6 | result.append(int(i)) 7 | else: 8 | a = result.pop() 9 | exec("result[-1] " + i + "= a") 10 | print(*result) 11 | 12 | 13 | if __name__ == "__main__": 14 | main() 15 | -------------------------------------------------------------------------------- /3/3.1/2.py: -------------------------------------------------------------------------------- 1 | # Кручу-верчу 2 | def main() -> None: 3 | print("\n".join([i for i in input()])) 4 | 5 | 6 | if __name__ == "__main__": 7 | main() 8 | -------------------------------------------------------------------------------- /3/3.1/20.py: -------------------------------------------------------------------------------- 1 | # Польский калькулятор — 2 2 | def f(n: int) -> int: 3 | return n * f(n - 1) if n > 1 else 1 4 | 5 | 6 | def main() -> None: 7 | elements = list(input().split()) 8 | result = [] 9 | for i in elements: 10 | if i.isdigit(): 11 | result.append(int(i)) 12 | elif i == '~': 13 | result[-1] *= -1 14 | elif i == "!": 15 | result[-1] = f(result[-1]) 16 | elif i == "#": 17 | result.append(result[-1]) 18 | elif i == "/": 19 | a = result.pop() 20 | result[-1] //= a 21 | elif i == "@": 22 | a = result.pop(-3) 23 | result.append(a) 24 | else: 25 | a = result.pop() 26 | exec("result[-1] " + i + "=a") 27 | print(*result) 28 | 29 | 30 | if __name__ == "__main__": 31 | main() 32 | -------------------------------------------------------------------------------- /3/3.1/3.py: -------------------------------------------------------------------------------- 1 | # Анонс новости 2 | def main(): 3 | n = int(input()) 4 | for _ in range(int(input())): 5 | print(s[:n - 3:] + "..." if len(s := input()) > n else s) 6 | 7 | 8 | if __name__ == "__main__": 9 | main() 10 | -------------------------------------------------------------------------------- /3/3.1/4.py: -------------------------------------------------------------------------------- 1 | # Очистка данных 2 | def main() -> None: 3 | while (s := input()) != "": 4 | print(s[2::] if s[0:2:] == "##" else s) if s[-1:-4:-1] != "@@@" else ... 5 | 6 | 7 | if __name__ == "__main__": 8 | main() 9 | -------------------------------------------------------------------------------- /3/3.1/5.py: -------------------------------------------------------------------------------- 1 | # А роза упала на лапу Азора 4.0 2 | def main() -> None: 3 | print("YES" if (string := input()) == string[::-1] else "NO") 4 | 5 | 6 | if __name__ == "__main__": 7 | main() 8 | -------------------------------------------------------------------------------- /3/3.1/6.py: -------------------------------------------------------------------------------- 1 | # Зайка — 6 2 | def main() -> None: 3 | print(sum([input().count("зайка") for _ in range(int(input()))])) 4 | 5 | 6 | if __name__ == "__main__": 7 | main() 8 | -------------------------------------------------------------------------------- /3/3.1/7.py: -------------------------------------------------------------------------------- 1 | # А и Б сидели на трубе 2 | def main() -> None: 3 | print(sum(list(map(int, input().split())))) 4 | 5 | 6 | if __name__ == "__main__": 7 | main() 8 | -------------------------------------------------------------------------------- /3/3.1/8.py: -------------------------------------------------------------------------------- 1 | # Зайка — 7 2 | def main() -> None: 3 | for _ in range(int(input())): 4 | print(string.index("зайка") + 1 if "зайка" in (string := input()) else "Заек нет =(") 5 | 6 | 7 | if __name__ == "__main__": 8 | main() 9 | -------------------------------------------------------------------------------- /3/3.1/9.py: -------------------------------------------------------------------------------- 1 | # Без комментариев 2 | def main() -> None: 3 | while (string := input()) != "": 4 | print(string[:string.index("#"):] if "#" in string else string) if string[0] != "#" else ... 5 | 6 | 7 | if __name__ == "__main__": 8 | main() 9 | -------------------------------------------------------------------------------- /3/3.1/solutions.md: -------------------------------------------------------------------------------- 1 | # Строки, кортежи, списки 2 | 3 | ### Азбука 4 | 5 | ```python 6 | def main() -> None: 7 | print("YES" if all(input()[0].upper() in "АБВ" for _ in range(int(input()))) else "NO") 8 | 9 | 10 | if __name__ == "__main__": 11 | main() 12 | ``` 13 | 14 | ### Кручу-верчу 15 | 16 | ```python 17 | def main() -> None: 18 | print("\n".join([i for i in input()])) 19 | 20 | 21 | if __name__ == "__main__": 22 | main() 23 | ``` 24 | 25 | ### Анонс новости 26 | 27 | ```python 28 | def main(): 29 | n = int(input()) 30 | for _ in range(int(input())): 31 | print(s[:n - 3:] + "..." if len(s := input()) > n else s) 32 | 33 | 34 | if __name__ == "__main__": 35 | main() 36 | ``` 37 | 38 | ### Очистка данных 39 | 40 | ```python 41 | def main() -> None: 42 | while (s := input()) != "": 43 | print(s[2::] if s[0:2:] == "###" else s) if s[-1:-4:-1] != "@@@" else ... 44 | 45 | 46 | if __name__ == "__main__": 47 | main() 48 | ``` 49 | 50 | ### А роза упала на лапу Азора 4.0 51 | 52 | ```python 53 | def main() -> None: 54 | print("YES" if (string := input()) == string[::-1] else "NO") 55 | 56 | 57 | if __name__ == "__main__": 58 | main() 59 | ``` 60 | 61 | ### Зайка — 6 62 | 63 | ```python 64 | def main() -> None: 65 | print(sum([input().count("зайка") for _ in range(int(input()))])) 66 | 67 | 68 | if __name__ == "__main__": 69 | main() 70 | ``` 71 | 72 | ### А и Б сидели на трубе 73 | 74 | ```python 75 | def main() -> None: 76 | print(sum(list(map(int, input().split())))) 77 | 78 | 79 | if __name__ == "__main__": 80 | main() 81 | ``` 82 | 83 | ### Зайка — 7 84 | 85 | ```python 86 | def main() -> None: 87 | for _ in range(int(input())): 88 | print(string.index("зайка") + 1 if "зайка" in (string := input()) else "Заек нет =(") 89 | 90 | 91 | if __name__ == "__main__": 92 | main() 93 | ``` 94 | 95 | ### Без комментариев 96 | 97 | ```python 98 | def main() -> None: 99 | while (string := input()) != "": 100 | print(string[:string.index("#"):] if "#" in string else string) if string[0] != "#" else ... 101 | 102 | 103 | if __name__ == "__main__": 104 | main() 105 | ``` 106 | 107 | ### Частотный анализ на минималках 108 | 109 | ```python 110 | def main() -> None: 111 | res = "" 112 | while (s := input()) != 'ФИНИШ': 113 | res += s 114 | line = str(res).lower().replace(" ", "") 115 | count, letter = 0, "" 116 | for char in set(line): 117 | if line.count(char) > count: 118 | letter, count = char, line.count(char) 119 | print(letter) 120 | 121 | 122 | if __name__ == "__main__": 123 | main() 124 | ``` 125 | 126 | ### Найдётся всё 127 | 128 | ```python 129 | def main() -> None: 130 | headings, request = [input() for _ in range(int(input()))], input() 131 | print(*[i for i in headings if request.lower() in i.lower()], sep='\n') 132 | 133 | 134 | if __name__ == "__main__": 135 | main() 136 | ``` 137 | 138 | ### Меню питания 139 | 140 | ```python 141 | def main() -> None: 142 | print(*[["Манная", "Гречневая", "Пшённая", "Овсяная", "Рисовая"][i % 5] for i in range(int(input()))], sep="\n") 143 | 144 | 145 | if __name__ == "__main__": 146 | main() 147 | ``` 148 | 149 | ### Массовое возведение в степень 150 | 151 | ```python 152 | def main() -> None: 153 | numbers, power = [int(input()) for _ in range(int(input()))], int(input()) 154 | print(*[i ** power for i in numbers], sep="\n") 155 | 156 | 157 | if __name__ == "__main__": 158 | main() 159 | ``` 160 | 161 | ### Массовое возведение в степень 2.0 162 | 163 | ```python 164 | def main() -> None: 165 | numbers, power = list(map(int, input().split())), int(input()) 166 | print(*[i ** power for i in numbers]) 167 | 168 | 169 | if __name__ == "__main__": 170 | main() 171 | ``` 172 | 173 | ### НОД 3.0 174 | 175 | ```python 176 | def GCD(num1: int, num2: int) -> int: 177 | while num1 != 0 and num2 != 0: 178 | num1, num2 = (num1 % num2, num2) if num1 > num2 else (num1, num2 % num1) 179 | return num1 + num2 180 | 181 | 182 | def main() -> None: 183 | numbers = list(map(int, input().split())) 184 | gcd = 0 185 | for i in range(len(numbers)): 186 | gcd = GCD(gcd, numbers[i]) 187 | print(gcd) 188 | 189 | 190 | if __name__ == "__main__": 191 | main() 192 | ``` 193 | 194 | ### Анонс новости 2.0 195 | 196 | ```python 197 | def main() -> None: 198 | length, strings = int(input()), [input() for _ in range(int(input()))] 199 | total = length 200 | for i in strings: 201 | if total <= 3: 202 | break 203 | print(i[:total:] if (total - len(i)) > 3 else i[:total - 3:] + "...") 204 | total -= len(i) 205 | 206 | 207 | if __name__ == "__main__": 208 | main() 209 | ``` 210 | 211 | ### А роза упала на лапу Азора 5.0 212 | 213 | ```python 214 | def main() -> None: 215 | print("YES" if (string := input().replace(" ", "").lower()) == string[::-1] else "NO") 216 | 217 | 218 | if __name__ == "__main__": 219 | main() 220 | ``` 221 | 222 | ### RLE 223 | 224 | ```python 225 | def main() -> None: 226 | line = input() 227 | letter, count = line[0], 1 228 | for i in line[1:]: 229 | if i == letter: 230 | count += 1 231 | else: 232 | print(letter, count) 233 | letter, count = i, 1 234 | print(letter, count) 235 | 236 | 237 | if __name__ == "__main__": 238 | main() 239 | ``` 240 | 241 | ### Польский калькулятор 242 | 243 | ```python 244 | def main() -> None: 245 | elements, result = list(input().split()), [] 246 | for i in elements: 247 | if i.isdigit(): 248 | result.append(int(i)) 249 | else: 250 | a = result.pop() 251 | exec("result[-1] " + i + "= a") 252 | print(*result) 253 | 254 | 255 | if __name__ == "__main__": 256 | main() 257 | ``` 258 | 259 | ### Польский калькулятор — 2 260 | 261 | ```python 262 | def f(n: int) -> int: 263 | return n * f(n - 1) if n > 1 else 1 264 | 265 | 266 | def main() -> None: 267 | elements = list(input().split()) 268 | result = [] 269 | for i in elements: 270 | if i.isdigit(): 271 | result.append(int(i)) 272 | elif i == '~': 273 | result[-1] *= -1 274 | elif i == "!": 275 | result[-1] = f(result[-1]) 276 | elif i == "#": 277 | result.append(result[-1]) 278 | elif i == "/": 279 | a = result.pop() 280 | result[-1] //= a 281 | elif i == "@": 282 | a = result.pop(-3) 283 | result.append(a) 284 | else: 285 | a = result.pop() 286 | exec("result[-1] " + i + "=a") 287 | print(*result) 288 | 289 | 290 | if __name__ == "__main__": 291 | main() 292 | ``` -------------------------------------------------------------------------------- /3/3.2/1.py: -------------------------------------------------------------------------------- 1 | # Символическая выжимка 2 | def main() -> None: 3 | print(*set(input()), sep="") 4 | 5 | 6 | if __name__ == "__main__": 7 | main() 8 | -------------------------------------------------------------------------------- /3/3.2/10.py: -------------------------------------------------------------------------------- 1 | # Транслитерация 2 | def main() -> None: 3 | alphabet = { 4 | "А": "A", "Б": "B", "В": "V", 5 | "Г": "G", "Д": "D", "Е": "E", 6 | "Ё": "E", "Ж": "ZH", "З": "Z", 7 | "И": "I", "Й": "I", "К": "K", 8 | "Л": "L", "М": "M", "Н": "N", 9 | "О": "O", "П": "P", "Р": "R", 10 | "С": "S", "Т": "T", "У": "U", 11 | "Ф": "F", "Х": "KH", "Ц": "TC", 12 | "Ч": "CH", "Ш": "SH", "Щ": "SHCH", 13 | "Ы": "Y", "Э": "E", "Ю": "IU", 14 | "Я": "IA", "Ь": "", "Ъ": "", 15 | } 16 | for letter in input(): 17 | if letter.upper() in "ЬЪ": 18 | continue 19 | elif letter.upper() in alphabet: 20 | if letter.isupper(): 21 | print(alphabet[letter][0].upper() + alphabet[letter][1:].lower(), end="") 22 | else: 23 | print(alphabet[letter.upper()].lower(), end="") 24 | else: 25 | print(letter, end="") 26 | 27 | 28 | if __name__ == "__main__": 29 | main() 30 | -------------------------------------------------------------------------------- /3/3.2/11.py: -------------------------------------------------------------------------------- 1 | # Однофамильцы 2 | def main() -> None: 3 | surnames = [input() for _ in range(int(input()))] 4 | print(sum([surnames.count(i) for i in set(surnames) if surnames.count(i) != 1])) 5 | 6 | 7 | if __name__ == "__main__": 8 | main() 9 | -------------------------------------------------------------------------------- /3/3.2/12.py: -------------------------------------------------------------------------------- 1 | # Однофамильцы — 2 2 | def main() -> None: 3 | surnames = [input() for _ in range(int(input()))] 4 | namesakes = sorted(set([x for x in surnames if surnames.count(x) != 1])) 5 | print(*[f"{i} - {surnames.count(i)}" for i in namesakes], sep="\n") if namesakes else print("Однофамильцев нет") 6 | 7 | 8 | if __name__ == "__main__": 9 | main() 10 | -------------------------------------------------------------------------------- /3/3.2/13.py: -------------------------------------------------------------------------------- 1 | # Дайте чего-нибудь новенького! 2 | def main() -> None: 3 | menu = [input() for _ in range(int(input()))] 4 | cooked = [] 5 | for _ in range(int(input())): 6 | cooked.extend([input() for _ in range(int(input()))]) 7 | print(*other, sep="\n") if (other := sorted(set(menu) - set(cooked))) else print("Готовить нечего") 8 | 9 | 10 | if __name__ == "__main__": 11 | main() 12 | -------------------------------------------------------------------------------- /3/3.2/14.py: -------------------------------------------------------------------------------- 1 | # Это будет шедевр! 2 | def main() -> None: 3 | products = [input() for _ in range(int(input()))] 4 | dishes, can_cook = {}, [] 5 | for _ in range(int(input())): 6 | name = input() 7 | dishes[name] = [input() for _ in range(int(input()))] 8 | can_cook.append(name) if len(set(dishes[name]) - set(products)) == 0 else ... 9 | print(*sorted(can_cook), sep="\n") if can_cook else print("Готовить нечего") 10 | 11 | 12 | if __name__ == "__main__": 13 | main() 14 | -------------------------------------------------------------------------------- /3/3.2/15.py: -------------------------------------------------------------------------------- 1 | # Двоичная статистика! 2 | def main() -> None: 3 | result = [] 4 | for i in [bin(x)[2:] for x in map(int, input().split())]: 5 | result.append({"digits": len(i), 6 | "units": i.count("1"), 7 | "zeros": i.count("0")}) 8 | print(result) 9 | 10 | 11 | if __name__ == "__main__": 12 | main() 13 | -------------------------------------------------------------------------------- /3/3.2/16.py: -------------------------------------------------------------------------------- 1 | # Зайка — 10 2 | def main() -> None: 3 | result = [] 4 | while string := input().split(): 5 | if "зайка" in string: 6 | index = 0 7 | for i in range(string.count("зайка")): 8 | index = string.index("зайка", index + i) 9 | if index == 0 and len(string) > 1: 10 | result.append(string[index + 1]) 11 | elif index == (len(string) - 1): 12 | result.append(string[index - 1]) 13 | else: 14 | result.append(string[index - 1]) 15 | result.append(string[index + 1]) 16 | print(*set(result), sep="\n") 17 | 18 | 19 | if __name__ == "__main__": 20 | main() 21 | -------------------------------------------------------------------------------- /3/3.2/17.py: -------------------------------------------------------------------------------- 1 | # Друзья друзей 2 | def main() -> None: 3 | close_friends = {} 4 | while (string := input()) != "": 5 | surname1, surname2 = string.split() 6 | close_friends.setdefault(surname1, []).append(surname2) 7 | close_friends.setdefault(surname2, []).append(surname1) 8 | 9 | friends, pairs = {x: [] for x in set(close_friends.keys())}, [] 10 | 11 | for key, value in close_friends.items(): 12 | for friend_key in value: 13 | if (key, friend_key) not in pairs: 14 | pairs.extend([(key, friend_key), (friend_key, key)]) 15 | friends[key].extend(close_friends[friend_key]) 16 | friends[friend_key].extend(close_friends[key]) 17 | 18 | for i in friends: 19 | friends[i] = [x for x in set(friends[i]) if x != i and x not in close_friends[i]] 20 | 21 | for i in sorted(friends): 22 | print(f"{i}: {', '.join(sorted(friends[i]))}") 23 | 24 | 25 | if __name__ == "__main__": 26 | main() 27 | -------------------------------------------------------------------------------- /3/3.2/18.py: -------------------------------------------------------------------------------- 1 | # Карта сокровищ 2 | def main() -> None: 3 | result = {} 4 | for _ in range(int(input())): 5 | cords = input().split() 6 | x = f'{cords[0][:-1]}-{cords[1][:-1]}' 7 | result[x] = result.get(x, 0) + 1 8 | print(max(result.values())) 9 | 10 | 11 | if __name__ == "__main__": 12 | main() 13 | -------------------------------------------------------------------------------- /3/3.2/19.py: -------------------------------------------------------------------------------- 1 | # Частная собственность 2 | def main() -> None: 3 | result = [] 4 | for i in range(int(input())): 5 | result.extend(set(input().split(": ")[1].split(", "))) 6 | result = [x for x in result if result.count(x) == 1] 7 | print(*(sorted(result)), sep="\n") 8 | 9 | 10 | if __name__ == "__main__": 11 | main() -------------------------------------------------------------------------------- /3/3.2/2.py: -------------------------------------------------------------------------------- 1 | # Символическая разница 2 | def main() -> None: 3 | print(*(set(input()) & set(input())), sep="") 4 | 5 | 6 | if __name__ == "__main__": 7 | main() 8 | -------------------------------------------------------------------------------- /3/3.2/20.py: -------------------------------------------------------------------------------- 1 | # Простая задача 4.0 2 | def LCD(num1: int, num2: int) -> int: 3 | while num1 != 0 and num2 != 0: 4 | num1, num2 = (num1 % num2, num2) if num1 > num2 else (num1, num2 % num1) 5 | return num1 + num2 6 | 7 | 8 | def main() -> None: 9 | string = sorted(set(map(int, input().split("; ")))) 10 | result = {str(i): [] for i in string} 11 | for i in string: 12 | result[str(i)].extend(str(j) for j in string if i != j and LCD(i, j) == 1) 13 | if result[str(i)]: 14 | print(f"{i} - {', '.join(result[str(i)])}") 15 | 16 | 17 | if __name__ == "__main__": 18 | main() 19 | -------------------------------------------------------------------------------- /3/3.2/3.py: -------------------------------------------------------------------------------- 1 | # Зайка — 8 2 | def main() -> None: 3 | elements = [] 4 | for _ in range(int(input())): 5 | elements.extend(input().split()) 6 | print(*set(elements), sep="\n") 7 | 8 | 9 | if __name__ == "__main__": 10 | main() 11 | -------------------------------------------------------------------------------- /3/3.2/4.py: -------------------------------------------------------------------------------- 1 | # Кашееды 2 | def main() -> None: 3 | n, m = [int(input()) for _ in range(2)] 4 | semolina = set([input() for _ in range(n)]) 5 | oatmeal = set([input() for _ in range(m)]) 6 | print(len(both) if len(both := (semolina & oatmeal)) else "Таких нет") 7 | 8 | 9 | if __name__ == "__main__": 10 | main() 11 | -------------------------------------------------------------------------------- /3/3.2/5.py: -------------------------------------------------------------------------------- 1 | # Кашееды — 2 2 | def main() -> None: 3 | n, m = [int(input()) for _ in range(2)] 4 | names = [input() for _ in range(n + m)] 5 | names = [i for i in names if names.count(i) == 1] 6 | print(len(names) if len(names) else "Таких нет") 7 | 8 | 9 | if __name__ == "__main__": 10 | main() 11 | -------------------------------------------------------------------------------- /3/3.2/6.py: -------------------------------------------------------------------------------- 1 | # Кашееды — 3 2 | def main() -> None: 3 | n, m = [int(input()) for _ in range(2)] 4 | names = [input() for _ in range(n + m)] 5 | names = [i for i in names if names.count(i) == 1] 6 | print(*(sorted(names)), sep="\n") if len(names) else print("Таких нет") 7 | 8 | 9 | if __name__ == "__main__": 10 | main() 11 | -------------------------------------------------------------------------------- /3/3.2/7.py: -------------------------------------------------------------------------------- 1 | # Азбука Морзе 2 | def main() -> None: 3 | Morse = { 4 | "A": ".-", "B": "-...", "C": "-.-.", 5 | "D": "-..", "E": ".", "F": "..-.", 6 | "G": "--.", "H": "....", "I": "..", 7 | "J": ".---", "K": "-.-", "L": ".-..", 8 | "M": "--", "N": "-.", "O": "---", 9 | "P": ".--.", "Q": "--.-", "R": ".-.", 10 | "S": "...", "T": "-", "U": "..-", 11 | "V": "...-", "W": ".--", "X": "-..-", 12 | "Y": "-.--", "Z": "--..", 13 | "0": "-----", "1": ".----", "2": "..---", 14 | "3": "...--", "4": "....-", "5": ".....", 15 | "6": "-....", "7": "--...", "8": "---..", 16 | "9": "----." 17 | } 18 | print(*[Morse[i] + " " if i in Morse else "\n" for i in input().upper()], sep="", end="") 19 | 20 | 21 | if __name__ == "__main__": 22 | main() 23 | -------------------------------------------------------------------------------- /3/3.2/8.py: -------------------------------------------------------------------------------- 1 | # Кашееды — 4 2 | def main() -> None: 3 | list = {} 4 | for i in range(int(input())): 5 | string = input().split() 6 | name, porridge = string[0], string[1:] 7 | for j in porridge: 8 | list.setdefault(j, []).append(name) 9 | print(*(sorted(list[n])), sep="\n") if (n := input()) in list else print("Таких нет") 10 | 11 | 12 | if __name__ == "__main__": 13 | main() 14 | -------------------------------------------------------------------------------- /3/3.2/9.py: -------------------------------------------------------------------------------- 1 | # Зайка — 9 2 | def main() -> None: 3 | words = [] 4 | while (string := input()) != "": 5 | words.extend(string.split()) 6 | print(*[f"{word} {words.count(word)}" for word in set(words)], sep="\n") 7 | 8 | 9 | if __name__ == "__main__": 10 | main() 11 | -------------------------------------------------------------------------------- /3/3.3/1.py: -------------------------------------------------------------------------------- 1 | # Список квадратов 2 | [x ** 2 for x in range(a, b + 1)] 3 | -------------------------------------------------------------------------------- /3/3.3/10.py: -------------------------------------------------------------------------------- 1 | # RLE наоборот 2 | "".join([i * j for i, j in rle]) 3 | -------------------------------------------------------------------------------- /3/3.3/2.py: -------------------------------------------------------------------------------- 1 | # Таблица умножения 2.0 2 | [[i * j for i in range(1, n + 1)] for j in range(1, n + 1)] 3 | -------------------------------------------------------------------------------- /3/3.3/3.py: -------------------------------------------------------------------------------- 1 | # Длины всех слов 2 | [len(x) for x in sentence.split()] 3 | -------------------------------------------------------------------------------- /3/3.3/4.py: -------------------------------------------------------------------------------- 1 | # Множество нечетных чисел 2 | {x for x in numbers if x % 2 != 0} 3 | -------------------------------------------------------------------------------- /3/3.3/5.py: -------------------------------------------------------------------------------- 1 | # Множество всех полных квадратов 2 | {x for x in numbers if int(x ** 0.5) ** 2 == x} 3 | -------------------------------------------------------------------------------- /3/3.3/6.py: -------------------------------------------------------------------------------- 1 | # Буквенная статистика 2 | {i: text.lower().count(i) for i in sorted(set(text.lower())) if i.isalpha()} 3 | -------------------------------------------------------------------------------- /3/3.3/7.py: -------------------------------------------------------------------------------- 1 | # Делители 2 | {i: [x for x in range(1, i + 1) if i % x == 0] for i in numbers} 3 | -------------------------------------------------------------------------------- /3/3.3/8.py: -------------------------------------------------------------------------------- 1 | # Аббревиатура 2 | "".join([x[0].upper() for x in string.split()]) 3 | -------------------------------------------------------------------------------- /3/3.3/9.py: -------------------------------------------------------------------------------- 1 | # Преобразование в строку 2 | " - ".join([str(x) for x in sorted(set(numbers))]) 3 | -------------------------------------------------------------------------------- /3/3.3/solutions.md: -------------------------------------------------------------------------------- 1 | # Списочные выражения. Модель памяти для типов языка Python 2 | 3 | ### Список квадратов 4 | 5 | ```python 6 | [x ** 2 for x in range(a, b + 1)] 7 | ``` 8 | 9 | ### Таблица умножения 2.0 10 | 11 | ```python 12 | [[i * j for i in range(1, n + 1)] for j in range(1, n + 1)] 13 | ``` 14 | 15 | ### Длины всех слов 16 | 17 | ```python 18 | [len(x) for x in sentence.split()] 19 | ``` 20 | 21 | ### Множество нечетных чисел 22 | 23 | ```python 24 | {x for x in numbers if x % 2 != 0} 25 | ``` 26 | 27 | ### Множество всех полных квадратов 28 | 29 | ```python 30 | {x for x in numbers if int(x ** 0.5) ** 2 == x} 31 | ``` 32 | 33 | ### Буквенная статистика 34 | 35 | ```python 36 | {i: text.lower().count(i) for i in sorted(set(text.lower())) if i.isalpha()} 37 | ``` 38 | 39 | ### Делители 40 | 41 | ```python 42 | {i: [x for x in range(1, i + 1) if i % x == 0] for i in numbers} 43 | ``` 44 | 45 | ### Аббревиатура 46 | 47 | ```python 48 | "".join([x[0].upper() for x in string.split()]) 49 | ``` 50 | 51 | ### Преобразование в строку 52 | 53 | ```python 54 | " - ".join([str(x) for x in sorted(set(numbers))]) 55 | ``` 56 | 57 | ### RLE наоборот 58 | 59 | ```python 60 | "".join([i * j for i, j in rle]) 61 | ``` -------------------------------------------------------------------------------- /3/3.4/1.py: -------------------------------------------------------------------------------- 1 | # Автоматизация списка 2 | def main() -> None: 3 | line = input() 4 | print(*[f"{line.split().index(word) + 1}. {word}" for word in line.split()], sep="\n") 5 | 6 | 7 | if __name__ == "__main__": 8 | main() 9 | -------------------------------------------------------------------------------- /3/3.4/10.py: -------------------------------------------------------------------------------- 1 | # Мы делили апельсин 2.0 2 | from itertools import product 3 | 4 | 5 | def main() -> None: 6 | n = int(input()) 7 | print("А Б В") 8 | for a, b, c in product(range(1, n + 1), repeat=3): 9 | print(a, b, c) if a + b + c == n else ... 10 | 11 | 12 | if __name__ == "__main__": 13 | main() 14 | -------------------------------------------------------------------------------- /3/3.4/11.py: -------------------------------------------------------------------------------- 1 | # Числовой прямоугольник 3.0 2 | def main() -> None: 3 | n, m = [int(input()) for _ in range(2)] 4 | width = len(str(n * m)) 5 | for a in range(1, n * m + 1): 6 | print(f"{a:>{width}}", end=" " if a % m != 0 else "\n") 7 | 8 | 9 | if __name__ == "__main__": 10 | main() 11 | -------------------------------------------------------------------------------- /3/3.4/12.py: -------------------------------------------------------------------------------- 1 | # Список покупок 2.0 2 | def main() -> None: 3 | products = [x for _ in range(int(input())) for x in input().split(", ")] 4 | print(*[f"{index}. {element}" for index, element in enumerate(sorted(products), start=1)], sep="\n") 5 | 6 | 7 | if __name__ == "__main__": 8 | main() 9 | -------------------------------------------------------------------------------- /3/3.4/13.py: -------------------------------------------------------------------------------- 1 | # Расстановка спортсменов 2 | from itertools import permutations 3 | 4 | 5 | def main() -> None: 6 | print("\n".join(", ".join(a) for a in permutations(sorted([input() for _ in range(int(input()))])))) 7 | 8 | 9 | if __name__ == "__main__": 10 | main() 11 | -------------------------------------------------------------------------------- /3/3.4/14.py: -------------------------------------------------------------------------------- 1 | # Спортивные гадания 2 | from itertools import permutations 3 | 4 | 5 | def main() -> None: 6 | print("\n".join(", ".join(a) for a in permutations(sorted([input() for _ in range(int(input()))]), r=3))) 7 | 8 | 9 | if __name__ == "__main__": 10 | main() 11 | -------------------------------------------------------------------------------- /3/3.4/15.py: -------------------------------------------------------------------------------- 1 | # Список покупок 3.0 2 | from itertools import permutations 3 | 4 | 5 | def main() -> None: 6 | for products in permutations(sorted([x for _ in range(int(input())) for x in input().split(", ")]), 3): 7 | print(*[" ".join(products)]) 8 | 9 | 10 | if __name__ == "__main__": 11 | main() 12 | -------------------------------------------------------------------------------- /3/3.4/16.py: -------------------------------------------------------------------------------- 1 | # Расклад таков... 2 | from itertools import product, permutations 3 | 4 | 5 | def main() -> None: 6 | raw_suit = input() 7 | suits = ["бубен", "пик", "треф", "червей"] 8 | best_suit = [x for x in suits if x[0] == raw_suit[0]][0] 9 | nominal = sorted([*[str(x) for x in range(2, 11)], "валет", "дама", "король", "туз"]) 10 | nominal.remove(input()) 11 | 12 | card_list = [f"{value} {suit}" for value, suit in product(nominal, suits)] 13 | card_layout_list = [", ".join(card_layout) for card_layout in product(card_list, repeat=3) if 14 | len(set(card_layout)) == 3] 15 | print(*([card_layout for card_layout in card_layout_list if best_suit in card_layout][:10]), sep="\n") 16 | 17 | 18 | if __name__ == "__main__": 19 | main() 20 | -------------------------------------------------------------------------------- /3/3.4/17.py: -------------------------------------------------------------------------------- 1 | # А есть ещё варианты? 2 | from itertools import product, permutations 3 | 4 | 5 | def main() -> None: 6 | raw_suit = input() 7 | suits = ["бубен", "пик", "треф", "червей"] 8 | best_suit = [x for x in suits if x[0] == raw_suit[0]][0] 9 | nominal = sorted([*[str(x) for x in range(2, 11)], "валет", "дама", "король", "туз"]) 10 | nominal.remove(input()) 11 | 12 | card_layout_tuple = tuple(permutations(product(nominal, suits), r=3)) 13 | card_layout_tuple = (", ".join(" ".join(card_tuple) for card_tuple in sorted(card_layout)) for card_layout in 14 | card_layout_tuple) 15 | card_layout_list = [card_layout for card_layout in sorted(set(card_layout_tuple)) if best_suit in card_layout] 16 | print(card_layout_list[card_layout_list.index(input()) + 1]) 17 | 18 | 19 | if __name__ == "__main__": 20 | main() 21 | -------------------------------------------------------------------------------- /3/3.4/18.py: -------------------------------------------------------------------------------- 1 | # Таблица истинности 2 | from itertools import product 3 | 4 | 5 | def main() -> None: 6 | print("a b c f") 7 | f = input() 8 | for a, b, c in product([0, 1], repeat=3): 9 | print(a, b, c, int(eval(f))) 10 | 11 | 12 | if __name__ == "__main__": 13 | main() 14 | -------------------------------------------------------------------------------- /3/3.4/19.py: -------------------------------------------------------------------------------- 1 | # Таблица истинности 2 2 | from itertools import product, repeat 3 | 4 | 5 | def main() -> None: 6 | f = input() 7 | print(" ".join(args := sorted({i for i in f if i.isupper()})) + " F") 8 | for i in product([0, 1], repeat=len(args)): 9 | print(*i, int(eval(f, dict(zip(args, i))))) 10 | 11 | 12 | if __name__ == "__main__": 13 | main() 14 | -------------------------------------------------------------------------------- /3/3.4/2.py: -------------------------------------------------------------------------------- 1 | # Сборы на прогулку 2 | def main() -> None: 3 | names1, names2 = [input().split(", ") for _ in range(2)] 4 | print(*[f"{names1[i]} - {names2[i]}" for i in range(min(len(names1), len(names2)))], sep="\n") 5 | 6 | 7 | if __name__ == "__main__": 8 | main() 9 | -------------------------------------------------------------------------------- /3/3.4/20.py: -------------------------------------------------------------------------------- 1 | # Таблицы истинности 3 2 | from itertools import product 3 | 4 | 5 | def postfix(expression: str, variables: list, operators: dict, priorities: dict) -> list: 6 | stack, result = [], [] 7 | for token in expression.split(): 8 | if token in variables: 9 | result.append(token) 10 | elif token == "(": 11 | stack.append(token) 12 | elif token == ")": 13 | while stack[-1] != "(": 14 | result.append(operators[stack.pop()]) 15 | stack.pop() 16 | elif token in operators: 17 | while stack and priorities[token] >= priorities[stack[-1]]: 18 | result.append(operators[stack.pop()]) 19 | stack.append(token) 20 | while stack: 21 | result.append(operators[stack.pop()]) 22 | return result 23 | 24 | 25 | def result(postfix_exp: list, variables: dict) -> int: 26 | stack = [] 27 | for token in postfix_exp: 28 | if token in variables: 29 | stack.append(variables[token]) 30 | else: 31 | if token == "not": 32 | stack.append(not stack.pop()) 33 | else: 34 | var2, var1 = stack.pop(), stack.pop() 35 | stack.append(eval(f"{var1} {token} {var2}")) 36 | return int(stack.pop()) 37 | 38 | 39 | def main() -> None: 40 | operators = { 41 | "not": "not", "and": "and", "or": "or", 42 | "^": "!=", "->": "<=", "~": "=="} 43 | priorities = {key: value for value, key in enumerate(["not", "and", "or", "^", "->", "~", "("])} 44 | 45 | statement = input() 46 | variables = sorted(set(filter(str.isupper, statement))) 47 | print(" ".join(variables), "F") 48 | 49 | statement = statement.replace("(", "( ").replace(")", " )") 50 | exp = postfix(statement, variables, operators, priorities) 51 | 52 | for row in product([0, 1], repeat=len(variables)): 53 | res = dict(zip(variables, row)) 54 | print(" ".join(map(str, row)), result(exp, res)) 55 | 56 | 57 | if __name__ == "__main__": 58 | main() 59 | -------------------------------------------------------------------------------- /3/3.4/3.py: -------------------------------------------------------------------------------- 1 | # Рациональная считалочка 2 | from itertools import count, takewhile 3 | 4 | 5 | def main() -> None: 6 | start, end, step = map(float, input().split()) 7 | print(*[f'{value:.2f}' for value in takewhile(lambda x: x <= end, count(start, step))], sep='\n') 8 | 9 | 10 | if __name__ == "__main__": 11 | main() 12 | -------------------------------------------------------------------------------- /3/3.4/4.py: -------------------------------------------------------------------------------- 1 | # Словарная ёлка 2 | from itertools import accumulate 3 | 4 | 5 | def main() -> None: 6 | print(*[word for word in accumulate(map(lambda x: x + " ", input().split()))], sep='\n') 7 | 8 | 9 | if __name__ == "__main__": 10 | main() 11 | -------------------------------------------------------------------------------- /3/3.4/5.py: -------------------------------------------------------------------------------- 1 | # Список покупок 2 | def main() -> None: 3 | for index, product in enumerate(sorted({word for _ in range(3) for word in input().split(", ")})): 4 | print(f"{index + 1}. {product}") 5 | 6 | 7 | if __name__ == "__main__": 8 | main() 9 | -------------------------------------------------------------------------------- /3/3.4/6.py: -------------------------------------------------------------------------------- 1 | # Колода карт 2 | def main() -> None: 3 | deck, suit = [(x, y) for x in [*[i for i in range(2, 11)], "валет", "дама", "король", "туз"] for y in 4 | ["пик", "треф", "бубен", "червей"]], input() 5 | print(*[f"{x} {y}" for x, y in deck if y != suit], sep="\n") 6 | 7 | 8 | if __name__ == "__main__": 9 | main() 10 | -------------------------------------------------------------------------------- /3/3.4/7.py: -------------------------------------------------------------------------------- 1 | # Игровая сетка 2 | from itertools import combinations 3 | 4 | 5 | def main() -> None: 6 | print(*[f"{x} - {y}" for x, y in combinations([input() for _ in range(int(input()))], 2)], sep="\n") 7 | 8 | 9 | if __name__ == "__main__": 10 | main() 11 | -------------------------------------------------------------------------------- /3/3.4/8.py: -------------------------------------------------------------------------------- 1 | # Меню питания 2.0 2 | def main() -> None: 3 | n = int(input()) 4 | porridge = [input() for _ in range(n)] 5 | print(*(porridge[i % n] for i in range(int(input()))), sep='\n') 6 | 7 | 8 | if __name__ == "__main__": 9 | main() 10 | -------------------------------------------------------------------------------- /3/3.4/9.py: -------------------------------------------------------------------------------- 1 | # Таблица умножения 3.0 2 | from itertools import product 3 | 4 | 5 | def main() -> None: 6 | n = int(input()) 7 | for a1, a2 in product(range(1, n + 1), repeat=2): 8 | print(a1 * a2, end=" ") 9 | if a2 == n: 10 | print() 11 | 12 | 13 | if __name__ == "__main__": 14 | main() 15 | 16 | -------------------------------------------------------------------------------- /3/3.4/solutions.md: -------------------------------------------------------------------------------- 1 | # Встроенные возможности по работе с коллекциями 2 | 3 | ### Автоматизация списка 4 | 5 | ```python 6 | def main() -> None: 7 | line = input() 8 | print(*[f"{line.split().index(word) + 1}. {word}" for word in line.split()], sep="\n") 9 | 10 | 11 | if __name__ == "__main__": 12 | main() 13 | ``` 14 | 15 | ### Сборы на прогулку 16 | 17 | ```python 18 | def main() -> None: 19 | names1, names2 = [input().split(", ") for _ in range(2)] 20 | print(*[f"{names1[i]} - {names2[i]}" for i in range(min(len(names1), len(names2)))], sep="\n") 21 | 22 | 23 | if __name__ == "__main__": 24 | main() 25 | ``` 26 | 27 | ### Рациональная считалочка 28 | 29 | ```python 30 | from itertools import count, takewhile 31 | 32 | 33 | def main() -> None: 34 | start, end, step = map(float, input().split()) 35 | print(*[f'{value:.2f}' for value in takewhile(lambda x: x <= end, count(start, step))], sep='\n') 36 | 37 | 38 | if __name__ == "__main__": 39 | main() 40 | ``` 41 | 42 | ### Словарная ёлка 43 | 44 | ```python 45 | from itertools import accumulate 46 | 47 | 48 | def main() -> None: 49 | print(*[word for word in accumulate(map(lambda x: x + " ", input().split()))], sep='\n') 50 | 51 | 52 | if __name__ == "__main__": 53 | main() 54 | ``` 55 | 56 | ### Список покупок 57 | 58 | ```python 59 | def main() -> None: 60 | for index, product in enumerate(sorted({word for _ in range(3) for word in input().split(", ")})): 61 | print(f"{index + 1}. {product}") 62 | 63 | 64 | if __name__ == "__main__": 65 | main() 66 | ``` 67 | 68 | ### Колода карт 69 | 70 | ```python 71 | def main() -> None: 72 | deck, suit = [(x, y) for x in [*[i for i in range(2, 11)], "валет", "дама", "король", "туз"] for y in 73 | ["пик", "треф", "бубен", "червей"]], input() 74 | print(*[f"{x} {y}" for x, y in deck if y != suit], sep="\n") 75 | 76 | 77 | if __name__ == "__main__": 78 | main() 79 | ``` 80 | 81 | ### Игровая сетка 82 | 83 | ```python 84 | from itertools import combinations 85 | 86 | 87 | def main() -> None: 88 | print(*[f"{x} - {y}" for x, y in combinations([input() for _ in range(int(input()))], 2)], sep="\n") 89 | 90 | 91 | if __name__ == "__main__": 92 | main() 93 | ``` 94 | 95 | ### Меню питания 2.0 96 | 97 | ```python 98 | def main() -> None: 99 | n = int(input()) 100 | porridge = [input() for _ in range(n)] 101 | print(*(porridge[i % n] for i in range(int(input()))), sep='\n') 102 | 103 | 104 | if __name__ == "__main__": 105 | main() 106 | ``` 107 | 108 | ### Таблица умножения 3.0 109 | 110 | ```python 111 | from itertools import product 112 | 113 | 114 | def main() -> None: 115 | n = int(input()) 116 | for a1, a2 in product(range(1, n + 1), repeat=2): 117 | print(a1 * a2, end=" ") 118 | if a2 == n: 119 | print() 120 | 121 | 122 | if __name__ == "__main__": 123 | main() 124 | ``` 125 | 126 | ### Мы делили апельсин 2.0 127 | 128 | ```python 129 | from itertools import product 130 | 131 | 132 | def main() -> None: 133 | n = int(input()) 134 | print("А Б В") 135 | for a, b, c in product(range(1, n + 1), repeat=3): 136 | print(a, b, c) if a + b + c == n else ... 137 | 138 | 139 | if __name__ == "__main__": 140 | main() 141 | ``` 142 | 143 | ### Числовой прямоугольник 3.0 144 | 145 | ```python 146 | def main() -> None: 147 | n, m = [int(input()) for _ in range(2)] 148 | width = len(str(n * m)) 149 | for a in range(1, n * m + 1): 150 | print(f"{a:>{width}}", end=" " if a % m != 0 else "\n") 151 | 152 | 153 | if __name__ == "__main__": 154 | main() 155 | ``` 156 | 157 | ### Список покупок 2.0 158 | 159 | ```python 160 | def main() -> None: 161 | products = [x for _ in range(int(input())) for x in input().split(", ")] 162 | print(*[f"{index}. {element}" for index, element in enumerate(sorted(products), start=1)], sep="\n") 163 | 164 | 165 | if __name__ == "__main__": 166 | main() 167 | ``` 168 | 169 | ### Расстановка спортсменов 170 | 171 | ```python 172 | from itertools import permutations 173 | 174 | 175 | def main() -> None: 176 | print("\n".join(", ".join(a) for a in permutations(sorted([input() for _ in range(int(input()))])))) 177 | 178 | 179 | if __name__ == "__main__": 180 | main() 181 | ``` 182 | 183 | ### Спортивные гадания 184 | 185 | ```python 186 | from itertools import permutations 187 | 188 | 189 | def main() -> None: 190 | print("\n".join(", ".join(a) for a in permutations(sorted([input() for _ in range(int(input()))]), r=3))) 191 | 192 | 193 | if __name__ == "__main__": 194 | main() 195 | ``` 196 | 197 | ### Список покупок 3.0 198 | 199 | ```python 200 | from itertools import permutations 201 | 202 | 203 | def main() -> None: 204 | for products in permutations(sorted([x for _ in range(int(input())) for x in input().split(", ")]), 3): 205 | print(*[" ".join(products)]) 206 | 207 | 208 | if __name__ == "__main__": 209 | main() 210 | ``` 211 | 212 | ### Расклад таков... 213 | 214 | ```python 215 | from itertools import product, permutations 216 | 217 | 218 | def main() -> None: 219 | raw_suit = input() 220 | suits = ["бубен", "пик", "треф", "червей"] 221 | best_suit = [x for x in suits if x[0] == raw_suit[0]][0] 222 | nominal = sorted([*[str(x) for x in range(2, 11)], "валет", "дама", "король", "туз"]) 223 | nominal.remove(input()) 224 | 225 | card_list = [f"{value} {suit}" for value, suit in product(nominal, suits)] 226 | card_layout_list = [", ".join(card_layout) for card_layout in product(card_list, repeat=3) if 227 | len(set(card_layout)) == 3] 228 | print(*([card_layout for card_layout in card_layout_list if best_suit in card_layout][:10]), sep="\n") 229 | 230 | 231 | if __name__ == "__main__": 232 | main() 233 | ``` 234 | 235 | ### А есть ещё варианты? 236 | 237 | ```python 238 | from itertools import product, permutations 239 | 240 | 241 | def main() -> None: 242 | raw_suit = input() 243 | suits = ["бубен", "пик", "треф", "червей"] 244 | best_suit = [x for x in suits if x[0] == raw_suit[0]][0] 245 | nominal = sorted([*[str(x) for x in range(2, 11)], "валет", "дама", "король", "туз"]) 246 | nominal.remove(input()) 247 | 248 | card_layout_tuple = tuple(permutations(product(nominal, suits), r=3)) 249 | card_layout_tuple = (", ".join(" ".join(card_tuple) for card_tuple in sorted(card_layout)) for card_layout in 250 | card_layout_tuple) 251 | card_layout_list = [card_layout for card_layout in sorted(set(card_layout_tuple)) if best_suit in card_layout] 252 | print(card_layout_list[card_layout_list.index(input()) + 1]) 253 | 254 | 255 | if __name__ == "__main__": 256 | main() 257 | ``` 258 | 259 | ### Таблица истинности 260 | 261 | ```python 262 | from itertools import product 263 | 264 | 265 | def main() -> None: 266 | print("a b c f") 267 | f = input() 268 | for a, b, c in product([0, 1], repeat=3): 269 | print(a, b, c, int(eval(f))) 270 | 271 | 272 | if __name__ == "__main__": 273 | main() 274 | ``` 275 | 276 | ### Таблица истинности 2 277 | 278 | ```python 279 | from itertools import product, repeat 280 | 281 | 282 | def main() -> None: 283 | f = input() 284 | print(" ".join(args := sorted({i for i in f if i.isupper()})) + " F") 285 | for i in product([0, 1], repeat=len(args)): 286 | print(*i, int(eval(f, dict(zip(args, i))))) 287 | 288 | 289 | if __name__ == "__main__": 290 | main() 291 | ``` 292 | 293 | ### Таблицы истинности 3 294 | 295 | ```python 296 | from itertools import product 297 | 298 | 299 | def postfix(expression: str, variables: list, operators: dict, priorities: dict) -> list: 300 | stack, result = [], [] 301 | for token in expression.split(): 302 | if token in variables: 303 | result.append(token) 304 | elif token == "(": 305 | stack.append(token) 306 | elif token == ")": 307 | while stack[-1] != "(": 308 | result.append(operators[stack.pop()]) 309 | stack.pop() 310 | elif token in operators: 311 | while stack and priorities[token] >= priorities[stack[-1]]: 312 | result.append(operators[stack.pop()]) 313 | stack.append(token) 314 | while stack: 315 | result.append(operators[stack.pop()]) 316 | return result 317 | 318 | 319 | def result(postfix_exp: list, variables: dict) -> int: 320 | stack = [] 321 | for token in postfix_exp: 322 | if token in variables: 323 | stack.append(variables[token]) 324 | else: 325 | if token == "not": 326 | stack.append(not stack.pop()) 327 | else: 328 | var2, var1 = stack.pop(), stack.pop() 329 | stack.append(eval(f"{var1} {token} {var2}")) 330 | return int(stack.pop()) 331 | 332 | 333 | def main() -> None: 334 | operators = { 335 | "not": "not", "and": "and", "or": "or", 336 | "^": "!=", "->": "<=", "~": "=="} 337 | priorities = {key: value for value, key in enumerate(["not", "and", "or", "^", "->", "~", "("])} 338 | 339 | statement = input() 340 | variables = sorted(set(filter(str.isupper, statement))) 341 | print(" ".join(variables), "F") 342 | 343 | statement = statement.replace("(", "( ").replace(")", " )") 344 | exp = postfix(statement, variables, operators, priorities) 345 | 346 | for row in product([0, 1], repeat=len(variables)): 347 | res = dict(zip(variables, row)) 348 | print(" ".join(map(str, row)), result(exp, res)) 349 | 350 | 351 | if __name__ == "__main__": 352 | main() 353 | ``` -------------------------------------------------------------------------------- /3/3.5/1.py: -------------------------------------------------------------------------------- 1 | # A+B+... 2 | from sys import stdin 3 | 4 | 5 | def main() -> None: 6 | print(sum(map(int, stdin.read().split()))) 7 | 8 | 9 | if __name__ == "__main__": 10 | main() 11 | -------------------------------------------------------------------------------- /3/3.5/10.py: -------------------------------------------------------------------------------- 1 | # Хвост 2 | def main() -> None: 3 | f, n = input(), int(input()) 4 | data = [] 5 | with open(f, "r") as f: 6 | for line in f: 7 | data.append(line) 8 | for line in data[-n:]: 9 | print(line.strip()) 10 | 11 | 12 | if __name__ == "__main__": 13 | main() 14 | -------------------------------------------------------------------------------- /3/3.5/11.py: -------------------------------------------------------------------------------- 1 | # Файловая статистика 2.0 2 | import json 3 | 4 | 5 | def main() -> None: 6 | file_in, file_out = [input() for _ in range(2)] 7 | numbers = [] 8 | with open(file_in, "r") as file: 9 | for line in file: 10 | numbers.extend([int(x) for x in line.split()]) 11 | data = { 12 | "count": len(numbers), 13 | "positive_count": len([x for x in numbers if x > 0]), 14 | "min": min(numbers), 15 | "max": max(numbers), 16 | "sum": sum(numbers), 17 | "average": round(sum(numbers) / len(numbers), 2)} 18 | with open(file_out, "w", encoding="UTF-8") as file: 19 | json.dump(data, file, ensure_ascii=False, indent=4) 20 | 21 | 22 | if __name__ == "__main__": 23 | main() 24 | -------------------------------------------------------------------------------- /3/3.5/12.py: -------------------------------------------------------------------------------- 1 | # Разделяй и властвуй 2 | def compare(numbers: list) -> int: 3 | odd = sum(1 for x in numbers if int(x) % 2 == 0) 4 | even = len(numbers) - odd 5 | return 0 if odd > even else 1 if odd < even else 2 6 | 7 | 8 | def main() -> None: 9 | numbers, even, odd, eq = [input() for _ in range(4)] 10 | lines, k = [], 0 11 | with open(numbers, encoding="UTF-8") as file: 12 | for line in file: 13 | lines.append([x for x in line.split()]) 14 | for t in even, odd, eq: 15 | with open(t, "w", encoding="UTF-8") as file: 16 | for i in range(len(lines)): 17 | for j in lines[i]: 18 | if compare(j) == k: 19 | print(j, end=" ", file=file) 20 | print("", file=file) 21 | k += 1 22 | 23 | 24 | if __name__ == "__main__": 25 | main() 26 | -------------------------------------------------------------------------------- /3/3.5/13.py: -------------------------------------------------------------------------------- 1 | # Обновление данных 2 | import json 3 | from sys import stdin 4 | 5 | 6 | def main() -> None: 7 | with open(user := input(), encoding="UTF-8") as file: 8 | data = json.load(file) 9 | for line in stdin: 10 | before = line[:line.find("=")].rstrip() 11 | after = line[line.find("==") + 2:].lstrip() 12 | data[before] = after.rstrip() 13 | with open(user, "w", encoding="UTF-8") as file: 14 | json.dump(data, file, ensure_ascii=False, indent=2) 15 | 16 | 17 | if __name__ == "__main__": 18 | main() 19 | -------------------------------------------------------------------------------- /3/3.5/14.py: -------------------------------------------------------------------------------- 1 | # Слияние данных 2 | import json 3 | 4 | 5 | def main() -> None: 6 | files = [input() for _ in range(2)] 7 | data = [{}, {}] 8 | for i in range(2): 9 | with open(files[i], "r") as file: 10 | data[i] = json.load(file) 11 | 12 | data[0] = {i["name"]: {key: value for key, value in i.items() if key != "name"} for i in data[0]} 13 | for param in data[1]: 14 | if param["name"] in data[0]: 15 | for key in param: 16 | if (key not in data[0][param["name"]] or param[key] > data[0][param["name"]][key]) and key != "name": 17 | data[0][param["name"]][key] = param[key] 18 | else: 19 | data[0][param["name"]] = {key: value for key, value in param.items() if key != "name"} 20 | 21 | with open(files[0], "w") as file: 22 | json.dump(data[0], file, ensure_ascii=False, indent=4) 23 | 24 | 25 | if __name__ == "__main__": 26 | main() 27 | -------------------------------------------------------------------------------- /3/3.5/15.py: -------------------------------------------------------------------------------- 1 | # Поставь себя на моё место 2 | from sys import stdin 3 | import json 4 | 5 | 6 | def main() -> None: 7 | user = [x.strip() for x in stdin] 8 | with open("scoring.json", encoding="UTF-8") as f: 9 | data = json.load(f) 10 | points = count = 0 11 | data = [{test["pattern"]: block["points"] // len(block["tests"]) for test in block["tests"]} for block in data] 12 | for i in data: 13 | for j in range(count, len(i) + count): 14 | if user[j] in i: 15 | points += i[user[j]] 16 | count += 1 17 | print(points) 18 | 19 | 20 | if __name__ == "__main__": 21 | main() 22 | -------------------------------------------------------------------------------- /3/3.5/16.py: -------------------------------------------------------------------------------- 1 | # Найдётся всё 3.0 2 | from sys import stdin 3 | 4 | 5 | def clear(string: str) -> str: 6 | string = string.replace("\n", " ") 7 | while " " in string: 8 | string = string.replace(" ", " ") 9 | return string 10 | 11 | 12 | def main() -> None: 13 | string, flag = input(), True 14 | files = [x.strip() for x in stdin] 15 | for name in files: 16 | with open(name, encoding="UTF-8") as file: 17 | data = "".join(file.readlines()).lower() 18 | if string.lower() in clear(data): 19 | print(name) 20 | flag = False 21 | print("404. Not Found") if flag else ... 22 | 23 | 24 | if __name__ == "__main__": 25 | main() 26 | -------------------------------------------------------------------------------- /3/3.5/17.py: -------------------------------------------------------------------------------- 1 | # Прятки 2 | def main() -> None: 3 | with open("secret.txt", "r", encoding="UTF-8") as file: 4 | for symbol in file.read(): 5 | print(chr(ord(symbol) % 128), end="") 6 | 7 | 8 | if __name__ == "__main__": 9 | main() 10 | -------------------------------------------------------------------------------- /3/3.5/18.py: -------------------------------------------------------------------------------- 1 | # Сколько вешать в байтах? 2 | import os 3 | import math 4 | 5 | 6 | def main() -> None: 7 | size, postfixes, index = os.path.getsize(input()), ["Б", "КБ", "МБ", "ГБ"], 0 8 | while size >= 1024 and index < len(postfixes) - 1: 9 | size = math.ceil(size / 1024) 10 | index += 1 11 | print(size, postfixes[index], sep="") 12 | 13 | 14 | if __name__ == "__main__": 15 | main() 16 | -------------------------------------------------------------------------------- /3/3.5/19.py: -------------------------------------------------------------------------------- 1 | # Это будет наш секрет 2 | def main() -> None: 3 | shift = int(input()) 4 | alphabet = "".join([chr(i) for i in range(ord("a"), ord("z") + 1)]) 5 | with open("public.txt", encoding="UTF-8") as file: 6 | data = file.read() 7 | words = [x.lower() for x in data] 8 | res = [alphabet[(alphabet.find(x.lower()) + shift) % 26] if x in alphabet else x for x in words] 9 | for x in range(len(res)): 10 | if data[x].isupper(): 11 | res[x] = res[x].upper() 12 | with open("private.txt", "w", encoding="UTF-8") as file: 13 | print(''.join(x for x in res), file=file) 14 | 15 | 16 | if __name__ == "__main__": 17 | main() 18 | -------------------------------------------------------------------------------- /3/3.5/2.py: -------------------------------------------------------------------------------- 1 | # Средний рост 2 | from sys import stdin 3 | 4 | 5 | def main() -> None: 6 | print(round(sum(x := [int(line.split()[2]) - int(line.split()[1]) for line in stdin.readlines()]) / len(x))) 7 | 8 | 9 | if __name__ == "__main__": 10 | main() 11 | -------------------------------------------------------------------------------- /3/3.5/20.py: -------------------------------------------------------------------------------- 1 | # Файловая сумма 2 | def main() -> None: 3 | with open("numbers.num", "rb") as file: 4 | numbers = file.read() 5 | print(sum([int.from_bytes(numbers[i:i + 2], "big") for i in range(0, len(numbers), 2)]) % 2 ** 16) 6 | 7 | 8 | if __name__ == "__main__": 9 | main() 10 | -------------------------------------------------------------------------------- /3/3.5/3.py: -------------------------------------------------------------------------------- 1 | # Без комментариев 2.0 2 | from sys import stdin 3 | 4 | 5 | def main() -> None: 6 | print(*[i[0:i.find("#")] for i in stdin.readlines() if not i[0] == "#"], sep="\n") 7 | 8 | 9 | if __name__ == "__main__": 10 | main() 11 | -------------------------------------------------------------------------------- /3/3.5/4.py: -------------------------------------------------------------------------------- 1 | # Найдётся всё 2.0 2 | from sys import stdin 3 | 4 | 5 | def main() -> None: 6 | x = [i.strip() for i in stdin] 7 | print(*[line for line in x[:-1] if x[-1].lower() in line.lower()], sep="\n") 8 | 9 | 10 | if __name__ == "__main__": 11 | main() 12 | -------------------------------------------------------------------------------- /3/3.5/5.py: -------------------------------------------------------------------------------- 1 | # А роза упала на лапу Азора 6.0 2 | from sys import stdin 3 | 4 | 5 | def main() -> None: 6 | data = [string.strip().split() for string in stdin] 7 | words = [word for line in data for word in line if word.lower() == word.lower()[::-1]] 8 | print(*sorted(set(words)), sep="\n") 9 | 10 | 11 | if __name__ == "__main__": 12 | main() 13 | -------------------------------------------------------------------------------- /3/3.5/6.py: -------------------------------------------------------------------------------- 1 | # Транслитерация 2.0 2 | def main() -> None: 3 | alphabet = { 4 | "А": "A", "Б": "B", "В": "V", 5 | "Г": "G", "Д": "D", "Е": "E", 6 | "Ё": "E", "Ж": "ZH", "З": "Z", 7 | "И": "I", "Й": "I", "К": "K", 8 | "Л": "L", "М": "M", "Н": "N", 9 | "О": "O", "П": "P", "Р": "R", 10 | "С": "S", "Т": "T", "У": "U", 11 | "Ф": "F", "Х": "KH", "Ц": "TC", 12 | "Ч": "CH", "Ш": "SH", "Щ": "SHCH", 13 | "Ы": "Y", "Э": "E", "Ю": "IU", 14 | "Я": "IA", "Ь": "", "Ъ": ""} 15 | data, translit_data = "", "" 16 | with open("cyrillic.txt", encoding="UTF-8") as file: 17 | for line in file: 18 | data += line 19 | 20 | for i in data: 21 | if i.upper() in alphabet: 22 | translit_data += alphabet[i.upper()].lower().capitalize() if i == i.upper() else alphabet[i.upper()].lower() 23 | else: 24 | translit_data += i 25 | 26 | with open("transliteration.txt", "w", encoding="UTF-8") as file: 27 | print(translit_data, file=file) 28 | 29 | 30 | if __name__ == "__main__": 31 | main() 32 | -------------------------------------------------------------------------------- /3/3.5/7.py: -------------------------------------------------------------------------------- 1 | # Файловая статистика 2 | def main() -> None: 3 | numbers = [] 4 | with open(input(), "r") as file: 5 | for line in file: 6 | numbers.extend([int(x) for x in line.split()]) 7 | statistics = [len(numbers), len([x for x in numbers if x > 0]), min(numbers), max(numbers), sum(numbers), 8 | round(sum(numbers) / len(numbers), 2)] 9 | print(*statistics, sep="\n") 10 | 11 | 12 | if __name__ == "__main__": 13 | main() 14 | -------------------------------------------------------------------------------- /3/3.5/8.py: -------------------------------------------------------------------------------- 1 | # Файловая разница 2 | def main() -> None: 3 | input_files = [input() for _ in range(2)] 4 | output_file = input() 5 | data = [set(), set()] 6 | for i in range(2): 7 | with open(input_files[i], "r") as file: 8 | for line in file: 9 | data[i].update({x for x in line.split()}) 10 | 11 | with open(output_file, "w") as file: 12 | for word in sorted(data[0] ^ data[1]): 13 | print(word, file=file) 14 | 15 | 16 | if __name__ == "__main__": 17 | main() 18 | -------------------------------------------------------------------------------- /3/3.5/9.py: -------------------------------------------------------------------------------- 1 | # Файловая чистка 2 | def main() -> None: 3 | input_file, output_file = [input() for _ in range(2)] 4 | data = [] 5 | with open(input_file, "r") as file: 6 | for line in file: 7 | data.append(line.strip().replace("\t", "").split()) 8 | data = [x for x in data if any(x)] 9 | with open(output_file, "w") as file: 10 | for line in data: 11 | print(" ".join(line), file=file) 12 | 13 | 14 | if __name__ == "__main__": 15 | main() 16 | -------------------------------------------------------------------------------- /4/4.1/1.py: -------------------------------------------------------------------------------- 1 | # Функциональное приветствие 2 | def print_hello(name: str) -> None: 3 | print(f"Hello, {name}!") -------------------------------------------------------------------------------- /4/4.1/10.py: -------------------------------------------------------------------------------- 1 | # Слияние 2 | def merge(tuple1: tuple, tuple2: tuple) -> tuple: 3 | both = list(tuple1) + list(tuple2) 4 | for i in range(len(both)): 5 | for j in range(0, len(both) - i - 1): 6 | if both[j] > both[j + 1]: 7 | both[j], both[j + 1] = both[j + 1], both[j] 8 | return tuple(both) 9 | -------------------------------------------------------------------------------- /4/4.1/2.py: -------------------------------------------------------------------------------- 1 | # Функциональный НОД 2 | def gcd(num1: int, num2: int) -> int: 3 | while num1 != 0 and num2 != 0: 4 | num1, num2 = (num1 % num2, num2) if num1 > num2 else (num1, num2 % num1) 5 | return num1 + num2 6 | -------------------------------------------------------------------------------- /4/4.1/3.py: -------------------------------------------------------------------------------- 1 | # Длина числа 2 | def number_length(num: int) -> int: 3 | return len(str(abs(num))) 4 | -------------------------------------------------------------------------------- /4/4.1/4.py: -------------------------------------------------------------------------------- 1 | # Имя of the month 2 | def month(num: int, lang: str) -> str: 3 | MONTH = { 4 | "en": [ 5 | "January", "February", "March", 6 | "April", "May", "June", 7 | "July", "August", "September", 8 | "October", "November", "December"], 9 | "ru": [ 10 | "Январь", "Февраль", "Март", 11 | "Апрель", "Май", "Июнь", 12 | "Июль", "Август", "Сентябрь", 13 | "Октябрь", "Ноябрь", "Декабрь"]} 14 | return MONTH[lang][num - 1] 15 | -------------------------------------------------------------------------------- /4/4.1/5.py: -------------------------------------------------------------------------------- 1 | # Числовая строка 2 | def split_numbers(line: str) -> tuple: 3 | return tuple(map(int, line.split())) 4 | -------------------------------------------------------------------------------- /4/4.1/6.py: -------------------------------------------------------------------------------- 1 | # Модернизация системы вывода 2 | words = [] 3 | 4 | 5 | def modern_print(word: str) -> None: 6 | print(word) if word not in words else ... 7 | words.append(word) 8 | -------------------------------------------------------------------------------- /4/4.1/7.py: -------------------------------------------------------------------------------- 1 | # Шахматный «обед» 2 | def can_eat(knight: tuple[int, int], other: tuple[int, int]) -> bool: 3 | return abs(knight[0] - other[0]) + abs(knight[1] - other[1]) == 3 4 | -------------------------------------------------------------------------------- /4/4.1/8.py: -------------------------------------------------------------------------------- 1 | # А роза упала на лапу Азора 7.0 2 | def is_palindrome(n) -> bool: 3 | return str(n) == str(n)[::-1] if isinstance(n, int) else n == n[::-1] 4 | -------------------------------------------------------------------------------- /4/4.1/9.py: -------------------------------------------------------------------------------- 1 | # Простая задача 5.0 2 | def is_prime(num: int) -> bool: 3 | return sorted({i for d in range(2, int(num ** 0.5) + 1) if num % d == 0 for i in (d, num // d)}) == [] 4 | -------------------------------------------------------------------------------- /4/4.1/solutions.md: -------------------------------------------------------------------------------- 1 | # Функции. Области видимости. Передача параметров в функции 2 | 3 | ### Функциональное приветствие 4 | 5 | ```python 6 | def print_hello(name: str) -> None: 7 | print(f"Hello, {name}!") 8 | ``` 9 | 10 | ### Функциональный НОД 11 | 12 | ```python 13 | def gcd(num1: int, num2: int) -> int: 14 | while num1 != 0 and num2 != 0: 15 | num1, num2 = (num1 % num2, num2) if num1 > num2 else (num1, num2 % num1) 16 | return num1 + num2 17 | ``` 18 | 19 | ### Длина числа 20 | 21 | ```python 22 | def number_length(num: int) -> int: 23 | return len(str(abs(num))) 24 | ``` 25 | 26 | ### Имя of the month 27 | 28 | ```python 29 | def month(num: int, lang: str) -> str: 30 | MONTH = { 31 | "en": [ 32 | "January", "February", "March", 33 | "April", "May", "June", 34 | "July", "August", "September", 35 | "October", "November", "December"], 36 | "ru": [ 37 | "Январь", "Февраль", "Март", 38 | "Апрель", "Май", "Июнь", 39 | "Июль", "Август", "Сентябрь", 40 | "Октябрь", "Ноябрь", "Декабрь"]} 41 | return MONTH[lang][num - 1] 42 | ``` 43 | 44 | ### Числовая строка 45 | 46 | ```python 47 | def split_numbers(line: str) -> tuple: 48 | return tuple(map(int, line.split())) 49 | ``` 50 | 51 | ### Модернизация системы вывода 52 | 53 | ```python 54 | words = [] 55 | 56 | 57 | def modern_print(word: str) -> None: 58 | print(word) if word not in words else ... 59 | words.append(word) 60 | ``` 61 | 62 | ### Шахматный «обед» 63 | 64 | ```python 65 | def can_eat(knight: tuple[int, int], other: tuple[int, int]) -> bool: 66 | return abs(knight[0] - other[0]) + abs(knight[1] - other[1]) == 3 67 | ``` 68 | 69 | ### А роза упала на лапу Азора 7.0 70 | 71 | ```python 72 | def is_palindrome(n) -> bool: 73 | return str(n) == str(n)[::-1] if isinstance(n, int) else n == n[::-1] 74 | ``` 75 | 76 | ### Простая задача 5.0 77 | 78 | ```python 79 | def is_prime(num: int) -> bool: 80 | return sorted({i for d in range(2, int(num ** 0.5) + 1) if num % d == 0 for i in (d, num // d)}) == [] 81 | ``` 82 | 83 | ### Слияние 84 | 85 | ```python 86 | def merge(tuple1: tuple, tuple2: tuple) -> tuple: 87 | both = list(tuple1) + list(tuple2) 88 | for i in range(len(both)): 89 | for j in range(0, len(both) - i - 1): 90 | if both[j] > both[j + 1]: 91 | both[j], both[j + 1] = both[j + 1], both[j] 92 | return tuple(both) 93 | ``` -------------------------------------------------------------------------------- /4/4.2/1.py: -------------------------------------------------------------------------------- 1 | # Генератор списков 2 | def make_list(length: int, value: int = 0) -> list: 3 | return [value] * length 4 | -------------------------------------------------------------------------------- /4/4.2/10.py: -------------------------------------------------------------------------------- 1 | # Ключевой секрет 2 | def secret_replace(text: str, **replaces) -> str: 3 | result, replaces = "", {d: (v, 0) for d, v in replaces.items()} 4 | print(replaces) 5 | for i in text: 6 | if i in replaces: 7 | result += replaces[i][0][replaces[i][1] % len(replaces[i][0])] 8 | replaces[i] = replaces[i][0], replaces[i][1] + 1 9 | else: 10 | result += i 11 | return result 12 | -------------------------------------------------------------------------------- /4/4.2/2.py: -------------------------------------------------------------------------------- 1 | # Генератор матриц 2 | def make_matrix(size, value: int = 0) -> list: 3 | if isinstance(size, int): 4 | return [[value for i in range(size)] for j in range(size)] 5 | return [[value for i in range(size[0])] for j in range(size[1])] 6 | -------------------------------------------------------------------------------- /4/4.2/3.py: -------------------------------------------------------------------------------- 1 | # Функциональный нод 2.0 2 | def GCD(num1: int, num2: int) -> int: 3 | while num1 != 0 and num2 != 0: 4 | num1, num2 = (num1 % num2, num2) if num1 > num2 else (num1, num2 % num1) 5 | return num1 + num2 6 | 7 | 8 | def gcd(*args) -> int: 9 | args, result = list(args), 0 10 | for i in range(len(args)): 11 | result = GCD(result, args[i]) 12 | return result 13 | -------------------------------------------------------------------------------- /4/4.2/4.py: -------------------------------------------------------------------------------- 1 | # Имя of the month 2.0 2 | def month(num: int, lang: str = "ru") -> str: 3 | MONTH = { 4 | "en": [ 5 | "January", "February", "March", 6 | "April", "May", "June", 7 | "July", "August", "September", 8 | "October", "November", "December"], 9 | "ru": [ 10 | "Январь", "Февраль", "Март", 11 | "Апрель", "Май", "Июнь", 12 | "Июль", "Август", "Сентябрь", 13 | "Октябрь", "Ноябрь", "Декабрь"]} 14 | return MONTH[lang][num - 1] 15 | -------------------------------------------------------------------------------- /4/4.2/5.py: -------------------------------------------------------------------------------- 1 | # Подготовка данных 2 | def to_string(*args, sep: str = " ", end: str = "\n") -> str: 3 | return sep.join(list(map(str, list(args)))) + end 4 | -------------------------------------------------------------------------------- /4/4.2/6.py: -------------------------------------------------------------------------------- 1 | # Кофейня 2 | def order(*args) -> str: 3 | temp = in_stock 4 | COFFEE = { 5 | "Эспрессо": {"coffee": 1}, 6 | "Капучино": {"coffee": 1, "milk": 3}, 7 | "Макиато": {"coffee": 2, "milk": 1}, 8 | "Кофе по-венски": {"coffee": 1, "cream": 2}, 9 | "Латте Макиато": {"coffee": 1, "milk": 2, "cream": 1}, 10 | "Кон Панна": {"coffee": 1, "cream": 1}} 11 | 12 | for grade in args: 13 | for ingridient in COFFEE[grade]: 14 | if COFFEE[grade].get(ingridient, 0) > in_stock[ingridient]: 15 | break 16 | else: 17 | for ingridient in COFFEE[grade]: 18 | in_stock[ingridient] -= COFFEE[grade][ingridient] 19 | return grade 20 | 21 | if in_stock == temp: 22 | return "К сожалению, не можем предложить Вам напиток" 23 | -------------------------------------------------------------------------------- /4/4.2/7.py: -------------------------------------------------------------------------------- 1 | # В эфире рубрика «Эксперименты» 2 | a = tuple() 3 | 4 | 5 | def enter_results(*args) -> None: 6 | global a 7 | a += args 8 | 9 | 10 | def get_sum() -> tuple[float, float]: 11 | return round(sum(a[::2]), 2), round(sum(a[1::2]), 2) 12 | 13 | 14 | def get_average() -> tuple[float, float]: 15 | return round(get_sum()[0] / (len(a) // 2), 2), round(get_sum()[1] / (len(a) // 2), 2) 16 | -------------------------------------------------------------------------------- /4/4.2/8.py: -------------------------------------------------------------------------------- 1 | # Длинная сортировка 2 | lambda x: (len(x), x.lower()) 3 | -------------------------------------------------------------------------------- /4/4.2/9.py: -------------------------------------------------------------------------------- 1 | # Чётная фильтрация 2 | lambda x: not sum(map(int, str(x))) % 2 -------------------------------------------------------------------------------- /4/4.2/solutions.md: -------------------------------------------------------------------------------- 1 | # Позиционные и именованные аргументы. Функции высших порядков. Лямбда-функции 2 | 3 | ### Генератор списков 4 | 5 | ```python 6 | def make_list(length: int, value: int = 0) -> list: 7 | return [value] * length 8 | ``` 9 | 10 | ### Генератор матриц 11 | 12 | ```python 13 | def make_matrix(size, value: int = 0) -> list: 14 | if isinstance(size, int): 15 | return [[value for i in range(size)] for j in range(size)] 16 | return [[value for i in range(size[0])] for j in range(size[1])] 17 | ``` 18 | 19 | ### Функциональный нод 2.0 20 | 21 | ```python 22 | def GCD(num1: int, num2: int) -> int: 23 | while num1 != 0 and num2 != 0: 24 | num1, num2 = (num1 % num2, num2) if num1 > num2 else (num1, num2 % num1) 25 | return num1 + num2 26 | 27 | 28 | def gcd(*args) -> int: 29 | args, result = list(args), 0 30 | for i in range(len(args)): 31 | result = GCD(result, args[i]) 32 | return result 33 | ``` 34 | 35 | ### Имя of the month 2.0 36 | 37 | ```python 38 | def month(num: int, lang: str = "ru") -> str: 39 | MONTH = { 40 | "en": [ 41 | "January", "February", "March", 42 | "April", "May", "June", 43 | "July", "August", "September", 44 | "October", "November", "December"], 45 | "ru": [ 46 | "Январь", "Февраль", "Март", 47 | "Апрель", "Май", "Июнь", 48 | "Июль", "Август", "Сентябрь", 49 | "Октябрь", "Ноябрь", "Декабрь"]} 50 | return MONTH[lang][num - 1] 51 | ``` 52 | 53 | ### Подготовка данных 54 | 55 | ```python 56 | def to_string(*args, sep: str = " ", end: str = "\n") -> str: 57 | return sep.join(list(map(str, list(args)))) + end 58 | ``` 59 | 60 | ### Кофейня 61 | 62 | ```python 63 | def order(*args) -> str: 64 | temp = in_stock 65 | COFFEE = { 66 | "Эспрессо": {"coffee": 1}, 67 | "Капучино": {"coffee": 1, "milk": 3}, 68 | "Макиато": {"coffee": 2, "milk": 1}, 69 | "Кофе по-венски": {"coffee": 1, "cream": 2}, 70 | "Латте Макиато": {"coffee": 1, "milk": 2, "cream": 1}, 71 | "Кон Панна": {"coffee": 1, "cream": 1}} 72 | 73 | for grade in args: 74 | for ingridient in COFFEE[grade]: 75 | if COFFEE[grade].get(ingridient, 0) > in_stock[ingridient]: 76 | break 77 | else: 78 | for ingridient in COFFEE[grade]: 79 | in_stock[ingridient] -= COFFEE[grade][ingridient] 80 | return grade 81 | 82 | if in_stock == temp: 83 | return "К сожалению, не можем предложить Вам напиток" 84 | ``` 85 | 86 | ### В эфире рубрика «Эксперименты» 87 | 88 | ```python 89 | a = tuple() 90 | 91 | 92 | def enter_results(*args) -> None: 93 | global a 94 | a += args 95 | 96 | 97 | def get_sum() -> tuple[float, float]: 98 | return round(sum(a[::2]), 2), round(sum(a[1::2]), 2) 99 | 100 | 101 | def get_average() -> tuple[float, float]: 102 | return round(get_sum()[0] / (len(a) // 2), 2), round(get_sum()[1] / (len(a) // 2), 2) 103 | ``` 104 | 105 | ### Длинная сортировка 106 | 107 | ```python 108 | lambda x: (len(x), x.lower()) 109 | ``` 110 | 111 | ### Чётная фильтрация 112 | 113 | ```python 114 | lambda x: not sum(map(int, str(x))) % 2 115 | ``` 116 | 117 | ### Ключевой секрет 118 | 119 | ```python 120 | def secret_replace(text: str, **replaces) -> str: 121 | result, replaces = "", {d: (v, 0) for d, v in replaces.items()} 122 | print(replaces) 123 | for i in text: 124 | if i in replaces: 125 | result += replaces[i][0][replaces[i][1] % len(replaces[i][0])] 126 | replaces[i] = replaces[i][0], replaces[i][1] + 1 127 | else: 128 | result += i 129 | return result 130 | ``` -------------------------------------------------------------------------------- /4/4.3/1.py: -------------------------------------------------------------------------------- 1 | # Рекурсивный сумматор 2 | def recursive_sum(*args) -> int: 3 | return 0 if not args else args[0] + recursive_sum(*args[1:]) 4 | -------------------------------------------------------------------------------- /4/4.3/10.py: -------------------------------------------------------------------------------- 1 | # "Выпрямление" списка 2 | def make_linear(old: list) -> list: 3 | return [item for i in old for item in (make_linear(i) if isinstance(i, list) else [i])] 4 | -------------------------------------------------------------------------------- /4/4.3/2.py: -------------------------------------------------------------------------------- 1 | # Рекурсивный сумматор цифр 2 | def recursive_digit_sum(num: int) -> int: 3 | return num % 10 + recursive_digit_sum(num // 10) if num != 0 else 0 4 | -------------------------------------------------------------------------------- /4/4.3/3.py: -------------------------------------------------------------------------------- 1 | # Многочлен N-ой степени 2 | def make_equation(*args) -> str: 3 | if len(args) == 1: 4 | return str(args[0]) 5 | line = ") * x " + ("- " if args[-1] < 0 else "+ ") + str(args[-1]) 6 | return "(" + make_equation(*args[:-1]) + line -------------------------------------------------------------------------------- /4/4.3/4.py: -------------------------------------------------------------------------------- 1 | # Декор результата 2 | def answer(function): 3 | def decorated(*args, **kwargs) -> str: 4 | return f"Результат функции: {function(*args, **kwargs)}" 5 | 6 | return decorated 7 | -------------------------------------------------------------------------------- /4/4.3/5.py: -------------------------------------------------------------------------------- 1 | # Накопление результата 2 | def result_accumulator(func): 3 | result = [] 4 | 5 | def decorated(*args, method: str = "accumulate"): 6 | result.append(func(*args)) 7 | if method == "drop": 8 | temp = result.copy() 9 | result.clear() 10 | return temp 11 | 12 | return decorated 13 | -------------------------------------------------------------------------------- /4/4.3/6.py: -------------------------------------------------------------------------------- 1 | # Сортировка слиянием 2 | def merge(left: list, right: list) -> list: 3 | result = [] 4 | while left and right: 5 | result.append(left.pop(0) if left[0] <= right[0] else right.pop(0)) 6 | return result + left + right 7 | 8 | 9 | def merge_sort(array: list) -> list: 10 | if len(array) <= 1: 11 | return array 12 | return merge(merge_sort(array[:len(array) // 2]), merge_sort(array[len(array) // 2:])) 13 | -------------------------------------------------------------------------------- /4/4.3/7.py: -------------------------------------------------------------------------------- 1 | # Однотипность не порок 2 | def same_type(function): 3 | def decorator(*args) -> bool: 4 | if len(set([type(i) for i in args])) != 1: 5 | print("Обнаружены различные типы данных") 6 | return False 7 | return function(*args) 8 | 9 | return decorator 10 | -------------------------------------------------------------------------------- /4/4.3/8.py: -------------------------------------------------------------------------------- 1 | # Генератор Фибоначчи 2 | def fibonacci(num: int) -> int: 3 | value1, value2 = 0, 1 4 | for _ in range(num): 5 | yield value1 6 | value1, value2 = value2, value1 + value2 -------------------------------------------------------------------------------- /4/4.3/9.py: -------------------------------------------------------------------------------- 1 | # Циклический генератор 2 | def cycle(line: list): 3 | while line: 4 | for number in line: 5 | yield number -------------------------------------------------------------------------------- /4/4.3/solutions.md: -------------------------------------------------------------------------------- 1 | # Рекурсия. Декораторы. Генераторы 2 | 3 | ### Рекурсивный сумматор 4 | 5 | ```python 6 | def recursive_sum(*args) -> int: 7 | return 0 if not args else args[0] + recursive_sum(*args[1:]) 8 | ``` 9 | 10 | ### Рекурсивный сумматор цифр 11 | 12 | ```python 13 | def recursive_digit_sum(num: int) -> int: 14 | return num % 10 + recursive_digit_sum(num // 10) if num != 0 else 0 15 | ``` 16 | 17 | ### Многочлен N-ой степени 18 | 19 | ```python 20 | def make_equation(*args) -> str: 21 | if len(args) == 1: 22 | return str(args[0]) 23 | line = ") * x " + ("- " if args[-1] < 0 else "+ ") + str(args[-1]) 24 | return "(" + make_equation(*args[:-1]) + line 25 | ``` 26 | 27 | ### Декор результата 28 | 29 | ```python 30 | def answer(function): 31 | def decorated(*args, **kwargs) -> str: 32 | return f"Результат функции: {function(*args, **kwargs)}" 33 | 34 | return decorated 35 | ``` 36 | 37 | ### Накопление результата 38 | 39 | ```python 40 | def result_accumulator(func): 41 | result = [] 42 | 43 | def decorated(*args, method: str = "accumulate"): 44 | result.append(func(*args)) 45 | if method == "drop": 46 | temp = result.copy() 47 | result.clear() 48 | return temp 49 | 50 | return decorated 51 | ``` 52 | 53 | ### Сортировка слиянием 54 | 55 | ```python 56 | def merge(left: list, right: list) -> list: 57 | result = [] 58 | while left and right: 59 | result.append(left.pop(0) if left[0] <= right[0] else right.pop(0)) 60 | return result + left + right 61 | 62 | 63 | def merge_sort(array: list) -> list: 64 | if len(array) <= 1: 65 | return array 66 | return merge(merge_sort(array[:len(array) // 2]), merge_sort(array[len(array) // 2:])) 67 | ``` 68 | 69 | ### Однотипность не порок 70 | 71 | ```python 72 | def same_type(function): 73 | def decorator(*args) -> bool: 74 | if len(set([type(i) for i in args])) != 1: 75 | print("Обнаружены различные типы данных") 76 | return False 77 | return function(*args) 78 | 79 | return decorator 80 | 81 | 82 | def fibonacci(num: int) -> int: 83 | value1, value2 = 0, 1 84 | for _ in range(num): 85 | yield value1 86 | value1, value2 = value2, value1 + value2 87 | ``` 88 | 89 | # Генератор Фибоначчи 90 | 91 | ```python 92 | def fibonacci(num: int) -> int: 93 | value1, value2 = 0, 1 94 | for _ in range(num): 95 | yield value1 96 | value1, value2 = value2, value1 + value2 97 | ``` 98 | 99 | ### Циклический генератор 100 | 101 | ```python 102 | def cycle(line: list): 103 | while line: 104 | for number in line: 105 | yield number 106 | ``` 107 | 108 | ### "Выпрямление" списка 109 | 110 | ```python 111 | def make_linear(old: list) -> list: 112 | return [item for i in old for item in (make_linear(i) if isinstance(i, list) else [i])] 113 | ``` -------------------------------------------------------------------------------- /5/5.1/1.py: -------------------------------------------------------------------------------- 1 | # Классная точка 2 | class Point: 3 | def __init__(self, x: int, y: int) -> None: 4 | self.x, self.y = x, y 5 | -------------------------------------------------------------------------------- /5/5.1/10.py: -------------------------------------------------------------------------------- 1 | # Стек 2 | class Stack: 3 | stack = [] 4 | 5 | def push(self, item) -> None: 6 | self.stack.append(item) 7 | 8 | def pop(self) -> None: 9 | return self.stack.pop(-1) 10 | 11 | def is_empty(self) -> int: 12 | return not len(self.stack) 13 | -------------------------------------------------------------------------------- /5/5.1/2.py: -------------------------------------------------------------------------------- 1 | # Классная точка 2.0 2 | class Point: 3 | def __init__(self, x: int, y: int) -> None: 4 | self.x, self.y = x, y 5 | 6 | def move(self, x: int, y: int) -> None: 7 | self.x += x 8 | self.y += y 9 | 10 | def length(self, point) -> int: 11 | return round((((point.x - self.x) ** 2) + ((point.y - self.y) ** 2)) ** 0.5, 2) 12 | -------------------------------------------------------------------------------- /5/5.1/3.py: -------------------------------------------------------------------------------- 1 | # Не нажимай красную кнопку! 2 | class RedButton: 3 | def __init__(self): 4 | self.value = 0 5 | 6 | def click(self) -> None: 7 | self.value += 1 8 | print("Тревога!") 9 | 10 | def count(self) -> int: 11 | return self.value 12 | -------------------------------------------------------------------------------- /5/5.1/4.py: -------------------------------------------------------------------------------- 1 | # Работа не волк 2 | class Programmer: 3 | titles = {"Junior": 10, "Middle": 15, "Senior": 20} 4 | time = money = 0 5 | 6 | def __init__(self, name: str, position: str) -> None: 7 | self.name = name 8 | self.position = position 9 | 10 | def rise(self) -> None: 11 | if self.position == list(self.titles.keys())[-1]: 12 | self.titles[list(self.titles.keys())[-1]] += 1 13 | else: 14 | self.position = list(self.titles.keys())[list(self.titles).index(self.position) + 1] 15 | 16 | def info(self) -> str: 17 | return f"{self.name} {self.time}ч. {self.money}тгр." 18 | 19 | def work(self, time: int) -> None: 20 | self.time += time 21 | self.money += time * self.titles[self.position] 22 | -------------------------------------------------------------------------------- /5/5.1/5.py: -------------------------------------------------------------------------------- 1 | # Классный прямоугольник 2 | class Rectangle: 3 | def __init__(self, point1: tuple[float, float], point2: tuple[float, float]) -> None: 4 | self.left_top_x = min(point1[0], point2[0]) 5 | self.left_top_y = max(point1[1], point2[1]) 6 | self.right_bottom_x = max(point1[0], point2[0]) 7 | self.right_bottom_y = min(point1[1], point2[1]) 8 | self.width = round(self.right_bottom_x - self.left_top_x, 2) 9 | self.height = round(self.left_top_y - self.right_bottom_y, 2) 10 | 11 | def perimeter(self) -> float: 12 | return round(2 * (self.width + self.height), 2) 13 | 14 | def area(self) -> float: 15 | return round(self.width * self.height, 2) 16 | -------------------------------------------------------------------------------- /5/5.1/6.py: -------------------------------------------------------------------------------- 1 | # Классный прямоугольник 2.0 2 | class Rectangle: 3 | def __init__(self, point1: tuple[float, float], point2: tuple[float, float]) -> None: 4 | self.left_top_x = min(point1[0], point2[0]) 5 | self.left_top_y = max(point1[1], point2[1]) 6 | self.right_bottom_x = max(point1[0], point2[0]) 7 | self.right_bottom_y = min(point1[1], point2[1]) 8 | self.width = round(self.right_bottom_x - self.left_top_x, 2) 9 | self.height = round(self.left_top_y - self.right_bottom_y, 2) 10 | 11 | def perimeter(self) -> float: 12 | return round(2 * (self.width + self.height), 2) 13 | 14 | def area(self) -> float: 15 | return round(self.width * self.height, 2) 16 | 17 | def get_pos(self) -> tuple[float, float]: 18 | return round(self.left_top_x, 2), round(self.left_top_y, 2) 19 | 20 | def get_size(self) -> tuple[float, float]: 21 | return round(self.width, 2), round(self.height, 2) 22 | 23 | def move(self, dx: float, dy: float) -> None: 24 | self.__init__((self.left_top_x + dx, self.left_top_y + dy), 25 | (self.right_bottom_x + dx, self.right_bottom_y + dy)) 26 | 27 | def resize(self, width: float, height: float) -> None: 28 | self.__init__(self.get_pos(), (self.left_top_x + width, self.left_top_y - height)) 29 | -------------------------------------------------------------------------------- /5/5.1/7.py: -------------------------------------------------------------------------------- 1 | # Классный прямоугольник 3.0 2 | class Rectangle: 3 | def __init__(self, point1: tuple[float, float], point2: tuple[float, float]) -> None: 4 | self.left_top_x = min(point1[0], point2[0]) 5 | self.left_top_y = max(point1[1], point2[1]) 6 | self.right_bottom_x = max(point1[0], point2[0]) 7 | self.right_bottom_y = min(point1[1], point2[1]) 8 | self.width = round(self.right_bottom_x - self.left_top_x, 2) 9 | self.height = round(self.left_top_y - self.right_bottom_y, 2) 10 | 11 | def perimeter(self) -> float: 12 | return round(2 * (self.width + self.height), 2) 13 | 14 | def area(self) -> float: 15 | return round(self.width * self.height, 2) 16 | 17 | def get_pos(self) -> tuple[float, float]: 18 | return round(self.left_top_x, 2), round(self.left_top_y, 2) 19 | 20 | def get_size(self) -> tuple[float, float]: 21 | return round(self.width, 2), round(self.height, 2) 22 | 23 | def move(self, dx: float, dy: float) -> None: 24 | self.__init__((self.left_top_x + dx, self.left_top_y + dy), 25 | (self.right_bottom_x + dx, self.right_bottom_y + dy)) 26 | 27 | def resize(self, width: float, height: float) -> None: 28 | self.__init__(self.get_pos(), (self.left_top_x + width, self.left_top_y - height)) 29 | 30 | def turn(self) -> None: 31 | delta = (self.width - self.height) / 2 32 | self.__init__((self.left_top_x + delta, self.left_top_y + delta), 33 | (self.right_bottom_x - delta, self.right_bottom_y - delta)) 34 | 35 | def scale(self, factor: float) -> None: 36 | self.__init__( 37 | (self.left_top_x - self.width / 2 * (factor - 1), 38 | self.left_top_y + self.height / 2 * (factor - 1)), 39 | (self.right_bottom_x + self.width / 2 * (factor - 1), 40 | self.right_bottom_y - self.height / 2 * (factor - 1))) 41 | -------------------------------------------------------------------------------- /5/5.1/8.py: -------------------------------------------------------------------------------- 1 | # Шашки 2 | class Checkers: 3 | def __init__(self) -> None: 4 | self.field: dict[str, Cell] = {} 5 | positions = [column + row for row in "87654321" for column in "ABCDEFGH"] 6 | statuses = "XBXBXBXBBXBXBXBXXBXBXBXBXXXXXXXXXXXXXXXXWXWXWXWXXWXWXWXWWXWXWXWX" 7 | for i in range(64): 8 | self.field[positions[i]] = Cell(statuses[i]) 9 | 10 | def move(self, f, t): 11 | self.field[f], self.field[t] = self.field[t], self.field[f] 12 | 13 | def get_cell(self, position): 14 | return self.field[position] 15 | 16 | 17 | class Cell: 18 | def __init__(self, coordinates: str) -> None: 19 | self.coordinates = coordinates 20 | 21 | def status(self) -> str: 22 | return self.coordinates 23 | -------------------------------------------------------------------------------- /5/5.1/9.py: -------------------------------------------------------------------------------- 1 | # Очередь 2 | class Queue: 3 | queue = [] 4 | 5 | def push(self, item) -> None: 6 | self.queue.append(item) 7 | 8 | def pop(self) -> None: 9 | return self.queue.pop(0) 10 | 11 | def is_empty(self) -> int: 12 | return not len(self.queue) 13 | -------------------------------------------------------------------------------- /5/5.1/solutions.md: -------------------------------------------------------------------------------- 1 | # Объектная модель Python. Классы, поля и методы 2 | 3 | ### Классная точка 4 | 5 | ```python 6 | class Point: 7 | def __init__(self, x: int, y: int) -> None: 8 | self.x, self.y = x, y 9 | ``` 10 | 11 | ### Классная точка 2.0 12 | 13 | ```python 14 | class Point: 15 | def __init__(self, x: int, y: int) -> None: 16 | self.x, self.y = x, y 17 | 18 | def move(self, x: int, y: int) -> None: 19 | self.x += x 20 | self.y += y 21 | 22 | def length(self, point) -> int: 23 | return round((((point.x - self.x) ** 2) + ((point.y - self.y) ** 2)) ** 0.5, 2) 24 | ``` 25 | 26 | ### Не нажимай красную кнопку! 27 | 28 | ```python 29 | class RedButton: 30 | def __init__(self): 31 | self.value = 0 32 | 33 | def click(self) -> None: 34 | self.value += 1 35 | print("Тревога!") 36 | 37 | def count(self) -> int: 38 | return self.value 39 | ``` 40 | 41 | ### Работа не волк 42 | 43 | ```python 44 | class Programmer: 45 | titles = {"Junior": 10, "Middle": 15, "Senior": 20} 46 | time = money = 0 47 | 48 | def __init__(self, name: str, position: str) -> None: 49 | self.name = name 50 | self.position = position 51 | 52 | def rise(self) -> None: 53 | if self.position == list(self.titles.keys())[-1]: 54 | self.titles[list(self.titles.keys())[-1]] += 1 55 | else: 56 | self.position = list(self.titles.keys())[list(self.titles).index(self.position) + 1] 57 | 58 | def info(self) -> str: 59 | return f"{self.name} {self.time}ч. {self.money}тгр." 60 | 61 | def work(self, time: int) -> None: 62 | self.time += time 63 | self.money += time * self.titles[self.position] 64 | ``` 65 | 66 | ### Классный прямоугольник 67 | 68 | ```python 69 | class Rectangle: 70 | def __init__(self, point1: tuple[float, float], point2: tuple[float, float]) -> None: 71 | self.left_top_x = min(point1[0], point2[0]) 72 | self.left_top_y = max(point1[1], point2[1]) 73 | self.right_bottom_x = max(point1[0], point2[0]) 74 | self.right_bottom_y = min(point1[1], point2[1]) 75 | self.width = round(self.right_bottom_x - self.left_top_x, 2) 76 | self.height = round(self.left_top_y - self.right_bottom_y, 2) 77 | 78 | def perimeter(self) -> float: 79 | return round(2 * (self.width + self.height), 2) 80 | 81 | def area(self) -> float: 82 | return round(self.width * self.height, 2) 83 | ``` 84 | 85 | ### Классный прямоугольник 2.0 86 | 87 | ```python 88 | class Rectangle: 89 | def __init__(self, point1: tuple[float, float], point2: tuple[float, float]) -> None: 90 | self.left_top_x = min(point1[0], point2[0]) 91 | self.left_top_y = max(point1[1], point2[1]) 92 | self.right_bottom_x = max(point1[0], point2[0]) 93 | self.right_bottom_y = min(point1[1], point2[1]) 94 | self.width = round(self.right_bottom_x - self.left_top_x, 2) 95 | self.height = round(self.left_top_y - self.right_bottom_y, 2) 96 | 97 | def perimeter(self) -> float: 98 | return round(2 * (self.width + self.height), 2) 99 | 100 | def area(self) -> float: 101 | return round(self.width * self.height, 2) 102 | 103 | def get_pos(self) -> tuple[float, float]: 104 | return round(self.left_top_x, 2), round(self.left_top_y, 2) 105 | 106 | def get_size(self) -> tuple[float, float]: 107 | return round(self.width, 2), round(self.height, 2) 108 | 109 | def move(self, dx: float, dy: float) -> None: 110 | self.__init__((self.left_top_x + dx, self.left_top_y + dy), 111 | (self.right_bottom_x + dx, self.right_bottom_y + dy)) 112 | 113 | def resize(self, width: float, height: float) -> None: 114 | self.__init__(self.get_pos(), (self.left_top_x + width, self.left_top_y - height)) 115 | ``` 116 | 117 | ### Классный прямоугольник 3.0 118 | 119 | ```python 120 | class Rectangle: 121 | def __init__(self, point1: tuple[float, float], point2: tuple[float, float]) -> None: 122 | self.left_top_x = min(point1[0], point2[0]) 123 | self.left_top_y = max(point1[1], point2[1]) 124 | self.right_bottom_x = max(point1[0], point2[0]) 125 | self.right_bottom_y = min(point1[1], point2[1]) 126 | self.width = round(self.right_bottom_x - self.left_top_x, 2) 127 | self.height = round(self.left_top_y - self.right_bottom_y, 2) 128 | 129 | def perimeter(self) -> float: 130 | return round(2 * (self.width + self.height), 2) 131 | 132 | def area(self) -> float: 133 | return round(self.width * self.height, 2) 134 | 135 | def get_pos(self) -> tuple[float, float]: 136 | return round(self.left_top_x, 2), round(self.left_top_y, 2) 137 | 138 | def get_size(self) -> tuple[float, float]: 139 | return round(self.width, 2), round(self.height, 2) 140 | 141 | def move(self, dx: float, dy: float) -> None: 142 | self.__init__((self.left_top_x + dx, self.left_top_y + dy), 143 | (self.right_bottom_x + dx, self.right_bottom_y + dy)) 144 | 145 | def resize(self, width: float, height: float) -> None: 146 | self.__init__(self.get_pos(), (self.left_top_x + width, self.left_top_y - height)) 147 | 148 | def turn(self) -> None: 149 | delta = (self.width - self.height) / 2 150 | self.__init__((self.left_top_x + delta, self.left_top_y + delta), 151 | (self.right_bottom_x - delta, self.right_bottom_y - delta)) 152 | 153 | def scale(self, factor: float) -> None: 154 | self.__init__( 155 | (self.left_top_x - self.width / 2 * (factor - 1), 156 | self.left_top_y + self.height / 2 * (factor - 1)), 157 | (self.right_bottom_x + self.width / 2 * (factor - 1), 158 | self.right_bottom_y - self.height / 2 * (factor - 1))) 159 | ``` 160 | 161 | ### Шашки 162 | 163 | ```python 164 | class Checkers: 165 | def __init__(self) -> None: 166 | self.field: dict[str, Cell] = {} 167 | positions = [column + row for row in "87654321" for column in "ABCDEFGH"] 168 | statuses = "XBXBXBXBBXBXBXBXXBXBXBXBXXXXXXXXXXXXXXXXWXWXWXWXXWXWXWXWWXWXWXWX" 169 | for i in range(64): 170 | self.field[positions[i]] = Cell(statuses[i]) 171 | 172 | def move(self, f, t): 173 | self.field[f], self.field[t] = self.field[t], self.field[f] 174 | 175 | def get_cell(self, position): 176 | return self.field[position] 177 | 178 | 179 | class Cell: 180 | def __init__(self, coordinates: str) -> None: 181 | self.coordinates = coordinates 182 | 183 | def status(self) -> str: 184 | return self.coordinates 185 | ``` 186 | 187 | ### Очередь 188 | 189 | ```python 190 | class Queue: 191 | queue = [] 192 | 193 | def push(self, item) -> None: 194 | self.queue.append(item) 195 | 196 | def pop(self) -> None: 197 | return self.queue.pop(0) 198 | 199 | def is_empty(self) -> int: 200 | return not len(self.queue) 201 | ``` 202 | 203 | ### Стек 204 | 205 | ```python 206 | class Stack: 207 | stack = [] 208 | 209 | def push(self, item) -> None: 210 | self.stack.append(item) 211 | 212 | def pop(self) -> None: 213 | return self.stack.pop(-1) 214 | 215 | def is_empty(self) -> int: 216 | return not len(self.stack) 217 | ``` -------------------------------------------------------------------------------- /5/5.2/1.py: -------------------------------------------------------------------------------- 1 | # Классная точка 3.0 2 | class Point: 3 | def __init__(self, x: int, y: int) -> None: 4 | self.x, self.y = x, y 5 | 6 | def move(self, x: int, y: int) -> None: 7 | self.x += x 8 | self.y += y 9 | 10 | def length(self, point) -> int: 11 | return round((((point.x - self.x) ** 2) + ((point.y - self.y) ** 2)) ** 0.5, 2) 12 | 13 | 14 | class PatchedPoint(Point): 15 | def __init__(self, *args) -> None: 16 | if not args: 17 | self.x, self.y = 0, 0 18 | elif len(args) == 1: 19 | self.x, self.y = args[0] 20 | else: 21 | self.x, self.y = args 22 | -------------------------------------------------------------------------------- /5/5.2/10.py: -------------------------------------------------------------------------------- 1 | # Дроби v0.7 2 | class Fraction: 3 | def __try_reduce(self) -> None: 4 | numerator, denominator = self.__numerator, self.__denominator 5 | while denominator: 6 | numerator, denominator = denominator, numerator % denominator 7 | self.__numerator, self.__denominator = self.__numerator // numerator, self.__denominator // numerator 8 | 9 | def __init__(self, *args) -> None: 10 | args = (args[0], 1) if len(args) == 1 and isinstance(args[0], int) else args 11 | if isinstance(args[0], str): 12 | args = tuple(map(int, args[0].split("/"))) if "/" in args[0] else (int(args[0]), 1) 13 | self.sign = 1 if args[0] * args[1] >= 0 else -1 14 | self.__numerator, self.__denominator = map(abs, (args[0], args[1])) 15 | self.__try_reduce() 16 | 17 | def numerator(self, number: int = 0) -> int: 18 | self.__init__(self.sign * number, self.denominator()) if number else ... 19 | return abs(self.__numerator) 20 | 21 | def denominator(self, number: int = 0) -> int: 22 | self.__init__(self.sign * self.numerator(), number) if number else ... 23 | return abs(self.__denominator) 24 | 25 | def reverse(self): 26 | return Fraction(self.sign * self.denominator(), self.numerator()) 27 | 28 | def __neg__(self): 29 | return Fraction(self.sign * -self.numerator(), self.denominator()) 30 | 31 | def __add__(self, other): 32 | other = Fraction(other) if type(other) is not Fraction else other 33 | numerator = (self.sign * self.numerator() * other.denominator() + 34 | other.sign * other.numerator() * self.denominator()) 35 | denominator = self.denominator() * other.denominator() 36 | return Fraction(numerator, denominator) 37 | 38 | def __iadd__(self, other): 39 | self.__dict__ = self.__add__(other).__dict__ 40 | return self 41 | 42 | def __radd__(self, other): 43 | return self.__add__(other) 44 | 45 | def __sub__(self, other): 46 | return self.__add__(-other) 47 | 48 | def __isub__(self, other): 49 | self.__dict__ = self.__sub__(other).__dict__ 50 | return self 51 | 52 | def __rsub__(self, other): 53 | return self.__neg__().__add__(other) 54 | 55 | def __mul__(self, other): 56 | other = Fraction(other) if type(other) is not Fraction else other 57 | numerator = self.sign * self.numerator() * other.sign * other.numerator() 58 | denominator = self.denominator() * other.denominator() 59 | return Fraction(numerator, denominator) 60 | 61 | def __imul__(self, other): 62 | self.__dict__ = self.__mul__(other).__dict__ 63 | return self 64 | 65 | def __rmul__(self, other): 66 | return self.__mul__(other) 67 | 68 | def __truediv__(self, other): 69 | return self.__mul__(other.reverse()) 70 | 71 | def __itruediv__(self, other): 72 | self.__dict__ = self.__truediv__(other).__dict__ 73 | return self 74 | 75 | def __rtruediv__(self, other): 76 | return self.reverse().__mul__(other) 77 | 78 | def __eq__(self, other): 79 | return self.__sub__(other).numerator() == 0 80 | 81 | def __ne__(self, other): 82 | return not self.__eq__(other) 83 | 84 | def __lt__(self, other): 85 | return self.__sub__(other).sign == -1 86 | 87 | def __le__(self, other): 88 | return self.__lt__(other) or self.__eq__(other) 89 | 90 | def __gt__(self, other): 91 | return not self.__le__(other) 92 | 93 | def __ge__(self, other): 94 | return not self.__lt__(other) 95 | 96 | def __str__(self) -> str: 97 | return f"{self.sign * self.numerator()}/{self.denominator()}" 98 | 99 | def __repr__(self) -> str: 100 | return f"Fraction('{self.sign * self.numerator()}/{self.denominator()}')" 101 | -------------------------------------------------------------------------------- /5/5.2/2.py: -------------------------------------------------------------------------------- 1 | # Классная точка 4.0 2 | class Point: 3 | def __init__(self, x: int, y: int) -> None: 4 | self.x, self.y = x, y 5 | 6 | def move(self, x: int, y: int) -> None: 7 | self.x += x 8 | self.y += y 9 | 10 | def length(self, point) -> int: 11 | return round((((point.x - self.x) ** 2) + ((point.y - self.y) ** 2)) ** 0.5, 2) 12 | 13 | 14 | class PatchedPoint(Point): 15 | def __init__(self, *args) -> None: 16 | if not args: 17 | self.x, self.y = 0, 0 18 | elif len(args) == 1: 19 | self.x, self.y = args[0] 20 | else: 21 | self.x, self.y = args 22 | 23 | def __str__(self) -> str: 24 | return f"({self.x}, {self.y})" 25 | 26 | def __repr__(self) -> str: 27 | return f"PatchedPoint({self.x}, {self.y})" -------------------------------------------------------------------------------- /5/5.2/3.py: -------------------------------------------------------------------------------- 1 | # Классная точка 5.0 2 | class Point: 3 | def __init__(self, x: int, y: int) -> None: 4 | self.x, self.y = x, y 5 | 6 | def move(self, x: int, y: int) -> None: 7 | self.x += x 8 | self.y += y 9 | 10 | def length(self, point) -> int: 11 | return round((((point.x - self.x) ** 2) + ((point.y - self.y) ** 2)) ** 0.5, 2) 12 | 13 | 14 | class PatchedPoint(Point): 15 | def __init__(self, *args) -> None: 16 | if not args: 17 | self.x, self.y = 0, 0 18 | elif len(args) == 1: 19 | self.x, self.y = args[0] 20 | else: 21 | self.x, self.y = args 22 | 23 | def __str__(self) -> str: 24 | return f"({self.x}, {self.y})" 25 | 26 | def __repr__(self) -> str: 27 | return f"PatchedPoint({self.x}, {self.y})" 28 | 29 | def __add__(self, point: tuple[int, int]): 30 | return PatchedPoint(self.x + point[0], self.y + point[1]) 31 | 32 | def __iadd__(self, point: tuple[int, int]): 33 | self.move(point[0], point[1]) 34 | return self 35 | -------------------------------------------------------------------------------- /5/5.2/4.py: -------------------------------------------------------------------------------- 1 | # Дроби v0.1 2 | class Fraction: 3 | def __try_reduce(self) -> None: 4 | numerator, denominator = self.__numerator, self.__denominator 5 | while denominator: 6 | numerator, denominator = denominator, numerator % denominator 7 | self.__numerator, self.__denominator = self.__numerator // numerator, self.__denominator // numerator 8 | 9 | def __init__(self, *args) -> None: 10 | args = tuple(map(int, args[0].split("/"))) if isinstance(args[0], str) else args 11 | self.__numerator, self.__denominator = map(abs, (args[0], args[1])) 12 | self.__try_reduce() 13 | 14 | def numerator(self, number: int = 0) -> int: 15 | self.__init__(number, self.denominator()) if number else ... 16 | return abs(self.__numerator) 17 | 18 | def denominator(self, number: int = 0) -> int: 19 | self.__init__(self.numerator(), number) if number else ... 20 | return abs(self.__denominator) 21 | 22 | def __str__(self) -> str: 23 | return f"{self.numerator()}/{self.denominator()}" 24 | 25 | def __repr__(self) -> str: 26 | return f"Fraction({self.numerator()}, {self.denominator()})" 27 | -------------------------------------------------------------------------------- /5/5.2/5.py: -------------------------------------------------------------------------------- 1 | # Дроби v0.2 2 | class Fraction: 3 | def __try_reduce(self) -> None: 4 | numerator, denominator = self.__numerator, self.__denominator 5 | while denominator: 6 | numerator, denominator = denominator, numerator % denominator 7 | self.__numerator, self.__denominator = self.__numerator // numerator, self.__denominator // numerator 8 | 9 | def __init__(self, *args) -> None: 10 | args = tuple(map(int, args[0].split("/"))) if isinstance(args[0], str) else args 11 | self.sign = 1 if args[0] * args[1] >= 0 else -1 12 | self.__numerator, self.__denominator = map(abs, (args[0], args[1])) 13 | self.__try_reduce() 14 | 15 | def numerator(self, number: int = 0) -> int: 16 | self.__init__(self.sign * number, self.denominator()) if number else ... 17 | return abs(self.__numerator) 18 | 19 | def denominator(self, number: int = 0) -> int: 20 | self.__init__(self.sign * self.numerator(), number) if number else ... 21 | return abs(self.__denominator) 22 | 23 | def __neg__(self): 24 | return Fraction(self.sign * -self.numerator(), self.denominator()) 25 | 26 | def __str__(self) -> str: 27 | return f"{self.sign * self.numerator()}/{self.denominator()}" 28 | 29 | def __repr__(self) -> str: 30 | return f"Fraction('{self.sign * self.numerator()}/{self.denominator()}')" 31 | -------------------------------------------------------------------------------- /5/5.2/6.py: -------------------------------------------------------------------------------- 1 | # Дроби v0.3 2 | class Fraction: 3 | def __try_reduce(self) -> None: 4 | numerator, denominator = self.__numerator, self.__denominator 5 | while denominator: 6 | numerator, denominator = denominator, numerator % denominator 7 | self.__numerator, self.__denominator = self.__numerator // numerator, self.__denominator // numerator 8 | 9 | def __init__(self, *args) -> None: 10 | args = tuple(map(int, args[0].split("/"))) if isinstance(args[0], str) else args 11 | self.sign = 1 if args[0] * args[1] >= 0 else -1 12 | self.__numerator, self.__denominator = map(abs, (args[0], args[1])) 13 | self.__try_reduce() 14 | 15 | def numerator(self, number: int = 0) -> int: 16 | self.__init__(self.sign * number, self.denominator()) if number else ... 17 | return abs(self.__numerator) 18 | 19 | def denominator(self, number: int = 0) -> int: 20 | self.__init__(self.sign * self.numerator(), number) if number else ... 21 | return abs(self.__denominator) 22 | 23 | def __neg__(self): 24 | return Fraction(self.sign * -self.numerator(), self.denominator()) 25 | 26 | def __add__(self, other): 27 | numerator = (self.sign * self.numerator() * other.denominator() + 28 | other.sign * other.numerator() * self.denominator()) 29 | denominator = self.denominator() * other.denominator() 30 | return Fraction(numerator, denominator) 31 | 32 | def __iadd__(self, other): 33 | self.__dict__ = self.__add__(other).__dict__ 34 | return self 35 | 36 | def __radd__(self, other): 37 | return self.__add__(other) 38 | 39 | def __sub__(self, other): 40 | return self.__add__(-other) 41 | 42 | def __isub__(self, other): 43 | self.__dict__ = self.__sub__(other).__dict__ 44 | return self 45 | 46 | def __rsub__(self, other): 47 | return self.__neg__().__add__(other) 48 | 49 | def __str__(self) -> str: 50 | return f"{self.sign * self.numerator()}/{self.denominator()}" 51 | 52 | def __repr__(self) -> str: 53 | return f"Fraction('{self.sign * self.numerator()}/{self.denominator()}')" 54 | -------------------------------------------------------------------------------- /5/5.2/7.py: -------------------------------------------------------------------------------- 1 | # Дроби v0.4 2 | class Fraction: 3 | def __try_reduce(self) -> None: 4 | numerator, denominator = self.__numerator, self.__denominator 5 | while denominator: 6 | numerator, denominator = denominator, numerator % denominator 7 | self.__numerator, self.__denominator = self.__numerator // numerator, self.__denominator // numerator 8 | 9 | def __init__(self, *args) -> None: 10 | args = tuple(map(int, args[0].split("/"))) if isinstance(args[0], str) else args 11 | self.sign = 1 if args[0] * args[1] >= 0 else -1 12 | self.__numerator, self.__denominator = map(abs, (args[0], args[1])) 13 | self.__try_reduce() 14 | 15 | def numerator(self, number: int = 0) -> int: 16 | self.__init__(self.sign * number, self.denominator()) if number else ... 17 | return abs(self.__numerator) 18 | 19 | def denominator(self, number: int = 0) -> int: 20 | self.__init__(self.sign * self.numerator(), number) if number else ... 21 | return abs(self.__denominator) 22 | 23 | def reverse(self): 24 | return Fraction(self.sign * self.denominator(), self.numerator()) 25 | 26 | def __neg__(self): 27 | return Fraction(self.sign * -self.numerator(), self.denominator()) 28 | 29 | def __add__(self, other): 30 | numerator = (self.sign * self.numerator() * other.denominator() + 31 | other.sign * other.numerator() * self.denominator()) 32 | denominator = self.denominator() * other.denominator() 33 | return Fraction(numerator, denominator) 34 | 35 | def __iadd__(self, other): 36 | self.__dict__ = self.__add__(other).__dict__ 37 | return self 38 | 39 | def __radd__(self, other): 40 | return self.__add__(other) 41 | 42 | def __sub__(self, other): 43 | return self.__add__(-other) 44 | 45 | def __isub__(self, other): 46 | self.__dict__ = self.__sub__(other).__dict__ 47 | return self 48 | 49 | def __rsub__(self, other): 50 | return self.__neg__().__add__(other) 51 | 52 | def __mul__(self, other): 53 | numerator = self.sign * self.numerator() * other.sign * other.numerator() 54 | denominator = self.denominator() * other.denominator() 55 | return Fraction(numerator, denominator) 56 | 57 | def __imul__(self, other): 58 | self.__dict__ = self.__mul__(other).__dict__ 59 | return self 60 | 61 | def __truediv__(self, other): 62 | return self.__mul__(other.reverse()) 63 | 64 | def __itruediv__(self, other): 65 | self.__dict__ = self.__truediv__(other).__dict__ 66 | return self 67 | 68 | def __str__(self) -> str: 69 | return f"{self.sign * self.numerator()}/{self.denominator()}" 70 | 71 | def __repr__(self) -> str: 72 | return f"Fraction('{self.sign * self.numerator()}/{self.denominator()}')" 73 | -------------------------------------------------------------------------------- /5/5.2/8.py: -------------------------------------------------------------------------------- 1 | # Дроби v0.5 2 | class Fraction: 3 | def __try_reduce(self) -> None: 4 | numerator, denominator = self.__numerator, self.__denominator 5 | while denominator: 6 | numerator, denominator = denominator, numerator % denominator 7 | self.__numerator, self.__denominator = self.__numerator // numerator, self.__denominator // numerator 8 | 9 | def __init__(self, *args) -> None: 10 | args = tuple(map(int, args[0].split("/"))) if isinstance(args[0], str) else args 11 | self.sign = 1 if args[0] * args[1] >= 0 else -1 12 | self.__numerator, self.__denominator = map(abs, (args[0], args[1])) 13 | self.__try_reduce() 14 | 15 | def numerator(self, number: int = 0) -> int: 16 | self.__init__(self.sign * number, self.denominator()) if number else ... 17 | return abs(self.__numerator) 18 | 19 | def denominator(self, number: int = 0) -> int: 20 | self.__init__(self.sign * self.numerator(), number) if number else ... 21 | return abs(self.__denominator) 22 | 23 | def reverse(self): 24 | return Fraction(self.sign * self.denominator(), self.numerator()) 25 | 26 | def __neg__(self): 27 | return Fraction(self.sign * -self.numerator(), self.denominator()) 28 | 29 | def __add__(self, other): 30 | numerator = (self.sign * self.numerator() * other.denominator() + 31 | other.sign * other.numerator() * self.denominator()) 32 | denominator = self.denominator() * other.denominator() 33 | return Fraction(numerator, denominator) 34 | 35 | def __iadd__(self, other): 36 | self.__dict__ = self.__add__(other).__dict__ 37 | return self 38 | 39 | def __radd__(self, other): 40 | return self.__add__(other) 41 | 42 | def __sub__(self, other): 43 | return self.__add__(-other) 44 | 45 | def __isub__(self, other): 46 | self.__dict__ = self.__sub__(other).__dict__ 47 | return self 48 | 49 | def __rsub__(self, other): 50 | return self.__neg__().__add__(other) 51 | 52 | def __mul__(self, other): 53 | numerator = self.sign * self.numerator() * other.sign * other.numerator() 54 | denominator = self.denominator() * other.denominator() 55 | return Fraction(numerator, denominator) 56 | 57 | def __imul__(self, other): 58 | self.__dict__ = self.__mul__(other).__dict__ 59 | return self 60 | 61 | def __truediv__(self, other): 62 | return self.__mul__(other.reverse()) 63 | 64 | def __itruediv__(self, other): 65 | self.__dict__ = self.__truediv__(other).__dict__ 66 | return self 67 | 68 | def __eq__(self, other): 69 | return self.__sub__(other).numerator() == 0 70 | 71 | def __ne__(self, other): 72 | return not self.__eq__(other) 73 | 74 | def __lt__(self, other): 75 | return self.__sub__(other).sign == -1 76 | 77 | def __le__(self, other): 78 | return self.__lt__(other) or self.__eq__(other) 79 | 80 | def __gt__(self, other): 81 | return not self.__le__(other) 82 | 83 | def __ge__(self, other): 84 | return not self.__lt__(other) 85 | 86 | def __str__(self) -> str: 87 | return f"{self.sign * self.numerator()}/{self.denominator()}" 88 | 89 | def __repr__(self) -> str: 90 | return f"Fraction('{self.sign * self.numerator()}/{self.denominator()}')" 91 | -------------------------------------------------------------------------------- /5/5.2/9.py: -------------------------------------------------------------------------------- 1 | # Дроби v0.6 2 | class Fraction: 3 | def __try_reduce(self) -> None: 4 | numerator, denominator = self.__numerator, self.__denominator 5 | while denominator: 6 | numerator, denominator = denominator, numerator % denominator 7 | self.__numerator, self.__denominator = self.__numerator // numerator, self.__denominator // numerator 8 | 9 | def __init__(self, *args) -> None: 10 | args = (args[0], 1) if len(args) == 1 and isinstance(args[0], int) else args 11 | if isinstance(args[0], str): 12 | args = tuple(map(int, args[0].split("/"))) if "/" in args[0] else (int(args[0]), 1) 13 | self.sign = 1 if args[0] * args[1] >= 0 else -1 14 | self.__numerator, self.__denominator = map(abs, (args[0], args[1])) 15 | self.__try_reduce() 16 | 17 | def numerator(self, number: int = 0) -> int: 18 | self.__init__(self.sign * number, self.denominator()) if number else ... 19 | return abs(self.__numerator) 20 | 21 | def denominator(self, number: int = 0) -> int: 22 | self.__init__(self.sign * self.numerator(), number) if number else ... 23 | return abs(self.__denominator) 24 | 25 | def reverse(self): 26 | return Fraction(self.sign * self.denominator(), self.numerator()) 27 | 28 | def __neg__(self): 29 | return Fraction(self.sign * -self.numerator(), self.denominator()) 30 | 31 | def __add__(self, other): 32 | other = Fraction(other) if type(other) is not Fraction else other 33 | numerator = (self.sign * self.numerator() * other.denominator() + 34 | other.sign * other.numerator() * self.denominator()) 35 | denominator = self.denominator() * other.denominator() 36 | return Fraction(numerator, denominator) 37 | 38 | def __iadd__(self, other): 39 | self.__dict__ = self.__add__(other).__dict__ 40 | return self 41 | 42 | def __radd__(self, other): 43 | return self.__add__(other) 44 | 45 | def __sub__(self, other): 46 | return self.__add__(-other) 47 | 48 | def __isub__(self, other): 49 | self.__dict__ = self.__sub__(other).__dict__ 50 | return self 51 | 52 | def __rsub__(self, other): 53 | return self.__neg__().__add__(other) 54 | 55 | def __mul__(self, other): 56 | other = Fraction(other) if type(other) is not Fraction else other 57 | numerator = self.sign * self.numerator() * other.sign * other.numerator() 58 | denominator = self.denominator() * other.denominator() 59 | return Fraction(numerator, denominator) 60 | 61 | def __imul__(self, other): 62 | self.__dict__ = self.__mul__(other).__dict__ 63 | return self 64 | 65 | def __truediv__(self, other): 66 | return self.__mul__(other.reverse()) 67 | 68 | def __itruediv__(self, other): 69 | self.__dict__ = self.__truediv__(other).__dict__ 70 | return self 71 | 72 | def __eq__(self, other): 73 | return self.__sub__(other).numerator() == 0 74 | 75 | def __ne__(self, other): 76 | return not self.__eq__(other) 77 | 78 | def __lt__(self, other): 79 | return self.__sub__(other).sign == -1 80 | 81 | def __le__(self, other): 82 | return self.__lt__(other) or self.__eq__(other) 83 | 84 | def __gt__(self, other): 85 | return not self.__le__(other) 86 | 87 | def __ge__(self, other): 88 | return not self.__lt__(other) 89 | 90 | def __str__(self) -> str: 91 | return f"{self.sign * self.numerator()}/{self.denominator()}" 92 | 93 | def __repr__(self) -> str: 94 | return f"Fraction('{self.sign * self.numerator()}/{self.denominator()}')" 95 | -------------------------------------------------------------------------------- /5/5.3/1.py: -------------------------------------------------------------------------------- 1 | # Обработка ошибок 2 | try: 3 | func() 4 | except Exception as exception: 5 | print(type(exception).__name__) 6 | else: 7 | print("No Exceptions") -------------------------------------------------------------------------------- /5/5.3/10.py: -------------------------------------------------------------------------------- 1 | # Валидация пароля 2 | from hashlib import sha256 3 | 4 | 5 | class MinLengthError(Exception): 6 | pass 7 | 8 | 9 | class PossibleCharError(Exception): 10 | pass 11 | 12 | 13 | class NeedCharError(Exception): 14 | pass 15 | 16 | 17 | def password_validation(password: str, min_length: int = 8, 18 | possible_chars: str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", 19 | at_least_one: bool = str.isdigit): 20 | if not isinstance(password, str): 21 | raise TypeError 22 | if len(password) < min_length: 23 | raise MinLengthError 24 | if any(i not in possible_chars for i in password): 25 | raise PossibleCharError 26 | if not any(map(at_least_one, password)): 27 | raise NeedCharError 28 | return sha256(password.encode()).hexdigest() 29 | -------------------------------------------------------------------------------- /5/5.3/2.py: -------------------------------------------------------------------------------- 1 | # Ломать — не строить 2 | try: 3 | func(None, None) 4 | except ValueError: 5 | print("Ура! Ошибка!") 6 | -------------------------------------------------------------------------------- /5/5.3/3.py: -------------------------------------------------------------------------------- 1 | # Ломать — не строить 2 2 | class Error: 3 | def __repr__(self): 4 | raise ValueError 5 | 6 | 7 | try: 8 | func(Error()) 9 | except ValueError: 10 | print("Ура! Ошибка!") 11 | -------------------------------------------------------------------------------- /5/5.3/4.py: -------------------------------------------------------------------------------- 1 | # Контроль параметров 2 | def only_positive_even_sum(value1, value2) -> int: 3 | if not isinstance(value1, int) or not isinstance(value2, int): 4 | raise TypeError 5 | elif not (value1 > 0 and not value1 % 2) or not (value2 > 0 and not value2 % 2): 6 | raise ValueError 7 | return value1 + value2 8 | -------------------------------------------------------------------------------- /5/5.3/5.py: -------------------------------------------------------------------------------- 1 | # Слияние с проверкой 2 | def merge(value1, value2): 3 | if not hasattr(value1, "__iter__") or not hasattr(value2, "__iter__"): 4 | raise StopIteration 5 | if not all(isinstance(x, type(value1[0])) for x in (list(value1) + list(value2))): 6 | raise TypeError 7 | if list(value1) != sorted(value1) or list(value2) != sorted(value2): 8 | raise ValueError 9 | return tuple(sorted(list(value1) + list(value2))) 10 | -------------------------------------------------------------------------------- /5/5.3/6.py: -------------------------------------------------------------------------------- 1 | # Корень зла 2 2 | class InfiniteSolutionsError(Exception): 3 | pass 4 | 5 | 6 | class NoSolutionsError(Exception): 7 | pass 8 | 9 | 10 | def find_roots(a, b, c) -> tuple[float, float]: 11 | if sum(1 for i in (a, b, c) if isinstance(i, (int, float)) is True) != 3: 12 | raise TypeError 13 | if a == b == c == 0: 14 | raise InfiniteSolutionsError 15 | elif (a == b == 0 and c != 0) or b ** 2 < 4 * a * c: 16 | raise NoSolutionsError 17 | elif b ** 2 == 4 * a * c: 18 | return -b / (2 * a), -b / (2 * a) 19 | elif a == 0: 20 | return -c / b 21 | else: 22 | solutions = sorted([(-b - (b ** 2 - 4 * a * c) ** 0.5) / (2 * a), (-b + (b ** 2 - 4 * a * c) ** 0.5) / (2 * a)]) 23 | return solutions[0], solutions[1] 24 | -------------------------------------------------------------------------------- /5/5.3/7.py: -------------------------------------------------------------------------------- 1 | # Валидация имени 2 | class CyrillicError(Exception): 3 | pass 4 | 5 | 6 | class CapitalError(Exception): 7 | pass 8 | 9 | 10 | def name_validation(name: str) -> str: 11 | if not isinstance(name, str): 12 | raise TypeError 13 | elif sum(letter.lower() in "абвгдеёжзийклмнопрстуфхцчшщьыъэюя" for letter in name) != len(name): 14 | raise CyrillicError 15 | elif name != name.lower().capitalize(): 16 | raise CapitalError 17 | return name 18 | -------------------------------------------------------------------------------- /5/5.3/8.py: -------------------------------------------------------------------------------- 1 | # Валидация имени пользователя 2 | class BadCharacterError(Exception): 3 | pass 4 | 5 | 6 | class StartsWithDigitError(Exception): 7 | pass 8 | 9 | 10 | def username_validation(username: str) -> str: 11 | if not isinstance(username, str): 12 | raise TypeError 13 | elif sum(letter.lower() in "abcdefghijklmnopqrstuvwxyz0123456789_" for letter in username) != len(username): 14 | raise BadCharacterError 15 | elif username[0] in "0123456789": 16 | raise StartsWithDigitError 17 | return username 18 | -------------------------------------------------------------------------------- /5/5.3/9.py: -------------------------------------------------------------------------------- 1 | # Валидация пользователя 2 | class CyrillicError(Exception): 3 | pass 4 | 5 | 6 | class CapitalError(Exception): 7 | pass 8 | 9 | 10 | class BadCharacterError(Exception): 11 | pass 12 | 13 | 14 | class StartsWithDigitError(Exception): 15 | pass 16 | 17 | 18 | def name_validation(name: str) -> str: 19 | if not isinstance(name, str): 20 | raise TypeError 21 | elif sum(letter.lower() in "абвгдеёжзийклмнопрстуфхцчшщьыъэюя" for letter in name) != len(name): 22 | raise CyrillicError 23 | elif name != name.lower().capitalize(): 24 | raise CapitalError 25 | return name 26 | 27 | 28 | def username_validation(username: str) -> str: 29 | if not isinstance(username, str): 30 | raise TypeError 31 | elif sum(letter.lower() in "abcdefghijklmnopqrstuvwxyz0123456789_" for letter in username) != len(username): 32 | raise BadCharacterError 33 | elif username[0] in "0123456789": 34 | raise StartsWithDigitError 35 | return username 36 | 37 | 38 | def user_validation(**kwargs) -> dict: 39 | keys = list(map(lambda x: x in ["last_name", "first_name", "username"], kwargs.keys())) 40 | values = list(map(lambda x: isinstance(x, str), kwargs.values())) 41 | if not all(keys) or len(keys) < 3: 42 | raise KeyError 43 | elif not all(values): 44 | raise TypeError 45 | name_validation(kwargs["last_name"]) 46 | name_validation(kwargs["first_name"]) 47 | username_validation(kwargs["username"]) 48 | return kwargs 49 | -------------------------------------------------------------------------------- /5/5.3/solutions.md: -------------------------------------------------------------------------------- 1 | # Модель исключений Python. Try, except, else, finally. Модули 2 | 3 | ### Обработка ошибок 4 | 5 | ```python 6 | try: 7 | func() 8 | except Exception as exception: 9 | print(type(exception).__name__) 10 | else: 11 | print("No Exceptions") 12 | ``` 13 | 14 | ### Ломать — не строить 15 | 16 | ```python 17 | try: 18 | func(None, None) 19 | except ValueError: 20 | print("Ура! Ошибка!") 21 | ``` 22 | 23 | ### Ломать — не строить 2 24 | 25 | ```python 26 | class Error: 27 | def __repr__(self): 28 | raise ValueError 29 | 30 | 31 | try: 32 | func(Error()) 33 | except ValueError: 34 | print("Ура! Ошибка!") 35 | ``` 36 | 37 | ### Контроль параметров 38 | 39 | ```python 40 | def only_positive_even_sum(value1, value2) -> int: 41 | if not isinstance(value1, int) or not isinstance(value2, int): 42 | raise TypeError 43 | elif not (value1 > 0 and not value1 % 2) or not (value2 > 0 and not value2 % 2): 44 | raise ValueError 45 | return value1 + value2 46 | ``` 47 | 48 | ### Слияние с проверкой 49 | 50 | ```python 51 | def merge(value1, value2): 52 | if not hasattr(value1, "__iter__") or not hasattr(value2, "__iter__"): 53 | raise StopIteration 54 | if not all(isinstance(x, type(value1[0])) for x in (list(value1) + list(value2))): 55 | raise TypeError 56 | if list(value1) != sorted(value1) or list(value2) != sorted(value2): 57 | raise ValueError 58 | return tuple(sorted(list(value1) + list(value2))) 59 | ``` 60 | 61 | ### Корень зла 2 62 | 63 | ```python 64 | class InfiniteSolutionsError(Exception): 65 | pass 66 | 67 | 68 | class NoSolutionsError(Exception): 69 | pass 70 | 71 | 72 | def find_roots(a, b, c) -> tuple[float, float]: 73 | if sum(1 for i in (a, b, c) if isinstance(i, (int, float)) is True) != 3: 74 | raise TypeError 75 | if a == b == c == 0: 76 | raise InfiniteSolutionsError 77 | elif (a == b == 0 and c != 0) or b ** 2 < 4 * a * c: 78 | raise NoSolutionsError 79 | elif b ** 2 == 4 * a * c: 80 | return -b / (2 * a), -b / (2 * a) 81 | elif a == 0: 82 | return -c / b 83 | else: 84 | solutions = sorted([(-b - (b ** 2 - 4 * a * c) ** 0.5) / (2 * a), (-b + (b ** 2 - 4 * a * c) ** 0.5) / (2 * a)]) 85 | return solutions[0], solutions[1] 86 | ``` 87 | 88 | ### Валидация имени 89 | 90 | ```python 91 | class CyrillicError(Exception): 92 | pass 93 | 94 | 95 | class CapitalError(Exception): 96 | pass 97 | 98 | 99 | def name_validation(name: str) -> str: 100 | if not isinstance(name, str): 101 | raise TypeError 102 | elif sum(letter.lower() in "абвгдеёжзийклмнопрстуфхцчшщьыъэюя" for letter in name) != len(name): 103 | raise CyrillicError 104 | elif name != name.lower().capitalize(): 105 | raise CapitalError 106 | return name 107 | ``` 108 | 109 | ### Валидация имени пользователя 110 | 111 | ```python 112 | class BadCharacterError(Exception): 113 | pass 114 | 115 | 116 | class StartsWithDigitError(Exception): 117 | pass 118 | 119 | 120 | def username_validation(username: str) -> str: 121 | if not isinstance(username, str): 122 | raise TypeError 123 | elif sum(letter.lower() in "abcdefghijklmnopqrstuvwxyz0123456789_" for letter in username) != len(username): 124 | raise BadCharacterError 125 | elif username[0] in "0123456789": 126 | raise StartsWithDigitError 127 | return username 128 | ``` 129 | 130 | ### Валидация пользователя 131 | 132 | ```python 133 | class CyrillicError(Exception): 134 | pass 135 | 136 | 137 | class CapitalError(Exception): 138 | pass 139 | 140 | 141 | class BadCharacterError(Exception): 142 | pass 143 | 144 | 145 | class StartsWithDigitError(Exception): 146 | pass 147 | 148 | 149 | def name_validation(name: str) -> str: 150 | if not isinstance(name, str): 151 | raise TypeError 152 | elif sum(letter.lower() in "абвгдеёжзийклмнопрстуфхцчшщьыъэюя" for letter in name) != len(name): 153 | raise CyrillicError 154 | elif name != name.lower().capitalize(): 155 | raise CapitalError 156 | return name 157 | 158 | 159 | def username_validation(username: str) -> str: 160 | if not isinstance(username, str): 161 | raise TypeError 162 | elif sum(letter.lower() in "abcdefghijklmnopqrstuvwxyz0123456789_" for letter in username) != len(username): 163 | raise BadCharacterError 164 | elif username[0] in "0123456789": 165 | raise StartsWithDigitError 166 | return username 167 | 168 | 169 | def user_validation(**kwargs) -> dict: 170 | keys = list(map(lambda x: x in ["last_name", "first_name", "username"], kwargs.keys())) 171 | values = list(map(lambda x: isinstance(x, str), kwargs.values())) 172 | if not all(keys) or len(keys) < 3: 173 | raise KeyError 174 | elif not all(values): 175 | raise TypeError 176 | name_validation(kwargs["last_name"]) 177 | name_validation(kwargs["first_name"]) 178 | username_validation(kwargs["username"]) 179 | return kwargs 180 | ``` 181 | 182 | ### Валидация пароля 183 | 184 | ```python 185 | from hashlib import sha256 186 | 187 | 188 | class MinLengthError(Exception): 189 | pass 190 | 191 | 192 | class PossibleCharError(Exception): 193 | pass 194 | 195 | 196 | class NeedCharError(Exception): 197 | pass 198 | 199 | 200 | def password_validation(password: str, min_length: int = 8, 201 | possible_chars: str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", 202 | at_least_one: bool = str.isdigit): 203 | if not isinstance(password, str): 204 | raise TypeError 205 | if len(password) < min_length: 206 | raise MinLengthError 207 | if any(i not in possible_chars for i in password): 208 | raise PossibleCharError 209 | if not any(map(at_least_one, password)): 210 | raise NeedCharError 211 | return sha256(password.encode()).hexdigest() 212 | ``` -------------------------------------------------------------------------------- /6/6.1/1.py: -------------------------------------------------------------------------------- 1 | # Математика — круто, но это не точно 2 | from math import log, pow, sin, cos, pi, e 3 | 4 | 5 | def main() -> None: 6 | print(log(pow(x := float(input()), 3 / 16), 32) + pow(x, cos((pi * x) / (2 * e))) - pow(sin(x / pi), 2)) 7 | 8 | 9 | if __name__ == "__main__": 10 | main() 11 | -------------------------------------------------------------------------------- /6/6.1/10.py: -------------------------------------------------------------------------------- 1 | # Лесенка 2 | import numpy as np 3 | 4 | 5 | def stairs(vector: np.array) -> np.array: 6 | return np.array([np.roll(vector, i) for i in range(len(vector))]) 7 | -------------------------------------------------------------------------------- /6/6.1/2.py: -------------------------------------------------------------------------------- 1 | # Потоковый НОД 2 | from math import gcd 3 | from sys import stdin 4 | 5 | 6 | def main() -> None: 7 | print(*[gcd(*map(int, i.split())) for i in stdin], sep="\n") 8 | 9 | 10 | if __name__ == "__main__": 11 | main() 12 | -------------------------------------------------------------------------------- /6/6.1/3.py: -------------------------------------------------------------------------------- 1 | # Есть варианты? 2 | from math import comb 3 | 4 | 5 | def main() -> None: 6 | n, m = map(int, input().split()) 7 | print(comb(n, m) * m // n, comb(n, m)) 8 | 9 | 10 | if __name__ == "__main__": 11 | main() 12 | -------------------------------------------------------------------------------- /6/6.1/4.py: -------------------------------------------------------------------------------- 1 | # Среднее не арифметическое 2 | from math import pow, prod 3 | 4 | 5 | def main() -> None: 6 | numbers = list(map(float, input().split())) 7 | print(pow(prod(numbers), 1 / len(numbers))) 8 | 9 | 10 | if __name__ == "__main__": 11 | main() 12 | -------------------------------------------------------------------------------- /6/6.1/5.py: -------------------------------------------------------------------------------- 1 | # Шаг навстречу 2 | from math import dist, cos, sin 3 | 4 | 5 | def main() -> None: 6 | deca = list(map(float, input().split())) 7 | pola = list(map(float, input().split())) 8 | print(dist((deca[0], deca[1]), (pola[0] * cos(pola[1]), pola[0] * sin(pola[1])))) 9 | 10 | 11 | if __name__ == "__main__": 12 | main() 13 | -------------------------------------------------------------------------------- /6/6.1/6.py: -------------------------------------------------------------------------------- 1 | # Матрица умножения 2 | import numpy as np 3 | 4 | 5 | def multiplication_matrix(n) -> np.array: 6 | matrix = np.arange(1, n + 1) 7 | return matrix * matrix[:, None] 8 | -------------------------------------------------------------------------------- /6/6.1/7.py: -------------------------------------------------------------------------------- 1 | # Шахматная подготовка 2 | import numpy as np 3 | 4 | 5 | def make_board(number: int) -> np.array: 6 | return np.array(np.rot90(np.indices((number, number)).sum(axis=0) % 2), dtype="int8") 7 | -------------------------------------------------------------------------------- /6/6.1/8.py: -------------------------------------------------------------------------------- 1 | # Числовая змейка 3.0 2 | import numpy as np 3 | 4 | 5 | def snake(m: int, n: int, direction: str = "H") -> np.array: 6 | matrix, num = np.zeros((n, m), dtype="int16"), 1 7 | for i in range(n if direction == "H" else m): 8 | if direction == "H": 9 | matrix[i] = np.arange(num, num + m) if i % 2 == 0 else np.arange(num + m - 1, num - 1, -1) 10 | else: 11 | matrix[:, i] = np.arange(num, num + n) if i % 2 == 0 else np.arange(num + n - 1, num - 1, -1) 12 | num += m if direction == "H" else n 13 | return matrix 14 | -------------------------------------------------------------------------------- /6/6.1/9.py: -------------------------------------------------------------------------------- 1 | # Вращение 2 | import numpy as np 3 | 4 | 5 | def rotate(matrix: np.array, angle: int) -> np.array: 6 | return np.rot90(matrix, (360 - angle) // 90) 7 | -------------------------------------------------------------------------------- /6/6.1/solutions.md: -------------------------------------------------------------------------------- 1 | # Модули math и numpy 2 | 3 | ### Математика — круто, но это не точно 4 | 5 | ```python 6 | from math import log, pow, sin, cos, pi, e 7 | 8 | 9 | def main() -> None: 10 | print(log(pow(x := float(input()), 3 / 16), 32) + pow(x, cos((pi * x) / (2 * e))) - pow(sin(x / pi), 2)) 11 | 12 | 13 | if __name__ == "__main__": 14 | main() 15 | ``` 16 | 17 | ### Потоковый НОД 18 | 19 | ```python 20 | from math import gcd 21 | from sys import stdin 22 | 23 | 24 | def main() -> None: 25 | print(*[gcd(*map(int, i.split())) for i in stdin], sep="\n") 26 | 27 | 28 | if __name__ == "__main__": 29 | main() 30 | ``` 31 | 32 | ### Есть варианты? 33 | 34 | ```python 35 | from math import comb 36 | 37 | 38 | def main() -> None: 39 | n, m = map(int, input().split()) 40 | print(comb(n, m) * m // n, comb(n, m)) 41 | 42 | 43 | if __name__ == "__main__": 44 | main() 45 | ``` 46 | 47 | ### Среднее не арифметическое 48 | 49 | ```python 50 | from math import pow, prod 51 | 52 | 53 | def main() -> None: 54 | numbers = list(map(float, input().split())) 55 | print(pow(prod(numbers), 1 / len(numbers))) 56 | 57 | 58 | if __name__ == "__main__": 59 | main() 60 | ``` 61 | 62 | ### Шаг навстречу 63 | 64 | ```python 65 | from math import dist, cos, sin 66 | 67 | 68 | def main() -> None: 69 | deca = list(map(float, input().split())) 70 | pola = list(map(float, input().split())) 71 | print(dist((deca[0], deca[1]), (pola[0] * cos(pola[1]), pola[0] * sin(pola[1])))) 72 | 73 | 74 | if __name__ == "__main__": 75 | main() 76 | ``` 77 | 78 | ### Матрица умножения 79 | 80 | ```python 81 | import numpy as np 82 | 83 | 84 | def multiplication_matrix(n) -> np.array: 85 | matrix = np.arange(1, n + 1) 86 | return matrix * matrix[:, None] 87 | ``` 88 | 89 | ### Шахматная подготовка 90 | 91 | ```python 92 | import numpy as np 93 | 94 | 95 | def make_board(number: int) -> np.array: 96 | return np.array(np.rot90(np.indices((number, number)).sum(axis=0) % 2), dtype="int8") 97 | ``` 98 | 99 | ### Числовая змейка 3.0 100 | 101 | ```python 102 | import numpy as np 103 | 104 | 105 | def snake(m: int, n: int, direction: str = "H") -> np.array: 106 | matrix, num = np.zeros((n, m), dtype="int16"), 1 107 | for i in range(n if direction == "H" else m): 108 | if direction == "H": 109 | matrix[i] = np.arange(num, num + m) if i % 2 == 0 else np.arange(num + m - 1, num - 1, -1) 110 | else: 111 | matrix[:, i] = np.arange(num, num + n) if i % 2 == 0 else np.arange(num + n - 1, num - 1, -1) 112 | num += m if direction == "H" else n 113 | return matrix 114 | ``` 115 | 116 | ### Вращение 117 | 118 | ```python 119 | import numpy as np 120 | 121 | 122 | def rotate(matrix: np.array, angle: int) -> np.array: 123 | return np.rot90(matrix, (360 - angle) // 90) 124 | ``` 125 | 126 | ### Лесенка 127 | 128 | ```python 129 | import numpy as np 130 | 131 | 132 | def stairs(vector: np.array) -> np.array: 133 | return np.array([np.roll(vector, i) for i in range(len(vector))]) 134 | ``` -------------------------------------------------------------------------------- /6/6.2/1.py: -------------------------------------------------------------------------------- 1 | # Длины всех слов - 2 2 | from pandas import Series 3 | 4 | 5 | def length_stats(text: str) -> Series: 6 | text = "".join(i for i in text if i.isalpha() or i == " ") 7 | words = sorted(set(text.lower().split())) 8 | return Series([len(i) for i in words], index=words) 9 | -------------------------------------------------------------------------------- /6/6.2/10.py: -------------------------------------------------------------------------------- 1 | # Экстремум функции 2 | from numpy import arange 3 | from pandas import Series 4 | 5 | 6 | def values(func, start: float, end: float, step: float) -> Series: 7 | index = arange(start, end + step, step) 8 | return Series(map(func, index), index=index, dtype="float64") 9 | 10 | 11 | def min_extremum(data: Series) -> float: 12 | return min(data[data == min(data)].index) 13 | 14 | 15 | def max_extremum(data: Series) -> float: 16 | return max(data[data == max(data)].index) 17 | -------------------------------------------------------------------------------- /6/6.2/2.py: -------------------------------------------------------------------------------- 1 | # Длины всех слов по чётности 2 | from pandas import Series 3 | 4 | 5 | def length_stats(text: str) -> tuple[Series, Series]: 6 | text = "".join(i for i in text if i.isalpha() or i == " ") 7 | words = sorted(set(text.lower().split())) 8 | odd, even = [i for i in words if len(i) % 2], [i for i in words if not len(i) % 2] 9 | return (Series([len(i) for i in odd], index=odd, dtype="int64"), 10 | Series([len(i) for i in even], index=even, dtype="int64")) 11 | -------------------------------------------------------------------------------- /6/6.2/3.py: -------------------------------------------------------------------------------- 1 | # Чек - 2 2 | from pandas import DataFrame, Series 3 | 4 | 5 | def cheque(price_list: Series, **kwargs) -> DataFrame: 6 | products = sorted(kwargs) 7 | product_dict = { 8 | "product": products, 9 | "price": [price_list[i] for i in products], 10 | "number": [kwargs[i] for i in products]} 11 | product_dict["cost"] = [price_list[i] * product_dict["number"][index] for index, i in enumerate(products)] 12 | return DataFrame(product_dict) 13 | -------------------------------------------------------------------------------- /6/6.2/4.py: -------------------------------------------------------------------------------- 1 | # Акция 2 | from pandas import DataFrame, Series 3 | 4 | 5 | def cheque(price_list: Series, **kwargs) -> DataFrame: 6 | products = sorted(kwargs) 7 | product_dict = { 8 | "product": products, 9 | "price": [price_list[i] for i in products], 10 | "number": [kwargs[i] for i in products]} 11 | product_dict["cost"] = [price_list[i] * product_dict["number"][index] for index, i in enumerate(products)] 12 | return DataFrame(product_dict) 13 | 14 | 15 | def discount(cheque: DataFrame) -> DataFrame: 16 | new_cheque = cheque.copy() 17 | for i in range(len(new_cheque.loc[:, "cost"])): 18 | new_cheque.loc[i, "cost"] /= 1 + (cheque.loc[:, "number"][i] > 2) 19 | return new_cheque 20 | -------------------------------------------------------------------------------- /6/6.2/5.py: -------------------------------------------------------------------------------- 1 | # Длинные слова 2 | from pandas import Series 3 | 4 | 5 | def get_long(data: Series, min_length: int = 5) -> Series: 6 | return data[data >= min_length] 7 | -------------------------------------------------------------------------------- /6/6.2/6.py: -------------------------------------------------------------------------------- 1 | # Отчёт успеваемости 2 | from pandas import DataFrame 3 | 4 | 5 | def best(journal: DataFrame) -> DataFrame: 6 | new_journal = journal.copy() 7 | return new_journal[ 8 | (new_journal["maths"] > 3) & (new_journal["physics"] > 3) & (new_journal["computer science"] > 3)] 9 | -------------------------------------------------------------------------------- /6/6.2/7.py: -------------------------------------------------------------------------------- 1 | # Отчёт неуспеваемости 2 | from pandas import DataFrame 3 | 4 | 5 | def need_to_work_better(journal: DataFrame) -> DataFrame: 6 | new_journal = journal.copy() 7 | return new_journal[ 8 | (new_journal["maths"] < 3) | (new_journal["physics"] < 3) | (new_journal["computer science"] < 3)] 9 | -------------------------------------------------------------------------------- /6/6.2/8.py: -------------------------------------------------------------------------------- 1 | # Обновление журнала 2 | from pandas import DataFrame 3 | 4 | 5 | def update(journal: DataFrame) -> DataFrame: 6 | new_journal = journal.copy() 7 | for i in range(len(new_journal.loc[:, "name"])): 8 | new_journal.loc[:, "average"] = (new_journal["maths"] + new_journal["physics"] + 9 | new_journal["computer science"]) / 3 10 | return new_journal.sort_values(by=["average", "name"], ascending=(False, True)) 11 | -------------------------------------------------------------------------------- /6/6.2/9.py: -------------------------------------------------------------------------------- 1 | # Бесконечный морской бой 2 | from pandas import read_csv 3 | 4 | 5 | def main() -> None: 6 | left_top, right_bottom = list(map(int, input().split())), list(map(int, input().split())) 7 | data = read_csv("data.csv") 8 | print(data[(left_top[0] <= data["x"]) & (data["x"] <= right_bottom[0]) & (right_bottom[1] <= data["y"]) & 9 | (data["y"] <= left_top[1])]) 10 | 11 | 12 | if __name__ == "__main__": 13 | main() 14 | -------------------------------------------------------------------------------- /6/6.2/solutions.md: -------------------------------------------------------------------------------- 1 | # Модуль pandas 2 | 3 | ### Длины всех слов - 2 4 | 5 | ```python 6 | from pandas import Series 7 | 8 | 9 | def length_stats(text: str) -> Series: 10 | text = "".join(i for i in text if i.isalpha() or i == " ") 11 | words = sorted(set(text.lower().split())) 12 | return Series([len(i) for i in words], index=words) 13 | ``` 14 | 15 | ### Длины всех слов по чётности 16 | 17 | ```python 18 | from pandas import Series 19 | 20 | 21 | def length_stats(text: str) -> tuple[Series, Series]: 22 | text = "".join(i for i in text if i.isalpha() or i == " ") 23 | words = sorted(set(text.lower().split())) 24 | odd, even = [i for i in words if len(i) % 2], [i for i in words if not len(i) % 2] 25 | return (Series([len(i) for i in odd], index=odd, dtype="int64"), 26 | Series([len(i) for i in even], index=even, dtype="int64")) 27 | ``` 28 | 29 | ### Чек - 2 30 | 31 | ```python 32 | from pandas import DataFrame, Series 33 | 34 | 35 | def cheque(price_list: Series, **kwargs) -> DataFrame: 36 | products = sorted(kwargs) 37 | product_dict = { 38 | "product": products, 39 | "price": [price_list[i] for i in products], 40 | "number": [kwargs[i] for i in products]} 41 | product_dict["cost"] = [price_list[i] * product_dict["number"][index] for index, i in enumerate(products)] 42 | return DataFrame(product_dict) 43 | ``` 44 | 45 | ### Акция 46 | 47 | ```python 48 | from pandas import DataFrame, Series 49 | 50 | 51 | def cheque(price_list: Series, **kwargs) -> DataFrame: 52 | products = sorted(kwargs) 53 | product_dict = { 54 | "product": products, 55 | "price": [price_list[i] for i in products], 56 | "number": [kwargs[i] for i in products]} 57 | product_dict["cost"] = [price_list[i] * product_dict["number"][index] for index, i in enumerate(products)] 58 | return DataFrame(product_dict) 59 | 60 | 61 | def discount(cheque: DataFrame) -> DataFrame: 62 | new_cheque = cheque.copy() 63 | for i in range(len(new_cheque.loc[:, "cost"])): 64 | new_cheque.loc[i, "cost"] /= 1 + (cheque.loc[:, "number"][i] > 2) 65 | return new_cheque 66 | ``` 67 | 68 | ### Длинные слова 69 | 70 | ```python 71 | from pandas import Series 72 | 73 | 74 | def get_long(data: Series, min_length: int = 5) -> Series: 75 | return data[data >= min_length] 76 | ``` 77 | 78 | ### Отчёт успеваемости 79 | 80 | ```python 81 | from pandas import DataFrame 82 | 83 | 84 | def best(journal: DataFrame) -> DataFrame: 85 | new_journal = journal.copy() 86 | return new_journal[ 87 | (new_journal["maths"] > 3) & (new_journal["physics"] > 3) & (new_journal["computer science"] > 3)] 88 | ``` 89 | 90 | ### Отчёт неуспеваемости 91 | 92 | ```python 93 | from pandas import DataFrame 94 | 95 | 96 | def need_to_work_better(journal: DataFrame) -> DataFrame: 97 | new_journal = journal.copy() 98 | return new_journal[ 99 | (new_journal["maths"] < 3) | (new_journal["physics"] < 3) | (new_journal["computer science"] < 3)] 100 | ``` 101 | 102 | ### Обновление журнала 103 | 104 | ```python 105 | from pandas import DataFrame 106 | 107 | 108 | def update(journal: DataFrame) -> DataFrame: 109 | new_journal = journal.copy() 110 | for i in range(len(new_journal.loc[:, "name"])): 111 | new_journal.loc[:, "average"] = (new_journal["maths"] + new_journal["physics"] + 112 | new_journal["computer science"]) / 3 113 | return new_journal.sort_values(by=["average", "name"], ascending=(False, True)) 114 | ``` 115 | 116 | ### Бесконечный морской бой 117 | 118 | ```python 119 | from pandas import read_csv 120 | 121 | 122 | def main() -> None: 123 | left_top, right_bottom = list(map(int, input().split())), list(map(int, input().split())) 124 | data = read_csv("data.csv") 125 | print(data[(left_top[0] <= data["x"]) & (data["x"] <= right_bottom[0]) & (right_bottom[1] <= data["y"]) & 126 | (data["y"] <= left_top[1])]) 127 | 128 | 129 | if __name__ == "__main__": 130 | main() 131 | 132 | ``` 133 | 134 | ### Экстремум функции 135 | 136 | ```python 137 | from numpy import arange 138 | from pandas import Series 139 | 140 | 141 | def values(func, start: float, end: float, step: float) -> Series: 142 | index = arange(start, end + step, step) 143 | return Series(map(func, index), index=index, dtype="float64") 144 | 145 | 146 | def min_extremum(data: Series) -> float: 147 | return min(data[data == min(data)].index) 148 | 149 | 150 | def max_extremum(data: Series) -> float: 151 | return max(data[data == max(data)].index) 152 | ``` -------------------------------------------------------------------------------- /6/6.3/1.py: -------------------------------------------------------------------------------- 1 | # Проверка системы 2 | from requests import get 3 | 4 | 5 | def main() -> None: 6 | print(get("http://127.0.0.1:5000").text) 7 | 8 | 9 | if __name__ == "__main__": 10 | main() 11 | -------------------------------------------------------------------------------- /6/6.3/10.py: -------------------------------------------------------------------------------- 1 | # Удаление данных 2 | from requests import delete 3 | 4 | 5 | def main() -> None: 6 | delete(f"http://{input()}/users/{input()}") 7 | 8 | 9 | if __name__ == "__main__": 10 | main() 11 | -------------------------------------------------------------------------------- /6/6.3/2.py: -------------------------------------------------------------------------------- 1 | # Суммирование ответов 2 | from requests import get 3 | 4 | 5 | def main() -> None: 6 | address, result = f"http://{input()}", 0 7 | while number := int(get(address).text): 8 | result += number 9 | print(result) 10 | 11 | 12 | if __name__ == "__main__": 13 | main() 14 | -------------------------------------------------------------------------------- /6/6.3/3.py: -------------------------------------------------------------------------------- 1 | # Суммирование ответов 2 2 | from requests import get 3 | 4 | 5 | def main() -> None: 6 | print(sum(i for i in get(f"http://{input()}").json() if isinstance(i, int))) 7 | 8 | 9 | if __name__ == "__main__": 10 | main() 11 | -------------------------------------------------------------------------------- /6/6.3/4.py: -------------------------------------------------------------------------------- 1 | # Конкретное значение 2 | from requests import get 3 | 4 | 5 | def main() -> None: 6 | address, key = f"http://{input()}", input() 7 | print(get(address).json().get(key, "No data")) 8 | 9 | 10 | if __name__ == "__main__": 11 | main() 12 | -------------------------------------------------------------------------------- /6/6.3/5.py: -------------------------------------------------------------------------------- 1 | # Суммирование ответов 3 2 | from requests import get 3 | from sys import stdin 4 | 5 | 6 | def main() -> None: 7 | address, ways = f"http://{input()}", [i.strip() for i in stdin] 8 | result = 0 9 | for way in ways: 10 | result += sum(get(address + way).json()) 11 | print(result) 12 | 13 | 14 | if __name__ == "__main__": 15 | main() 16 | -------------------------------------------------------------------------------- /6/6.3/6.py: -------------------------------------------------------------------------------- 1 | # Список пользователей 2 | from requests import get 3 | 4 | 5 | def main() -> None: 6 | address = f"http://{input()}/users" 7 | names = sorted(f"{user["last_name"]} {user["first_name"]}" for user in get(address).json()) 8 | print("\n".join(names)) 9 | 10 | 11 | if __name__ == "__main__": 12 | main() 13 | -------------------------------------------------------------------------------- /6/6.3/7.py: -------------------------------------------------------------------------------- 1 | # Рассылка сообщений 2 | from requests import get 3 | from sys import stdin 4 | 5 | 6 | def main() -> None: 7 | address, text = f"http://{input()}/users/{input()}", "".join(i for i in stdin.read()) 8 | try: 9 | print(text.format(**get(address).json())) 10 | except (ValueError, KeyError): 11 | print("Пользователь не найден") 12 | 13 | 14 | if __name__ == "__main__": 15 | main() 16 | 17 | -------------------------------------------------------------------------------- /6/6.3/8.py: -------------------------------------------------------------------------------- 1 | # Регистрация нового пользователя 2 | from requests import post 3 | from json import dumps 4 | 5 | 6 | def main() -> None: 7 | address = f"http://{input()}/users" 8 | post(address, data=dumps({"username": input(), "last_name": input(), "first_name": input(), "email": input()})) 9 | 10 | 11 | if __name__ == "__main__": 12 | main() 13 | -------------------------------------------------------------------------------- /6/6.3/9.py: -------------------------------------------------------------------------------- 1 | # Изменение данных 2 | from requests import put 3 | from json import dumps 4 | from sys import stdin 5 | 6 | 7 | def main() -> None: 8 | address = f"http://{input()}/users/{input()}" 9 | put(address, data=dumps({line[0]: line[1] for line in (i.strip().split("=") for i in stdin)})) 10 | 11 | 12 | if __name__ == "__main__": 13 | main() 14 | -------------------------------------------------------------------------------- /6/6.3/solutions.md: -------------------------------------------------------------------------------- 1 | # Модуль requests 2 | 3 | ### Проверка системы 4 | 5 | ```python 6 | from requests import get 7 | 8 | 9 | def main() -> None: 10 | print(get("http://127.0.0.1:5000").text) 11 | 12 | 13 | if __name__ == "__main__": 14 | main() 15 | ``` 16 | 17 | ### Суммирование ответов 18 | 19 | ```python 20 | from requests import get 21 | 22 | 23 | def main() -> None: 24 | address, result = f"http://{input()}", 0 25 | while number := int(get(address).text): 26 | result += number 27 | print(result) 28 | 29 | 30 | if __name__ == "__main__": 31 | main() 32 | ``` 33 | 34 | ### Суммирование ответов 2 35 | 36 | ```python 37 | from requests import get 38 | 39 | 40 | def main() -> None: 41 | print(sum(i for i in get(f"http://{input()}").json() if isinstance(i, int))) 42 | 43 | 44 | if __name__ == "__main__": 45 | main() 46 | ``` 47 | 48 | ### Конкретное значение 49 | 50 | ```python 51 | from requests import get 52 | 53 | 54 | def main() -> None: 55 | address, key = f"http://{input()}", input() 56 | print(get(address).json().get(key, "No data")) 57 | 58 | 59 | if __name__ == "__main__": 60 | main() 61 | ``` 62 | 63 | ### Суммирование ответов 3 64 | 65 | ```python 66 | from requests import get 67 | from sys import stdin 68 | 69 | 70 | def main() -> None: 71 | address, ways = f"http://{input()}", [i.strip() for i in stdin] 72 | result = 0 73 | for way in ways: 74 | result += sum(get(address + way).json()) 75 | print(result) 76 | 77 | 78 | if __name__ == "__main__": 79 | main() 80 | ``` 81 | 82 | ### Список пользователей 83 | 84 | ```python 85 | from requests import get 86 | 87 | 88 | def main() -> None: 89 | address = f"http://{input()}/users" 90 | names = sorted(f"{user["last_name"]} {user["first_name"]}" for user in get(address).json()) 91 | print("\n".join(names)) 92 | 93 | 94 | if __name__ == "__main__": 95 | main() 96 | ``` 97 | 98 | ### Рассылка сообщений 99 | 100 | ```python 101 | from requests import get 102 | from sys import stdin 103 | 104 | 105 | def main() -> None: 106 | address, text = f"http://{input()}/users/{input()}", "".join(i for i in stdin.read()) 107 | try: 108 | print(text.format(**get(address).json())) 109 | except (ValueError, KeyError): 110 | print("Пользователь не найден") 111 | 112 | 113 | if __name__ == "__main__": 114 | main() 115 | ``` 116 | 117 | ### Регистрация нового пользователя 118 | 119 | ```python 120 | from requests import post 121 | from json import dumps 122 | 123 | 124 | def main() -> None: 125 | address = f"http://{input()}/users" 126 | post(address, data=dumps({"username": input(), "last_name": input(), "first_name": input(), "email": input()})) 127 | 128 | 129 | if __name__ == "__main__": 130 | main() 131 | ``` 132 | 133 | ### Изменение данных 134 | 135 | ```python 136 | from requests import put 137 | from json import dumps 138 | from sys import stdin 139 | 140 | 141 | def main() -> None: 142 | address = f"http://{input()}/users/{input()}" 143 | put(address, data=dumps({line[0]: line[1] for line in (i.strip().split("=") for i in stdin)})) 144 | 145 | 146 | if __name__ == "__main__": 147 | main() 148 | ``` 149 | 150 | ### Удаление данных 151 | 152 | ```python 153 | from requests import delete 154 | 155 | 156 | def main() -> None: 157 | delete(f"http://{input()}/users/{input()}") 158 | 159 | 160 | if __name__ == "__main__": 161 | main() 162 | ``` -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2025 MIkhail Khorokhorin 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Solutions for yandex education handbook "Основы Python" 2 | 3 | ### [2.1. Ввод и вывод данных. Операции с числами, строками. Форматирование](https://github.com/mikhailkhorokhorin/yandex-handbook-python/blob/main/2/2.1/solutions.md) 4 | ### [2.2. Условный оператор](https://github.com/mikhailkhorokhorin/yandex-handbook-python/blob/main/2/2.2/solutions.md) 5 | ### [2.3. Циклы](https://github.com/mikhailkhorokhorin/yandex-handbook-python/blob/main/2/2.3/solutions.md) 6 | ### [2.4. Вложенные циклы](https://github.com/mikhailkhorokhorin/yandex-handbook-python/blob/main/2/2.4/solutions.md) 7 | ### [3.1. Строки, кортежи, списки](https://github.com/mikhailkhorokhorin/yandex-handbook-python/blob/main/3/3.1/solutions.md) 8 | ### [3.2. Множества, словари](https://github.com/mikhailkhorokhorin/yandex-handbook-python/blob/main/3/3.2/solutions.md) 9 | ### [3.3. Списочные выражения. Модель памяти для типов языка Python](https://github.com/mikhailkhorokhorin/yandex-handbook-python/blob/main/3/3.3/solutions.md) 10 | ### [3.4. Встроенные возможности по работе с коллекциями](https://github.com/mikhailkhorokhorin/yandex-handbook-python/blob/main/3/3.4/solutions.md) 11 | ### [3.5. Потоковый ввод/вывод. Работа с текстовыми файлами. JSON](https://github.com/mikhailkhorokhorin/yandex-handbook-python/blob/main/3/3.5/solutions.md) 12 | ### [4.1. Функции. Области видимости. Передача параметров в функции](https://github.com/mikhailkhorokhorin/yandex-handbook-python/blob/main/4/4.1/solutions.md) 13 | ### [4.2. Позиционные и именованные аргументы. Функции высших порядков. Лямбда-функции](https://github.com/mikhailkhorokhorin/yandex-handbook-python/blob/main/4/4.2/solutions.md) 14 | ### [4.3. Рекурсия. Декораторы. Генераторы](https://github.com/mikhailkhorokhorin/yandex-handbook-python/blob/main/4/4.3/solutions.md) 15 | ### [5.1. Объектная модель Python. Классы, поля и методы](https://github.com/mikhailkhorokhorin/yandex-handbook-python/blob/main/5/5.1/solutions.md) 16 | ### [5.2. Волшебные методы, переопределение методов. Наследование](https://github.com/mikhailkhorokhorin/yandex-handbook-python/blob/main/5/5.2/solutions.md) 17 | ### [5.3. Модель исключений Python. Try, except, else, finally. Модули](https://github.com/mikhailkhorokhorin/yandex-handbook-python/blob/main/5/5.3/solutions.md) 18 | ### [6.1. Модули math и numpy](https://github.com/mikhailkhorokhorin/yandex-handbook-python/blob/main/6/6.1/solutions.md) 19 | ### [6.2. Модуль pandas](https://github.com/mikhailkhorokhorin/yandex-handbook-python/blob/main/6/6.2/solutions.md) 20 | ### [6.3. Модуль requests](https://github.com/mikhailkhorokhorin/yandex-handbook-python/blob/main/6/6.3/solutions.md) 21 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [project] 2 | name = "yandex-handbook-python" 3 | version = "0.1.0" 4 | description = "Solutions for yandex education handbook \"Основы Python\"" 5 | authors = [ 6 | {name = "mikhailkhorokhorin"} 7 | ] 8 | license = {text = "MIT"} 9 | readme = "README.md" 10 | requires-python = ">=3.13" 11 | dependencies = [ 12 | "numpy (>=2.2.3,<3.0.0)", 13 | "requests (>=2.32.3,<3.0.0)", 14 | "pandas (>=2.2.3,<3.0.0)", 15 | "black (>=25.1.0,<26.0.0)" 16 | ] 17 | 18 | 19 | [build-system] 20 | requires = ["poetry-core>=2.0.0,<3.0.0"] 21 | build-backend = "poetry.core.masonry.api" 22 | --------------------------------------------------------------------------------