{ "nbformat": 4, "nbformat_minor": 0, "metadata": { "colab": { "provenance": [] }, "kernelspec": { "name": "python3", "display_name": "Python 3" }, "language_info": { "name": "python" } }, "cells": [ { "cell_type": "markdown", "source": [ "# TI-253(F/R) jan 2026\n", "## 1. Python 3 Tutorial\n", "https://docs.python.org/3/tutorial/index.html\n", "## 2.1 Automate the Boring Stuff with Python\n", "https://automatetheboringstuff.com/\n", "## 2.2 Automate the Boring Stuff Workbook\n", "https://inventwithpython.com/automate3workbook/\n", "## @YouTube\n", "https://www.youtube.com/playlist?list=PL0-84-yl1fUnRuXGFe_F7qSH1LEnn9LkW\n", "## 3. Python 3 Library Reference/Documentation\n", "https://docs.python.org/3/library/index.html\n", "## 4. PyCharm\n", "https://www.jetbrains.com/pycharm/" ], "metadata": { "id": "9cSCqFjf1lcD" } }, { "cell_type": "markdown", "source": [ "## Контроль за ходом выполнения программы\n", "### if-elif-else" ], "metadata": { "id": "YeiTEdYzzV77" } }, { "cell_type": "code", "source": [ "x = int(input())\n", "if 0 == x:\n", " print('ZERO')\n", "elif x % 2:\n", " print('ODD')\n", "else:\n", " print('EVEN')\n", "\n", "string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'\n", "non_null = string1 or string2 or string3\n", "print(non_null)" ], "metadata": { "id": "xXFPPZRjzKyT" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "### match-case" ], "metadata": { "id": "ANbA4h-WzlEE" } }, { "cell_type": "code", "source": [ "status = int(input())\n", "match status:\n", " case 400:\n", " pass\n", " case 404:\n", " print(\"Not found\")\n", " case 418:\n", " print(\"I'm a teapot\")\n", " case _:\n", " print(\"Something's wrong with the internet\")" ], "metadata": { "id": "tHw87ANWzuZs" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "### Циклы for и while" ], "metadata": { "id": "87eHwxJZz4hs" } }, { "cell_type": "code", "source": [ "k = 3\n", "while True:\n", " print(\"hello\\n\")\n", " k = k - 1\n", " if k <= 0: break\n", "\n", "j = 3\n", "while j:\n", " print(\"hello\\n\")\n", " j = j - 1\n", "\n", "i = range(1, 10, 2) # создание \"ленивого\" диапазона от 1 до 9 с шагом 2\n", "for a, _ in enumerate(i): # итерирование по диапазону с выводом порядкового номера элемента\n", " print(f\"hello {a} {_}\")\n", "\n", "# числа Фибоначчи\n", "a, b = 0, 1\n", "while a < 10:\n", " print(a)\n", " a, b = b, a+b" ], "metadata": { "id": "-pIYdb7xz8-J" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "### Функции\n", "#### Structure and Interpretation of Computer Programs (JS, Python etc.)\n", "https://sourceacademy.org/sicpjs/1" ], "metadata": { "id": "QLDCC-l40Yn3" } }, { "cell_type": "code", "source": [ "def atest(i = 0, *args):\n", " print(i)\n", " if len(args):\n", " print(args[0]) # анонимные аргументы в списке\n", "\n", "def ktest(i = 0, **kwargs):\n", " print(i)\n", " for _ in kwargs.items(): # именованные аргументы в словаре\n", " print(_)\n", "\n", "# дерево рекурсии чисел Фибоначчи\n", "def fib1(n):\n", " return n if n <= 1 else fib1(n - 1) + fib1(n - 2)" ], "metadata": { "id": "bgOLgmM40auF" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "#### Линейная рекурсия и рекурсивная итерация" ], "metadata": { "id": "jgsLKfK07b_R" } }, { "cell_type": "code", "source": [ "def factorial1(n):\n", " return 1 if n == 1 else n * factorial1(n - 1)\n", "\n", "def factorial2(n): return fact_iter(1, 1, n)\n", "\n", "def fact_iter(product, counter, max_count):\n", " return product if counter > max_count else fact_iter(counter * product, counter + 1, max_count)\n", "\n", "def fib2(n): return fib_iter(1, 0, n)\n", "\n", "def fib_iter(a, b, count):\n", " return b if count == 0 else fib_iter(a + b, a, count - 1)" ], "metadata": { "id": "Z4YhnQIm7c3Y" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "#### Замыкания функций (closures) и генераторы (yield)" ], "metadata": { "id": "UTbrY-317M9U" } }, { "cell_type": "code", "source": [ "# f..g\n", "# def g(y)\n", "def f(x):\n", " def g(y):\n", " return x + y\n", "\n", " return g\n", "\n", "x = f(1)(2)\n", "\n", "def gen(x):\n", " k = 0\n", " while k <= x:\n", " yield k\n", " k += 1\n", "\n", "for i in gen(10):\n", " print(i)\n", "\n", "print(*gen(10))" ], "metadata": { "id": "CeusmQrd7Ohc" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "## Классы и объекты" ], "metadata": { "id": "DVKhUdRO0xOS" } }, { "cell_type": "code", "source": [ "class Int():\n", " __x = 0 # скрытая переменная\n", " _y = 1 # защищенная переменная\n", "\n", " def __init__(self, i=0, j=1): # конструктор\n", " self.__x = i\n", " self._y = j\n", "\n", " def __str__(self): # приведение типа к строке\n", " return f\"{self.__x} {self._y}\"\n", "\n", " def __repr__(self): # строковое представление\n", " return str(self)\n", "\n", "a = Int()\n", "b = Int(10, 20)\n", "\n", "print(str(a), a._Int__x, a._y)\n", "print(b)" ], "metadata": { "id": "kTxsNTNJ00GI" }, "execution_count": null, "outputs": [] }, { "cell_type": "code", "source": [ "import time\n", "\n", "class My:\n", " def __bool__(self): # перегрузка конструктора приведения типа My к типу bool\n", " r = int(time.time())\n", " return False if r % 2 else True\n", "\n", "def is_empty(l):\n", " if l:\n", " print(\"Full\")\n", " else:\n", " print(\"Empty\")\n", "\n", "is_empty(0)\n", "is_empty([])\n", "is_empty(\"\")\n", "is_empty(My())" ], "metadata": { "id": "Cz2j1hUi_Y0y" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "### Обработка ошибок с помощью raise и except" ], "metadata": { "id": "_ze6m6m-8J7I" } }, { "cell_type": "code", "source": [ "def divide(a, b):\n", " if b == 0: raise ZeroDivisionError\n", " if b < 0: raise EnvironmentError\n", " return a / b\n", "\n", "try:\n", " xxx = divide(1, 1)\n", "except ZeroDivisionError as e:\n", " print(f\"possible zero division: {e}\")\n", "except EnvironmentError:\n", " print(\"Error\")\n", "else:\n", " print(xxx)" ], "metadata": { "id": "Oq_RVpcO8MS8" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "### Обработка ошибок с помощью возвращаемых значений" ], "metadata": { "id": "zCa6wE8t8YK9" } }, { "cell_type": "code", "source": [ "def divide(a, b):\n", " if b == 0: return (None, \"Zero division\")\n", " if b < 0: return (None, \"Generic error\")\n", " return (a / b, None)\n", "\n", "xxx = divide(1, 0)\n", "if not xxx[0]: print(xxx[1])" ], "metadata": { "id": "E89FFhzw8Z4P" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "### Списки" ], "metadata": { "id": "kPO6sz7x9Lgn" } }, { "cell_type": "code", "source": [ "l = [] # пустой список\n", "l.append(1) # добавление элемиента в конец списка\n", "l.append('hello')\n", "\n", "m = [2, 'goodbye'] # список может содержать элементы разных типов\n", "c = l + m # перегруженный оператор сложения для конкатенации списков\n", "for i in c[:2]: # итерирование по списку до третьего элемента\n", " print(f\"{i}\")\n", "\n", "print(c[-1]) # индекс последнего элемента списка независимо от его длины\n", "print(c[len(c) - 1])\n", "\n", "for i in range(1, len(c) + 1):\n", " print(c[-i])\n", "\n", "x = l.pop() # удаление последнего элемента списка\n", "\n", "print('hello' in l) # проверка на наличие элемента в списке\n", "\n", "x = 'A' if 1 in l else 'B' # условное присваивание\n", "print(x)\n", "\n", "for _ in reversed(l): # проход списка в обратном порядке без изменения\n", " print(_)" ], "metadata": { "id": "nw_9LgiY9LKd" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "#### Диапазоны и перечисления" ], "metadata": { "id": "oxKJfenu9eTP" } }, { "cell_type": "code", "source": [ "l = list(range(0, 10)) # приведение диапазона к списку\n", "\n", "for i, j in enumerate(l):\n", " if (j % 2 == 0): l.pop(i) # удаление элементов из списка через перечисление\n", "\n", "for i in l: print(i)\n", "\n", "l = [i for i in l if x % 2 != 0] # фильтрование элементов списка без удаления\n", "\n", "for i in l: print(i)" ], "metadata": { "id": "SZPS-pZV9hUJ" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "#### Фильтрация и распаковка значений списка" ], "metadata": { "id": "EPJOpyYQ9yp3" } }, { "cell_type": "code", "source": [ "def filtr(l, p): return [i for i in l if p(i)]\n", "\n", "l = [1, 2, 3, 4, 5, 6, 7, 8, 9]\n", "l = filtr(l, lambda x: x % 2 != 0)\n", "\n", "a, b, *c = l\n", "print(c)" ], "metadata": { "id": "_Zgzssz091yB" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "#### Функции zip и sorted для \"ленивой\" обработки элементов списка" ], "metadata": { "id": "4_5J9LSV9_Nf" } }, { "cell_type": "code", "source": [ "questions = ['name', 'quest', 'favorite color']\n", "answers = ['lancelot', 'the holy grail', 'blue', 'yellow']\n", "for q, a in zip(questions, answers):\n", " print('What is your {0}? It is {1}.'.format(q, a))\n", "\n", "basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']\n", "for i in sorted(basket):\n", " print(i)\n", "\n", "print(*basket)" ], "metadata": { "id": "n8w6yGkS9_k-" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "#### Кортежи и списки\n", "Лексикографическое сравнение" ], "metadata": { "id": "9vXBsxnc-FXz" } }, { "cell_type": "code", "source": [ "(1, 2, 3) < (1, 2, 4)\n", "[1, 2, 3] < [1, 2, 4]\n", "'ABC' < 'C' < 'Pascal' < 'Python'\n", "(1, 2, 3, 4) < (1, 2, 4)\n", "(1, 2) < (1, 2, -1)\n", "(1, 2, 3) == (1.0, 2.0, 3.0)\n", "(1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4)" ], "metadata": { "id": "zxj4rs3u-KMg" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "### Множества и операции над множествами" ], "metadata": { "id": "F1FhvH2s-Psd" } }, { "cell_type": "code", "source": [ "a = set('abracadabra')\n", "b = set('alacazam')\n", "\n", "print(a - b)\n", "print(a | b)\n", "print(a & b)\n", "print(a ^ b)" ], "metadata": { "id": "gW3JD5LU-TRt" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "### Словари и операции над словарями" ], "metadata": { "id": "U6t5vKPy-esL" } }, { "cell_type": "code", "source": [ "d = {'a': 1, 'b': 2} # словарь (хэш-таблица из пар \"ключ-значение\")\n", "\n", "for k, v in d.items(): # итерирование по словарю\n", " print(v)\n", "\n", "print(d['a']) # элемент по ключу\n", "\n", "d['c'] = 3 # изменение существующего или вставка нового ключа со значением\n", "print(d['c'])" ], "metadata": { "id": "cJGIlRCd-hhe" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "Обработка текста с помощью словаря" ], "metadata": { "id": "fqvbe0zY-lE5" } }, { "cell_type": "code", "source": [ "text = '''\n", "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin suscipit mattis lorem sed facilisis. Donec iaculis sodales nisi non vestibulum. Donec molestie arcu a nulla lobortis imperdiet ac id elit. Integer finibus ut ex sed ornare. Curabitur purus elit, convallis faucibus condimentum ac, mattis a lorem. Sed ac aliquet nisi. Nam vehicula tellus turpis, vitae fermentum risus sollicitudin et. Sed ex arcu, semper in sodales a, molestie eu lectus. Proin eget semper diam. Vestibulum semper massa nec accumsan fermentum. Cras non velit vel lorem pulvinar consectetur sit amet a felis.\n", "\n", "Mauris ultrices leo eu risus egestas interdum in quis justo. Fusce convallis consectetur tincidunt. Quisque lectus nisi, eleifend in suscipit et, porta id ipsum. Etiam nec orci in libero ornare bibendum vel eu purus. Quisque vulputate ullamcorper augue vel faucibus. Sed euismod nunc quis sodales volutpat. Sed vel sem eros. Maecenas vitae condimentum neque, sed porttitor libero. Pellentesque ultrices lacus vel luctus semper. Mauris auctor arcu enim, non auctor nisl porta vel. Fusce at sapien vitae diam viverra pretium. Phasellus viverra mauris nunc, sed accumsan felis fermentum nec. Proin volutpat vel elit non posuere.\n", "Vestibulum at iaculis nisi, posuere ultrices dolor. Aliquam tortor nisl, molestie ac neque ac, pharetra tristique enim. Morbi quis nisi in urna porta rutrum quis a nisi. Aliquam at consequat nisi. Nullam lobortis dapibus ipsum ut consequat. Fusce lacinia tortor eget ipsum ultrices, a sagittis leo consequat. Donec suscipit, tortor ut placerat efficitur, nisi turpis blandit ipsum, iaculis gravida elit quam at tellus. Pellentesque quis urna id enim luctus auctor et eu nisi. Nam dui enim, euismod in ultricies id, luctus in sem. Mauris et diam id massa lacinia gravida id id urna. Nam finibus ex non est rutrum, et rhoncus ligula consectetur. Donec nec sollicitudin lacus.\n", "Ut fringilla ligula ac lectus ullamcorper posuere. Aliquam erat volutpat. Donec luctus dui a augue malesuada, vel venenatis nulla sodales. Vestibulum efficitur erat elit, non mattis leo rutrum nec. Proin non nibh lorem. Vivamus eu tincidunt dolor. Quisque eget turpis congue, volutpat augue ac, accumsan ipsum. Vestibulum sit amet euismod turpis. Aliquam eu blandit arcu, sit amet fermentum nunc. Praesent aliquet aliquet eros. Praesent feugiat euismod purus, at tincidunt quam rutrum eget. Aliquam eu ullamcorper urna, auctor lacinia lectus. Curabitur neque nisl, aliquet convallis dignissim eget, eleifend eget ante.\n", "Ut et faucibus orci. Ut sed laoreet felis, ac scelerisque sem. Nullam aliquet cursus lacinia. Mauris a est eleifend, tristique magna sit amet, vehicula nisl. Praesent pretium fringilla magna. Sed rutrum neque enim, sed elementum ipsum venenatis ut. Nullam turpis turpis, rhoncus sit amet neque eu, lobortis ultrices ipsum. Suspendisse potenti. Sed viverra urna et orci molestie pellentesque. Nulla varius neque vitae metus commodo, nec rhoncus augue sollicitudin. Quisque non consequat nisi. Quisque facilisis, velit in sollicitudin rutrum, lorem dui suscipit lacus, eget blandit nunc dolor in turpis. Integer sapien nulla, malesuada ullamcorper elit quis, facilisis mattis urna. Nunc auctor sapien augue, eget lobortis ipsum vulputate eu.\n", "'''\n", "\n", "t = text.lower()\n", " .strip(\".,-\\n\")\n", " .replace(\".\", '')\n", " .replace(\",\", '')\n", " .replace(\"\\n\", '')\n", " .split(' ') # токенизация текста\n", "\n", "d = {}\n", "\n", "for word in t: # итерирование по токенам\n", " d.setdefault(word, 0) # вставка ключа со значением по умолчанию\n", " d[word] = d[word] + 1\n", "\n", "print(d.get('lorem', 0)) # доступ к ключу с проверкой на случай, если его не существует" ], "metadata": { "id": "5bLkVoPm-n56" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "## Практические задания\n", "Вывести на экран треугольник заданной формы из заданных символов." ], "metadata": { "id": "jBbL3Cbm003p" } }, { "cell_type": "code", "source": [ "n = 5\n", "k = 1\n", "\n", "while k <= n:\n", " print((' ' * (n - k)) + ('0' * (2 * k - 1)))\n", " k += 1" ], "metadata": { "id": "FrNiT8tz7v_-" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "Write a program that accepts an integer from the user. If the integer is divisible by 3, the program should print Fizz. If the integer is divisible by 5, the program should print Buzz. If the integer is divisible by 3 and 5, the program should print Fizz Buzz. Otherwise, the program should print the number the user entered." ], "metadata": { "id": "7hh51XWs72p8" } }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "m8jno03A-mAe", "outputId": "5bd640a1-dc61-4b23-848b-aaf88f765944" }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "FizzBuzz\n" ] } ], "source": [ "def fizz_buzz1(n):\n", " out = \"\"\n", " if n % 3 == 0: out += \"Fizz\"\n", " if n % 5 == 0: out += \"Buzz\"\n", " if out == \"\": out += str(n)\n", " return out\n", "\n", "def fizz_buzz2(s : str, map : dict[int, str], p : callable) -> str:\n", " n = int(s)\n", " r = \"\"\n", " for k, v in map.items():\n", " if p(n, k): r += v\n", "\n", " return r or s\n", "\n", "print(fizz_buzz1(int(input())))\n", "print(fizz_buzz2(\"15\",\n", " {3: \"Fizz\", 5: \"Buzz\", 7: \"Buff\"},\n", " (lambda x, y: x % y == 0)))" ] }, { "cell_type": "markdown", "source": [ "Простая арифметика" ], "metadata": { "id": "loAzVbmo__7v" } }, { "cell_type": "code", "source": [ "def plus_one(a): return a + 1\n", "\n", "def add(a, b):\n", " total_sum = a\n", " for _ in range(b):\n", " total_sum = plus_one(total_sum)\n", " return total_sum\n", "\n", "def multiply(a, b):\n", " if b == 0 or a == 0: return 0\n", " c = 0\n", " for _ in range(b):\n", " c = add(c, a)\n", " return c" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "BiHUAr5eF7CH", "outputId": "ca19b5a2-61eb-4d63-e928-364cf96572bb" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "before 0\n", "after 4\n", "before 4\n", "after 8\n", "before 8\n", "after 12\n", "before 12\n", "after 16\n", "16\n" ] } ] }, { "cell_type": "markdown", "source": [ "Банковские транзакции" ], "metadata": { "id": "GQosMPfxBihY" } }, { "cell_type": "code", "source": [ "def after_transaction(balance, transaction):\n", " tmp = balance + transaction\n", " if tmp >= 0: balance = tmp\n", " return balance\n", "\n", "print(after_transaction(500, 20))\n", "print(after_transaction(300, -200))\n", "print(after_transaction(3, -1000))\n", "print(after_transaction(3, -4))\n", "print(after_transaction(3, -3))" ], "metadata": { "id": "m38AFTs_BlTc" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "Тик-так с задержкой" ], "metadata": { "id": "naDVZys_AEyV" } }, { "cell_type": "code", "source": [ "import time\n", "\n", "def tick_tock(n):\n", " for i in range(1, n + 1):\n", " print(\"tick...\" if i % 2 else \"tock...\")\n", " time.sleep(1)" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "Ycx10dn-gUqD", "outputId": "5ef65c54-7937-40b1-bd17-8ffb643630ac" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Empty\n" ] } ] }, { "cell_type": "markdown", "source": [ "Панграмма" ], "metadata": { "id": "3ow1ls9pAJ5a" } }, { "cell_type": "code", "source": [ "def f(s : str) -> bool:\n", " tmp = set()\n", " for ch in s:\n", " if ch.isalpha():\n", " tmp.add(ch.upper())\n", "\n", " return len(tmp) == 26\n", "\n", "print(f(\"The quick brown fox jumps over the yellow lazy dog.\"))" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "EGQCrZwjn4o7", "outputId": "d2fc3cf1-9400-41df-809d-407c6fc9f71c" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "False\n" ] } ] }, { "cell_type": "markdown", "source": [ "Навигатор" ], "metadata": { "id": "W30ETwPsCHvv" } }, { "cell_type": "code", "source": [ "def get_end_coordinates(directions):\n", " x, y = 0, 0\n", "\n", " for d in directions:\n", " if d == 'N': y += 1\n", " elif d == 'S': y -= 1\n", " elif d == 'E': x += 1\n", " elif d == 'W': x -= 1\n", "\n", " return x, y\n", "\n", "directions = []\n", "while(True):\n", " text = str(input())\n", " if text == \"\": break\n", " t = text.upper()\n", " if t in [\"N\", \"S\", \"W\", \"E\"]:\n", " directions.append(t)\n", "\n", "print(get_end_coordinates(directions))" ], "metadata": { "id": "crcM0v_wCJJA" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "Случайные числа" ], "metadata": { "id": "eJsonUrwCSOt" } }, { "cell_type": "code", "source": [ "def get_random_weather_data():\n", " import random\n", " t = random.uniform(-50.0, 50.0)\n", " return dict(\n", " temp=t,\n", " feels_like=random.uniform(t - 10.0, t + 10.0),\n", " humidity=random.randrange(100),\n", " pressure=random.randrange(990, 1100),\n", " )\n", "\n", "print(get_random_weather_data())\n", "\n", "def get_average_temperature(weather_data):\n", " s = 0\n", " for d in weather_data:\n", " s += d['temp']\n", " return s / len(weather_data)\n", "\n", "data = []\n", "for _ in range(100):\n", " data.append(get_random_weather_data())\n", "\n", "get_average_temperature(data)" ], "metadata": { "id": "3REmV4MRCT8l" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "Губка Боб" ], "metadata": { "id": "BM2a7OLfCfEy" } }, { "cell_type": "code", "source": [ "def spongecase(text):\n", " t = \"\"\n", " k = 0\n", " for ch in text:\n", " if not ch.isalpha():\n", " t += ch\n", " continue\n", "\n", " if k % 2:\n", " t += ch.upper()\n", " else:\n", " t += ch.lower()\n", "\n", " k += 1\n", "\n", " return t\n", "\n", "spongecase(str(input()))" ], "metadata": { "id": "7Je5yWqdCgSO" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "Секретное слово" ], "metadata": { "id": "OPxaTgncCjbV" } }, { "cell_type": "code", "source": [ "\n", "def get_word_hint(secret_word, guess_word):\n", " s = secret_word.upper()\n", " t = guess_word.upper()[:5]\n", "\n", " hint = \"\"\n", " for i, ch in enumerate(s):\n", " if ch == t[i]:\n", " hint += ('O')\n", " elif t[i] in s:\n", " hint += ('o')\n", " else:\n", " hint += ('x')\n", "\n", " return hint, hint == \"OOOOO\"\n", "\n", "words = 'MITTS FLOAT BRICK LIKED DWARF COMMA GNASH ROOMS UNITE BEARS SPOOL ARMOR'.split()\n", "\n", "import random\n", "\n", "secret = words[random.randint(0, len(words) - 1)]\n", "while True:\n", " hint, stop = get_word_hint(secret, str(input()))\n", " print(\"WIN!\" if stop else hint)\n", " if stop: break" ], "metadata": { "id": "ftBb8MqVCkvz" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "## The Zen of Python, by Tim Peters" ], "metadata": { "id": "XRm0qBbB1V4k" } }, { "cell_type": "code", "source": [ "import this" ], "metadata": { "id": "uBJm068M1Z6r" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "1. Beautiful is better than ugly.\n", "2. Explicit is better than implicit.\n", "3. Simple is better than complex.\n", "4. Complex is better than complicated.\n", "5. Flat is better than nested.\n", "6. Sparse is better than dense.\n", "7. Readability counts.\n", "8. Special cases aren't special enough to break the rules.\n", "9. Although practicality beats purity.\n", "10. Errors should never pass silently.\n", "11. Unless explicitly silenced.\n", "12. In the face of ambiguity, refuse the temptation to guess.\n", "13. There should be one-- and preferably only one --obvious way to do it.\n", "14. Although that way may not be obvious at first unless you're Dutch.\n", "16. Now is better than never.\n", "17. Although never is often better than *right* now.\n", "18. If the implementation is hard to explain, it's a bad idea.\n", "19. If the implementation is easy to explain, it may be a good idea.\n", "20. Namespaces are one honking great idea -- let's do more of those!" ], "metadata": { "id": "k2WzhFM31hWF" } } ] }