[
  {
    "path": ".gitignore",
    "content": "# Prerequisites\n*.d\n\n# Compiled Object files\n*.slo\n*.lo\n*.o\n*.obj\n\n# Precompiled Headers\n*.gch\n*.pch\n\n# Compiled Dynamic libraries\n*.so\n*.dylib\n*.dll\n\n# Fortran module files\n*.mod\n*.smod\n\n# Compiled Static libraries\n*.lai\n*.la\n*.a\n*.lib\n\n# Executables\n*.exe\n*.out\n*.app\n\n.idea\n__pycache__\n"
  },
  {
    "path": "LICENSE",
    "content": "# Публичная лицензия Creative Commons С указанием авторства-С сохранением условий версии 4.0 Международная\n\nОсуществляя Лицензируемые права (как указано ниже), Вы принимаете и соглашаетесь соблюдать условия настоящей Публичной лицензии Creative Commons С указанием авторства-С сохранением условий версии 4.0 Международная (далее - \"Публичная Лицензия\"). В том объеме, в котором настоящая Публичная Лицензия может считаться договором, Вам предоставляются Лицензируемые права в качестве встречного предоставления за принятие Вами условий такого договора. Лицензиар предоставляет Вам такие права с учетом благ, которые Лицензиар получает от предоставления доступа к Лицензируемому Материалу на указанных условиях.\n\nРаздел 1 – Определения.\n\n    Адаптированный Материал означает материал, охраняемый Авторским Правом И Другими Схожими Правами, производный от Лицензируемого Материала или основанный на Лицензируемом Материале, который содержит перевод, измененный вариант, аранжировку, преобразованный вариант или иную переработку Лицензируемого Материала, таким образом, который требует разрешения Лицензиара в соответствии с Авторским Правом И Другими Схожими Правами. Для целей настоящей Публичной Лицензии, в том случае, если Лицензируемый Материал является музыкальным произведением, исполнением или фонограммой, синхронизация такого Лицензируемого Материала с движущимся изображением всегда порождает \"Адаптированный Материал\".\n    Лицензия на Адаптированный Материал означает лицензию, которую Вы применяете в отношении Авторского Права И Других Схожих Прав на Ваш вклад в создание Адаптированного Материала в соответствии с условиями настоящей Публичной Лицензии.\n    Лицензия, Совместимая С Лицензией Creative Commons BY-SA означает лицензию, входящую в перечень лицензий, размещенный по адресу: creativecommons.org/compatiblelicenses, которая признается Creative Commons по существу эквивалентом настоящей Публичной Лицензии.\n    Авторское Право И Другие Схожие Права означают авторские и/или другие аналогичные права, тесно связанные с авторскими правами, включая, но не ограничиваясь этим, права на исполнение, сообщение передач организаций вещания, фонограмму и Права Sui Generis на Базы Данных независимо от того, каким образом права обозначаются или классифицируются. Для целей настоящей Публичной Лицензии права, указанные в подпунктах 1 и 2 пункта (b) Раздела 2 не являются Авторским Правом И Другими Схожими Правами.\n    Эффективные Технические Меры означают меры, которые при отсутствии надлежащих полномочий нельзя обойти в соответствии с законодательством, направленным на выполнение обязательств в соответствии со Статьей 11 Договора Всемирной организации интеллектуальной собственности (ВОИС) по авторскому праву, принятого 20 декабря 1996 года и/или иными подобными международными соглашениями.\n    Исключения И Ограничения означают свободное использование (fair use, fair dealing) и/или любые иные исключения из Авторского Права И Других Схожих Прав или ограничения таких прав, которые применяются в отношении Вашего использования Лицензируемого Материала.\n    Элементы Лицензии означают атрибуты лицензии, перечисленные в названии настоящей Публичной Лицензии Creative Commons. Элементами Лицензии настоящей Публичной Лицензии являются: С указанием авторства и С сохранением условий.\n    Лицензируемый Материал означает произведение искусства или литературы, базу данных или другой материал, в отношении которого Лицензиар применил настоящую Публичную Лицензию.\n    Лицензируемые Права означают права, предоставляемые Вам в соответствии с условиями настоящей Публичной Лицензии в объеме, ограниченном всеми Авторскими Правами И Другими Схожими Правами, которые применимы к Вашему использованию Лицензируемого Материала и которые Лицензиар вправе Вам предоставить.\n    Лицензиар означает физическое лицо (физические лица) или юридическое лицо (юридические лица), предоставляющее права на условиях настоящей Публичной Лицензии.\n    Предоставление означает предоставление материала неограниченному кругу лиц любыми средствами или способами, для использования которых требуется разрешение согласно Лицензируемых Прав, в том числе воспроизведение, публичный показ, публичное исполнение, распространение, сообщение или импорт, а также доведение материала до всеобщего сведения таким образом, при котором любое лицо может иметь доступ к нему из любого места и в любое время по собственному выбору.\n    Права Sui Generis на Базы Данных означают права, не являющиеся авторским правом, проистекающие из Директивы 96/9/СЕ Европейского парламента и Совета от 11 марта 1996 года о правовой охране баз данных, с учетом изменений и/или исправлений, а также и другие схожие по существу права где-либо в мире.\n    Вы означает физическое или юридическое лицо, осуществляющее Лицензируемые Права в соответствии с настоящей Публичной Лицензией. Термины \"Ваш\", \"Ваши\", \"Вам\", \"Вами\" имеют соответствующее значение.\n\nРаздел 2 – Объем лицензии.\n\n    Предоставление лицензии.\n        В соответствии с условиями настоящей Публичной Лицензии Лицензиар предоставляет Вам действующую на территории всех стран мира, безвозмездную, без права сублицензирования, неисключительную, не подлежащую отмене лицензию на осуществление Лицензируемых Прав на Лицензируемый Материал путем:\n            воспроизведения и Предоставления Лицензируемого Материала целиком или в части; а также\n            создания, воспроизведения и Предоставления Адаптированного Материала.\n        Исключения И Ограничения. Во избежание неоднозначного толкования, если Исключения и Ограничения применяются в отношении Вашего способа использования Лицензируемого материала, настоящая Публичная Лицензия не применяется, и Вы не обязаны выполнять ее условия.\n        Срок действия лицензии. Настоящая Публичная Лицензия действует в течение срока, указанного в пункте (a) Раздела 6.\n        Носители и форматы: разрешение на внесение технических изменений. Лицензиар предоставляет Вам право осуществлять Лицензируемые Права с использованием всех известных носителей и форматов, а также носителей и форматов, которые будут созданы в будущем, и вносить с этой целью любые необходимые технические изменения. Лицензиар отказывается от и/или соглашается не осуществлять какие-либо права или полномочия, позволяющие запретить внесение Вами технических изменений, необходимых для осуществления Лицензируемых Прав, включая технические изменения, необходимые для обхода Эффективных Технических Мер. Для целей настоящей Публичной Лицензии внесение изменений, разрешенных в подпункте (4) пункта (а) Раздела 2, само по себе не является созданием Адаптированного Материала.\n        Последующие получатели.\n            Оферта от Лицензиара – Лицензируемый Материал. Каждый получатель Лицензируемого Материала автоматически получает оферту от Лицензиара на осуществление Лицензируемых Прав в соответствии с условиями настоящей Публичной Лицензии.\n            Дополнительная оферта от Лицензиара – Адаптированный Материал. Каждый получатель Адаптированного Материала от Вас автоматически получает оферту от Лицензиара на осуществление Лицензируемых Прав на Адаптированный Материал в соответствии с условиями Лицензии на Адаптированный Материал, применяемой Вами.\n            Отсутствие ограничений на последующее использование. Вы не можете предлагать или устанавливать какие-либо дополнительные или иные условия, или применять Эффективные Технические Меры в отношении Лицензируемого Материала, если это ограничивает осуществление Лицензируемых Прав любым получателем Лицензируемого Материала.\n        Отсутствие одобрения. Никакое положение настоящей Публичной Лицензии не является разрешением и не может быть истолковано как разрешение утверждать или предполагать, что Вы или использование Вами Лицензируемого Материала каким-либо образом связаны с Лицензиаром, имеете финансовую поддержку, одобрение или официальный статус, предоставленные Лицензиаром или иными лицами, указанными Лицензиаром для указания авторства, как предусмотрено в подпункте (i) (А) (1) пункта (а) Раздела 3.\n\n    Иные права.\n        Личные неимущественные права, такие как право на неприкосновенность произведения, а также права на публичность и изображение гражданина, неприкосновенность частной жизни или иные аналогичные личные права не предоставляются на основе настоящей Публичной Лицензии. Тем не менее, в максимально возможной степени Лицензиар отказывается или соглашается не осуществлять любые такие права, принадлежащие ему, в объеме, необходимом, чтобы позволить Вам осуществлять Лицензируемые Права, но не иначе.\n        Патентные права и права на товарные знаки и знаки обслуживания не предоставляются по настоящей Публичной Лицензии.\n        В той мере, в которой это возможно, Лицензиар отказывается от любого права на получение от Вас вознаграждения за осуществление Вами Лицензируемых Прав, как непосредственно, так и через любые организации по коллективному управлению правами или любую добровольную, обязательную государственную или принудительную систему лицензирования. Во всех иных случаях Лицензиар сохраняет право на получение такого вознаграждения.\n\nРаздел 3 – Условия лицензии.\n\nВы можете осуществлять Лицензируемые Права исключительно при условии соблюдения следующих условий.\n\n    Указание авторства.\n\n        Если Вы Предоставляете Лицензируемый Материал (в том числе в измененном виде), Вы должны:\n            сохранить следующие сведения, если они предоставлены Лицензиаром вместе с Лицензируемым Материалом:\n                информацию об создателе (создателях) Лицензируемого Материала, а также любых других лицах, указанных Лицензиаром, обладающих правом на указание авторства, любым разумным способом, по требованию Лицензиара (в том числе с использованием псевдонима, если таковой указан);\n                уведомление об авторском праве;\n                уведомление об использовании настоящей Публичной Лицензии;\n                уведомление об отказе от гарантий;\n                Унифицированный Идентификатор Ресурса (URI) или гиперссылку на Лицензируемый Материал, в той мере, в которой это практически выполнимо;\n            указать, если Вами внесены изменения в Лицензируемый Материал, и сохранить указание на любые предыдущие изменения; а также\n            указать, что Лицензируемый Материал предоставляется на условиях настоящей Публичной Лицензии, и предоставить текст, или Унифицированный Идентификатор Ресурса (URI), или гиперссылку на настоящую Публичную Лицензию.\n        Вы можете выполнить положения подпункта (1) пункта (а) Раздела 3 любым разумным способом в зависимости от носителя, способа и контекста, посредством которых вы Предоставляете Лицензируемый Материал. Например, разумным признается выполнение данного условия путем указания Унифицированного Идентификатора Ресурса (URI) или гиперссылки на ресурс, который содержит необходимую информацию.\n        По требованию Лицензиара Вы должны, насколько это практически выполнимо, удалить любую информацию, указанную в подпункте (А) (1) пункта (а) Раздела 3.\n    С сохранением условий.\n\n    В дополнение к условиям, указанным в пункте (а) Раздела 3, если вы Предоставляете Адаптированный Материал, созданный Вами, то применяются также следующие условия.\n        В качестве Лицензии на Адаптированный Материал, которую Вы применяете, должна быть применена лицензия Creative Commons с теми же Элементами Лицензии, данной версии или более поздней версии, или Лицензия, Совместимая С Лицензией BY-SA.\n        Вы должны включить текст, Унифицированный Идентификатор Ресурса (URI) или гиперссылку на Лицензию на Адаптированный Материал, которую Вы применяете. Вы можете выполнить данное условие любым разумным способом в зависимости от носителя, способа и контекста, посредством которых Вы Предоставляете Адаптированный Материал.\n        Вы не можете предлагать или устанавливать какие-либо дополнительные или иные условия или применять Эффективные Технические Меры в отношении Адаптированного Материала, которые ограничивают осуществление прав, предоставленных в соответствии с Лицензией на Адаптированный Материал, которую Вы применяете.\n\nРаздел 4 – Права Sui Generis на Базы Данных.\n\nЕсли Лицензируемые Права включают Права Sui Generis на Базы Данных, которые применимы в отношении Вашего использования Лицензируемого Материала:\n\n    во избежание неоднозначного толкования в соответствии с подпунктом (1) пункта (а) Раздела 2 Вам предоставляются права на извлечение, повторное использование, воспроизведение и Предоставление содержимого базы данных полностью или в существенной части;\n    если Вы включаете содержимое базы данных полностью или его существенную часть в базу данных, в отношении которой у Вас имеются Права на содержимое баз данных, в этом случае база данных, в отношении которой у Вас имеются Права на содержимое баз данных (но не ее отдельные составляющие), является Адаптированным Материалом, в том числе в целях, указанных в пункте (b) Раздела 3; а также\n    Вы должны соблюдать условия, изложенные в пункте (а) Раздела 3, если Вы Предоставляете содержимое базы данных полностью или его существенную часть.\n\nВо избежание неоднозначного толкования данный Раздел 4 дополняет и не заменяет Ваши обязательства в соответствии с настоящей Публичной Лицензией, если Лицензируемые Права включают другие Авторские Права И Другие Схожие Права.\n\nРаздел 5 – Отказ от гарантий и ограничение ответственности.\n\n    Если иное отдельно не оговорено Лицензиаром, насколько это возможно, Лицензиар предлагает Лицензируемый Материал по принципу \"как есть\" и в том виде, в котором такой материал существует, и не дает никаких заверений или гарантий в отношении Лицензируемого Материала, выраженных в явном виде, предполагаемых, установленных законом или иных, включая, без ограничений, гарантии правового титула, товарной пригодности, пригодности для какой-либо определенной цели, гарантии не нарушения прав, отсутствия скрытых или других дефектов, точности, наличия или отсутствия ошибок, как известных, так и неизвестных, или как поддающихся, так и не поддающихся обнаружению. В том случае, если отказ от гарантий не разрешен полностью или частично, такой отказ может не применяться в отношении Вас.\n    В той мере, в которой это возможно, Лицензиар не несет перед Вами никакой ответственности на основании любой правовой доктрины (в том числе, но не ограничиваясь, в результате неосторожности), за какие-либо прямые, особые, непрямые, случайные, косвенные или иные убытки и штрафные выплаты, издержки, затраты или ущерб, возникшие в результате применения настоящей Публичной Лицензии или использования Лицензируемого Материала, даже если Лицензиар был уведомлен о возможности возникновения таких затрат, издержек или убытков. В том случае если ограничение ответственности полностью или частично не допускается, настоящее ограничение может не применяться в отношении Вас.\n\n    Отказ от гарантий и ограничение ответственности, изложенные выше, должны толковаться таким образом, чтобы в максимально допустимой степени соответствовать абсолютному отказу от гарантий и отказу от какой-либо ответственности.\n\nРаздел 6 – Срок действия и прекращение действия.\n\n    Настоящая Публичная Лицензия действует в течение срока действия Авторского Права И Других Схожих Прав, предоставляемых в соответствии с настоящей Публичной Лицензией. При этом если Вы не соблюдаете какое-либо условие настоящей Публичной Лицензии, действие Ваших прав в соответствии с настоящей Публичной Лицензией автоматически прекращается.\n\n    Если Ваше право на использование Лицензируемого Материала прекратилось в соответствии с пунктом (а) Раздела 6, оно считается восстановленным:\n        автоматически в момент устранения Вами нарушения, если такое нарушение устранено в течение 30 дней с момента его обнаружения; или\n        в случае четко выраженного решения Лицензиара о восстановлении права.\n    Во избежание неоднозначного толкования пункт (b) Раздела 6 не затрагивает каких-либо прав Лицензиара на поиск средств правовой защиты от допущенных Вами нарушений условий настоящей Публичной Лицензии.\n    Во избежание неоднозначного толкования Лицензиар может также предлагать Лицензируемый Материал на иных лицензионных условиях или остановить распространение Лицензируемого Материала в любое время; однако, это не прекращает действия Публичной Лицензии.\n    Разделы 1, 5, 6, 7 и 8 продолжают действовать после прекращения действия настоящей Публичной Лицензии.\n\nРаздел 7 – Прочие условия.\n\n    Лицензиар не должен быть связан никакими дополнительными или иными условиями, сообщенными Вами, без его согласия, выраженного в явном виде.\n    Любые дополнительные договоренности или понимания, касающиеся Лицензируемого Материала, которые не указаны в настоящей Публичной Лицензии, являются отдельными и независимыми от условий настоящей Публичной Лицензии.\n\nРаздел 8 – Толкование.\n\n    Во избежание неоднозначного толкования настоящая Публичная Лицензия не может и не должна толковаться как сокращение, ограничение или наложение условий в отношении любого использования Лицензируемого Материала, которое может быть осуществлено на законных основаниях без разрешения, предоставляемого в соответствии с настоящей Публичной Лицензией.\n    Если какое-либо положение настоящей Публичной Лицензии считается не имеющим законной силы, оно должно быть, насколько это возможно, автоматически исправлено в минимально необходимой степени для наделения такого положения законной силой. Если такое положение невозможно исправить, оно должно быть исключено из текста настоящей Публичной Лицензии без ущерба для законной силы остальных положений лицензии.\n    Никакое условие или положение настоящей Публичной Лицензии не будет считаться отмененным, а нарушение - согласованным, если Лицензиар в явной форме не выразит свое согласие с такой отменой или нарушением.\n    Никакое условие или положение настоящей Публичной Лицензии не является и не может быть истолковано как ограничение или отказ от каких-либо привилегий и иммунитетов, применимых в отношении Лицензиара и/или в отношении Вас, включая отказ от судебных процессов в какой-либо юрисдикции или какой-либо подведомственности.\n"
  },
  {
    "path": "README.md",
    "content": "# Алгоритмы и структуры данных (С++), 2020 г.\n\nПрограммный код с лекций по информатике Хирьянова Т.Ф.\nна ФТШ ЛФИ МФТИ (ФОПФ) в 2020 году.\n\nЛицензия на материалы курса: ![Attribution ShareAlike CC BY-SA 4.0](https://licensebuttons.net/l/by-sa/4.0/88x31.png)\n\nСайт курса: http://cs.mipt.ru/cpp_algo\n\n## Рабочая программа дисциплины \"Информатика\":\n\nпо дисциплине: Информатика\nпо направлению: 03.03.01 «Прикладные математика и физика»\nфизтех-школа:\tЛФИ\nкафедра:\tинформатики и вычислительной математики\nкурс:\t1\nсеместр:\t2\n\nТрудоёмкость:\n- лекции – 30 часов\n- лабораторные занятия – 60 часов\n- самостоятельная работа – 90 часов\n\nВСЕГО АУДИТОРНЫХ ЧАСОВ – 90\n\nПрограмму и задание составил:\tст. преп. Т.Ф. Хирьянов\n\n### Тематический план семестра\n\n1. Ввод-вывод, ветвления и циклы. Однопроходные алгоритмы. Структура простой программы. Переменные С++: необходимость объявления, строгость типизации, присваивание. Ввод-вывод в std:: потоки cin, cout, cerr. Арифметические операции +, -, \\*, /. Операторы сравнения <, <=, ==, !=. Описание простых функций. Cинхронный вызов и возврат по стеку вызовов. Метки и goto. Доводы против оператора goto Эдсгера Дейкстры. Оператор for. Генерация арифметической и геометрической прогрессий. Оператор if. Фильтрация потока чисел. Оператор while. Алгоритм Евклида на С++. Вложенные и каскадные условные конструкции. Обработка последовательностей: подсчёт, сумма, произведение, поиск максимального. Инициализация переменной при поиске максимума и минимума.\n2. Целый и логический типы. Алгоритмы полного перебора. Двоичное представление данных. Двоичное кодирование. Двоичная СС и кольца вычетов. Знаковые целые: дополнительный код. Целочисленные типы С++11: intN_t. Явное приведение типа. Битовые операции с целыми: сдвиги, наложение маски. Обмен переменных значениями: универсальный и через XOR. Остаток при делении нацело: %. Разложение числа на цифры. Логический тип bool. Операции !, &&, ||, ^ и , not, and, or, xor. Индуктивные функции: поиск числа, проверка критерия. Алгоритмы полного перебора. Тест простоты числа с использованием переменной-флага. Разложение числа на множители. Управление циклом: break, continue. Определение типа struct. Функция sizeof().\n3. Плавающая точка. Математические методы. Представление вещественных чисел в памяти ПК. Cтандарт IEEE 754-2008. Типы чисел с плавающей точкой в С++ и их соответствие стандарту. Арифметика чисел с плавающей запятой (точкой). Ошибки вычислений. Машинная точность. Иерархия типов чисел в С++. Неявное приведение типа. «Грабли»: приоритет беззнаковых, деление целых. Список всех операций С++ с приоритетами. Модуль cmath. Математические функции С++: выражение аналитических функций. Суммирования ряда Тейлора. Численное интегрирование. Бисекция. Поиск корня уравнения методом двоичного поиска.\n4. Одномерные массивы. Адреса и указатели. Массивы в С++. Хранение в памяти. Фиксированный размер и однотипность элементов. Скорость доступа к элементам. Решето Эратосфена. Копирование массива. Копирование с реверсом. Реверс массива и циклический сдвиг. Добавление и удаление элемента в конце и в начале массива. Стек, очередь и дек на массиве. Адреса и указатели в С++. Размер ячейки для хранения адреса. Разыменование * и взятие адреса &. Адресная арифметика в С++. Преобразование типа указателя. Тип void*. Реинтерпретация данных. Массивы структур struct и структура struct, содержащая массив. Проверка корректности скобочной последовательности.\n5. Универсальные сортировки O(N2). Сортировка массива: постановка задачи. Сортировка обезьяны (без реализации). Проверка упорядоченности за O(N). Сортировка дурака. Сортировка методом пузырька. Сортировка вставками. Сортировка выбором. Устойчивость сортировок.\n6. Связные списки. Динамическая память. Выделение и освобождение динамической памяти: malloc(), calloc(), free(). Операторы new и delete. Ошибки работы с памятью. Контроль за динамической памятью. Некорректные адреса. Инициализация указателей: NULL и nullptr. Создание одномерного динамического массива. Реаллокация в памяти для динамического расширения массива. Списки: односвязный, двусвязный, кольцо. Асимптотика связных списков для разных задач. Стек на односвязном списке. Дек на двусвязном списке.\n7. Двумерные массивы. Обычные двумерные массивы в С++. Заполнение двумерного массива. Треугольник Паскаля. Транспонирование матрицы. Умножение матриц. Динамические двумерные массивы в С++. Линеаризация двумерного массива вручную. Функции. Синхронный вызов. Возврат по стеку вызовов. Сегмент STACK и передача параметров по значению. Модель памяти приложения. Локальные и глобальные переменные. Передача массива в функцию и возврат из функции в С++. Проблема ответственности за освобождение памяти.\n8. Бинпоиск и спецсортировки. Линейный поиск в массиве. Бинарный поиск в упорядоченном массиве. Сортировка подсчётом. Поразрядная сортировка.\n9. Рекурсия. Метод ветвей и границ. Прямой и обратный ход рекурсии. Факториал числа. Алгоритм Евклида. Быстрое возведение в степень. Вычисление чисел Фибоначчи. Ханойские башни. Рекурсивная генерация всех чисел длины M. Генерация всех перестановок в массиве. Перебор с возвратом: метод ветвей и границ.\n10. Быстрые сортировки. Принцип «Разделяй и властвуй». Умножение Карацубы. Быстрая сортировка Тони Хоара. Сортировка слиянием.\n11. Динамическое программирование. Количество траекторий на схеме дорог. Проблема повторных вычислений на примере чисел Фибоначчи. Динамическое программирование сверху и снизу. Кузнечик: количество траекторий, траектория минимальной стоимости.\n12. Двумерное динамическое программирование. Алгоритм укладки рюкзака (дискретный). Наибольшая общая подпоследовательность. Наибольшая возрастающая подпоследовательность.\n13. Строки и работа с файлами. Кодировки символов: ASCII, однобайтные и семейство Unicode. Строка как массив символов. Си-строки и ANSI-строки. Почему Си-строки не следует использовать для обработки текста. Проверка равенства строк. Простой и вероятностный алгоритмы. Вычисление расстояния Левенштейна. Поиск последовательности редакционных изменений. Работа с файлами в чистом Си. Два уровня API.\n14. Поиск подстрок. С++ строки std::string. Поиск подстроки: наивный алгоритм. Префикс-функция. Алгоритм Кнута-Морриса-Пратта. Z-функция и Z-алгоритм. Работа с потоками ifstream, ofstream, fstream. Форматирование ввода-вывода: iomanip.\n15. Параллелизм на системах с общей памятью. Ресурс параллельности. Потоки. Асинхронные вызовы.\n\n\n### Методические указания обучающимся\n\nВаша цель — запомнить классические алгоритмы и структуры данных, знать их асимптотическую сложность, уметь их описывать устно, а также программировать их на языке C++.\nКурс содержит три вида учебной деятельности: 1) лекции, 2) лабораторные работы и 3) самостоятельная работа.\n\nНа лекциях по информатике излагается теория, разбираются алгоритмы с реализацией на C++. Посещение не обязательно, но пропуск лекций существенно усложняет выполнение лабораторных и домашних работ. Именно лекции задают содержательную линию учебного курса.\n\nОписания лабораторных работ появляются по ходу семестра на сайте http://cs.mipt.ru/cpp_algo. Очное присутствие на лабораторных обязательно. Типичная работа представляет из себя: а) текст для изучения; б) упражнения; в) контест с автоматизированной системой проверки. Автоматически проверяемые задачи допускается доделывать дома в качестве самостоятельной работы. В самостоятельную работу включается также подготовка к сдаче устного зачёта. В течение семестра на лабораторных занятиях проводится 2 контрольные работы: промежуточная и итоговая.\n\n### Оценивание\n\nДифференцированный зачёт сдаётся устно. Рекомендуемая итоговая оценка студента по предмету — это среднее арифметическое взвешенное оценок по лабораторным работам и контрольным.\nПреподаватель, экзаменующий студента, видит все эти оценки по отдельности, а также рекомендуемую итоговую оценку. Исходя из ответа студента итоговая оценка в зачётку может быть отклонена от рекомендуемой на ±2 балла (по 10-балльной шкале).\nЕсли преподаватель хочет повысить или понизить оценку на большее число баллов, он советуется со старшим преподавателем курса. Студент при несогласии с итоговой оценкой может потребовать апелляции у старшего преподавателя (в конце зачётной недели).\n"
  },
  {
    "path": "cpp_algo/lec_01/1_bot.cpp",
    "content": "#include <iostream>\n\nint main()\n{\n    using namespace std;\n    string name;\n    int age;\n\n    cout << \"- Hello! What is your name?\" << endl;\n    cerr << \"> \";\n    cin >> name;\n    cout << \"- I'm glad to see you, \" << name << \"!\" << endl\n         <<\"- What is your age?\" << endl;\n    cerr << \"> \";\n    cin >> age;\n    cout << \"- I thought you are \" << age + 1\n         << \" year old. You look younger!\" << endl;\n\n    return 0;\n}\n"
  },
  {
    "path": "cpp_algo/lec_01/1_bot.py",
    "content": "print(\"- Hello! What is your name?\")\nname = input(\"> \")\nprint(\"- I'm glad to see you, \", name,\n      \"!\", sep=\"\")\nprint(\"- What is your age?\")\nage = int(input(\"> \"))\nprint(\"- I thought you are \", age + 1,\n      \" year old. You look younger!\")\n"
  },
  {
    "path": "cpp_algo/lec_01/2_euclid.cpp",
    "content": "#include <iostream>\n\nint euclid_gcd(int a, int b)\n{   // Алгоритм Евклида поиска НОД\n    while (a != b) {\n        if (a > b) {\n            a -= b;\n        } else {\n            b -= a;\n        }\n    }\n    return a;\n}\n\nint main()\n{\n    using namespace std;\n    int x, y;\n\n    cout << \"Enter integer. x = \";\n    cin >> x;\n    cout << \"Enter integer. y = \";\n    cin >> y;\n    cout << \"GCD(x, y) = \" << euclid_gcd(x, y) << endl;\n\n    return 0;\n}\n"
  },
  {
    "path": "cpp_algo/lec_01/2_euclid.py",
    "content": "\n\ndef euclid_gcd(a: int, b: int):\n    # Алгоритм Евклида поиска НОД\n    while a != b:\n        if a > b:\n            a -= b\n        else:\n            b -= a\n    return a\n\nx = int(input(\"Enter integer. x = \"))\ny = int(input(\"Enter integer. y = \"))\nprint(\"GCD(x, y) =\", euclid_gcd(x, y))\n"
  },
  {
    "path": "cpp_algo/lec_01/3_goto_nightmare.cpp",
    "content": "#include <iostream>\n\nint euclid_gcd(int a, int b)\n{   // Алгоритм Евклида поиска НОД\nloop_begin:\n    if (a == b) goto loop_end;\n    if (!(a > b)) goto else_action;\n    a -= b;\n    goto after_if;\nelse_action:\n    b -= a;\nafter_if:\n    goto loop_begin;\nloop_end:\n    return a;\n}\n\nint main()\n{\n    using namespace std;\n    int x, y;\n\n    cout << \"Enter integer. x = \";\n    cin >> x;\n    cout << \"Enter integer. y = \";\n    cin >> y;\n    cout << \"GCD(x, y) = \" << euclid_gcd(x, y) << endl;\n\n    return 0;\n}\n"
  },
  {
    "path": "cpp_algo/lec_01/hello.cpp",
    "content": "#include <iostream>\n\nint main()\n{\n    using namespace std;\n\n    cout << \"Hello, world!\" << endl;\n\n    return 777;\n}\n"
  },
  {
    "path": "cpp_algo/lec_01/in.txt",
    "content": "John\n17\n\n"
  },
  {
    "path": "cpp_algo/lec_01/out.txt",
    "content": "- Hello! What is your name?\n- I'm glad to see you, Katapulta!\n- What is your age?\n- I thought you are 2 year old. You look younger!\n"
  },
  {
    "path": "cpp_algo/lec_02/1_bits.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nint main()\n{\n    uint8_t x, y;\n\n    x = 10;\n    y = 12;\n\n    cout << (unsigned int) (x & y) << endl;\n    cout << (unsigned int) (x | y) << endl;\n    cout << (unsigned int) (x ^ y) << endl;\n    cout << (unsigned int) (~x) << endl;\n    y = ~x;\n    cout << (unsigned int) (y) << endl;\n\n    return 0;\n}\n"
  },
  {
    "path": "cpp_algo/lec_03/expressions.cpp",
    "content": "#include <iostream>\n#include <cmath>\n\nusing namespace std;\n\ndouble f(double x);\n\nint main()\n{\n    double x;\n    cin >> x;\n    cout << f(x) << endl;\n\n    double s = 0;\n    double factor;\n    for(int n = 0, factor=1; n < 10; n++) {\n        s += pow(-1, n)*pow(x, 2*n + 1)/factor;\n        factor *= 2*n*(2*n + 1);\n    }\n    cout << s;\n\n    return 0;\n}\n\ndouble f(double x)\n{\n    return 2*sin(x);\n}\n"
  },
  {
    "path": "cpp_algo/lec_04/1_func_params.cpp",
    "content": "/* Аргументы в функцию передаются по значению, т.е.\n * при вызове функции для хранения фактических переданных значений\n * создаются временные переменные - ячейки памяти на сегменте STACK.\n * После выхода из функции эти переменные уничтожаются.\n *\n*/\n#include <iostream>\n\nvoid increment(int a) // При вызове появится переменная a с копией значения b.\n{\n    std::cout << a << '\\n';\n    a = a + 1;        // Значение a увеличится на 1.\n    std::cout << a << '\\n';\n}                     // Однако, при выходе из функции переменная a уничтожится.\n\nint main()\n{\n    using namespace std;\n    int b = 3;\n    \n    increment(b);     // Здесь число 3 будет скопировано из b во временную a.\n    cout << b << endl;   // Естественно, вызов функции inc(b) не изменил b.\n    \n    return 0;\n}\n"
  },
  {
    "path": "cpp_algo/lec_04/2_func_params.cpp",
    "content": "/* Аргументы в функцию передаются по значению, т.е.\n * при вызове функции для хранения фактических переданных значений\n * создаются временные переменные - ячейки памяти на сегменте STACK.\n * После выхода из функции эти переменные уничтожаются.\n *\n*/\n#include <iostream>\n\nvoid increment(int* a) // При вызове появится переменная a с адресом b.\n{\n    *a = *a + 1;      // Значение по адресу a увеличится на 1.\n}                     // Однако, при выходе из функции указатель a уничтожится.\n\nint main()\n{\n    using namespace std;\n    int b = 3;\n    \n    increment(&b);     // Здесь будет скопирован адрес переменной b.\n    cout << b << endl;   // Естественно, вызов функции inc(b) не изменил b.\n    \n    return 0;\n}\n"
  },
  {
    "path": "cpp_algo/lec_04/3_struct.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nstruct t_Pair {  // создаём новый тип t_Pair\n    int a;\n    int b;\n};\n\nt_Pair return_pair(int x)\n{\n    t_Pair result; // создаю локальный экземпляр структуры t_Pair\n\n    result.a = x*x;  // Заполняю его нужными значениями.\n    result.b = x*x*x;\n\n    return result;  // Возвращаю его как результат.\n}\n\nint main()\n{\n    int x;\n    cin >> x;\n\n    t_Pair y = return_pair(x);\n    cout << y.a << ' ' << y.b << '\\n';\n\n    return 0;\n}\n"
  },
  {
    "path": "cpp_algo/lec_04/4_struct_to_function.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nstruct t_Pair {\n    int a;\n    int b;\n};\n\nvoid modify_pair(t_Pair *p)\n{\n    p->a += 1;\n    (*p).b += 10;\n}\n\nint main()\n{\n    t_Pair x;\n    cin >> x.a >> x.b;\n\n    t_Pair y;\n    y = x;\n\n    modify_pair(&x);\n\n    cout << x.a << ' ' << x.b << '\\n';\n    cout << y.a << ' ' << y.b << '\\n';\n\n    return 0;\n}\n"
  },
  {
    "path": "cpp_algo/lec_04/5_sizeof.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nstruct t_Pair {\n    int a;\n    int b;\n};\n\nint main()\n{\n    int8_t x;\n    int y;\n    long long int z;\n    float a;\n    double b;\n    t_Pair p;\n\n    cout << sizeof(x) << '\\n';\n    cout << sizeof(int) << '\\n';\n    cout << sizeof(int*) << '\\n';\n    cout << sizeof(z) << '\\n';\n    cout << sizeof(a) << '\\n';\n    cout << sizeof(b) << '\\n';\n    cout << sizeof(p) << '\\n';\n\n    cout << sizeof(&x) << '\\n';\n    cout << sizeof(&y) << '\\n';\n    cout << sizeof(&z) << '\\n';\n    cout << sizeof(&a) << '\\n';\n    cout << sizeof(&b) << '\\n';\n    cout << sizeof(&p) << '\\n';\n\n    return 0;\n}\n"
  },
  {
    "path": "cpp_algo/lec_04/6_reinterpret.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nint main()\n{\n    int64_t x;\n    double y;\n\n    // Я хочу \"переосмыслить\" сами байты double значения 1.0 как будто они - байты int64_t\n    y = 1.0;\n    // x = *(int64_t*)(&y);   WARNING!!! Not to do this way! Use reinterpret_cast.\n    // x = *static_cast<int64_t *>(&y); ERROR! can't statically cast double* to int64_t*\n    x = *reinterpret_cast<int64_t *>(&y);\n    \n    cout << x << '\\n';\n\n    return 0;\n}\n"
  },
  {
    "path": "cpp_algo/lec_04/7_segfault.cpp",
    "content": "#include <iostream>\n\nint main()\n{\n    int x = 2;\n    int A[10];\n    int y = 256;\n    \n    A[10] = 1;\n    std::cout << x << ' ' << y << '\\n';\n\n    for(y = 0; y < 100; y++)  // выход за границы массива - undefined behaviour\n    { // (It's worse than Segmentation fault!!!)\n        A[y] = (y + 1) % 5;\n        std::cout << A[y] << '\\n';\n    }\n\n    return 0;\n}\n"
  },
  {
    "path": "cpp_algo/lec_04/8_Eratosthenes.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nint main()\n{\n    int n;\n    std::cin >> n;\n    \n    bool sieve[n+1];  // not to interpret 0 and 1-st elements - not prime numbers nor composite\n    for(int i = 2; i < n + 1; i++) {\n        sieve[i] = true;\n    }\n    int x = 2;\n    while (x*x <= n) {\n        if (sieve[x]) { //found new prime\n            for (int y = x*x; y <= n; y += x) {\n                sieve[y] = false; // composite\n            }\n        }\n        x += 1;\n    }\n    \n    for (int i = 2; i < n + 1; i++) {\n        if (sieve[i]) {\n            std::cout << i << '\\t';\n        }\n    }\n    std::cout << '\\n';\n    return 0;\n}\n"
  },
  {
    "path": "cpp_algo/lec_05/1_copy.cpp",
    "content": ""
  },
  {
    "path": "cpp_algo/lec_05/2_reverse.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nint main()\n{\n    int N = 5;\n    int A[N] = {1, 2, 3, 4, 5};\n    \n    for(int i = 0; i < N / 2; ++i) {\n        int tmp = A[i];\n        A[i] = A[N-1-i];\n        A[N-1-i] = tmp;\n    }\n    \n    for(int i = 0; i < N; ++i) {\n        cout << A[i] << '\\t';\n    }\n    cout << '\\n';\n\n    return 0;\n}\n"
  },
  {
    "path": "cpp_algo/lec_05/3_append.cpp",
    "content": "#include <iostream>\nusing namespace std;\n\nconst int MAX_A_SIZE = 100;\n\nint main()\n{\n    int N = MAX_A_SIZE;\n    int A[N];\n    int top = 0;\n    int x;\n\n    cin >> x;\n    while (x != 0) {\n        A[top++] = x;\n\n        cin >> x;\n    }\n\n    for(int i = 0; i < top; ++i) {\n        cout << A[i] << '\\t';\n    }\n    cout << '\\n';\n\n    return 0;\n}\n"
  },
  {
    "path": "cpp_algo/lec_05/4_stack.cpp",
    "content": "#include <iostream>\nusing namespace std;\n\nconst int MAX_A_SIZE = 100;\n\nint main()\n{\n    int N = MAX_A_SIZE;\n    int A[N];\n    int top = 0;\n    int x;\n\n    cin >> x;\n    while (x != 0) {\n        A[top++] = x;\n\n        cin >> x;\n    }\n\n    while (top > 0) {\n        cout << A[--top] << '\\t';\n    }\n    cout << '\\n';\n\n    return 0;\n}\n"
  },
  {
    "path": "cpp_algo/lec_05/4a_braces.cpp",
    "content": ""
  },
  {
    "path": "cpp_algo/lec_05/5_check_sorted.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nint main()\n{\n    int N = 5;\n    int A[N] = {1, 3, 2, 4, 5};\n    \n    bool is_sorted = true;\n    int i = 0;\n    while (i < N-1)\n    {\n        if (A[i] > A[i+1]) {\n            is_sorted = false;\n            break;\n        }\n        i += 1;\n    }\n\n    cout << is_sorted << '\\n';\n    \n    return 0;\n}\n"
  },
  {
    "path": "cpp_algo/lec_05/6_fool.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nint main()\n{\n    int N = 5;\n    int A[N] = {5, 4, 3, 2, 1};\n    \n    int i = 0;\n    while (i < N-1)\n    {\n        if (A[i] > A[i+1]) {\n            int tmp = A[i];\n            A[i] = A[i+1];\n            A[i+1] = tmp;\n            i = 0;\n        } else {\n            i += 1;\n        }\n    }\n\n    for(int i = 0; i < N; ++i) {\n        cout << A[i] << '\\t';\n    }\n    cout << '\\n';\n    \n    return 0;\n}\n"
  },
  {
    "path": "cpp_algo/lec_05/6a_fool_asympotic.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nint main()\n{\n    int N = 10000;\n    int A[N];\n    for(int i = 0; i < N; i++) A[i] = N-i;\n    \n    int i = 0;\n    while (i < N-1)\n    {\n        if (A[i] > A[i+1]) {\n            int tmp = A[i];\n            A[i] = A[i+1];\n            A[i+1] = tmp;\n            i = 0;\n        } else {\n            i += 1;\n        }\n    }\n\n    cout << \"Hello!\" << '\\n';\n    \n    return 0;\n}\n"
  },
  {
    "path": "cpp_algo/lec_05/7_bubble.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nint main()\n{\n    int N = 5;\n    int A[N] = {1, 3, 2, 5, 4};\n    \n    bool is_sorted = false;\n    while (not is_sorted) {\n        int i = 0;\n        is_sorted = true;\n        while (i < N-1)\n        {\n            if (A[i] > A[i+1]) {\n                int tmp = A[i];\n                A[i] = A[i+1];\n                A[i+1] = tmp;\n                is_sorted = false;\n            }\n            i += 1;\n        }\n    }\n\n    for(int i = 0; i < N; ++i) {\n        cout << A[i] << '\\t';\n    }\n    cout << '\\n';\n    \n    return 0;\n}\n"
  },
  {
    "path": "cpp_algo/lec_05/8_insert.cpp",
    "content": ""
  },
  {
    "path": "cpp_algo/lec_05/9_choice.cpp",
    "content": ""
  },
  {
    "path": "cpp_algo/lec_06/1_pointers.cpp",
    "content": ""
  },
  {
    "path": "cpp_algo/lec_06/2_structs.cpp",
    "content": "#include <iostream>\n\nstruct node_t {\n    int data;\n    node_t *next;\n};\n\nvoid go_through(node_t *p)\n{\n    while (p != nullptr) {\n        std::cout << p->data << '\\n';\n        p = p->next;\n    }\n}\n\nint main()\n{\n    node_t A[5];\n    for(int i = 0; i < 5; i++) {\n        A[i].data = i+1;\n        A[i].next = A + i + 1;\n    }\n    A[4].next = nullptr;\n\n    node_t *p_begin = A;\n    go_through(p_begin);\n\n    return 0;\n}\n"
  },
  {
    "path": "cpp_algo/lec_06/3_malloc.c",
    "content": "#include <stdlib.h>\n#include <stdio.h>\n\nint main()\n{\n    for (int i = 0; i < 100; i++) {\n        double *pd = (double *)malloc(10 * sizeof(double));\n        if (pd != NULL)\n        {\n            //адресная арифметика обеспечит перебор адресов\n            // от pd до pd + 9*sizeof(double) включительно\n            for(double *p = pd; p < pd + 10; p++)\n                *p = 0.0; //зануляем ячейку памяти типа double\n        } else {\n            printf(\"Не удалось выделить память.\");\n        }\n        free(pd);\n    }\n    return 0;\n}\n"
  },
  {
    "path": "cpp_algo/lec_06/4_new.cpp",
    "content": "#include <iostream>\n\nstruct node_t {\n    int data;\n    node_t *next;\n};\n\nvoid go_through(node_t *p)\n{\n    while (p != nullptr) {\n        std::cout << p->data << '\\n';\n        p = p->next;\n    }\n}\n\n\nint main()\n{\n    node_t *p_begin = new node_t;\n\n    node_t *p = p_begin;\n    for(int i = 0; i < 5; i++) {\n        p->data = i+1;\n        p->next = new node_t;\n        p = p->next;\n    }\n    p->data = 777;\n    p->next = nullptr;\n\n    go_through(p_begin);\n\n    return 0;\n}\n"
  },
  {
    "path": "cpp_algo/lec_06/5_leaks.cpp",
    "content": ""
  },
  {
    "path": "cpp_algo/lec_07/1_array1d.cpp",
    "content": "#include <iostream>\n\nusing namespace std; // really it's bad to do such way!\n\nint main()\n{\n    int N;\n    N = 3;\n\n    int A[N];\n    for(int i = 0; i < N; i++) {\n        A[i] = i+1;\n    }\n\n    for(int i = 0; i < N; i++) {\n        cout << A[i] << '\\t';\n    }\n    cout << endl;\n\n    return 0;\n}\n"
  },
  {
    "path": "cpp_algo/lec_07/2_array2d.cpp",
    "content": "#include <iostream>\n\nusing namespace std; // really it's bad to do such way!\n\nint main()\n{\n    int N, M;\n    cin >> N >> M;\n\n    int A[N][M];\n    for(int i = 0; i < N; i++) {\n        for(int j = 0; j < M; j++) {\n            A[i][j] = i*M + j;\n        }\n    }\n\n    for(int i = 0; i < N; i++) {\n        for(int j = 0; j < M; j++) {\n            cout << A[i][j] << '\\t';\n        }\n        cout << '\\n';\n    }\n\n    // memory investigation\n    int *p = reinterpret_cast<int *>(A);\n    for(int i = 0; i < M*N; i++) {\n        cout << *(p + i) << ' ';\n    }\n\n    return 0;\n}\n\n"
  },
  {
    "path": "cpp_algo/lec_07/2_array2d.s",
    "content": "\na.out:     формат файла elf64-x86-64\n\n\nДизассемблирование раздела .init:\n\n0000000000001000 <_init>:\n    1000:\t48 83 ec 08          \tsub    $0x8,%rsp\n    1004:\t48 8b 05 dd 2f 00 00 \tmov    0x2fdd(%rip),%rax        # 3fe8 <__gmon_start__>\n    100b:\t48 85 c0             \ttest   %rax,%rax\n    100e:\t74 02                \tje     1012 <_init+0x12>\n    1010:\tff d0                \tcallq  *%rax\n    1012:\t48 83 c4 08          \tadd    $0x8,%rsp\n    1016:\tc3                   \tretq   \n\nДизассемблирование раздела .plt:\n\n0000000000001020 <.plt>:\n    1020:\tff 35 e2 2f 00 00    \tpushq  0x2fe2(%rip)        # 4008 <_GLOBAL_OFFSET_TABLE_+0x8>\n    1026:\tff 25 e4 2f 00 00    \tjmpq   *0x2fe4(%rip)        # 4010 <_GLOBAL_OFFSET_TABLE_+0x10>\n    102c:\t0f 1f 40 00          \tnopl   0x0(%rax)\n\n0000000000001030 <_ZNSirsERi@plt>:\n    1030:\tff 25 e2 2f 00 00    \tjmpq   *0x2fe2(%rip)        # 4018 <_ZNSirsERi@GLIBCXX_3.4>\n    1036:\t68 00 00 00 00       \tpushq  $0x0\n    103b:\te9 e0 ff ff ff       \tjmpq   1020 <.plt>\n\n0000000000001040 <__cxa_atexit@plt>:\n    1040:\tff 25 da 2f 00 00    \tjmpq   *0x2fda(%rip)        # 4020 <__cxa_atexit@GLIBC_2.2.5>\n    1046:\t68 01 00 00 00       \tpushq  $0x1\n    104b:\te9 d0 ff ff ff       \tjmpq   1020 <.plt>\n\n0000000000001050 <_ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_c@plt>:\n    1050:\tff 25 d2 2f 00 00    \tjmpq   *0x2fd2(%rip)        # 4028 <_ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_c@GLIBCXX_3.4>\n    1056:\t68 02 00 00 00       \tpushq  $0x2\n    105b:\te9 c0 ff ff ff       \tjmpq   1020 <.plt>\n\n0000000000001060 <_ZNSt8ios_base4InitC1Ev@plt>:\n    1060:\tff 25 ca 2f 00 00    \tjmpq   *0x2fca(%rip)        # 4030 <_ZNSt8ios_base4InitC1Ev@GLIBCXX_3.4>\n    1066:\t68 03 00 00 00       \tpushq  $0x3\n    106b:\te9 b0 ff ff ff       \tjmpq   1020 <.plt>\n\n0000000000001070 <_ZNSolsEi@plt>:\n    1070:\tff 25 c2 2f 00 00    \tjmpq   *0x2fc2(%rip)        # 4038 <_ZNSolsEi@GLIBCXX_3.4>\n    1076:\t68 04 00 00 00       \tpushq  $0x4\n    107b:\te9 a0 ff ff ff       \tjmpq   1020 <.plt>\n\nДизассемблирование раздела .plt.got:\n\n0000000000001080 <__cxa_finalize@plt>:\n    1080:\tff 25 4a 2f 00 00    \tjmpq   *0x2f4a(%rip)        # 3fd0 <__cxa_finalize@GLIBC_2.2.5>\n    1086:\t66 90                \txchg   %ax,%ax\n\nДизассемблирование раздела .text:\n\n0000000000001090 <_start>:\n    1090:\t31 ed                \txor    %ebp,%ebp\n    1092:\t49 89 d1             \tmov    %rdx,%r9\n    1095:\t5e                   \tpop    %rsi\n    1096:\t48 89 e2             \tmov    %rsp,%rdx\n    1099:\t48 83 e4 f0          \tand    $0xfffffffffffffff0,%rsp\n    109d:\t50                   \tpush   %rax\n    109e:\t54                   \tpush   %rsp\n    109f:\t4c 8d 05 4a 04 00 00 \tlea    0x44a(%rip),%r8        # 14f0 <__libc_csu_fini>\n    10a6:\t48 8d 0d e3 03 00 00 \tlea    0x3e3(%rip),%rcx        # 1490 <__libc_csu_init>\n    10ad:\t48 8d 3d c1 00 00 00 \tlea    0xc1(%rip),%rdi        # 1175 <main>\n    10b4:\tff 15 26 2f 00 00    \tcallq  *0x2f26(%rip)        # 3fe0 <__libc_start_main@GLIBC_2.2.5>\n    10ba:\tf4                   \thlt    \n    10bb:\t0f 1f 44 00 00       \tnopl   0x0(%rax,%rax,1)\n\n00000000000010c0 <deregister_tm_clones>:\n    10c0:\t48 8d 3d 89 2f 00 00 \tlea    0x2f89(%rip),%rdi        # 4050 <__TMC_END__>\n    10c7:\t48 8d 05 82 2f 00 00 \tlea    0x2f82(%rip),%rax        # 4050 <__TMC_END__>\n    10ce:\t48 39 f8             \tcmp    %rdi,%rax\n    10d1:\t74 15                \tje     10e8 <deregister_tm_clones+0x28>\n    10d3:\t48 8b 05 fe 2e 00 00 \tmov    0x2efe(%rip),%rax        # 3fd8 <_ITM_deregisterTMCloneTable>\n    10da:\t48 85 c0             \ttest   %rax,%rax\n    10dd:\t74 09                \tje     10e8 <deregister_tm_clones+0x28>\n    10df:\tff e0                \tjmpq   *%rax\n    10e1:\t0f 1f 80 00 00 00 00 \tnopl   0x0(%rax)\n    10e8:\tc3                   \tretq   \n    10e9:\t0f 1f 80 00 00 00 00 \tnopl   0x0(%rax)\n\n00000000000010f0 <register_tm_clones>:\n    10f0:\t48 8d 3d 59 2f 00 00 \tlea    0x2f59(%rip),%rdi        # 4050 <__TMC_END__>\n    10f7:\t48 8d 35 52 2f 00 00 \tlea    0x2f52(%rip),%rsi        # 4050 <__TMC_END__>\n    10fe:\t48 29 fe             \tsub    %rdi,%rsi\n    1101:\t48 c1 fe 03          \tsar    $0x3,%rsi\n    1105:\t48 89 f0             \tmov    %rsi,%rax\n    1108:\t48 c1 e8 3f          \tshr    $0x3f,%rax\n    110c:\t48 01 c6             \tadd    %rax,%rsi\n    110f:\t48 d1 fe             \tsar    %rsi\n    1112:\t74 14                \tje     1128 <register_tm_clones+0x38>\n    1114:\t48 8b 05 d5 2e 00 00 \tmov    0x2ed5(%rip),%rax        # 3ff0 <_ITM_registerTMCloneTable>\n    111b:\t48 85 c0             \ttest   %rax,%rax\n    111e:\t74 08                \tje     1128 <register_tm_clones+0x38>\n    1120:\tff e0                \tjmpq   *%rax\n    1122:\t66 0f 1f 44 00 00    \tnopw   0x0(%rax,%rax,1)\n    1128:\tc3                   \tretq   \n    1129:\t0f 1f 80 00 00 00 00 \tnopl   0x0(%rax)\n\n0000000000001130 <__do_global_dtors_aux>:\n    1130:\t80 3d 61 31 00 00 00 \tcmpb   $0x0,0x3161(%rip)        # 4298 <completed.7325>\n    1137:\t75 2f                \tjne    1168 <__do_global_dtors_aux+0x38>\n    1139:\t55                   \tpush   %rbp\n    113a:\t48 83 3d 8e 2e 00 00 \tcmpq   $0x0,0x2e8e(%rip)        # 3fd0 <__cxa_finalize@GLIBC_2.2.5>\n    1141:\t00 \n    1142:\t48 89 e5             \tmov    %rsp,%rbp\n    1145:\t74 0c                \tje     1153 <__do_global_dtors_aux+0x23>\n    1147:\t48 8b 3d fa 2e 00 00 \tmov    0x2efa(%rip),%rdi        # 4048 <__dso_handle>\n    114e:\te8 2d ff ff ff       \tcallq  1080 <__cxa_finalize@plt>\n    1153:\te8 68 ff ff ff       \tcallq  10c0 <deregister_tm_clones>\n    1158:\tc6 05 39 31 00 00 01 \tmovb   $0x1,0x3139(%rip)        # 4298 <completed.7325>\n    115f:\t5d                   \tpop    %rbp\n    1160:\tc3                   \tretq   \n    1161:\t0f 1f 80 00 00 00 00 \tnopl   0x0(%rax)\n    1168:\tc3                   \tretq   \n    1169:\t0f 1f 80 00 00 00 00 \tnopl   0x0(%rax)\n\n0000000000001170 <frame_dummy>:\n    1170:\te9 7b ff ff ff       \tjmpq   10f0 <register_tm_clones>\n\n0000000000001175 <main>:\n    1175:\t55                   \tpush   %rbp\n    1176:\t48 89 e5             \tmov    %rsp,%rbp\n    1179:\t41 57                \tpush   %r15\n    117b:\t41 56                \tpush   %r14\n    117d:\t41 55                \tpush   %r13\n    117f:\t41 54                \tpush   %r12\n    1181:\t53                   \tpush   %rbx\n    1182:\t48 81 ec 88 00 00 00 \tsub    $0x88,%rsp\n    1189:\t48 89 e0             \tmov    %rsp,%rax\n    118c:\t48 89 85 58 ff ff ff \tmov    %rax,-0xa8(%rbp)\n    1193:\t48 8d 45 94          \tlea    -0x6c(%rbp),%rax\n    1197:\t48 89 c6             \tmov    %rax,%rsi\n    119a:\t48 8d 3d df 2f 00 00 \tlea    0x2fdf(%rip),%rdi        # 4180 <_ZSt3cin@@GLIBCXX_3.4>\n    11a1:\te8 8a fe ff ff       \tcallq  1030 <_ZNSirsERi@plt>\n    11a6:\t48 89 c2             \tmov    %rax,%rdx\n    11a9:\t48 8d 45 90          \tlea    -0x70(%rbp),%rax\n    11ad:\t48 89 c6             \tmov    %rax,%rsi\n    11b0:\t48 89 d7             \tmov    %rdx,%rdi\n    11b3:\te8 78 fe ff ff       \tcallq  1030 <_ZNSirsERi@plt>\n    11b8:\t8b 45 90             \tmov    -0x70(%rbp),%eax\n    11bb:\t48 98                \tcltq   \n    11bd:\t48 8d 48 ff          \tlea    -0x1(%rax),%rcx\n    11c1:\t48 89 4d b0          \tmov    %rcx,-0x50(%rbp)\n    11c5:\t48 89 c8             \tmov    %rcx,%rax\n    11c8:\t48 83 c0 01          \tadd    $0x1,%rax\n    11cc:\t48 89 85 60 ff ff ff \tmov    %rax,-0xa0(%rbp)\n    11d3:\t48 c7 85 68 ff ff ff \tmovq   $0x0,-0x98(%rbp)\n    11da:\t00 00 00 00 \n    11de:\t48 89 c8             \tmov    %rcx,%rax\n    11e1:\t48 83 c0 01          \tadd    $0x1,%rax\n    11e5:\t48 8d 1c 85 00 00 00 \tlea    0x0(,%rax,4),%rbx\n    11ec:\t00 \n    11ed:\t8b 45 94             \tmov    -0x6c(%rbp),%eax\n    11f0:\t48 98                \tcltq   \n    11f2:\t48 8d 70 ff          \tlea    -0x1(%rax),%rsi\n    11f6:\t48 89 75 a8          \tmov    %rsi,-0x58(%rbp)\n    11fa:\t48 89 c8             \tmov    %rcx,%rax\n    11fd:\t48 83 c0 01          \tadd    $0x1,%rax\n    1201:\t48 89 45 80          \tmov    %rax,-0x80(%rbp)\n    1205:\t48 c7 45 88 00 00 00 \tmovq   $0x0,-0x78(%rbp)\n    120c:\t00 \n    120d:\t48 89 f0             \tmov    %rsi,%rax\n    1210:\t48 83 c0 01          \tadd    $0x1,%rax\n    1214:\t48 89 85 70 ff ff ff \tmov    %rax,-0x90(%rbp)\n    121b:\t48 c7 85 78 ff ff ff \tmovq   $0x0,-0x88(%rbp)\n    1222:\t00 00 00 00 \n    1226:\t4c 8b 45 80          \tmov    -0x80(%rbp),%r8\n    122a:\t4c 8b 4d 88          \tmov    -0x78(%rbp),%r9\n    122e:\t4c 89 ca             \tmov    %r9,%rdx\n    1231:\t4c 8b 95 70 ff ff ff \tmov    -0x90(%rbp),%r10\n    1238:\t4c 8b 9d 78 ff ff ff \tmov    -0x88(%rbp),%r11\n    123f:\t49 0f af d2          \timul   %r10,%rdx\n    1243:\t4c 89 d8             \tmov    %r11,%rax\n    1246:\t49 0f af c0          \timul   %r8,%rax\n    124a:\t48 8d 3c 02          \tlea    (%rdx,%rax,1),%rdi\n    124e:\t4c 89 c0             \tmov    %r8,%rax\n    1251:\t49 f7 e2             \tmul    %r10\n    1254:\t48 01 d7             \tadd    %rdx,%rdi\n    1257:\t48 89 fa             \tmov    %rdi,%rdx\n    125a:\t48 89 c8             \tmov    %rcx,%rax\n    125d:\t48 83 c0 01          \tadd    $0x1,%rax\n    1261:\t49 89 c6             \tmov    %rax,%r14\n    1264:\t41 bf 00 00 00 00    \tmov    $0x0,%r15d\n    126a:\t48 89 f0             \tmov    %rsi,%rax\n    126d:\t48 83 c0 01          \tadd    $0x1,%rax\n    1271:\t49 89 c4             \tmov    %rax,%r12\n    1274:\t41 bd 00 00 00 00    \tmov    $0x0,%r13d\n    127a:\t4c 89 fa             \tmov    %r15,%rdx\n    127d:\t49 0f af d4          \timul   %r12,%rdx\n    1281:\t4c 89 e8             \tmov    %r13,%rax\n    1284:\t49 0f af c6          \timul   %r14,%rax\n    1288:\t48 8d 3c 02          \tlea    (%rdx,%rax,1),%rdi\n    128c:\t4c 89 f0             \tmov    %r14,%rax\n    128f:\t49 f7 e4             \tmul    %r12\n    1292:\t48 01 d7             \tadd    %rdx,%rdi\n    1295:\t48 89 fa             \tmov    %rdi,%rdx\n    1298:\t48 89 c8             \tmov    %rcx,%rax\n    129b:\t48 8d 50 01          \tlea    0x1(%rax),%rdx\n    129f:\t48 89 f0             \tmov    %rsi,%rax\n    12a2:\t48 83 c0 01          \tadd    $0x1,%rax\n    12a6:\t48 0f af c2          \timul   %rdx,%rax\n    12aa:\t48 8d 14 85 00 00 00 \tlea    0x0(,%rax,4),%rdx\n    12b1:\t00 \n    12b2:\tb8 10 00 00 00       \tmov    $0x10,%eax\n    12b7:\t48 83 e8 01          \tsub    $0x1,%rax\n    12bb:\t48 01 d0             \tadd    %rdx,%rax\n    12be:\tb9 10 00 00 00       \tmov    $0x10,%ecx\n    12c3:\tba 00 00 00 00       \tmov    $0x0,%edx\n    12c8:\t48 f7 f1             \tdiv    %rcx\n    12cb:\t48 6b c0 10          \timul   $0x10,%rax,%rax\n    12cf:\t48 29 c4             \tsub    %rax,%rsp\n    12d2:\t48 89 e0             \tmov    %rsp,%rax\n    12d5:\t48 83 c0 03          \tadd    $0x3,%rax\n    12d9:\t48 c1 e8 02          \tshr    $0x2,%rax\n    12dd:\t48 c1 e0 02          \tshl    $0x2,%rax\n    12e1:\t48 89 45 a0          \tmov    %rax,-0x60(%rbp)\n    12e5:\tc7 45 bc 00 00 00 00 \tmovl   $0x0,-0x44(%rbp)\n    12ec:\t8b 45 94             \tmov    -0x6c(%rbp),%eax\n    12ef:\t39 45 bc             \tcmp    %eax,-0x44(%rbp)\n    12f2:\t7d 4b                \tjge    133f <main+0x1ca>\n    12f4:\tc7 45 c0 00 00 00 00 \tmovl   $0x0,-0x40(%rbp)\n    12fb:\t8b 45 90             \tmov    -0x70(%rbp),%eax\n    12fe:\t39 45 c0             \tcmp    %eax,-0x40(%rbp)\n    1301:\t7d 36                \tjge    1339 <main+0x1c4>\n    1303:\t8b 45 90             \tmov    -0x70(%rbp),%eax\n    1306:\t0f af 45 bc          \timul   -0x44(%rbp),%eax\n    130a:\t89 c2                \tmov    %eax,%edx\n    130c:\t48 89 df             \tmov    %rbx,%rdi\n    130f:\t48 c1 ef 02          \tshr    $0x2,%rdi\n    1313:\t8b 45 c0             \tmov    -0x40(%rbp),%eax\n    1316:\t8d 0c 02             \tlea    (%rdx,%rax,1),%ecx\n    1319:\t48 8b 45 a0          \tmov    -0x60(%rbp),%rax\n    131d:\t8b 55 c0             \tmov    -0x40(%rbp),%edx\n    1320:\t48 63 f2             \tmovslq %edx,%rsi\n    1323:\t8b 55 bc             \tmov    -0x44(%rbp),%edx\n    1326:\t48 63 d2             \tmovslq %edx,%rdx\n    1329:\t48 0f af d7          \timul   %rdi,%rdx\n    132d:\t48 01 f2             \tadd    %rsi,%rdx\n    1330:\t89 0c 90             \tmov    %ecx,(%rax,%rdx,4)\n    1333:\t83 45 c0 01          \taddl   $0x1,-0x40(%rbp)\n    1337:\teb c2                \tjmp    12fb <main+0x186>\n    1339:\t83 45 bc 01          \taddl   $0x1,-0x44(%rbp)\n    133d:\teb ad                \tjmp    12ec <main+0x177>\n    133f:\tc7 45 c4 00 00 00 00 \tmovl   $0x0,-0x3c(%rbp)\n    1346:\t8b 45 94             \tmov    -0x6c(%rbp),%eax\n    1349:\t39 45 c4             \tcmp    %eax,-0x3c(%rbp)\n    134c:\t7d 68                \tjge    13b6 <main+0x241>\n    134e:\tc7 45 c8 00 00 00 00 \tmovl   $0x0,-0x38(%rbp)\n    1355:\t8b 45 90             \tmov    -0x70(%rbp),%eax\n    1358:\t39 45 c8             \tcmp    %eax,-0x38(%rbp)\n    135b:\t7d 42                \tjge    139f <main+0x22a>\n    135d:\t48 89 de             \tmov    %rbx,%rsi\n    1360:\t48 c1 ee 02          \tshr    $0x2,%rsi\n    1364:\t48 8b 45 a0          \tmov    -0x60(%rbp),%rax\n    1368:\t8b 55 c8             \tmov    -0x38(%rbp),%edx\n    136b:\t48 63 ca             \tmovslq %edx,%rcx\n    136e:\t8b 55 c4             \tmov    -0x3c(%rbp),%edx\n    1371:\t48 63 d2             \tmovslq %edx,%rdx\n    1374:\t48 0f af d6          \timul   %rsi,%rdx\n    1378:\t48 01 ca             \tadd    %rcx,%rdx\n    137b:\t8b 04 90             \tmov    (%rax,%rdx,4),%eax\n    137e:\t89 c6                \tmov    %eax,%esi\n    1380:\t48 8d 3d d9 2c 00 00 \tlea    0x2cd9(%rip),%rdi        # 4060 <_ZSt4cout@@GLIBCXX_3.4>\n    1387:\te8 e4 fc ff ff       \tcallq  1070 <_ZNSolsEi@plt>\n    138c:\tbe 09 00 00 00       \tmov    $0x9,%esi\n    1391:\t48 89 c7             \tmov    %rax,%rdi\n    1394:\te8 b7 fc ff ff       \tcallq  1050 <_ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_c@plt>\n    1399:\t83 45 c8 01          \taddl   $0x1,-0x38(%rbp)\n    139d:\teb b6                \tjmp    1355 <main+0x1e0>\n    139f:\tbe 0a 00 00 00       \tmov    $0xa,%esi\n    13a4:\t48 8d 3d b5 2c 00 00 \tlea    0x2cb5(%rip),%rdi        # 4060 <_ZSt4cout@@GLIBCXX_3.4>\n    13ab:\te8 a0 fc ff ff       \tcallq  1050 <_ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_c@plt>\n    13b0:\t83 45 c4 01          \taddl   $0x1,-0x3c(%rbp)\n    13b4:\teb 90                \tjmp    1346 <main+0x1d1>\n    13b6:\t48 8b 45 a0          \tmov    -0x60(%rbp),%rax\n    13ba:\t48 89 45 98          \tmov    %rax,-0x68(%rbp)\n    13be:\tc7 45 cc 00 00 00 00 \tmovl   $0x0,-0x34(%rbp)\n    13c5:\t8b 55 90             \tmov    -0x70(%rbp),%edx\n    13c8:\t8b 45 94             \tmov    -0x6c(%rbp),%eax\n    13cb:\t0f af c2             \timul   %edx,%eax\n    13ce:\t39 45 cc             \tcmp    %eax,-0x34(%rbp)\n    13d1:\t7d 37                \tjge    140a <main+0x295>\n    13d3:\t8b 45 cc             \tmov    -0x34(%rbp),%eax\n    13d6:\t48 98                \tcltq   \n    13d8:\t48 8d 14 85 00 00 00 \tlea    0x0(,%rax,4),%rdx\n    13df:\t00 \n    13e0:\t48 8b 45 98          \tmov    -0x68(%rbp),%rax\n    13e4:\t48 01 d0             \tadd    %rdx,%rax\n    13e7:\t8b 00                \tmov    (%rax),%eax\n    13e9:\t89 c6                \tmov    %eax,%esi\n    13eb:\t48 8d 3d 6e 2c 00 00 \tlea    0x2c6e(%rip),%rdi        # 4060 <_ZSt4cout@@GLIBCXX_3.4>\n    13f2:\te8 79 fc ff ff       \tcallq  1070 <_ZNSolsEi@plt>\n    13f7:\tbe 20 00 00 00       \tmov    $0x20,%esi\n    13fc:\t48 89 c7             \tmov    %rax,%rdi\n    13ff:\te8 4c fc ff ff       \tcallq  1050 <_ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_c@plt>\n    1404:\t83 45 cc 01          \taddl   $0x1,-0x34(%rbp)\n    1408:\teb bb                \tjmp    13c5 <main+0x250>\n    140a:\tb8 00 00 00 00       \tmov    $0x0,%eax\n    140f:\t48 8b a5 58 ff ff ff \tmov    -0xa8(%rbp),%rsp\n    1416:\t48 8d 65 d8          \tlea    -0x28(%rbp),%rsp\n    141a:\t5b                   \tpop    %rbx\n    141b:\t41 5c                \tpop    %r12\n    141d:\t41 5d                \tpop    %r13\n    141f:\t41 5e                \tpop    %r14\n    1421:\t41 5f                \tpop    %r15\n    1423:\t5d                   \tpop    %rbp\n    1424:\tc3                   \tretq   \n\n0000000000001425 <_Z41__static_initialization_and_destruction_0ii>:\n    1425:\t55                   \tpush   %rbp\n    1426:\t48 89 e5             \tmov    %rsp,%rbp\n    1429:\t48 83 ec 10          \tsub    $0x10,%rsp\n    142d:\t89 7d fc             \tmov    %edi,-0x4(%rbp)\n    1430:\t89 75 f8             \tmov    %esi,-0x8(%rbp)\n    1433:\t83 7d fc 01          \tcmpl   $0x1,-0x4(%rbp)\n    1437:\t75 32                \tjne    146b <_Z41__static_initialization_and_destruction_0ii+0x46>\n    1439:\t81 7d f8 ff ff 00 00 \tcmpl   $0xffff,-0x8(%rbp)\n    1440:\t75 29                \tjne    146b <_Z41__static_initialization_and_destruction_0ii+0x46>\n    1442:\t48 8d 3d 50 2e 00 00 \tlea    0x2e50(%rip),%rdi        # 4299 <_ZStL8__ioinit>\n    1449:\te8 12 fc ff ff       \tcallq  1060 <_ZNSt8ios_base4InitC1Ev@plt>\n    144e:\t48 8d 15 f3 2b 00 00 \tlea    0x2bf3(%rip),%rdx        # 4048 <__dso_handle>\n    1455:\t48 8d 35 3d 2e 00 00 \tlea    0x2e3d(%rip),%rsi        # 4299 <_ZStL8__ioinit>\n    145c:\t48 8b 05 95 2b 00 00 \tmov    0x2b95(%rip),%rax        # 3ff8 <_ZNSt8ios_base4InitD1Ev@GLIBCXX_3.4>\n    1463:\t48 89 c7             \tmov    %rax,%rdi\n    1466:\te8 d5 fb ff ff       \tcallq  1040 <__cxa_atexit@plt>\n    146b:\t90                   \tnop\n    146c:\tc9                   \tleaveq \n    146d:\tc3                   \tretq   \n\n000000000000146e <_GLOBAL__sub_I_main>:\n    146e:\t55                   \tpush   %rbp\n    146f:\t48 89 e5             \tmov    %rsp,%rbp\n    1472:\tbe ff ff 00 00       \tmov    $0xffff,%esi\n    1477:\tbf 01 00 00 00       \tmov    $0x1,%edi\n    147c:\te8 a4 ff ff ff       \tcallq  1425 <_Z41__static_initialization_and_destruction_0ii>\n    1481:\t5d                   \tpop    %rbp\n    1482:\tc3                   \tretq   \n    1483:\t66 2e 0f 1f 84 00 00 \tnopw   %cs:0x0(%rax,%rax,1)\n    148a:\t00 00 00 \n    148d:\t0f 1f 00             \tnopl   (%rax)\n\n0000000000001490 <__libc_csu_init>:\n    1490:\t41 57                \tpush   %r15\n    1492:\t49 89 d7             \tmov    %rdx,%r15\n    1495:\t41 56                \tpush   %r14\n    1497:\t49 89 f6             \tmov    %rsi,%r14\n    149a:\t41 55                \tpush   %r13\n    149c:\t41 89 fd             \tmov    %edi,%r13d\n    149f:\t41 54                \tpush   %r12\n    14a1:\t4c 8d 25 00 29 00 00 \tlea    0x2900(%rip),%r12        # 3da8 <__frame_dummy_init_array_entry>\n    14a8:\t55                   \tpush   %rbp\n    14a9:\t48 8d 2d 08 29 00 00 \tlea    0x2908(%rip),%rbp        # 3db8 <__init_array_end>\n    14b0:\t53                   \tpush   %rbx\n    14b1:\t4c 29 e5             \tsub    %r12,%rbp\n    14b4:\t48 83 ec 08          \tsub    $0x8,%rsp\n    14b8:\te8 43 fb ff ff       \tcallq  1000 <_init>\n    14bd:\t48 c1 fd 03          \tsar    $0x3,%rbp\n    14c1:\t74 1b                \tje     14de <__libc_csu_init+0x4e>\n    14c3:\t31 db                \txor    %ebx,%ebx\n    14c5:\t0f 1f 00             \tnopl   (%rax)\n    14c8:\t4c 89 fa             \tmov    %r15,%rdx\n    14cb:\t4c 89 f6             \tmov    %r14,%rsi\n    14ce:\t44 89 ef             \tmov    %r13d,%edi\n    14d1:\t41 ff 14 dc          \tcallq  *(%r12,%rbx,8)\n    14d5:\t48 83 c3 01          \tadd    $0x1,%rbx\n    14d9:\t48 39 dd             \tcmp    %rbx,%rbp\n    14dc:\t75 ea                \tjne    14c8 <__libc_csu_init+0x38>\n    14de:\t48 83 c4 08          \tadd    $0x8,%rsp\n    14e2:\t5b                   \tpop    %rbx\n    14e3:\t5d                   \tpop    %rbp\n    14e4:\t41 5c                \tpop    %r12\n    14e6:\t41 5d                \tpop    %r13\n    14e8:\t41 5e                \tpop    %r14\n    14ea:\t41 5f                \tpop    %r15\n    14ec:\tc3                   \tretq   \n    14ed:\t0f 1f 00             \tnopl   (%rax)\n\n00000000000014f0 <__libc_csu_fini>:\n    14f0:\tc3                   \tretq   \n\nДизассемблирование раздела .fini:\n\n00000000000014f4 <_fini>:\n    14f4:\t48 83 ec 08          \tsub    $0x8,%rsp\n    14f8:\t48 83 c4 08          \tadd    $0x8,%rsp\n    14fc:\tc3                   \tretq   \n"
  },
  {
    "path": "cpp_algo/lec_07/2_array_param.cpp",
    "content": "#include <iostream>\n\nusing namespace std; // really it's bad to do such way!\n\nint main()\n{\n    int N, M;\n    cin >> N >> M;\n\n    int A[N][M];\n    for(int i = 0; i < N; i++) {\n        for(int j = 0; j < M; j++) {\n            A[i][j] = i*M + j;\n        }\n    }\n\n    for(int i = 0; i < N; i++) {\n        for(int j = 0; j < M; j++) {\n            cout << A[i][j] << '\\t';\n        }\n        cout << '\\n';\n    }\n\n    // memory investigation\n    int *p = reinterpret_cast<int *>(A);\n    for(int i = 0; i < M*N; i++) {\n        cout << *(p + i) << ' ';\n    }\n\n    return 0;\n}\n\n"
  },
  {
    "path": "cpp_algo/lec_07/3_array_param.cpp",
    "content": "#include <iostream>\n\nusing namespace std; // really it's bad to do such way!\n\nconst int M_MAXIMAL = 100;\n\nvoid print_array2d(int A[][M_MAXIMAL], int N, int M)\n{\n    for(int i = 0; i < N; i++) {\n        for(int j = 0; j < M; j++) {\n            cout << A[i][j] << '\\t';\n        }\n        cout << '\\n';\n    }\n}\n\nint main()\n{\n    int N, M;\n    cin >> N >> M;\n\n    int A[N][M_MAXIMAL];\n\n    for(int i = 0; i < N; i++) {\n        for(int j = 0; j < M; j++) {\n            A[i][j] = i*M + j;\n        }\n    }\n\n    print_array2d(A, N, M);\n\n    // memory investigation\n    int *p = reinterpret_cast<int *>(A);\n    for(int i = 0; i < M*N; i++) {\n        cout << *(p + i) << ' ';\n    }\n\n    return 0;\n}\n\n"
  },
  {
    "path": "cpp_algo/lec_07/4_array_param.cpp",
    "content": "#include <iostream>\n\nusing namespace std; // really it's bad to do such way!\n\nvoid print_array2d(int *p, int N, int M)\n{\n    for(int i = 0; i < N; i++) {\n        for(int j = 0; j < M; j++) {\n            cout << p[i*M + j] << '\\t'; // A[i][j]\n        }\n        cout << '\\n';\n    }\n}\n\nint main()\n{\n    int N, M;\n    cin >> N >> M;\n\n    int A[N][M];\n\n    for(int i = 0; i < N; i++) {\n        for(int j = 0; j < M; j++) {\n            A[i][j] = i*M + j;\n        }\n    }\n\n    print_array2d(reinterpret_cast<int*>(A), N, M);\n\n    // memory investigation\n    int *p = reinterpret_cast<int *>(A);\n    for(int i = 0; i < M*N; i++) {\n        cout << *(p + i) << ' ';\n    }\n\n    return 0;\n}\n\n"
  },
  {
    "path": "cpp_algo/lec_07/5_linearized_manually.cpp",
    "content": "#include <iostream>\n\nusing namespace std; // really it's bad to do such way!\n\nvoid print_array2d(int *A, int N, int M)\n{\n    for(int i = 0; i < N; i++) {\n        for(int j = 0; j < M; j++) {\n            cout << A[i*M + j] << '\\t'; // A[i][j]\n        }\n        cout << '\\n';\n    }\n}\n\nint main()\n{\n    int N, M;\n    cin >> N >> M;\n\n    int A[N*M];\n\n    for(int i = 0; i < N; i++) {\n        for(int j = 0; j < M; j++) {\n            A[i*M + j] = i*M + j;\n        }\n    }\n\n    print_array2d(A, N, M);\n\n    return 0;\n}\n\n"
  },
  {
    "path": "cpp_algo/lec_07/6_dynamical.cpp",
    "content": "#include <iostream>\n\nusing namespace std; // really it's bad to do such way!\n\nvoid print_array2d(int *A, int N, int M)\n{\n    for(int i = 0; i < N; i++) {\n        for(int j = 0; j < M; j++) {\n            cout << A[i*M + j] << '\\t'; // A[i][j]\n        }\n        cout << '\\n';\n    }\n}\n\nint main()\n{\n    int N, M;\n    cin >> N >> M;\n\n    // memory allocation\n    int **A = new int*[N];\n    for(int i = 0; i < N; i++) {\n        A[i] = new int[M];\n    }\n\n    for(int i = 0; i < N; i++) {\n        for(int j = 0; j < M; j++) {\n            A[i][j] = i*M + j;\n        }\n    }\n\n    for(int i = 0; i < N; i++) {\n        for(int j = 0; j < M; j++) {\n            cout << A[i][j] << '\\t';\n        }\n        cout << '\\n';\n    }\n\n    for(int i = 0; i < N; i++) {\n        delete[] A[i];\n    }\n    delete[] A;\n\n    return 0;\n}\n\n"
  },
  {
    "path": "cpp_algo/lec_07/7_dynamical.cpp",
    "content": "#include <iostream>\n\nusing namespace std; // really it's bad to do such way!\n\nvoid print_array2d(int *A, int N, int M)\n{\n    for(int i = 0; i < N; i++) {\n        for(int j = 0; j < M; j++) {\n            cout << A[i*M + j] << '\\t'; // A[i][j]\n        }\n        cout << '\\n';\n    }\n}\n\nint main()\n{\n    int N, M;\n    cin >> N >> M;\n\n    // memory allocation\n    int **A = new int*[N];\n    A[0] = new int[N*M];\n    for(int i = 1; i < N; i++) {\n        A[i] = A[0] + M*i;\n    }\n\n    for(int i = 0; i < N; i++) {\n        for(int j = 0; j < M; j++) {\n            A[i][j] = i*M + j;\n        }\n    }\n\n    for(int i = 0; i < N; i++) {\n        for(int j = 0; j < M; j++) {\n            cout << A[i][j] << '\\t';\n        }\n        cout << '\\n';\n    }\n\n    print_array2d(A[0], M, N);\n\n    delete[] A[0];\n    delete[] A;\n\n    return 0;\n}\n\n"
  },
  {
    "path": "cpp_algo/lec_08/bin_search.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nint left_bound(int A[], int N, int x)\n{\n    int left = -1;  // A[left] < x\n    int right = N;  // A[right] >= x\n    while (right - left > 1) {\n        int middle = (left + right) / 2;\n        if (A[middle] < x)\n            left = middle;\n        else\n            right = middle;\n    }    \n    return left;\n}\n\nint find(int A[], int N, int x)\n{\n    int left = left_bound(A, N, x);\n    int potential_first_index_of_x_in_A = left + 1;\n    if (potential_first_index_of_x_in_A < N and \n        A[potential_first_index_of_x_in_A] == x)\n        return potential_first_index_of_x_in_A;\n    else\n        return -1; // x not found\n\n}\n\nint main()\n{\n    int N = 10;\n    int A[] = {1, 3, 3, 7, 7, 7, 7, 9, 10, 10};\n    int x;\n\n    for(int i = 0; i < N; i++)\n        cout << A[i] << '\\t';\n    cout << '\\n';\n    cin >> x;\n    cout << \"left boundary of x is: \" << left_bound(A, N, x) << '\\n';\n\n    return 0;\n}\n\n"
  },
  {
    "path": "cpp_algo/lec_08/count_sort.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nvoid count_sort(int A[], int N)\n{\n    // Я ОБЯЗАН знать диапазон сортируемых чисел (считаю, что они от 0 до 9)\n    int F[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};\n    for(int i = 0; i < N; i++) {\n        F[A[i]]++;\n    }\n    int i = 0;\n    for(int x = 0; x < 10; x++) {  // перебираю всевозможные значения ключа! (их M штук)\n        for(int k = 0; k < F[x]; k++) {\n            A[i] = x;\n            i++;\n        }\n    }\n}\n\nvoid generate_random_array(int A[], int N, int M)\n{\n    for(int i = 0; i < N; i++)\n        A[i] = rand() % M;\n}\n\nvoid print_array(int A[], int N)\n{\n    for(int i = 0; i < N; i++)\n        cout << A[i] << '\\t';\n    cout << '\\n';\n}\n\nint main()\n{\n    int N = 10;\n    int A[N];\n\n    generate_random_array(A, N, 10);\n    print_array(A, N);\n    count_sort(A, N);\n    print_array(A, N);\n\n    return 0;\n}\n\n"
  },
  {
    "path": "cpp_algo/lec_08/lin_search.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nint find(int A[], int N, int x)\n{\n    for(int i = 0; i < N; i++)\n        if (A[i] == x)\n            return i;\n    return -1;\n}\n\nint main()\n{\n    int N = 10;\n    int A[] = {1, 3, 3, 7, 7, 7, 7, 9, 10, 10};\n    int x;\n\n    for(int i = 0; i < N; i++)\n        cout << A[i] << '\\t';\n    cout << '\\n';\n    cin >> x;\n    cout << \"index of x is: \" << find(A, N, x) << '\\n';\n\n    return 0;\n}\n\n"
  },
  {
    "path": "cpp_algo/lec_08/radix_sort.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nvoid radix_sort(int *A, int N)\n{\n    int *a0 = new int[N];\n    int *a1 = new int[N];\n    \n    for(int radix = 0; radix < 32; radix++) {\n        int a0_size = 0;\n        int a1_size = 0;\n        for(int i = 0; i < N; i++) {\n            if ((A[i] & (1 << radix)) == 0)\n                a0[a0_size++] = A[i];\n            else\n                a1[a1_size++] = A[i];\n        }\n        for(int i = 0; i < a0_size; i++)\n            A[i] = a0[i];\n        for(int i = 0; i < a1_size; i++)\n            A[a0_size + i] = a1[i];\n    }\n    delete[] a0;\n    delete[] a1;\n}\n\nvoid generate_random_array(int A[], int N, int M)\n{\n    for(int i = 0; i < N; i++)\n        A[i] = rand() % M;\n}\n\nvoid print_array(int A[], int N)\n{\n    for(int i = 0; i < N; i++)\n        cout << A[i] << '\\t';\n    cout << '\\n';\n}\n\nint main()\n{\n    int N = 10;\n    int A[N];\n\n    generate_random_array(A, N, 1000);\n    print_array(A, N);\n    radix_sort(A, N);\n    print_array(A, N);\n\n    return 0;\n}\n\n"
  },
  {
    "path": "cpp_algo/lec_09/1_factorial.cpp",
    "content": "/**\n* Factorial really should not be writter with recursion!\n*/\n\n#include <iostream>\n\nint64_t factorial(int16_t n)\n{\n    std::cout << \"factorial(\" << n << \") is called. \\n\";\n    int64_t result;\n    if (n == 0) {  // base case:\n        result = 1;\n    } else {       // recurrent case: \n        result = factorial(n - 1)*n;\n    }\n    std::cout << \"factorial(\" << n << \") is exitting.\\n\";\n    return result;\n}\n\n\nint main()\n{\n    int16_t x;\n    std::cin >> x;\n    std::cout << factorial(x) << '\\n';\n\n    return 0;\n}\n"
  },
  {
    "path": "cpp_algo/lec_09/2_main.cpp",
    "content": "#include <iostream>\n\nint main(int argc, char *argv[])\n{\n    if (argc > 1)\n        return main(argc - 1, argv) * argc;\n    else\n        return 1;\n}\n"
  },
  {
    "path": "cpp_algo/lec_09/3_euclid.cpp",
    "content": "#include <iostream>\n\nint gcd(int a, int b)\n{\n    return (b == 0) ? a : gcd(b, a % b);\n}\n\nint main()\n{\n    int a, b;\n    std::cin >> a >> b;\n    std::cout << gcd(a, b) << '\\n';\n    return 0;\n}\n\n"
  },
  {
    "path": "cpp_algo/lec_09/4_hanoi.cpp",
    "content": "#include <iostream>\n\n/**\n* Hanoi solution finder.\n* param i: start pin number\n* param k: finish pin number\n* param n: number of disks\n*/\n\nvoid hanoi(int i, int k, int n)\n{\n    if (n == 1) {\n        std::cout << \"Move disk 1 from pin \" << i \n                  << \" to pin \" << k << \".\\n\";\n    } else {\n        int tmp = 6 - i - k; // third pin (temporary)\n        hanoi(i, tmp, n - 1);\n        std::cout << \"Move disk \" << n << \" from pin \" << i \n                  << \" to pin \" << k << \".\\n\";\n        hanoi(tmp, k, n - 1);\n    }\n}\n\nint main()\n{\n    hanoi(1, 2, 4);\n\n    return 0;\n}\n"
  },
  {
    "path": "cpp_algo/lec_09/5_bin_gen.cpp",
    "content": "#include <iostream>\n\nconst int MAX_BINARY_DIGITS_TO_GENERATE = 100;\n\nvoid generate_binary_numbers(int digits_left_to_generate)\n{\n    static int digits_combination[MAX_BINARY_DIGITS_TO_GENERATE];\n    static int top = 0;\n\n    if (digits_left_to_generate == 0) {  // base case\n        for(int i = 0; i < top; i++)\n            std::cout << digits_combination[i];\n        std::cout << '\\n';\n    } else {  // recursive case\n        digits_combination[top++] = 1;\n        generate_binary_numbers(digits_left_to_generate - 1);\n        top--;\n\n        digits_combination[top++] = 0;\n        generate_binary_numbers(digits_left_to_generate - 1);\n        top--;\n    }\n\n}\n\n\nint main()\n{\n    int n;\n    std::cout << \"Enter bin number length: \";\n    std::cin >> n;\n    generate_binary_numbers(n);\n    return 0;\n}\n"
  },
  {
    "path": "cpp_algo/lec_10/1_permutations.cpp",
    "content": "#include <iostream>\n\nconst int MAX_BINARY_DIGITS_TO_GENERATE = 100;\n\nvoid permutations(int16_t number, int16_t current, int16_t buffer[], bool used[])\n{\n    if (current == number) {  // base case\n        for(int i = 0; i < number; i++)\n            std::cout << buffer[i] << ' ';\n        std::cout << '\\n';\n    } else {  // recursive case\n        for (int16_t variant = 0; variant < number; variant++) {\n            if (not used[variant]) { // cutting the recursive tree\n                buffer[current] = variant;\n                used[variant] = true;\n                permutations(number, current + 1, buffer, used);\n                used[variant] = false;\n            }\n        }\n    }\n}\n\n\nint main()\n{\n    int16_t n;\n    std::cout << \"Enter length to generate all permutations: \";\n    std::cin >> n;\n    if (n > 20) {\n        std::cerr << \"Your number is too big!\";\n        return 1;\n    } else if (n <= 0) {\n        std::cerr << \"Your number is negative!\";\n        return 1;\n    }\n\n    int16_t buffer[n];\n    bool used[n] = {false}; // suspect that used will be initialized by zeroes (to be interpreted as false)\n    permutations(n, 0, buffer, used);\n\n    return 0;\n}\n\n"
  },
  {
    "path": "cpp_algo/lec_10/2_merge_sort.cpp",
    "content": "#include <iostream>\n#include <array>\n\nconst int MAX_ARRAY_SIZE = 100000;\n\nvoid merge_sort(double *array, int16_t array_size)\n{\n    if (array_size <= 1) return;  // base case. Critical to implement it!!!\n        \n    int16_t middle = array_size / 2;\n    double *left = array;\n    double *right = array + middle;\n    // BEWARE! Using address arithmetics: pointer + number gives shifted array begin\n    int16_t left_size = middle;\n    int16_t right_size = array_size - left_size;\n\n    // recursion goes here:\n    merge_sort(left, left_size);\n    merge_sort(right, right_size);\n    \n    // Merge these two already sorted parts of array:\n    double *buffer = new double[array_size];\n    int16_t left_i = 0;\n    int16_t right_i = 0;\n    int16_t buffer_i = 0;\n    while (left_i < left_size and right_i < right_size) {\n        if (left[left_i] <= right[right_i]) {\n            // taking the lesser from the left part of array\n            buffer[buffer_i] = left[left_i];\n            left_i += 1;\n            buffer_i += 1;\n        } else {\n            // taking the lesser from the right part of array\n            buffer[buffer_i] = right[right_i];\n            right_i += 1;\n            buffer_i += 1;\n        }\n    }\n    while (left_i < left_size) { // copying left elements from the left size (if there is left something)\n        buffer[buffer_i] = left[left_i];\n        left_i += 1;\n        buffer_i += 1;\n    }\n    while (right_i < right_size) { // copying right elements from the right size (if there is right something)\n        buffer[buffer_i] = right[right_i];\n        right_i += 1;\n        buffer_i += 1;\n    }\n    \n    // copying from buffer to original array:\n    for(int16_t i = 0; i < array_size; i++) {\n        array[i] = buffer[i];\n    }\n    delete[] buffer;\n}\n\nvoid input_array(double *array, int16_t n)\n{\n    for (int i = 0; i < n; i++) {\n        std::cin >> array[i];\n    }\n}\n\nvoid print_array(double *array, int16_t n)\n{\n    for (int i = 0; i < n; i++) {\n        std::cout << array[i] << ' ';\n    }\n    std::cout << '\\n';\n}\n\nint main()\n{\n    int16_t array_size;\n    std::cout << \"Enter size of array: \";\n    std::cin >> array_size;\n    if (array_size <= 0 or array_size > MAX_ARRAY_SIZE) {\n        std::cerr << \"Your array size is unacceptable!\\n\";\n        return 1;\n    }\n    double *array = new double[array_size];\n    \n    input_array(array, array_size);\n    merge_sort(array, array_size);\n    print_array(array, array_size);\n\n    delete[] array;\n\n    return 0;\n}\n"
  },
  {
    "path": "cpp_algo/lec_11/1_fibonacci.cpp",
    "content": "#include <iostream>\n#include <cassert>\n\n\nuint64_t fib_recursive(int n)\n{\n    assert(n >= 0);\n\n    if (n == 0 or n == 1) {\n        return n;\n    } else {\n        return fib_recursive(n-1) + fib_recursive(n-2);\n    }\n}\n\nuint64_t fib_dynamic(int n)\n{\n    uint64_t result;\n    uint64_t *fib = new uint64_t[n + 1];\n    fib[0] = 0;\n    fib[1] = 1;\n    for (int i = 2; i <= n; i++) {\n        fib[i] = fib[i-1] + fib[i-2];\n    }\n    \n    result = fib[n];\n    delete[] fib;\n    return result;\n}\n\n\nint main()\n{\n    uint64_t (*fib)(int);\n    int version = 0;\n    std::cout << \"Which version of Fibonacci function to use? (0 - recursive, 1 - dynamic)\\n\";\n    std::cin >> version;\n    if (version == 0) {\n        fib = fib_recursive;\n    } else {\n        fib = fib_dynamic;\n    }\n\n    for (int n = 0; n <= 100; n++) {\n        std::cout << n << '\\t' << fib(n) << '\\n';\n    }\n\n    return 0;\n}\n"
  },
  {
    "path": "cpp_algo/lec_11/2_hopper_economist.cpp",
    "content": "#include <iostream>\n#include <cassert>\n\n\nint min_cost(int n, int price[])\n{\n    int cost[n + 1];\n    // base cases:\n    cost[1] = price[1];\n    cost[2] = price[1] + price[2];\n\n    for (int i = 3; i <= n; i++) {\n        // recursive case:\n        cost[i] = std::min(cost[i-1], cost[i-2]) + price[i];\n    }\n    \n    std::cout << \"Min cost path (reversed) = [\";\n    int current = n;\n    std::cout << current << \" \";\n    while(current != 1) {\n        if (cost[current - 1] == cost[current] - price[current])\n            current = current - 1;\n        else if (cost[current - 2] == cost[current] - price[current])\n            current = current - 2;\n        else\n            throw -1; // Nonsence! I should never achive this line!\n        std::cout << current << \" \";\n    }\n    std::cout << \"]\\n\";\n    \n    return cost[n];\n}\n\n\nint main()\n{\n    int n;\n    std::cout << \"Hopper economist wants to go from point 1 to point n. Enter n:\\n\";\n    std::cin >> n;\n    if (n > 100) {\n        std::cout << \"Your number is too big! maximum is 100.\\n\";\n        return -1;\n    }\n    int price[101];\n    std::cout << \"Enter prices of visiting point (from point 1 to point n):\\n\";\n    for (int i = 1; i <= n; i++) {\n        std::cin >> price[i];\n    }\n   \n    std::cout << \"Min cost of achieving point n from point 1 is \" << min_cost(n, price) << '\\n';\n\n    return 0;\n}\n"
  },
  {
    "path": "cpp_algo/lec_12/1_ant.cpp",
    "content": "#include <iostream>\n#include <cassert>\n\n\nuint64_t combinations_recursive(int i, int j)\n{\n    assert(i > 0 and j > 0);\n\n    if (i == 1 or j == 1) {\n        return 1;\n    } else {\n        return combinations_recursive(i, j-1) + combinations_recursive(i-1, j);\n    }\n}\n\nuint64_t combinations_dynamic(int n, int m)\n{\n    uint64_t result;\n    // memory allocation for K function:\n    uint64_t **K = new uint64_t*[n + 1];\n    for(int i = 0; i <= n; i++) {\n        K[i] = new uint64_t[m + 1];\n    }\n\n    // base cases:\n    for (int i = 1; i <= n; i++) {\n        K[i][1] = 1;\n    }\n    for (int j = 1; j <= m; j++) {\n        K[1][j] = 1;\n    }\n\n    // recursive cases:\n    for (int i = 2; i <= n; i++) {\n        for (int j = 2; j <= m; j++) {\n            K[i][j] = K[i-1][j] + K[i][j-1];\n        }\n    }\n    \n    // return value with correct liberation of allocated memory\n    result = K[n][m];\n    for(int i = 0; i <= n; i++)\n        delete K[i];\n    delete[] K;\n    return result;\n}\n\n\nint main()\n{\n    uint64_t (*combinations)(int, int);\n    int version = 0;\n    std::cout << \"Which version of function to use? (0 - recursive, 1 - dynamic)\\n\";\n    std::cin >> version;\n    if (version == 0) {\n        combinations = combinations_recursive;\n    } else {\n        combinations = combinations_dynamic;\n    }\n\n    for (int i = 1; i <= 30; i++) {\n        for (int j = 1; j <= 12; j++) {\n            std::cout << combinations(i, j) << '\\t';\n        }\n        std::cout << '\\n';\n    }\n\n    return 0;\n}\n"
  },
  {
    "path": "cpp_algo/lec_12/2_ant_array.cpp",
    "content": "#include <iostream>\n#include <cassert>\n#include <vector>\n\n\nuint64_t combinations_recursive(int i, int j)\n{\n    assert(i > 0 and j > 0);\n\n    if (i == 1 or j == 1) {\n        return 1;\n    } else {\n        return combinations_recursive(i, j-1) + combinations_recursive(i-1, j);\n    }\n}\n\nuint64_t combinations_dynamic(int n, int m)\n{\n    std::vector<std::vector<uint64_t>> K;\n    K.resize(n + 1);\n    for (int i = 1; i <= n; i++) {\n        K[i].resize(m + 1);\n    }\n\n    // base cases:\n    for (int i = 1; i <= n; i++) {\n        K[i][1] = 1;\n    }\n    for (int j = 1; j <= m; j++) {\n        K[1][j] = 1;\n    }\n\n    // recursive cases:\n    for (int i = 2; i <= n; i++) {\n        for (int j = 2; j <= m; j++) {\n            K[i][j] = K[i-1][j] + K[i][j-1];\n        }\n    }\n    \n    return K[n][m];\n}\n\n\nint main()\n{\n    uint64_t (*combinations)(int, int);\n    int version = 0;\n    std::cout << \"Which version of function to use? (0 - recursive, 1 - dynamic)\\n\";\n    std::cin >> version;\n    if (version == 0) {\n        combinations = combinations_recursive;\n    } else {\n        combinations = combinations_dynamic;\n    }\n\n    for (int i = 1; i <= 30; i++) {\n        for (int j = 1; j <= 12; j++) {\n            std::cout << combinations(i, j) << '\\t';\n        }\n        std::cout << '\\n';\n    }\n\n    return 0;\n}\n"
  },
  {
    "path": "cpp_algo/lec_12/3_bagpack.cpp",
    "content": "#include <iostream>\n#include <cassert>\n#include <vector>\n\n\ndouble max_backpack_value(std::vector<std::pair<int, double>> treasures,\n                            int capacity)\n{\n    // 2D array of answers - to be filled in.\n    std::vector<std::vector<double>> F;\n    F.resize(capacity + 1);\n    for (int i = 0; i <= capacity; i++) {\n        F[i].resize(treasures.size() + 1);\n    }\n    std::cout << \"DEBUG 1\\n\";\n\n    // base cases:\n    for (int i = 0; i <= capacity; i++) {\n        F[i][0] = 0;\n    }\n    for (int j = 0; j <= treasures.size(); j++) {\n        F[0][j] = 0;\n    }\n    std::cout << \"DEBUG 2\\n\";\n\n    // recursive cases:\n    for (int j = 1; j <= treasures.size(); j++) {\n        int weight = treasures[j-1].first;\n        double value = treasures[j-1].second;\n\n        for (int k = 1; k < weight; k++) {\n            F[k][j] = F[k][j-1];\n        }\n        for (int k = weight; k <= capacity; k++) {\n            F[k][j] = std::max(F[k][j-1], value + F[k-weight][j-1]);\n        }\n    }\n    \n    return F[capacity][treasures.size()];\n}\n\n\nint main()\n{\n    int treasures_number;\n    std::cout << \"Enter number of treasures:\";\n    std::cin >> treasures_number;\n\n    std::vector<std::pair<int, double>> treasures;\n    for (int i = 0; i < treasures_number; i++) {\n        int weight;\n        double value;\n        std::cout << \"Enter treasure[\" << i << \"] weight and value:\";\n        std::cin >> weight >> value;\n        treasures.push_back(std::make_pair(weight, value));\n    }\n\n    int capacity;\n    std::cout << \"Enter backpack carrying capacity:\";\n    std::cin >> capacity;\n\n    std::cout << max_backpack_value(treasures, capacity) << '\\n';\n\n    return 0;\n}\n"
  },
  {
    "path": "cpp_algo/lec_12/input_data.txt",
    "content": "4\n2 3\n3 1\n5 6\n1 2\n5\n"
  },
  {
    "path": "cpp_algo/lec_13/1_strcat_problem.cpp",
    "content": "#include <cstring>\n#include <cstdlib>\n#include <cstdio>\n\nint main()\n{\n    const char *s = \"Hello, World! \";\n    printf(\"%s\\n\", s);\n    printf(\"strlen(s) = %d\\n\", strlen(s));\n\n    int times_to_concatenate;\n    scanf(\"%d\", &times_to_concatenate);\n\n    size_t buffer_length = strlen(s) * times_to_concatenate + 1;\n    char *buffer = (char*) malloc(buffer_length * sizeof(char));\n    buffer[0] = '\\0';\n    printf(\"%s\\n\", buffer);\n    \n    for (int i = 0; i < times_to_concatenate; i++) {\n        strcat(buffer, s);\n    }\n    //printf(\"%s\\n\", buffer);\n    \n    free(buffer);\n    return 0;\n}\n\n\n"
  },
  {
    "path": "cpp_algo/lec_13/2_strcat_solution.cpp",
    "content": "#include <string>\n#include <iostream>\n\n\nint main()\n{\n    // This is used to speedup input in automatic testing:\n    std::ios_base::sync_with_stdio(false);\n    std::cin.tie(nullptr);\n\n    std::string hello = \"Hello, World! \";\n    std::string result;\n\n    std::cout << hello << std::endl;\n    int times_to_concatenate;\n    std::cin >> times_to_concatenate;\n    \n    for (int i = 0; i < times_to_concatenate; i++) {\n        result += hello;\n    }\n\n    //std::cout << result << std::endl;\n    return 0;\n}\n"
  },
  {
    "path": "cpp_algo/lec_13/3_levenstein.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <string>\n\n\nint levenstein_distance(std::string a, std::string b)\n{\n    // 2D array of answers - to be filled in.\n    std::vector<std::vector<int>> L;\n    L.resize(a.length() + 1);\n    for (int i = 0; i <= a.length(); i++) {\n        L[i].resize(b.length() + 1);\n    }\n\n    // base cases:\n    for (int i = 0; i <= a.length(); i++) {\n        L[i][0] = i;\n    }\n    for (int k = 0; k <= b.length(); k++) {\n        L[0][k] = k;\n    }\n\n    // recursive cases:\n    for (int i = 1; i <= a.length(); i++) {\n        for (int k = 1; k <= b.length(); k++) {\n            if (a[i-1] == b[k-1]) // Last chars are the same!\n                L[i][k] = L[i-1][k-1];\n            else  // Last chars are different - so we need to add or remove last in a or b.\n                L[i][k] = std::min(std::min(L[i-1][k], L[i][k-1]), L[i-1][k-1]) + 1;\n        }\n    }\n    \n    return L[a.length()][b.length()];\n}\n\n\nint main()\n{\n    std::string a, b;\n    std::cout << \"Enter string A:\";\n    std::cin >> a;\n    std::cout << \"Enter string B:\";\n    std::cin >> b;\n\n    std::cout << \"Levenstein distance between A and B is:\";\n    std::cout << levenstein_distance(a, b) << '\\n';\n\n    return 0;\n}\n"
  },
  {
    "path": "cpp_algo/lec_14/1_vector_list.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <list>\n#include <string>\n\nvoid vector_example()\n{\n    std::vector<std::string> words;\n    std::string word;\n\n    getline(std::cin, word);\n    while (word != \"\") {\n        words.push_back(word);\n        getline(std::cin, word);\n    }\n    \n    for(int i = 0; i < words.size(); ++i) {\n        std::cout << words[i] << '\\t';\n    }\n    std::cout << std::endl;\n}    \n\nvoid list_example()\n{\n    std::list<std::string> words;\n    std::string word;\n\n    getline(std::cin, word);\n    while (word != \"\") {\n        words.push_back(word);\n        getline(std::cin, word);\n    }\n    \n    for(std::list<std::string>::iterator p = words.begin(); p != words.end(); ++p) {\n        std::cout << *p << '\\t';\n    }\n    std::cout << std::endl;\n\n    for(auto p = words.begin(); p != words.end(); ++p) {\n        std::cout << *p << '\\t';\n    }\n    for(auto &word: words) {\n        std::cout << word << '\\t';\n    }\n    std::cout << std::endl;\n}    \n\nint main()\n{\n    list_example();\n    return 0;\n}\n"
  },
  {
    "path": "cpp_algo/lec_14/2_kmp.cpp",
    "content": "#include <string>\n#include <iostream>\n#include <vector>\n\nstd::vector<int> prefix_function_kmp(std::string s)\n{\n    int n = s.length();\n    std::vector<int> pi(n, 0);\n    for (int i = 1; i < n; ++i) {\n        int k = pi[i-1];\n        while (k > 0 and s[i] != s[k]) {\n            k = pi[k-1];\n        }\n        if (s[i] == s[k])\n            k += 1;\n        pi[i] = k;\n    }\n    return pi;\n}\n\nint main()\n{\n    std::string line;\n    getline(std::cin, line);\n    std::string tmp;\n    getline(std::cin, tmp);\n\n    std::string summary = tmp + '#' + line;\n    std::vector<int> pi = prefix_function_kmp(summary);\n    \n    int counter = 0;\n    for (auto x: pi) {\n        if (x == tmp.size())\n            counter++;\n    }\n    std::cout << \"Number of cases template is substring in string: \" << counter << std::endl;\n}\n"
  },
  {
    "path": "cpp_algo/lec_15/01_vector_usage.cpp",
    "content": "#include <vector>\n#include <iostream>\n#include <algorithm>\n\nvoid procedure(int x)\n{\n    std::cout << x << '\\n';\n}\n\n\nint main()\n{\n    std::vector<int> A;\n\n    for(int i = 0; i < 10; i++)\n        A.push_back(i);\n    \n    // НЕУКЛЮЖАЯ ВЕРСИЯ:\n    std::vector<int>::iterator it1 = A.begin();\n    while (it1 != A.end()) {\n        std::cout << *it1 << \"\\n\";\n        ++it1;\n    }\n    // почти УКЛЮЖАЯ ВЕРСИЯ:\n    auto it2 = A.begin();\n    while (it2 != A.end()) {\n        std::cout << *it2 << \"\\n\";\n        ++it2;\n    }\n    for (auto it3 = A.begin(); it3 != A.end(); ++it3) {\n        std::cout << *it3 << \"\\n\";\n    }\n\n    std::cout << \"for_each:\\n\";\n    std::for_each(A.begin(), A.end(), procedure);\n\n    std::cout << \"range based for:\\n\";\n    for (auto x: A) {\n        std::cout << x << ' ';\n    }\n\n    return 0;\n}\n"
  },
  {
    "path": "cpp_algo/lec_15/02_list_usage.cpp",
    "content": "#include <list>\n#include <iostream>\n#include <algorithm>\n\nvoid procedure(int x)\n{\n    std::cout << x << '\\n';\n}\n\n\nint main()\n{\n    std::list<int> A;\n\n    for(int i = 0; i < 10; i++)\n        A.push_back(i);\n    \n    // НЕУКЛЮЖАЯ ВЕРСИЯ:\n    std::list<int>::iterator it1 = A.begin();\n    while (it1 != A.end()) {\n        std::cout << *it1 << \"\\n\";\n        ++it1;\n    }\n    // почти УКЛЮЖАЯ ВЕРСИЯ:\n    auto it2 = A.begin();\n    while (it2 != A.end()) {\n        std::cout << *it2 << \"\\n\";\n        ++it2;\n    }\n    for (auto it3 = A.begin(); it3 != A.end(); ++it3) {\n        std::cout << *it3 << \"\\n\";\n    }\n\n    std::cout << \"for_each:\\n\";\n    std::for_each(A.begin(), A.end(), procedure);\n\n    std::cout << \"range based for:\\n\";\n    for (auto x: A) {\n        std::cout << x << ' ';\n    }\n\n    return 0;\n}\n"
  },
  {
    "path": "cpp_algo/lec_16/1_simple_class.cpp",
    "content": "#include <iostream>\n#include <string>\n\n// Developer #1\nstruct Student\n{\nprivate:\n    std::string name;\n    std::string group;\n    int age;\n    double *memory;\n\npublic:\n    Student(std::string name_, std::string group_, int age_)\n    {\n        name = name_;\n        group = group_;\n        age = age_;\n        std::cout << \"Hooray!!! Me \" << name << \" enrolled to the course!\\n\";\n        //RESOURCE ALLOCATION\n        memory = new double[100];\n    }\n\n    ~Student()\n    {\n        std::cout << \"Ouch!!! Me \" << name << \" dismissed from the course!\\n\";\n        //RESOURCE DEALLOCATION\n        delete[] memory;\n    }\n\n    void print() const\n    {\n        std::cout << name << \" \" << group << \" \";\n        std::cout << age << \"\\n\";\n    }\n\n    void ageing()\n    {\n        std::cout << \"Hooray!!! Today is my birthday! I'm \" << name << '\\n';\n        age += 1;\n        print(); //the same as this->print()\n    }\n};\n\n// Developer #2\nint main()\n{\n    Student a(\"Petya\", \"B02-991\", 18);\n\n    a.print();\n    a.ageing();\n    a.print();\n\n    Student b(\"Vasya\", \"B012\", 17);\n    b.print();\n    b = a; // RAII concept is broken HERE!\n    b.print();\n}\n\n\n"
  },
  {
    "path": "cpp_algo/lec_16/2_overloading.cpp",
    "content": "#include <iostream>\n\nvoid foo(unsigned char x)\n{\n    std::cout << \" foo(unsigned char) is called\\n\";\n}\n\nvoid foo(int x)\n{\n    std::cout << \" foo(int) is called\\n\";\n}\n\nvoid foo(double x)\n{\n    std::cout << \" foo(double) is called\\n\";\n}\n\n\nint main()\n{\n    foo('A');\n    foo(1);\n    foo(4.5);\n    foo(23U); //delete to make code work\n\n    return 0;\n}\n"
  },
  {
    "path": "cpp_algo/lec_16/3_abs_template.cpp",
    "content": "#include <iostream>\n\ntemplate <typename T>\nT my_abs(T x)\n{\n    if (x < 0)\n        return -x;\n    else\n        return x;\n}\n\nint main()\n{\n    std::cout << my_abs('A') << \"\\n\";\n    std::cout << my_abs(-23) << \"\\n\";\n    std::cout << my_abs(-3.5) << \"\\n\";\n\n    return 0;\n}\n"
  },
  {
    "path": "cpp_algo/lec_17/1_fin_automata_1.cpp",
    "content": "#include <iostream>\n#include <string>\n\ninline bool is_alpha(char symbol)\n{\n    return (symbol >= 'a' and symbol <= 'z') or\n           (symbol >= 'A' and symbol <= 'Z');\n}\n\nint main()\n{\n    std::string s;\n    std::getline(std::cin, s);\n    int word_len = 0;\n    int pos = 0;\nout_of_word:\n    if (pos >= s.length()) goto the_end;\n    if (is_alpha(s[pos])) {\n        pos++;\n        word_len = 1;\n        goto in_word;\n    } else {\n        pos++;\n        goto out_of_word;\n    }\nin_word:\n    if (pos >= s.length()) goto the_end;\n    if (is_alpha(s[pos])) {\n        pos++;\n        word_len += 1;\n        goto in_word;\n    } else {\n        pos++;\n        std::cout << \"Word length: \" << word_len << '\\n';\n        goto out_of_word;\n    }\nthe_end:\n\n\n    std::cout << s << '\\n';\n\n    return 0;\n}\n"
  },
  {
    "path": "cpp_algo/lec_17/2_fin_automata_2.cpp",
    "content": "#include <iostream>\n#include <string>\n\nenum AutomataState{\n    out_of_word = 0,\n    in_word = 1\n};\n\ninline bool is_alpha(char symbol)\n{\n    return (symbol >= 'a' and symbol <= 'z') or\n           (symbol >= 'A' and symbol <= 'Z');\n}\n\nint main()\n{\n    std::string s;\n    std::getline(std::cin, s);\n    int word_len = 0;\n\n    AutomataState state = out_of_word;\n\n    for (int pos = 0; pos < s.length(); pos++) {\n        switch(state) {\n            case out_of_word:\n                if (is_alpha(s[pos])) {\n                    word_len = 1;\n                    state = in_word;\n                } else {\n                    state = out_of_word;\n                }\n                break;\n            case in_word:\n                if (is_alpha(s[pos])) {\n                    word_len += 1;\n                    state = in_word;\n                } else {\n                    std::cout << \"Word length: \" << word_len << '\\n';\n                    state = out_of_word;\n                }\n        }\n    }\n\n    std::cout << s << '\\n';\n\n    return 0;\n}\n"
  },
  {
    "path": "cpp_algo/lec_18/rabin_karp.cpp",
    "content": "#include <iostream>\n#include <string>\n\nconst P = 257;\n\nuint32_t hash(std::string s)\n{\n    uint32_t sum = 0;\n    uint32_t factor = 1;\n    \n    for(int i = s.length() - 1; i >= 0; i--) {\n        sum += s[i]*factor;\n        factor *= P;\n    }\n} \n\nint main()\n{\n    std::string s;\n    std::getline(std::cin, s);\n\n    std::string pattern;\n    std::getline(std::cin, pattern);\n    uint32_t pattern_hash = hash(pattern);\n\n    uint32 M = pattern.length();\n    \n    uint32_t pattern_hash = hash(s);\n    \n\n\n    return 0;\n}\n\n"
  },
  {
    "path": "cpp_algo/lec_20/1_set.cpp",
    "content": "#include <iostream>\n#include <set>\n#include <string>\n\nvoid set_example()\n{\n    std::set<std::string> words;\n    std::string word;\n\n    getline(std::cin, word);\n    while (word != \"\") {\n        words.insert(word);\n        getline(std::cin, word);\n    }\n\n    for(auto &word: words) {\n        std::cout << word << '\\t';\n    }\n    std::cout << std::endl;\n\n    std::cout << \"Enter key to find in set: \";\n    std::cin >> word;\n\n    if (words.find(word) != words.end()) {\n        std::cout  << \"Found it!\\n\";\n    } else {\n        std::cout  << \"Not found it...\\n\";\n    }\n}\n\nint main()\n{\n    set_example();\n    return 0;\n}\n"
  },
  {
    "path": "cpp_algo/lec_20/2_unordered_set.cpp",
    "content": "#include <iostream>\n#include <unordered_set>\n#include <string>\n\nvoid set_example()\n{\n    std::unordered_set<std::string> words;\n    std::string word;\n\n    getline(std::cin, word);\n    while (word != \"\") {\n        words.insert(word);\n        getline(std::cin, word);\n    }\n\n    for(auto &word: words) {\n        std::cout << word << '\\t';\n    }\n    std::cout << std::endl;\n\n    std::cout << \"Enter key to find in set: \";\n    std::cin >> word;\n\n    if (words.find(word) != words.end()) {\n        std::cout  << \"Found it!\\n\";\n    } else {\n        std::cout  << \"Not found it...\\n\";\n    }\n}\n\nint main()\n{\n    set_example();\n    return 0;\n}\n"
  },
  {
    "path": "cpp_algo/lec_20/set_input.txt",
    "content": "pear\napple\ncarrot\ncabbage\ncucumber\nsalad\npotato\nonion\n\napple\n"
  },
  {
    "path": "cpp_algo/lec_21/1.txt",
    "content": "// SOme text is here.\n"
  },
  {
    "path": "cpp_algo/lec_21/2_euclid.cpp",
    "content": "#include <iostream>\n\nint euclid_gcd(int a, int b)\n{   // Алгоритм Евклида поиска НОД\n    while (a != b) {\n        if (a > b) {\n            a -= b;\n        } else {\n            b -= a;\n        }\n    }\n    return a;\n}\n\nint main()\n{\n    using namespace std;\n    int x, y;\n\n    cout << \"Enter integer. x = \";\n    cin >> x;\n    cout << \"Enter integer. y = \";\n    cin >> y;\n    cout << \"GCD(x, y) = \" << euclid_gcd(x, y) << endl;\n\n    return 0;\n}\n"
  },
  {
    "path": "cpp_algo/lec_21/2_euclid.s",
    "content": "\t.file\t\"2_euclid.cpp\"\n\t.text\n\t.section\t.rodata\n\t.type\t_ZStL19piecewise_construct, @object\n\t.size\t_ZStL19piecewise_construct, 1\n_ZStL19piecewise_construct:\n\t.zero\t1\n\t.local\t_ZStL8__ioinit\n\t.comm\t_ZStL8__ioinit,1,1\n\t.text\n\t.globl\t_Z10euclid_gcdii\n\t.type\t_Z10euclid_gcdii, @function\n_Z10euclid_gcdii:\n.LFB1518:\n\t.cfi_startproc\n\tpushq\t%rbp\n\t.cfi_def_cfa_offset 16\n\t.cfi_offset 6, -16\n\tmovq\t%rsp, %rbp\n\t.cfi_def_cfa_register 6\n\tmovl\t%edi, -4(%rbp)\n\tmovl\t%esi, -8(%rbp)\n.L5:\n\tmovl\t-4(%rbp), %eax\n\tcmpl\t-8(%rbp), %eax\n\tje\t.L2\n\tmovl\t-4(%rbp), %eax\n\tcmpl\t-8(%rbp), %eax\n\tjle\t.L3\n\tmovl\t-8(%rbp), %eax\n\tsubl\t%eax, -4(%rbp)\n\tjmp\t.L5\n.L3:\n\tmovl\t-4(%rbp), %eax\n\tsubl\t%eax, -8(%rbp)\n\tjmp\t.L5\n.L2:\n\tmovl\t-4(%rbp), %eax\n\tpopq\t%rbp\n\t.cfi_def_cfa 7, 8\n\tret\n\t.cfi_endproc\n.LFE1518:\n\t.size\t_Z10euclid_gcdii, .-_Z10euclid_gcdii\n\t.section\t.rodata\n.LC0:\n\t.string\t\"Enter integer. x = \"\n.LC1:\n\t.string\t\"Enter integer. y = \"\n.LC2:\n\t.string\t\"GCD(x, y) = \"\n\t.text\n\t.globl\tmain\n\t.type\tmain, @function\nmain:\n.LFB1519:\n\t.cfi_startproc\n\tpushq\t%rbp\n\t.cfi_def_cfa_offset 16\n\t.cfi_offset 6, -16\n\tmovq\t%rsp, %rbp\n\t.cfi_def_cfa_register 6\n\tpushq\t%rbx\n\tsubq\t$24, %rsp\n\t.cfi_offset 3, -24\n\tleaq\t.LC0(%rip), %rsi\n\tleaq\t_ZSt4cout(%rip), %rdi\n\tcall\t_ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_PKc@PLT\n\tleaq\t-20(%rbp), %rax\n\tmovq\t%rax, %rsi\n\tleaq\t_ZSt3cin(%rip), %rdi\n\tcall\t_ZNSirsERi@PLT\n\tleaq\t.LC1(%rip), %rsi\n\tleaq\t_ZSt4cout(%rip), %rdi\n\tcall\t_ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_PKc@PLT\n\tleaq\t-24(%rbp), %rax\n\tmovq\t%rax, %rsi\n\tleaq\t_ZSt3cin(%rip), %rdi\n\tcall\t_ZNSirsERi@PLT\n\tleaq\t.LC2(%rip), %rsi\n\tleaq\t_ZSt4cout(%rip), %rdi\n\tcall\t_ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_PKc@PLT\n\tmovq\t%rax, %rbx\n\tmovl\t-24(%rbp), %edx\n\tmovl\t-20(%rbp), %eax\n\tmovl\t%edx, %esi\n\tmovl\t%eax, %edi\n\tcall\t_Z10euclid_gcdii\n\tmovl\t%eax, %esi\n\tmovq\t%rbx, %rdi\n\tcall\t_ZNSolsEi@PLT\n\tmovq\t%rax, %rdx\n\tmovq\t_ZSt4endlIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_@GOTPCREL(%rip), %rax\n\tmovq\t%rax, %rsi\n\tmovq\t%rdx, %rdi\n\tcall\t_ZNSolsEPFRSoS_E@PLT\n\tmovl\t$0, %eax\n\taddq\t$24, %rsp\n\tpopq\t%rbx\n\tpopq\t%rbp\n\t.cfi_def_cfa 7, 8\n\tret\n\t.cfi_endproc\n.LFE1519:\n\t.size\tmain, .-main\n\t.type\t_Z41__static_initialization_and_destruction_0ii, @function\n_Z41__static_initialization_and_destruction_0ii:\n.LFB2008:\n\t.cfi_startproc\n\tpushq\t%rbp\n\t.cfi_def_cfa_offset 16\n\t.cfi_offset 6, -16\n\tmovq\t%rsp, %rbp\n\t.cfi_def_cfa_register 6\n\tsubq\t$16, %rsp\n\tmovl\t%edi, -4(%rbp)\n\tmovl\t%esi, -8(%rbp)\n\tcmpl\t$1, -4(%rbp)\n\tjne\t.L11\n\tcmpl\t$65535, -8(%rbp)\n\tjne\t.L11\n\tleaq\t_ZStL8__ioinit(%rip), %rdi\n\tcall\t_ZNSt8ios_base4InitC1Ev@PLT\n\tleaq\t__dso_handle(%rip), %rdx\n\tleaq\t_ZStL8__ioinit(%rip), %rsi\n\tmovq\t_ZNSt8ios_base4InitD1Ev@GOTPCREL(%rip), %rax\n\tmovq\t%rax, %rdi\n\tcall\t__cxa_atexit@PLT\n.L11:\n\tnop\n\tleave\n\t.cfi_def_cfa 7, 8\n\tret\n\t.cfi_endproc\n.LFE2008:\n\t.size\t_Z41__static_initialization_and_destruction_0ii, .-_Z41__static_initialization_and_destruction_0ii\n\t.type\t_GLOBAL__sub_I__Z10euclid_gcdii, @function\n_GLOBAL__sub_I__Z10euclid_gcdii:\n.LFB2009:\n\t.cfi_startproc\n\tpushq\t%rbp\n\t.cfi_def_cfa_offset 16\n\t.cfi_offset 6, -16\n\tmovq\t%rsp, %rbp\n\t.cfi_def_cfa_register 6\n\tmovl\t$65535, %esi\n\tmovl\t$1, %edi\n\tcall\t_Z41__static_initialization_and_destruction_0ii\n\tpopq\t%rbp\n\t.cfi_def_cfa 7, 8\n\tret\n\t.cfi_endproc\n.LFE2009:\n\t.size\t_GLOBAL__sub_I__Z10euclid_gcdii, .-_GLOBAL__sub_I__Z10euclid_gcdii\n\t.section\t.init_array,\"aw\"\n\t.align 8\n\t.quad\t_GLOBAL__sub_I__Z10euclid_gcdii\n\t.hidden\t__dso_handle\n\t.ident\t\"GCC: (Debian 8.3.0-6) 8.3.0\"\n\t.section\t.note.GNU-stack,\"\",@progbits\n"
  },
  {
    "path": "cpp_algo/lec_21/cmake_project/CMakeLists.txt",
    "content": "cmake_minimum_required(VERSION 2.8)\t # Проверка версии CMake.\n\nproject(main)\t\t\t# Название проекта\nset(SOURCE_EXE main.cpp)\t# Установка переменной со списком исходников для исполняемого файла\nset(SOURCE_LIB mylib.cpp)\t# Тоже самое, но для библиотеки\nadd_library(mylib STATIC ${SOURCE_LIB})\t# Создание статической библиотеки с именем foo\nadd_executable(main ${SOURCE_EXE})\t# Создает исполняемый файл с именем main\n\ntarget_link_libraries(main mylib)\t\t# Линковка программы с библиотекой\n\n"
  },
  {
    "path": "cpp_algo/lec_21/cmake_project/Makefile",
    "content": "# CMAKE generated file: DO NOT EDIT!\n# Generated by \"Unix Makefiles\" Generator, CMake Version 3.13\n\n# Default target executed when no arguments are given to make.\ndefault_target: all\n\n.PHONY : default_target\n\n# Allow only one \"make -f Makefile2\" at a time, but pass parallelism.\n.NOTPARALLEL:\n\n\n#=============================================================================\n# Special targets provided by cmake.\n\n# Disable implicit rules so canonical targets will work.\n.SUFFIXES:\n\n\n# Remove some rules from gmake that .SUFFIXES does not remove.\nSUFFIXES =\n\n.SUFFIXES: .hpux_make_needs_suffix_list\n\n\n# Suppress display of executed commands.\n$(VERBOSE).SILENT:\n\n\n# A target that is always out of date.\ncmake_force:\n\n.PHONY : cmake_force\n\n#=============================================================================\n# Set environment variables for the build.\n\n# The shell in which to execute make rules.\nSHELL = /bin/sh\n\n# The CMake executable.\nCMAKE_COMMAND = /usr/bin/cmake\n\n# The command to remove a file.\nRM = /usr/bin/cmake -E remove -f\n\n# Escaping for special characters.\nEQUALS = =\n\n# The top-level source directory on which CMake was run.\nCMAKE_SOURCE_DIR = /home/tkhirianov/lec_2020/cpp_algo/lec_21/cmake_project\n\n# The top-level build directory on which CMake was run.\nCMAKE_BINARY_DIR = /home/tkhirianov/lec_2020/cpp_algo/lec_21/cmake_project\n\n#=============================================================================\n# Targets provided globally by CMake.\n\n# Special rule for the target rebuild_cache\nrebuild_cache:\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Running CMake to regenerate build system...\"\n\t/usr/bin/cmake -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR)\n.PHONY : rebuild_cache\n\n# Special rule for the target rebuild_cache\nrebuild_cache/fast: rebuild_cache\n\n.PHONY : rebuild_cache/fast\n\n# Special rule for the target edit_cache\nedit_cache:\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"No interactive CMake dialog available...\"\n\t/usr/bin/cmake -E echo No\\ interactive\\ CMake\\ dialog\\ available.\n.PHONY : edit_cache\n\n# Special rule for the target edit_cache\nedit_cache/fast: edit_cache\n\n.PHONY : edit_cache/fast\n\n# The main all target\nall: cmake_check_build_system\n\t$(CMAKE_COMMAND) -E cmake_progress_start /home/tkhirianov/lec_2020/cpp_algo/lec_21/cmake_project/CMakeFiles /home/tkhirianov/lec_2020/cpp_algo/lec_21/cmake_project/CMakeFiles/progress.marks\n\t$(MAKE) -f CMakeFiles/Makefile2 all\n\t$(CMAKE_COMMAND) -E cmake_progress_start /home/tkhirianov/lec_2020/cpp_algo/lec_21/cmake_project/CMakeFiles 0\n.PHONY : all\n\n# The main clean target\nclean:\n\t$(MAKE) -f CMakeFiles/Makefile2 clean\n.PHONY : clean\n\n# The main clean target\nclean/fast: clean\n\n.PHONY : clean/fast\n\n# Prepare targets for installation.\npreinstall: all\n\t$(MAKE) -f CMakeFiles/Makefile2 preinstall\n.PHONY : preinstall\n\n# Prepare targets for installation.\npreinstall/fast:\n\t$(MAKE) -f CMakeFiles/Makefile2 preinstall\n.PHONY : preinstall/fast\n\n# clear depends\ndepend:\n\t$(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 1\n.PHONY : depend\n\n#=============================================================================\n# Target rules for targets named mylib\n\n# Build rule for target.\nmylib: cmake_check_build_system\n\t$(MAKE) -f CMakeFiles/Makefile2 mylib\n.PHONY : mylib\n\n# fast build rule for target.\nmylib/fast:\n\t$(MAKE) -f CMakeFiles/mylib.dir/build.make CMakeFiles/mylib.dir/build\n.PHONY : mylib/fast\n\n#=============================================================================\n# Target rules for targets named main\n\n# Build rule for target.\nmain: cmake_check_build_system\n\t$(MAKE) -f CMakeFiles/Makefile2 main\n.PHONY : main\n\n# fast build rule for target.\nmain/fast:\n\t$(MAKE) -f CMakeFiles/main.dir/build.make CMakeFiles/main.dir/build\n.PHONY : main/fast\n\nmain.o: main.cpp.o\n\n.PHONY : main.o\n\n# target to build an object file\nmain.cpp.o:\n\t$(MAKE) -f CMakeFiles/main.dir/build.make CMakeFiles/main.dir/main.cpp.o\n.PHONY : main.cpp.o\n\nmain.i: main.cpp.i\n\n.PHONY : main.i\n\n# target to preprocess a source file\nmain.cpp.i:\n\t$(MAKE) -f CMakeFiles/main.dir/build.make CMakeFiles/main.dir/main.cpp.i\n.PHONY : main.cpp.i\n\nmain.s: main.cpp.s\n\n.PHONY : main.s\n\n# target to generate assembly for a file\nmain.cpp.s:\n\t$(MAKE) -f CMakeFiles/main.dir/build.make CMakeFiles/main.dir/main.cpp.s\n.PHONY : main.cpp.s\n\nmylib.o: mylib.cpp.o\n\n.PHONY : mylib.o\n\n# target to build an object file\nmylib.cpp.o:\n\t$(MAKE) -f CMakeFiles/mylib.dir/build.make CMakeFiles/mylib.dir/mylib.cpp.o\n.PHONY : mylib.cpp.o\n\nmylib.i: mylib.cpp.i\n\n.PHONY : mylib.i\n\n# target to preprocess a source file\nmylib.cpp.i:\n\t$(MAKE) -f CMakeFiles/mylib.dir/build.make CMakeFiles/mylib.dir/mylib.cpp.i\n.PHONY : mylib.cpp.i\n\nmylib.s: mylib.cpp.s\n\n.PHONY : mylib.s\n\n# target to generate assembly for a file\nmylib.cpp.s:\n\t$(MAKE) -f CMakeFiles/mylib.dir/build.make CMakeFiles/mylib.dir/mylib.cpp.s\n.PHONY : mylib.cpp.s\n\n# Help Target\nhelp:\n\t@echo \"The following are some of the valid targets for this Makefile:\"\n\t@echo \"... all (the default if no target is provided)\"\n\t@echo \"... clean\"\n\t@echo \"... depend\"\n\t@echo \"... rebuild_cache\"\n\t@echo \"... mylib\"\n\t@echo \"... edit_cache\"\n\t@echo \"... main\"\n\t@echo \"... main.o\"\n\t@echo \"... main.i\"\n\t@echo \"... main.s\"\n\t@echo \"... mylib.o\"\n\t@echo \"... mylib.i\"\n\t@echo \"... mylib.s\"\n.PHONY : help\n\n\n\n#=============================================================================\n# Special targets to cleanup operation of make.\n\n# Special rule to run CMake to check the build system integrity.\n# No rule that depends on this can have commands that come from listfiles\n# because they might be regenerated.\ncmake_check_build_system:\n\t$(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 0\n.PHONY : cmake_check_build_system\n\n"
  },
  {
    "path": "cpp_algo/lec_21/cmake_project/cmake_install.cmake",
    "content": "# Install script for directory: /home/tkhirianov/lec_2020/cpp_algo/lec_21/cmake_project\n\n# Set the install prefix\nif(NOT DEFINED CMAKE_INSTALL_PREFIX)\n  set(CMAKE_INSTALL_PREFIX \"/usr/local\")\nendif()\nstring(REGEX REPLACE \"/$\" \"\" CMAKE_INSTALL_PREFIX \"${CMAKE_INSTALL_PREFIX}\")\n\n# Set the install configuration name.\nif(NOT DEFINED CMAKE_INSTALL_CONFIG_NAME)\n  if(BUILD_TYPE)\n    string(REGEX REPLACE \"^[^A-Za-z0-9_]+\" \"\"\n           CMAKE_INSTALL_CONFIG_NAME \"${BUILD_TYPE}\")\n  else()\n    set(CMAKE_INSTALL_CONFIG_NAME \"\")\n  endif()\n  message(STATUS \"Install configuration: \\\"${CMAKE_INSTALL_CONFIG_NAME}\\\"\")\nendif()\n\n# Set the component getting installed.\nif(NOT CMAKE_INSTALL_COMPONENT)\n  if(COMPONENT)\n    message(STATUS \"Install component: \\\"${COMPONENT}\\\"\")\n    set(CMAKE_INSTALL_COMPONENT \"${COMPONENT}\")\n  else()\n    set(CMAKE_INSTALL_COMPONENT)\n  endif()\nendif()\n\n# Install shared libraries without execute permission?\nif(NOT DEFINED CMAKE_INSTALL_SO_NO_EXE)\n  set(CMAKE_INSTALL_SO_NO_EXE \"1\")\nendif()\n\n# Is this installation the result of a crosscompile?\nif(NOT DEFINED CMAKE_CROSSCOMPILING)\n  set(CMAKE_CROSSCOMPILING \"FALSE\")\nendif()\n\nif(CMAKE_INSTALL_COMPONENT)\n  set(CMAKE_INSTALL_MANIFEST \"install_manifest_${CMAKE_INSTALL_COMPONENT}.txt\")\nelse()\n  set(CMAKE_INSTALL_MANIFEST \"install_manifest.txt\")\nendif()\n\nstring(REPLACE \";\" \"\\n\" CMAKE_INSTALL_MANIFEST_CONTENT\n       \"${CMAKE_INSTALL_MANIFEST_FILES}\")\nfile(WRITE \"/home/tkhirianov/lec_2020/cpp_algo/lec_21/cmake_project/${CMAKE_INSTALL_MANIFEST}\"\n     \"${CMAKE_INSTALL_MANIFEST_CONTENT}\")\n"
  },
  {
    "path": "cpp_algo/lec_21/cmake_project/main.cpp",
    "content": "#include <iostream>\n#include \"mylib.h\"\n#include \"mylib.h\" // doesn't matter because of HEADER GUARD in library header\n#include \"mylib.h\"\n#include \"mylib.h\"\n\nint main()\n{\n    using namespace std;\n    int x, y;\n\n    cout << \"Enter integer. x = \";\n    cin >> x;\n    cout << \"Enter integer. y = \";\n    cin >> y;\n    cout << \"GCD(x, y) = \" << euclid_gcd(x, y) << endl;\n\n    return 0;\n}\n"
  },
  {
    "path": "cpp_algo/lec_21/cmake_project/mylib.cpp",
    "content": "#include \"mylib.h\"\n\nint euclid_gcd(int a, int b)\n{   // Алгоритм Евклида поиска НОД\n    while (a != b) {\n        if (a > b) {\n            a -= b;\n        } else {\n            b -= a;\n        }\n    }\n    return a;\n}\n"
  },
  {
    "path": "cpp_algo/lec_21/cmake_project/mylib.h",
    "content": "#ifndef MYLIB_HEADER_GUARD\n#define MYLIB_HEADER_GUARD\n\n\nconst int scale_x = 100;\n\nint euclid_gcd(int a, int b);\n\n#endif //MYLIB_HEADER_GUARD\n"
  },
  {
    "path": "cpp_algo/lec_21/hello.cpp",
    "content": "#include <iostream>\n#include \"1.txt\"\n\n#define HELLO_MESSAGE \"Hello, world!\" \n\n#define MAX(x, y) x > y ? x : y\n\nusing namespace std;\n\nint foo(int x)\n{  \n    cout << \"foo(\" << x << \")\\n\";\n    return x;\n}\n\nint main()\n{\n    cout << HELLO_MESSAGE << endl;\n    int x = 3;\n    int z = MAX(foo(x), 2);  // LOOK HERE FOR A BUG!\n    cout << z << endl;\n\n    cout << MAX(5, 2) << endl;  // LOOK HERE FOR A BUG!\n\n    return 0;\n}\n"
  },
  {
    "path": "cpp_algo/lec_21/project/Makefile",
    "content": "all: main.exe\n\nmain.exe: main.o mylib.o\n\tg++ -o main.exe main.o mylib.o\n\nmain.o: main.cpp mylib.h\n\tg++ -c main.cpp\n\nmylib.o: mylib.cpp mylib.h\n\tg++ -c mylib.cpp\n\nclean:\n\trm *.o main.exe\n"
  },
  {
    "path": "cpp_algo/lec_21/project/main.cpp",
    "content": "#include <iostream>\n#include \"mylib.h\"\n#include \"mylib.h\" // doesn't matter because of HEADER GUARD in library header\n#include \"mylib.h\"\n#include \"mylib.h\"\n\nint main()\n{\n    using namespace std;\n    int x, y;\n\n    cout << \"Enter integer. x = \";\n    cin >> x;\n    cout << \"Enter integer. y = \";\n    cin >> y;\n    cout << \"GCD(x, y) = \" << euclid_gcd(x, y) << endl;\n\n    return 0;\n}\n"
  },
  {
    "path": "cpp_algo/lec_21/project/mylib.cpp",
    "content": "#include \"mylib.h\"\n\nint euclid_gcd(int a, int b)\n{   // Алгоритм Евклида поиска НОД\n    while (a != b) {\n        if (a > b) {\n            a -= b;\n        } else {\n            b -= a;\n        }\n    }\n    return a;\n}\n"
  },
  {
    "path": "cpp_algo/lec_21/project/mylib.h",
    "content": "#ifndef MYLIB_HEADER_GUARD\n#define MYLIB_HEADER_GUARD\n\n\nconst int scale_x = 100;\n\nint euclid_gcd(int a, int b);\n\n#endif //MYLIB_HEADER_GUARD\n"
  },
  {
    "path": "cpp_algo/lec_22/1_graphs_storage.cpp",
    "content": "#include <iostream>\n#include <map>\n#include <set>\n#include <vector>\n\ntypedef int32_t vertex_t;\ntypedef std::set<vertex_t> SetOfVertexes;\n\nclass AbstractGraph {\npublic:\n    int vertexes_number = 0;\n    int edges_number = 0;\n\n    virtual void input() = 0;\n    virtual void print() const = 0;\n};\n\nclass Graph_type1: public AbstractGraph\n{\npublic:\n    std::set<std::pair<vertex_t, vertex_t>> set_of_edges;\n\n    void input()\n    {\n        std::cin >> vertexes_number;\n        std::cin >> edges_number;\n        set_of_edges.clear();\n        for (vertex_t i = 0; i < edges_number; i++) {\n            vertex_t a, b;\n            std::cin >> a >> b;\n            set_of_edges.insert(std::make_pair(a, b));\n        }\n    }\n\n    void print() const\n    {\n        std::cout << \"Vertexes number = \"\n                  << vertexes_number << std::endl;\n        for(auto edge: set_of_edges) {\n            std::cout << \"(\" << edge.first << \", \" << edge.second << \") \";\n        }\n        std::cout << std::endl;\n    }\n};\n\n\nclass Graph_type2: public AbstractGraph\n{\npublic:\n    /// Matrix of adjasency\n    std::vector<std::vector<bool>> matrix;\n\n    void input()\n    {\n        std::cin >> vertexes_number;\n        // Как только узнал количество вершин, создаю матрицу нужного размера\n        matrix.resize(vertexes_number);\n        for (auto &line: matrix) {\n            line.resize(vertexes_number, false);\n        }\n\n        std::cin >> edges_number;\n        for (vertex_t i = 0; i < edges_number; i++) {\n            vertex_t a, b;\n            std::cin >> a >> b;\n            matrix[a][b] = 1;\n            matrix[b][a] = 1;\n        }\n    }\n\n    void print() const\n    {\n        std::cout << \"Vertexes number = \"\n                  << vertexes_number << std::endl;\n\n        for(vertex_t a = 0; a < vertexes_number; a++) {\n            for(vertex_t b = 0; b < vertexes_number; b++) {\n                std::cout << matrix[a][b] << \"  \";\n            }\n            std::cout << std::endl;\n        }\n        std::cout << std::endl;\n    }\n};\n\n\n\nint main()\n{\n    Graph_type2 g1;\n    g1.input();\n    g1.print();\n}\n"
  },
  {
    "path": "cpp_algo/lec_23/1_dfs.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include \"graph.hpp\"\n\nvoid just_dfs(const Graph_t &graph,\n              vertex_t start,\n              std::vector<bool> &used)\n{\n    used[start] = true;\n    std::cout << start << ' ';\n    auto neighbours_list = graph.sets_of_neighbours[start];\n    for(auto neighbour: neighbours_list) {\n        if (not used[neighbour])\n            just_dfs(graph, neighbour, used);\n    }\n}\n\n\nint main()\n{\n    Graph_t g;\n    g.input();\n    g.print();\n\n    std::cout << \"Enter start vertex: \";\n    vertex_t start;\n    std::cin >> start;\n    std::vector<bool> used_vertexes;\n    used_vertexes.resize(g.vertexes_number, false);\n    just_dfs(g, start, used_vertexes);\n    std::cout << \"\\n\";\n}\n"
  },
  {
    "path": "cpp_algo/lec_23/2_bfs.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <deque>\n#include \"graph.hpp\"\n\nvoid just_bfs(const Graph_t &graph,\n              vertex_t start,\n              std::vector<bool> &fired)\n{\n    fired[start] = true;\n    std::deque<vertex_t> firing_list;\n    firing_list.push_back(start);\n\n    std::cout << start << '\\t';\n    while (not firing_list.empty()) {\n        vertex_t current = firing_list.front();\n        firing_list.pop_front();\n\n        auto neighbours_list = graph.sets_of_neighbours[current];\n        for(auto neighbour: neighbours_list) {\n            if (not (fired[neighbour])) {\n                std::cout << neighbour << \"\\t\";\n                fired[neighbour] = true;\n                firing_list.push_back(neighbour);\n            }\n        }\n    }\n    std::cout << '\\n';\n}\n\n\nint main()\n{\n    Graph_t g;\n    g.input();\n    g.print();\n\n    std::cout << \"Enter start vertex: \";\n    vertex_t start;\n    std::cin >> start;\n    std::vector<bool> used_vertexes;\n    used_vertexes.resize(g.vertexes_number, false);\n    just_bfs(g, start, used_vertexes);\n    std::cout << \"\\n\";\n}\n"
  },
  {
    "path": "cpp_algo/lec_23/graph.hpp",
    "content": "#ifndef _GRAPH_HPP__\n#define _GRAPH_HPP__\n\n#include <iostream>\n#include <map>\n#include <set>\n#include <vector>\n\ntypedef int32_t vertex_t;\ntypedef std::set<vertex_t> SetOfVertexes;\n\n\nclass Graph_t\n{\npublic:\n    int vertexes_number = 0;\n    int edges_number = 0;\n    // списки смежности для каждой вершины графа:\n    std::vector<std::set<vertex_t>> sets_of_neighbours;\n\n    void input()\n    {\n        std::cin >> vertexes_number;\n        std::cin >> edges_number;\n        // полная очистка массива списков смежности\n        sets_of_neighbours.clear();\n        // создаю пустые списки смежности для каждой вершины:\n        sets_of_neighbours.resize(vertexes_number);\n        for (int i = 0; i < edges_number; i++) {\n            vertex_t a, b;\n            std::cin >> a >> b;\n            sets_of_neighbours[a].insert(b); // у вершины a - сосед b\n            sets_of_neighbours[b].insert(a); // у вершины a - сосед b\n        }\n    }\n\n    void print() const\n    {\n        std::cout << \"Vertexes number = \"\n                  << vertexes_number << std::endl;\n        for(vertex_t vertex = 0; vertex < vertexes_number; vertex++) {\n            std::cout << vertex << \": [\";\n            for(auto neighbour: sets_of_neighbours[vertex]) {\n                std::cout << neighbour << \", \";\n            }\n            std::cout << \"\\b\\b]\\n\";\n        }\n        std::cout << std::endl;\n    }\n};\n\n#endif //_GRAPH_HPP__\n"
  },
  {
    "path": "cpp_algo/lec_23/input1.txt",
    "content": "5\n7\n0 1\n1 2\n2 0\n0 3\n3 4\n0 4\n1 4\n0\n"
  },
  {
    "path": "cpp_algo/lec_24/check_DAG.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include \"graph.hpp\"\n\nbool check_DAG(const OrGraph_t &graph,\n              vertex_t start,\n              std::vector<bool> &used)\n{\n    used[start] = true;\n    auto neighbours_list = graph.sets_of_neighbours[start];\n    for(auto neighbour: neighbours_list) {\n        if (neighbour == start) {\n            continue;\n        }\n        if (used[neighbour]) // Пытаемся попасть в соседнюю ранее пройденную вершину. Цикл!\n           return false; \n        bool is_DAG = check_DAG(graph, neighbour, used);\n        if (not is_DAG) return false;\n    }\n    return true; // Достигаю этой точки, только если не случилось return false.\n}\n\n\nint main()\n{\n    OrGraph_t g;\n    g.input();\n    g.print();\n\n    std::vector<bool> used_vertexes;\n    used_vertexes.resize(g.vertexes_number, false);\n    bool is_DAG = true;\n    for (vertex_t v = 0; v < g.vertexes_number; v++) {\n        if (used_vertexes[v]) continue;\n        if (not check_DAG(g, v, used_vertexes)) {\n            is_DAG = false;\n            break;\n        }\n    }\n    if (is_DAG)\n        std::cout << \"Acyclic graph.\\n\";\n    else\n        std::cout << \"Cyclic graph.\\n\";\n}\n"
  },
  {
    "path": "cpp_algo/lec_24/graph.hpp",
    "content": "#ifndef _GRAPH_HPP__\n#define _GRAPH_HPP__\n\n#include <iostream>\n#include <map>\n#include <set>\n#include <vector>\n\ntypedef int32_t vertex_t;\ntypedef std::set<vertex_t> SetOfVertexes;\n\n\nclass OrGraph_t\n{\npublic:\n    int vertexes_number = 0;\n    int edges_number = 0;\n    // списки смежности для каждой вершины графа:\n    std::vector<std::set<vertex_t>> sets_of_neighbours;\n\n    void input()\n    {\n        std::cin >> vertexes_number;\n        std::cin >> edges_number;\n        // полная очистка массива списков смежности\n        sets_of_neighbours.clear();\n        // создаю пустые списки смежности для каждой вершины:\n        sets_of_neighbours.resize(vertexes_number);\n        for (int i = 0; i < edges_number; i++) {\n            vertex_t a, b;\n            std::cin >> a >> b;\n            sets_of_neighbours[a].insert(b); // у вершины a - сосед b\n        }\n    }\n\n    void print() const\n    {\n        std::cout << \"Vertexes number = \"\n                  << vertexes_number << std::endl;\n        for(vertex_t vertex = 0; vertex < vertexes_number; vertex++) {\n            std::cout << vertex << \": [\";\n            for(auto neighbour: sets_of_neighbours[vertex]) {\n                std::cout << neighbour << \", \";\n            }\n            std::cout << \"\\b\\b]\\n\";\n        }\n        std::cout << std::endl;\n    }\n};\n\nclass Graph_t\n{\npublic:\n    int vertexes_number = 0;\n    int edges_number = 0;\n    // списки смежности для каждой вершины графа:\n    std::vector<std::set<vertex_t>> sets_of_neighbours;\n\n    void input()\n    {\n        std::cin >> vertexes_number;\n        std::cin >> edges_number;\n        // полная очистка массива списков смежности\n        sets_of_neighbours.clear();\n        // создаю пустые списки смежности для каждой вершины:\n        sets_of_neighbours.resize(vertexes_number);\n        for (int i = 0; i < edges_number; i++) {\n            vertex_t a, b;\n            std::cin >> a >> b;\n            sets_of_neighbours[a].insert(b); // у вершины a - сосед b\n        }\n    }\n\n    void print() const\n    {\n        std::cout << \"Vertexes number = \"\n                  << vertexes_number << std::endl;\n        for(vertex_t vertex = 0; vertex < vertexes_number; vertex++) {\n            std::cout << vertex << \": [\";\n            for(auto neighbour: sets_of_neighbours[vertex]) {\n                std::cout << neighbour << \", \";\n            }\n            std::cout << \"\\b\\b]\\n\";\n        }\n        std::cout << std::endl;\n    }\n};\n\n#endif //_GRAPH_HPP__\n"
  },
  {
    "path": "python/lec_01/01_input_print.py",
    "content": "#!/usr/bin/env python3\n\nname = input(\"Как тебя зовут? \")\nprint(f\"Привет, {name}!\")\nname = input(\"Как твоя фамилия? \")\nprint(f\"Ясно, {name}!\")\n\nprint(name + lastname)\n"
  },
  {
    "path": "python/lec_01/02_if_else.py",
    "content": "x = int(input())\ny = int(input())\n\nif x > 0 and y > 0:\n    print(1)\nelif x < 0 and y > 0:\n    print(2)\nelif x < 0 and y < 0:\n    print(3)\nelif x > 0 and y < 0:\n    print(4)\nelse:\n    print(\"НИКОГДА!\")\n            \n"
  },
  {
    "path": "python/lec_01/03_nested_for.py",
    "content": "import turtle\n\ndef david():\n    for step in range(6):\n        turtle.begin_fill()\n        for i in range(3):\n            turtle.forward(50)\n            turtle.left(360 / 3)\n        turtle.end_fill()\n        \n        turtle.forward(50)\n        turtle.right(60)\n\n\nturtle.shape('turtle')\nturtle.shapesize(2)\nturtle.color('green', 'yellow')\nturtle.speed(10)\n\ndavid()\nturtle.backward(200)\ndavid()\n\nturtle.hideturtle()\n"
  },
  {
    "path": "python/lec_03/1_function_experiments.py",
    "content": "def foo(x, y=0, z=0):\n    return 100*x + 10*y + 1*z\n\n\ndef bar(*args, named_parameter=\"bar\"):\n    for arg in args:\n        print(named_parameter, 'arg =', arg)\n\n\nbar()\nbar(['the', 'list', 'of', 'strings'])\nbar(1, 2, 3)\nbar(\"jelly\", \"fish\")\nbar(\"jelly\", \"fish\", named_parameter='SEPARATOR')\n\n'''print(foo(1, 2, 3))\nprint(foo(z=1, x=2, y=3))  # named parameters\nprint(foo(1, 2))\nprint(foo(7))\n'''"
  },
  {
    "path": "python/lec_03/2_pygame_draw_test.py",
    "content": "# Import a library of functions called 'pygame'\nimport pygame\nfrom math import pi\n\n# Initialize the game engine\npygame.init()\n\nx = 10\n\n# Define the colors we will use in RGB format\nBLACK = (0, 0, 0)\nWHITE = (255, 255, 255)\nBLUE = (0, 0, 255)\nGREEN = (0, 255, 0)\nRED = (255, 0, 0)\n\n# Set the height and width of the screen\nsize = [400, 300]\nscreen = pygame.display.set_mode(size)\n\npygame.display.set_caption(\"Example code for the draw module\")\n\n# Loop until the user clicks the close button.\ndone = False\nclock = pygame.time.Clock()\n\nwhile not done:\n    x += 1  # global x is changing\n\n    # This limits the while loop to a max of 10 times per second.\n    # Leave this out and we will use all CPU we can.\n    clock.tick(10)\n\n    for event in pygame.event.get():  # User did something\n        if event.type == pygame.QUIT:  # If user clicked close\n            done = True  # Flag that we are done so we exit this loop\n\n    # All drawing code happens after the for loop and but\n    # inside the main while done==False loop.\n\n    # Clear the screen and set the screen background\n    screen.fill(WHITE)\n\n    # Draw on the screen a GREEN line from (0, 0) to (50, 30)\n    # 5 pixels wide.\n    pygame.draw.line(screen, GREEN, [0, 0], [50, x], 5)\n\n    # Draw on the screen 3 BLACK lines, each 5 pixels wide.\n    # The 'False' means the first and last points are not connected.\n    pygame.draw.lines(screen, BLACK, False, [[0, 80], [50, 90], [200, 80], [220, 30]], 5)\n\n    # Draw on the screen a GREEN line from (0, 50) to (50, 80)\n    # Because it is an antialiased line, it is 1 pixel wide.\n    pygame.draw.aaline(screen, GREEN, [0, 50], [50, 80], True)\n\n    # Draw a rectangle outline\n    pygame.draw.rect(screen, BLACK, [75, 10+x, 50, 20+x], 2)\n\n    # Draw a solid rectangle\n    pygame.draw.rect(screen, BLACK, [150, 10+x, 50, 20])\n\n    # Draw a rectangle with rounded corners\n    pygame.draw.rect(screen, GREEN, [115, 210, 70, 40], 10)\n    pygame.draw.rect(screen, RED, [135, 260, 50, 30], 0)\n\n    # Draw an ellipse outline, using a rectangle as the outside boundaries\n    pygame.draw.ellipse(screen, RED, [225, 10, 50, 20], 2)\n\n    # Draw an solid ellipse, using a rectangle as the outside boundaries\n    pygame.draw.ellipse(screen, RED, [300, 10, 50, 20])\n\n    # This draws a triangle using the polygon command\n    pygame.draw.polygon(screen, BLACK, [[100, 100], [0, 200], [200, 200]], 5)\n\n    # Draw an arc as part of an ellipse.\n    # Use radians to determine what angle to draw.\n    pygame.draw.arc(screen, BLACK, [210, 75, 150, 125], 0, pi / 2, 2)\n    pygame.draw.arc(screen, GREEN, [210, 75, 150, 125], pi / 2, pi, 2)\n    pygame.draw.arc(screen, BLUE, [210, 75, 150, 125], pi, 3 * pi / 2, 2)\n    pygame.draw.arc(screen, RED, [210, 75, 150, 125], 3 * pi / 2, 2 * pi, 2)\n\n    # Draw a circle\n    pygame.draw.circle(screen, BLUE, [60, 250], 40)\n\n    # Draw only one circle quadrant\n    pygame.draw.circle(screen, BLUE, [250, 250], 40, 0)\n    pygame.draw.circle(screen, RED, [250, 250], 40, 30)\n    pygame.draw.circle(screen, GREEN, [250, 250], 40, 20)\n    pygame.draw.circle(screen, BLACK, [250, 250], 40, 10)\n\n    # Go ahead and update the screen with what we've drawn.\n    # This MUST happen after all the other drawing commands.\n    pygame.display.flip()\n\n# Be IDLE friendly\npygame.quit()"
  },
  {
    "path": "python/lec_04/football_1.py",
    "content": "# Original author: https://github.com/johoule/stuff/\r\n\r\n\r\n# Imports\r\nimport pygame\r\nimport math\r\nimport random\r\n\r\n# Initialize game engine\r\npygame.init()\r\n\r\n# Window\r\nSIZE = (800, 600)\r\nTITLE = \"Major League Soccer\"\r\nscreen = pygame.display.set_mode(SIZE)\r\npygame.display.set_caption(TITLE)\r\n\r\n# Timer\r\nclock = pygame.time.Clock()\r\nrefresh_rate = 60\r\n\r\n# Colors\r\n''' add colors you use as RGB values here '''\r\nRED = (255, 0, 0)\r\nGREEN = (52, 166, 36)\r\nBLUE = (29, 116, 248)\r\nWHITE = (255, 255, 255)\r\nBLACK = (0, 0, 0)\r\nORANGE = (255, 125, 0)\r\nDARK_BLUE = (18, 0, 91)\r\nDARK_GREEN = (0, 94, 0)\r\nGRAY = (130, 130, 130)\r\nYELLOW = (255, 255, 110)\r\nSILVER = (200, 200, 200)\r\nDAY_GREEN = (41, 129, 29)\r\nNIGHT_GREEN = (0, 64, 0)\r\nBRIGHT_YELLOW = (255, 244, 47)\r\nNIGHT_GRAY = (104, 98, 115)\r\nck = (127, 33, 33)\r\n\r\nDARKNESS = pygame.Surface(SIZE)\r\nDARKNESS.set_alpha(200)\r\nDARKNESS.fill((0, 0, 0))\r\n\r\nSEE_THROUGH = pygame.Surface((800, 180))\r\nSEE_THROUGH.set_alpha(150)\r\nSEE_THROUGH.fill((124, 118, 135))\r\n\r\n\r\ndef draw_cloud(x, y):\r\n    pygame.draw.ellipse(SEE_THROUGH, cloud_color, [x, y + 8, 10, 10])\r\n    pygame.draw.ellipse(SEE_THROUGH, cloud_color, [x + 6, y + 4, 8, 8])\r\n    pygame.draw.ellipse(SEE_THROUGH, cloud_color, [x + 10, y, 16, 16])\r\n    pygame.draw.ellipse(SEE_THROUGH, cloud_color, [x + 20, y + 8, 10, 10])\r\n    pygame.draw.rect(SEE_THROUGH, cloud_color, [x + 6, y + 8, 18, 10])\r\n\r\n\r\ndef draw_fence():\r\n    \"\"\"\r\n    This function draws fence of football field in particular place.\r\n    :return:\r\n    \"\"\"\r\n    y = 170\r\n    for x in range(5, 800, 30):\r\n        pygame.draw.polygon(screen, NIGHT_GRAY, [[x + 2, y], [x + 2, y + 15], [x, y + 15], [x, y]])\r\n\r\n    y = 170\r\n    for x in range(5, 800, 3):\r\n        pygame.draw.line(screen, NIGHT_GRAY, [x, y], [x, y + 15], 1)\r\n\r\n    x = 0\r\n    for y in range(170, 185, 4):\r\n        pygame.draw.line(screen, NIGHT_GRAY, [x, y], [x + 800, y], 1)\r\n\r\n\r\n\r\n# Config\r\nlights_on = True\r\nday = True\r\n\r\nstars = []\r\nfor n in range(200):\r\n    x = random.randrange(0, 800)\r\n    y = random.randrange(0, 200)\r\n    r = random.randrange(1, 2)\r\n    stars.append([x, y, r, r])\r\n\r\nclouds = []\r\nfor i in range(20):\r\n    x = random.randrange(-100, 1600)\r\n    y = random.randrange(0, 150)\r\n    clouds.append([x, y])\r\n\r\n# Game loop\r\ndone = False\r\n\r\nwhile not done:\r\n    # Event processing (React to key presses, mouse clicks, etc.)\r\n    ''' for now, we'll just check to see if the X is clicked '''\r\n    for event in pygame.event.get():\r\n        if event.type == pygame.QUIT:\r\n            done = True\r\n        elif event.type == pygame.KEYDOWN:\r\n            if event.key == pygame.K_l:\r\n                lights_on = not lights_on\r\n            elif event.key == pygame.K_d:\r\n                day = not day\r\n\r\n    # Game logic (Check for collisions, update points, etc.)\r\n    ''' leave this section alone for now '''\r\n    if lights_on:\r\n        light_color = YELLOW\r\n    else:\r\n        light_color = SILVER\r\n\r\n    if day:\r\n        sky_color = BLUE\r\n        field_color = GREEN\r\n        stripe_color = DAY_GREEN\r\n        cloud_color = WHITE\r\n    else:\r\n        sky_color = DARK_BLUE\r\n        field_color = DARK_GREEN\r\n        stripe_color = NIGHT_GREEN\r\n        cloud_color = NIGHT_GRAY\r\n\r\n    for c in clouds:\r\n        c[0] -= 0.5  # WHAT???\r\n\r\n        if c[0] < -100:\r\n            c[0] = random.randrange(800, 1600)\r\n            c[1] = random.randrange(0, 150)\r\n\r\n    # Drawing code (Describe the picture. It isn't actually drawn yet.)\r\n    screen.fill(sky_color)\r\n    SEE_THROUGH.fill(ck)\r\n    SEE_THROUGH.set_colorkey(ck)\r\n\r\n    if not day:\r\n        # stars\r\n        for s in stars:\r\n            pygame.draw.ellipse(screen, WHITE, s)\r\n\r\n    pygame.draw.rect(screen, field_color, [0, 180, 800, 420])\r\n    pygame.draw.rect(screen, stripe_color, [0, 180, 800, 42])\r\n    pygame.draw.rect(screen, stripe_color, [0, 264, 800, 52])\r\n    pygame.draw.rect(screen, stripe_color, [0, 368, 800, 62])\r\n    pygame.draw.rect(screen, stripe_color, [0, 492, 800, 82])\r\n\r\n    draw_fence()\r\n\r\n    if day:\r\n        pygame.draw.ellipse(screen, BRIGHT_YELLOW, [520, 50, 40, 40])\r\n    else:\r\n        pygame.draw.ellipse(screen, WHITE, [520, 50, 40, 40])\r\n        pygame.draw.ellipse(screen, sky_color, [530, 45, 40, 40])\r\n\r\n    for c in clouds:\r\n        draw_cloud(c[0], c[1])\r\n    screen.blit(SEE_THROUGH, (0, 0))\r\n\r\n    # out of bounds lines\r\n    pygame.draw.line(screen, WHITE, [0, 580], [800, 580], 5)\r\n    # left\r\n    pygame.draw.line(screen, WHITE, [0, 360], [140, 220], 5)\r\n    pygame.draw.line(screen, WHITE, [140, 220], [660, 220], 3)\r\n    # right\r\n    pygame.draw.line(screen, WHITE, [660, 220], [800, 360], 5)\r\n\r\n    # safety circle\r\n    pygame.draw.ellipse(screen, WHITE, [240, 500, 320, 160], 5)\r\n\r\n    # 18 yard line goal box\r\n    pygame.draw.line(screen, WHITE, [260, 220], [180, 300], 5)\r\n    pygame.draw.line(screen, WHITE, [180, 300], [620, 300], 3)\r\n    pygame.draw.line(screen, WHITE, [620, 300], [540, 220], 5)\r\n\r\n    # arc at the top of the goal box\r\n    pygame.draw.arc(screen, WHITE, [330, 280, 140, 40], math.pi, 2 * math.pi, 5)\r\n\r\n    # score board pole\r\n    pygame.draw.rect(screen, GRAY, [390, 120, 20, 70])\r\n\r\n    # score board\r\n    pygame.draw.rect(screen, BLACK, [300, 40, 200, 90])\r\n    pygame.draw.rect(screen, WHITE, [302, 42, 198, 88], 2)\r\n\r\n    # goal\r\n    pygame.draw.rect(screen, WHITE, [320, 140, 160, 80], 5)\r\n    pygame.draw.line(screen, WHITE, [340, 200], [460, 200], 3)\r\n    pygame.draw.line(screen, WHITE, [320, 220], [340, 200], 3)\r\n    pygame.draw.line(screen, WHITE, [480, 220], [460, 200], 3)\r\n    pygame.draw.line(screen, WHITE, [320, 140], [340, 200], 3)\r\n    pygame.draw.line(screen, WHITE, [480, 140], [460, 200], 3)\r\n\r\n    # 6 yard line goal box\r\n    pygame.draw.line(screen, WHITE, [310, 220], [270, 270], 3)\r\n    pygame.draw.line(screen, WHITE, [270, 270], [530, 270], 2)\r\n    pygame.draw.line(screen, WHITE, [530, 270], [490, 220], 3)\r\n\r\n    # light pole 1\r\n    pygame.draw.rect(screen, GRAY, [150, 60, 20, 140])\r\n    pygame.draw.ellipse(screen, GRAY, [150, 195, 20, 10])\r\n\r\n    # lights\r\n    pygame.draw.line(screen, GRAY, [110, 60], [210, 60], 2)\r\n    pygame.draw.ellipse(screen, light_color, [110, 40, 20, 20])\r\n    pygame.draw.ellipse(screen, light_color, [130, 40, 20, 20])\r\n    pygame.draw.ellipse(screen, light_color, [150, 40, 20, 20])\r\n    pygame.draw.ellipse(screen, light_color, [170, 40, 20, 20])\r\n    pygame.draw.ellipse(screen, light_color, [190, 40, 20, 20])\r\n    pygame.draw.line(screen, GRAY, [110, 40], [210, 40], 2)\r\n    pygame.draw.ellipse(screen, light_color, [110, 20, 20, 20])\r\n    pygame.draw.ellipse(screen, light_color, [130, 20, 20, 20])\r\n    pygame.draw.ellipse(screen, light_color, [150, 20, 20, 20])\r\n    pygame.draw.ellipse(screen, light_color, [170, 20, 20, 20])\r\n    pygame.draw.ellipse(screen, light_color, [190, 20, 20, 20])\r\n    pygame.draw.line(screen, GRAY, [110, 20], [210, 20], 2)\r\n\r\n    # light pole 2\r\n    pygame.draw.rect(screen, GRAY, [630, 60, 20, 140])\r\n    pygame.draw.ellipse(screen, GRAY, [630, 195, 20, 10])\r\n\r\n    # lights\r\n\r\n    pygame.draw.line(screen, GRAY, [590, 60], [690, 60], 2)\r\n    pygame.draw.ellipse(screen, light_color, [590, 40, 20, 20])\r\n    pygame.draw.ellipse(screen, light_color, [610, 40, 20, 20])\r\n    pygame.draw.ellipse(screen, light_color, [630, 40, 20, 20])\r\n    pygame.draw.ellipse(screen, light_color, [650, 40, 20, 20])\r\n    pygame.draw.ellipse(screen, light_color, [670, 40, 20, 20])\r\n    pygame.draw.line(screen, GRAY, [590, 40], [690, 40], 2)\r\n    pygame.draw.ellipse(screen, light_color, [590, 20, 20, 20])\r\n    pygame.draw.ellipse(screen, light_color, [610, 20, 20, 20])\r\n    pygame.draw.ellipse(screen, light_color, [630, 20, 20, 20])\r\n    pygame.draw.ellipse(screen, light_color, [650, 20, 20, 20])\r\n    pygame.draw.ellipse(screen, light_color, [670, 20, 20, 20])\r\n    pygame.draw.line(screen, GRAY, [590, 20], [690, 20], 2)\r\n\r\n    # net\r\n    pygame.draw.line(screen, WHITE, [325, 140], [341, 200], 1)\r\n    pygame.draw.line(screen, WHITE, [330, 140], [344, 200], 1)\r\n    pygame.draw.line(screen, WHITE, [335, 140], [347, 200], 1)\r\n    pygame.draw.line(screen, WHITE, [340, 140], [350, 200], 1)\r\n    pygame.draw.line(screen, WHITE, [345, 140], [353, 200], 1)\r\n    pygame.draw.line(screen, WHITE, [350, 140], [356, 200], 1)\r\n    pygame.draw.line(screen, WHITE, [355, 140], [359, 200], 1)\r\n    pygame.draw.line(screen, WHITE, [360, 140], [362, 200], 1)\r\n    pygame.draw.line(screen, WHITE, [364, 140], [365, 200], 1)\r\n    pygame.draw.line(screen, WHITE, [368, 140], [369, 200], 1)\r\n    pygame.draw.line(screen, WHITE, [372, 140], [373, 200], 1)\r\n    pygame.draw.line(screen, WHITE, [376, 140], [377, 200], 1)\r\n    pygame.draw.line(screen, WHITE, [380, 140], [380, 200], 1)\r\n    pygame.draw.line(screen, WHITE, [384, 140], [384, 200], 1)\r\n    pygame.draw.line(screen, WHITE, [388, 140], [388, 200], 1)\r\n    pygame.draw.line(screen, WHITE, [392, 140], [392, 200], 1)\r\n    pygame.draw.line(screen, WHITE, [396, 140], [396, 200], 1)\r\n    pygame.draw.line(screen, WHITE, [400, 140], [400, 200], 1)\r\n    pygame.draw.line(screen, WHITE, [404, 140], [404, 200], 1)\r\n    pygame.draw.line(screen, WHITE, [408, 140], [408, 200], 1)\r\n    pygame.draw.line(screen, WHITE, [412, 140], [412, 200], 1)\r\n    pygame.draw.line(screen, WHITE, [416, 140], [416, 200], 1)\r\n    pygame.draw.line(screen, WHITE, [420, 140], [420, 200], 1)\r\n    pygame.draw.line(screen, WHITE, [424, 140], [423, 200], 1)\r\n    pygame.draw.line(screen, WHITE, [428, 140], [427, 200], 1)\r\n    pygame.draw.line(screen, WHITE, [432, 140], [431, 200], 1)\r\n    pygame.draw.line(screen, WHITE, [436, 140], [435, 200], 1)\r\n    pygame.draw.line(screen, WHITE, [440, 140], [438, 200], 1)\r\n    pygame.draw.line(screen, WHITE, [445, 140], [441, 200], 1)\r\n    pygame.draw.line(screen, WHITE, [450, 140], [444, 200], 1)\r\n    pygame.draw.line(screen, WHITE, [455, 140], [447, 200], 1)\r\n    pygame.draw.line(screen, WHITE, [460, 140], [450, 200], 1)\r\n    pygame.draw.line(screen, WHITE, [465, 140], [453, 200], 1)\r\n    pygame.draw.line(screen, WHITE, [470, 140], [456, 200], 1)\r\n    pygame.draw.line(screen, WHITE, [475, 140], [459, 200], 1)\r\n\r\n    # net part 2\r\n    pygame.draw.line(screen, WHITE, [320, 140], [324, 216], 1)\r\n    pygame.draw.line(screen, WHITE, [320, 140], [326, 214], 1)\r\n    pygame.draw.line(screen, WHITE, [320, 140], [328, 212], 1)\r\n    pygame.draw.line(screen, WHITE, [320, 140], [330, 210], 1)\r\n    pygame.draw.line(screen, WHITE, [320, 140], [332, 208], 1)\r\n    pygame.draw.line(screen, WHITE, [320, 140], [334, 206], 1)\r\n    pygame.draw.line(screen, WHITE, [320, 140], [336, 204], 1)\r\n    pygame.draw.line(screen, WHITE, [320, 140], [338, 202], 1)\r\n\r\n    # net part 3\r\n    pygame.draw.line(screen, WHITE, [480, 140], [476, 216], 1)\r\n    pygame.draw.line(screen, WHITE, [480, 140], [474, 214], 1)\r\n    pygame.draw.line(screen, WHITE, [480, 140], [472, 212], 1)\r\n    pygame.draw.line(screen, WHITE, [480, 140], [470, 210], 1)\r\n    pygame.draw.line(screen, WHITE, [480, 140], [468, 208], 1)\r\n    pygame.draw.line(screen, WHITE, [480, 140], [466, 206], 1)\r\n    pygame.draw.line(screen, WHITE, [480, 140], [464, 204], 1)\r\n    pygame.draw.line(screen, WHITE, [480, 140], [462, 202], 1)\r\n\r\n    # net part 4\r\n    pygame.draw.line(screen, WHITE, [324, 144], [476, 144], 1)\r\n    pygame.draw.line(screen, WHITE, [324, 148], [476, 148], 1)\r\n    pygame.draw.line(screen, WHITE, [324, 152], [476, 152], 1)\r\n    pygame.draw.line(screen, WHITE, [324, 156], [476, 156], 1)\r\n    pygame.draw.line(screen, WHITE, [324, 160], [476, 160], 1)\r\n    pygame.draw.line(screen, WHITE, [324, 164], [476, 164], 1)\r\n    pygame.draw.line(screen, WHITE, [324, 168], [476, 168], 1)\r\n    pygame.draw.line(screen, WHITE, [324, 172], [476, 172], 1)\r\n    pygame.draw.line(screen, WHITE, [324, 176], [476, 176], 1)\r\n    pygame.draw.line(screen, WHITE, [335, 180], [470, 180], 1)\r\n    pygame.draw.line(screen, WHITE, [335, 184], [465, 184], 1)\r\n    pygame.draw.line(screen, WHITE, [335, 188], [465, 188], 1)\r\n    pygame.draw.line(screen, WHITE, [335, 192], [465, 192], 1)\r\n    pygame.draw.line(screen, WHITE, [335, 196], [465, 196], 1)\r\n\r\n    # stands right\r\n    pygame.draw.polygon(screen, RED, [[680, 220], [800, 340], [800, 290], [680, 180]])\r\n    pygame.draw.polygon(screen, WHITE, [[680, 180], [800, 100], [800, 290]])\r\n\r\n    # stands left\r\n    pygame.draw.polygon(screen, RED, [[120, 220], [0, 340], [0, 290], [120, 180]])\r\n    pygame.draw.polygon(screen, WHITE, [[120, 180], [0, 100], [0, 290]])\r\n    # people\r\n\r\n    # corner flag right\r\n    pygame.draw.line(screen, BRIGHT_YELLOW, [140, 220], [135, 190], 3)\r\n    pygame.draw.polygon(screen, RED, [[132, 190], [125, 196], [135, 205]])\r\n\r\n    # corner flag left\r\n    pygame.draw.line(screen, BRIGHT_YELLOW, [660, 220], [665, 190], 3)\r\n    pygame.draw.polygon(screen, RED, [[668, 190], [675, 196], [665, 205]])\r\n\r\n    # DARKNESS\r\n    if not day and not lights_on:\r\n        screen.blit(DARKNESS, (0, 0))\r\n\r\n        # WHAT???\r\n    # pygame.draw.polygon(screen, BLACK, [[200, 200], [50,400], [600, 500]], 10)\r\n\r\n    ''' angles for arcs are measured in radians (a pre-cal topic) '''\r\n    # pygame.draw.arc(screen, ORANGE, [100, 100, 100, 100], 0, math.pi/2, 1)\r\n    # pygame.draw.arc(screen, BLACK, [100, 100, 100, 100], 0, math.pi/2, 50)\r\n\r\n    # Update screen (Actually draw the picture in the window.)\r\n    pygame.display.flip()\r\n\r\n    # Limit refresh rate of game loop\r\n    clock.tick(refresh_rate)\r\n\r\n# Close window and quit\r\npygame.quit()\r\n"
  },
  {
    "path": "python/lec_05/house.py",
    "content": "\ndef main():\n    x, y = 300, 400\n    width, height = 200, 300\n\n    draw_house(x, y, width, height)\n\n\ndef draw_house(x, y, width, height):\n    \"\"\"\n    Нарисовать домик ширины width и высоты height от опорной точки (x, y),\n    которая находится в середине нижней точки фундамента.\n    :param x: координата x середины домика\n    :param y: координата y низа фундамента\n    :param width: полная ширина домика (фундамен или вылеты крыши включены)\n    :param height: полная высота домика\n    :return: None\n    \"\"\"\n    print('Типа рисую домик...', x, y, width, height)\n    foundation_height = 0.05 * height\n    walls_width = 0.9 * width\n    walls_height = 0.5 * height\n    roof_height = height - foundation_height - walls_height\n\n    draw_house_foundation(x, y, width, foundation_height)\n    draw_house_walls(x, y - foundation_height, walls_width, walls_height)\n    draw_house_roof(x, y - foundation_height - walls_height, width, roof_height)\n\n\ndef draw_house_foundation(x, y, width, height):\n    \"\"\"\n    Нарисовать основание домика ширины width и высоты height от опорной точки (x, y),\n    которая находится в середине нижней точки фундамента.\n    :param x: координата x середины фундамента\n    :param y: координата y низа фундамента\n    :param width: полная ширина фундамена\n    :param height: полная высота фундамента\n    :return: None\n    \"\"\"\n    print('Типа рисую основание...', x, y, width, height)\n    pass\n\n\ndef draw_house_walls(x, y, width, height):\n    print('Типа рисую стены...', x, y, width, height)\n    pass\n\n\ndef draw_house_roof(x, y, width, height):\n    print('Типа рисую крышу...', x, y, width, height)\n    pass\n\n\nmain()\n"
  },
  {
    "path": "python/lec_06/football_1.py",
    "content": "# Original author: https://github.com/johoule/stuff/\r\n\r\n\r\n# Imports\r\nimport pygame\r\nimport math\r\nimport random\r\n\r\n# Initialize game engine\r\npygame.init()\r\n\r\n# Window\r\nSIZE = (800, 600)\r\nTITLE = \"Major League Soccer\"\r\nscreen = pygame.display.set_mode(SIZE)\r\npygame.display.set_caption(TITLE)\r\n\r\n# Timer\r\nclock = pygame.time.Clock()\r\nrefresh_rate = 60\r\n\r\n# Colors\r\n''' add colors you use as RGB values here '''\r\nRED = (235, 0, 0)\r\nGREEN = (52, 169, 36)\r\nBLUE = (29, 116, 248)\r\nWHITE = (255, 255, 255)\r\nBLACK = (0, 0, 0)\r\nORANGE = (255, 125, 0)\r\nDARK_BLUE = (18, 0, 91)\r\nDARK_GREEN = (0, 94, 0)\r\nGRAY = (130, 130, 130)\r\nYELLOW = (255, 255, 110)\r\nSILVER = (200, 200, 200)\r\nDAY_GREEN = (41, 129, 29)\r\nNIGHT_GREEN = (0, 64, 0)\r\nBRIGHT_YELLOW = (255, 244, 47)\r\nNIGHT_GRAY = (104, 98, 115)\r\nck = (127, 33, 33)\r\n\r\nDARKNESS = pygame.Surface(SIZE)\r\nDARKNESS.set_alpha(200)\r\nDARKNESS.fill((0, 0, 0))\r\n\r\nSEE_THROUGH = pygame.Surface((800, 180))\r\nSEE_THROUGH.set_alpha(150)\r\nSEE_THROUGH.fill((124, 118, 135))\r\n\r\n\r\ndef draw_cloud(x, y):\r\n    pygame.draw.ellipse(SEE_THROUGH, cloud_color, [x, y + 8, 10, 10])\r\n    pygame.draw.ellipse(SEE_THROUGH, cloud_color, [x + 6, y + 4, 8, 8])\r\n    pygame.draw.ellipse(SEE_THROUGH, cloud_color, [x + 10, y, 16, 16])\r\n    pygame.draw.ellipse(SEE_THROUGH, cloud_color, [x + 20, y + 8, 10, 10])\r\n    pygame.draw.rect(SEE_THROUGH, cloud_color, [x + 6, y + 8, 18, 10])\r\n\r\n\r\ndef draw_fence():\r\n    \"\"\"\r\n    This function draws fence of football field in particular place.\r\n    :return:\r\n    \"\"\"\r\n    y = 170\r\n    for x in range(5, 800, 30):\r\n        pygame.draw.polygon(screen, NIGHT_GRAY, [[x + 2, y], [x + 2, y + 15], [x, y + 15], [x, y]])\r\n\r\n    y = 170\r\n    for x in range(5, 800, 3):\r\n        pygame.draw.line(screen, NIGHT_GRAY, [x, y], [x, y + 15], 1)\r\n\r\n    x = 0\r\n    for y in range(170, 185, 4):\r\n        pygame.draw.line(screen, NIGHT_GRAY, [x, y], [x + 800, y], 1)\r\n\r\n\r\ndef key_down_handler(event):\r\n    global lights_on, day\r\n    if event.key == pygame.K_l:\r\n        lights_on = not lights_on\r\n    elif event.key == pygame.K_d:\r\n        day = not day\r\n\r\n\r\n# Config\r\nlights_on = True\r\nday = True\r\n\r\nstars = []\r\nfor n in range(200):\r\n    x = random.randrange(0, 800)\r\n    y = random.randrange(0, 200)\r\n    r = random.randrange(1, 2)\r\n    stars.append([x, y, r, r])\r\n\r\nclouds = []\r\nfor i in range(20):\r\n    x = random.randrange(-100, 1600)\r\n    y = random.randrange(0, 150)\r\n    clouds.append([x, y])\r\n\r\n# Game loop\r\ndone = False\r\n\r\nwhile not done:\r\n    # Event processing (React to key presses, mouse clicks, etc.)\r\n    ''' for now, we'll just check to see if the X is clicked '''\r\n    for event in pygame.event.get():\r\n        if event.type == pygame.QUIT:\r\n            done = True\r\n        elif event.type == pygame.KEYDOWN:\r\n            key_down_handler(event)\r\n    # Game logic (Check for collisions, update points, etc.)\r\n    ''' leave this section alone for now '''\r\n    if lights_on:\r\n        light_color = YELLOW\r\n    else:\r\n        light_color = SILVER\r\n\r\n    if day:\r\n        sky_color = BLUE\r\n        field_color = GREEN\r\n        stripe_color = DAY_GREEN\r\n        cloud_color = WHITE\r\n    else:\r\n        sky_color = DARK_BLUE\r\n        field_color = DARK_GREEN\r\n        stripe_color = NIGHT_GREEN\r\n        cloud_color = NIGHT_GRAY\r\n\r\n    for c in clouds:\r\n        c[0] -= 0.5  # WHAT???\r\n\r\n        if c[0] < -100:\r\n            c[0] = random.randrange(800, 1600)\r\n            c[1] = random.randrange(0, 150)\r\n\r\n    # Drawing code (Describe the picture. It isn't actually drawn yet.)\r\n    screen.fill(sky_color)\r\n    SEE_THROUGH.fill(ck)\r\n    SEE_THROUGH.set_colorkey(ck)\r\n\r\n    if not day:\r\n        # stars\r\n        for s in stars:\r\n            pygame.draw.ellipse(screen, WHITE, s)\r\n\r\n    pygame.draw.rect(screen, field_color, [0, 180, 800, 420])\r\n    pygame.draw.rect(screen, stripe_color, [0, 180, 800, 42])\r\n    pygame.draw.rect(screen, stripe_color, [0, 264, 800, 52])\r\n    pygame.draw.rect(screen, stripe_color, [0, 368, 800, 62])\r\n    pygame.draw.rect(screen, stripe_color, [0, 492, 800, 82])\r\n\r\n    draw_fence()\r\n\r\n    if day:\r\n        pygame.draw.ellipse(screen, BRIGHT_YELLOW, [520, 50, 40, 40])\r\n    else:\r\n        pygame.draw.ellipse(screen, WHITE, [520, 50, 40, 40])\r\n        pygame.draw.ellipse(screen, sky_color, [530, 45, 40, 40])\r\n\r\n    for c in clouds:\r\n        draw_cloud(c[0], c[1])\r\n    screen.blit(SEE_THROUGH, (0, 0))\r\n\r\n    # out of bounds lines\r\n    pygame.draw.line(screen, WHITE, [0, 580], [800, 580], 5)\r\n    # left\r\n    pygame.draw.line(screen, WHITE, [0, 360], [140, 220], 5)\r\n    pygame.draw.line(screen, WHITE, [140, 220], [660, 220], 3)\r\n    # right\r\n    pygame.draw.line(screen, WHITE, [660, 220], [800, 360], 5)\r\n\r\n    # safety circle\r\n    pygame.draw.ellipse(screen, WHITE, [240, 500, 320, 160], 5)\r\n\r\n    # 18 yard line goal box\r\n    pygame.draw.line(screen, WHITE, [260, 220], [180, 300], 5)\r\n    pygame.draw.line(screen, WHITE, [180, 300], [620, 300], 3)\r\n    pygame.draw.line(screen, WHITE, [620, 300], [540, 220], 5)\r\n\r\n    # arc at the top of the goal box\r\n    pygame.draw.arc(screen, WHITE, [330, 280, 140, 40], math.pi, 2 * math.pi, 5)\r\n\r\n    # score board pole\r\n    pygame.draw.rect(screen, GRAY, [390, 120, 20, 70])\r\n\r\n    # score board\r\n    pygame.draw.rect(screen, BLACK, [300, 40, 200, 90])\r\n    pygame.draw.rect(screen, WHITE, [302, 42, 198, 88], 2)\r\n\r\n    # goal\r\n    pygame.draw.rect(screen, WHITE, [320, 140, 160, 80], 5)\r\n    pygame.draw.line(screen, WHITE, [340, 200], [460, 200], 3)\r\n    pygame.draw.line(screen, WHITE, [320, 220], [340, 200], 3)\r\n    pygame.draw.line(screen, WHITE, [480, 220], [460, 200], 3)\r\n    pygame.draw.line(screen, WHITE, [320, 140], [340, 200], 3)\r\n    pygame.draw.line(screen, WHITE, [480, 140], [460, 200], 3)\r\n\r\n    # 6 yard line goal box\r\n    pygame.draw.line(screen, WHITE, [310, 220], [270, 270], 3)\r\n    pygame.draw.line(screen, WHITE, [270, 270], [530, 270], 2)\r\n    pygame.draw.line(screen, WHITE, [530, 270], [490, 220], 3)\r\n\r\n    # light pole 1\r\n    pygame.draw.rect(screen, GRAY, [150, 60, 20, 140])\r\n    pygame.draw.ellipse(screen, GRAY, [150, 195, 20, 10])\r\n\r\n    # lights\r\n    pygame.draw.line(screen, GRAY, [110, 60], [210, 60], 2)\r\n    pygame.draw.ellipse(screen, light_color, [110, 40, 20, 20])\r\n    pygame.draw.ellipse(screen, light_color, [130, 40, 20, 20])\r\n    pygame.draw.ellipse(screen, light_color, [150, 40, 20, 20])\r\n    pygame.draw.ellipse(screen, light_color, [170, 40, 20, 20])\r\n    pygame.draw.ellipse(screen, light_color, [190, 40, 20, 20])\r\n    pygame.draw.line(screen, GRAY, [110, 40], [210, 40], 2)\r\n    pygame.draw.ellipse(screen, light_color, [110, 20, 20, 20])\r\n    pygame.draw.ellipse(screen, light_color, [130, 20, 20, 20])\r\n    pygame.draw.ellipse(screen, light_color, [150, 20, 20, 20])\r\n    pygame.draw.ellipse(screen, light_color, [170, 20, 20, 20])\r\n    pygame.draw.ellipse(screen, light_color, [190, 20, 20, 20])\r\n    pygame.draw.line(screen, GRAY, [110, 20], [210, 20], 2)\r\n\r\n    # light pole 2\r\n    pygame.draw.rect(screen, GRAY, [630, 60, 20, 140])\r\n    pygame.draw.ellipse(screen, GRAY, [630, 195, 20, 10])\r\n\r\n    # lights\r\n\r\n    pygame.draw.line(screen, GRAY, [590, 60], [690, 60], 2)\r\n    pygame.draw.ellipse(screen, light_color, [590, 40, 20, 20])\r\n    pygame.draw.ellipse(screen, light_color, [610, 40, 20, 20])\r\n    pygame.draw.ellipse(screen, light_color, [630, 40, 20, 20])\r\n    pygame.draw.ellipse(screen, light_color, [650, 40, 20, 20])\r\n    pygame.draw.ellipse(screen, light_color, [670, 40, 20, 20])\r\n    pygame.draw.line(screen, GRAY, [590, 40], [690, 40], 2)\r\n    pygame.draw.ellipse(screen, light_color, [590, 20, 20, 20])\r\n    pygame.draw.ellipse(screen, light_color, [610, 20, 20, 20])\r\n    pygame.draw.ellipse(screen, light_color, [630, 20, 20, 20])\r\n    pygame.draw.ellipse(screen, light_color, [650, 20, 20, 20])\r\n    pygame.draw.ellipse(screen, light_color, [670, 20, 20, 20])\r\n    pygame.draw.line(screen, GRAY, [590, 20], [690, 20], 2)\r\n\r\n    # net\r\n    pygame.draw.line(screen, WHITE, [325, 140], [341, 200], 1)\r\n    pygame.draw.line(screen, WHITE, [330, 140], [344, 200], 1)\r\n    pygame.draw.line(screen, WHITE, [335, 140], [347, 200], 1)\r\n    pygame.draw.line(screen, WHITE, [340, 140], [350, 200], 1)\r\n    pygame.draw.line(screen, WHITE, [345, 140], [353, 200], 1)\r\n    pygame.draw.line(screen, WHITE, [350, 140], [356, 200], 1)\r\n    pygame.draw.line(screen, WHITE, [355, 140], [359, 200], 1)\r\n    pygame.draw.line(screen, WHITE, [360, 140], [362, 200], 1)\r\n    pygame.draw.line(screen, WHITE, [364, 140], [365, 200], 1)\r\n    pygame.draw.line(screen, WHITE, [368, 140], [369, 200], 1)\r\n    pygame.draw.line(screen, WHITE, [372, 140], [373, 200], 1)\r\n    pygame.draw.line(screen, WHITE, [376, 140], [377, 200], 1)\r\n    pygame.draw.line(screen, WHITE, [380, 140], [380, 200], 1)\r\n    pygame.draw.line(screen, WHITE, [384, 140], [384, 200], 1)\r\n    pygame.draw.line(screen, WHITE, [388, 140], [388, 200], 1)\r\n    pygame.draw.line(screen, WHITE, [392, 140], [392, 200], 1)\r\n    pygame.draw.line(screen, WHITE, [396, 140], [396, 200], 1)\r\n    pygame.draw.line(screen, WHITE, [400, 140], [400, 200], 1)\r\n    pygame.draw.line(screen, WHITE, [404, 140], [404, 200], 1)\r\n    pygame.draw.line(screen, WHITE, [408, 140], [408, 200], 1)\r\n    pygame.draw.line(screen, WHITE, [412, 140], [412, 200], 1)\r\n    pygame.draw.line(screen, WHITE, [416, 140], [416, 200], 1)\r\n    pygame.draw.line(screen, WHITE, [420, 140], [420, 200], 1)\r\n    pygame.draw.line(screen, WHITE, [424, 140], [423, 200], 1)\r\n    pygame.draw.line(screen, WHITE, [428, 140], [427, 200], 1)\r\n    pygame.draw.line(screen, WHITE, [432, 140], [431, 200], 1)\r\n    pygame.draw.line(screen, WHITE, [436, 140], [435, 200], 1)\r\n    pygame.draw.line(screen, WHITE, [440, 140], [438, 200], 1)\r\n    pygame.draw.line(screen, WHITE, [445, 140], [441, 200], 1)\r\n    pygame.draw.line(screen, WHITE, [450, 140], [444, 200], 1)\r\n    pygame.draw.line(screen, WHITE, [455, 140], [447, 200], 1)\r\n    pygame.draw.line(screen, WHITE, [460, 140], [450, 200], 1)\r\n    pygame.draw.line(screen, WHITE, [465, 140], [453, 200], 1)\r\n    pygame.draw.line(screen, WHITE, [470, 140], [456, 200], 1)\r\n    pygame.draw.line(screen, WHITE, [475, 140], [459, 200], 1)\r\n\r\n    # net part 2\r\n    pygame.draw.line(screen, WHITE, [320, 140], [324, 216], 1)\r\n    pygame.draw.line(screen, WHITE, [320, 140], [326, 214], 1)\r\n    pygame.draw.line(screen, WHITE, [320, 140], [328, 212], 1)\r\n    pygame.draw.line(screen, WHITE, [320, 140], [330, 210], 1)\r\n    pygame.draw.line(screen, WHITE, [320, 140], [332, 208], 1)\r\n    pygame.draw.line(screen, WHITE, [320, 140], [334, 206], 1)\r\n    pygame.draw.line(screen, WHITE, [320, 140], [336, 204], 1)\r\n    pygame.draw.line(screen, WHITE, [320, 140], [338, 202], 1)\r\n\r\n    # net part 3\r\n    pygame.draw.line(screen, WHITE, [480, 140], [476, 216], 1)\r\n    pygame.draw.line(screen, WHITE, [480, 140], [474, 214], 1)\r\n    pygame.draw.line(screen, WHITE, [480, 140], [472, 212], 1)\r\n    pygame.draw.line(screen, WHITE, [480, 140], [470, 210], 1)\r\n    pygame.draw.line(screen, WHITE, [480, 140], [468, 208], 1)\r\n    pygame.draw.line(screen, WHITE, [480, 140], [466, 206], 1)\r\n    pygame.draw.line(screen, WHITE, [480, 140], [464, 204], 1)\r\n    pygame.draw.line(screen, WHITE, [480, 140], [462, 202], 1)\r\n\r\n    # net part 4\r\n    pygame.draw.line(screen, WHITE, [324, 144], [476, 144], 1)\r\n    pygame.draw.line(screen, WHITE, [324, 148], [476, 148], 1)\r\n    pygame.draw.line(screen, WHITE, [324, 152], [476, 152], 1)\r\n    pygame.draw.line(screen, WHITE, [324, 156], [476, 156], 1)\r\n    pygame.draw.line(screen, WHITE, [324, 160], [476, 160], 1)\r\n    pygame.draw.line(screen, WHITE, [324, 164], [476, 164], 1)\r\n    pygame.draw.line(screen, WHITE, [324, 168], [476, 168], 1)\r\n    pygame.draw.line(screen, WHITE, [324, 172], [476, 172], 1)\r\n    pygame.draw.line(screen, WHITE, [324, 176], [476, 176], 1)\r\n    pygame.draw.line(screen, WHITE, [335, 180], [470, 180], 1)\r\n    pygame.draw.line(screen, WHITE, [335, 184], [465, 184], 1)\r\n    pygame.draw.line(screen, WHITE, [335, 188], [465, 188], 1)\r\n    pygame.draw.line(screen, WHITE, [335, 192], [465, 192], 1)\r\n    pygame.draw.line(screen, WHITE, [335, 196], [465, 196], 1)\r\n\r\n    # stands right\r\n    pygame.draw.polygon(screen, RED, [[680, 220], [800, 340], [800, 290], [680, 180]])\r\n    pygame.draw.polygon(screen, WHITE, [[680, 180], [800, 100], [800, 290]])\r\n\r\n    # stands left\r\n    pygame.draw.polygon(screen, RED, [[120, 220], [0, 340], [0, 290], [120, 180]])\r\n    pygame.draw.polygon(screen, WHITE, [[120, 180], [0, 100], [0, 290]])\r\n    # people\r\n\r\n    # corner flag right\r\n    pygame.draw.line(screen, BRIGHT_YELLOW, [140, 220], [135, 190], 3)\r\n    pygame.draw.polygon(screen, RED, [[132, 190], [125, 196], [135, 205]])\r\n\r\n    # corner flag left\r\n    pygame.draw.line(screen, BRIGHT_YELLOW, [660, 220], [665, 190], 3)\r\n    pygame.draw.polygon(screen, RED, [[668, 190], [675, 196], [665, 205]])\r\n\r\n    # DARKNESS\r\n    if not day and not lights_on:\r\n        screen.blit(DARKNESS, (0, 0))\r\n\r\n        # WHAT???\r\n    # pygame.draw.polygon(screen, BLACK, [[200, 200], [50,400], [600, 500]], 10)\r\n\r\n    ''' angles for arcs are measured in radians (a pre-cal topic) '''\r\n    # pygame.draw.arc(screen, ORANGE, [100, 100, 100, 100], 0, math.pi/2, 1)\r\n    # pygame.draw.arc(screen, BLACK, [100, 100, 100, 100], 0, math.pi/2, 50)\r\n\r\n    # Update screen (Actually draw the picture in the window.)\r\n    pygame.display.flip()\r\n\r\n    # Limit refresh rate of game loop\r\n    clock.tick(refresh_rate)\r\n\r\n# Close window and quit\r\npygame.quit()\r\n"
  },
  {
    "path": "python/lec_07/house.py",
    "content": "\ndef main():\n    x, y = 300, 400\n    width, height = 200, 300\n\n    draw_house(x, y, width, height)\n\n\ndef draw_house(x, y, width, height):\n    \"\"\"\n    Нарисовать домик ширины width и высоты height от опорной точки (x, y),\n    которая находится в середине нижней точки фундамента.\n    :param x: координата x середины домика\n    :param y: координата y низа фундамента\n    :param width: полная ширина домика (фундамен или вылеты крыши включены)\n    :param height: полная высота домика\n    :return: None\n    \"\"\"\n    print('Типа рисую домик...', x, y, width, height)\n    foundation_height = 0.05 * height\n    walls_width = 0.9 * width\n    walls_height = 0.5 * height\n    roof_height = height - foundation_height - walls_height\n\n    draw_house_foundation(x, y, width, foundation_height)\n    draw_house_walls(x, y - foundation_height, walls_width, walls_height)\n    draw_house_roof(x, y - foundation_height - walls_height, width, roof_height)\n\n\ndef draw_house_foundation(x, y, width, height):\n    \"\"\"\n    Нарисовать основание домика ширины width и высоты height от опорной точки (x, y),\n    которая находится в середине нижней точки фундамента.\n    :param x: координата x середины фундамента\n    :param y: координата y низа фундамента\n    :param width: полная ширина фундамена\n    :param height: полная высота фундамента\n    :return: None\n    \"\"\"\n    print('Типа рисую основание...', x, y, width, height)\n    pass\n\n\ndef draw_house_walls(x, y, width, height):\n    print('Типа рисую стены...', x, y, width, height)\n    pass\n\n\ndef draw_house_roof(x, y, width, height):\n    print('Типа рисую крышу...', x, y, width, height)\n    pass\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "python/lec_07/lib.py",
    "content": "\ndef foo(x):\n    print('foo(', x, ') is called')\n\n\ndef bar(x, y):\n    print(x + y)\n\ndef print_name():\n    print(__name__)\n\n\nprint_name()\n"
  },
  {
    "path": "python/lec_07/main.py",
    "content": "import lib\n\nlib.foo(5)\nlib.bar(2, 3)\nprint('from module main.py __name__ ==', __name__)\n"
  },
  {
    "path": "python/lec_08/01_class.py",
    "content": "class Dragon:\n    def __init__(self, name):\n        self.name = name\n        self.health = 100\n\n    def is_alive(self):\n        return self.health > 0\n\n    def get_damage(self, damage):\n        self.health -= damage\n        if self.health < 0:\n            self.health = 0\n\n    def talk(self):\n        print(self.name, 'health', self.health, '. Hit me!')\n\n    def final_cry(self):\n        print(self.name, 'is dead...')\n\ndef main():\n    \n    enemy_list = [Dragon('Smog'), Dragon('Hidra')]\n    finish = False\n    while not finish:\n        enemy = enemy_list[0]\n        enemy.talk()\n        damage = int(input())\n        enemy.get_damage(damage)\n        if not enemy.is_alive(): # удалить из списка мёртвого врага\n            enemy.final_cry()\n            enemy_list.pop(0)\n        if not enemy_list:  # проверить пуст ли список врагов\n            finish = True\n        \n    print('You win!')\n\nmain()\n        \n\n"
  },
  {
    "path": "python/lec_08/02_encapsulation_example.py",
    "content": "# coding=UTF-8\nclass PositiveInt:\n    __a = 0\n    __counter = 0\n\n    def set_a(self, a):\n        self.__counter += 1\n        if a >= 0:\n            self.__a = int(a)\n        else:\n            print(\"Wrong parameter, an internal state won't change.\" )\n\n    def get_a(self):\n        print(\"Was set\", self.__counter, \"times.\")\n        return self.__a\n\n\nif __name__ == \"__main__\":\n    value = PositiveInt()\n\n    print(value.get_a())\n\n    value.set_a(10)\n    print(value.get_a())\n\n    value.set_a(-10)\n    print(value.get_a())\n"
  },
  {
    "path": "python/lec_08/2016-pacman/LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    {one line to give the program's name and a brief idea of what it does.}\n    Copyright (C) {year}  {name of author}\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    {project}  Copyright (C) {year}  {fullname}\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<http://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<http://www.gnu.org/philosophy/why-not-lgpl.html>.\n"
  },
  {
    "path": "python/lec_08/2016-pacman/README.md",
    "content": "# pacman\nПреподавательская версия проекта Pacman\n"
  },
  {
    "path": "python/lec_08/2016-pacman/pacman.py",
    "content": "import sys\nimport pygame\nfrom pygame.locals import *\nfrom math import floor\nimport random\n\n\ndef init_window():\n    pygame.init()\n    pygame.display.set_mode((512, 512))\n    pygame.display.set_caption('Pacman')\n\n\ndef draw_background(scr, img=None):\n    if img:\n        scr.blit(img, (0, 0))\n    else:\n        bg = pygame.Surface(scr.get_size())\n        bg.fill((128, 128, 128))\n        scr.blit(bg, (0, 0))\n\n\nclass GameObject(pygame.sprite.Sprite):\n    def __init__(self, img, x, y, tile_size, map_size):\n        pygame.sprite.Sprite.__init__(self)\n        self.image = pygame.image.load(img)\n        self.screen_rect = None\n        self.x = 0\n        self.y = 0\n        self.tick = 0\n        self.tile_size = tile_size\n        self.map_size = map_size\n        self.set_coord(x, y)\n\n    def set_coord(self, x, y):\n        self.x = x\n        self.y = y\n        self.screen_rect = Rect(floor(x) * self.tile_size, floor(y) * self.tile_size, self.tile_size, self.tile_size )\n\n    def game_tick(self):\n        self.tick += 1\n\n    def draw(self, scr):\n        scr.blit(self.image, (self.screen_rect.x, self.screen_rect.y))\n\n\nclass Ghost(GameObject):\n    def __init__(self, x, y, tile_size, map_size):\n        GameObject.__init__(self, './resources/ghost.png', x, y, tile_size, map_size)\n        self.direction = 0\n        self.velocity = 4.0 / 10.0\n\n    def game_tick(self):\n        super(Ghost, self).game_tick()\n        if self.tick % 20 == 0 or self.direction == 0:\n            self.direction = random.randint(1, 4)\n\n        if self.direction == 1:\n            self.x += self.velocity\n            if self.x >= self.map_size-1:\n                self.x = self.map_size-1\n                self.direction = random.randint(1, 4)\n        elif self.direction == 2:\n            self.y += self.velocity\n            if self.y >= self.map_size-1:\n                self.y = self.map_size-1\n                self.direction = random.randint(1, 4)\n        elif self.direction == 3:\n            self.x -= self.velocity\n            if self.x <= 0:\n                self.x = 0\n                self.direction = random.randint(1, 4)\n        elif self.direction == 4:\n            self.y -= self.velocity\n            if self.y <= 0:\n                self.y = 0\n                self.direction = random.randint(1, 4)\n        self.set_coord(self.x, self.y)\n\n\nclass Pacman(GameObject):\n    def __init__(self, x, y, tile_size, map_size):\n        GameObject.__init__(self, './resources/pacman.png', x, y, tile_size, map_size)\n        self.direction = 0\n        self.velocity = 4.0 / 10.0\n\n    def game_tick(self):\n        super(Pacman, self).game_tick()\n        if self.direction == 1:\n            self.x += self.velocity\n            if self.x >= self.map_size-1:\n                self.x = self.map_size-1\n        elif self.direction == 2:\n            self.y += self.velocity\n            if self.y >= self.map_size-1:\n                self.y = self.map_size-1\n        elif self.direction == 3:\n            self.x -= self.velocity\n            if self.x <= 0:\n                self.x = 0\n        elif self.direction == 4:\n            self.y -= self.velocity\n            if self.y <= 0:\n                self.y = 0\n\n        self.set_coord(self.x, self.y)\n\n\ndef process_events(events, packman):\n    for event in events:\n        if (event.type == QUIT) or (event.type == KEYDOWN and event.key == K_ESCAPE):\n            sys.exit(0)\n        elif event.type == KEYDOWN:\n            if event.key == K_LEFT:\n                packman.direction = 3\n            elif event.key == K_RIGHT:\n                packman.direction = 1\n            elif event.key == K_UP:\n                packman.direction = 4\n            elif event.key == K_DOWN:\n                packman.direction = 2\n            elif event.key == K_SPACE:\n                packman.direction = 0\n\n\nif __name__ == '__main__':\n    init_window()\n    tile_size = 32\n    map_size = 16\n    ghost = Ghost(0, 0, tile_size, map_size)\n    pacman = Pacman(5, 5, tile_size, map_size)\n    background = None #pygame.image.load(\"./resources/background.png\")\n    screen = pygame.display.get_surface()\n\n    while True:\n        process_events(pygame.event.get(), pacman)\n        pygame.time.delay(100)\n        ghost.game_tick()\n        pacman.game_tick()\n        draw_background(screen, background)\n        pacman.draw(screen)\n        ghost.draw(screen)\n        pygame.display.update()\n"
  },
  {
    "path": "python/lec_08/cannon/LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<https://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<https://www.gnu.org/licenses/why-not-lgpl.html>.\n"
  },
  {
    "path": "python/lec_08/cannon/README.md",
    "content": "# cannon\nНабросок игры \"Пушка\"\n\nРеализация ООП.\n\n\nСсылка на старую игру пушка: http://judge.mipt.ru/mipt_cs_on_python3_2016/labs/lab10.html#id4\n"
  },
  {
    "path": "python/lec_08/cannon/cannon.py",
    "content": "import random as rnd\nimport math\nimport pygame\n\nfrom my_colors import *\n\nFPS = 20\nGRAVITY_ACCELERATION = 9.8  # Ускорение свободного падения для снаряда.\nSCREEN_WIDTH, SCREEN_HEIGHT = 800, 600\n\n\nclass Cannon:\n    max_velocity = 10\n\n    def __init__(self, x, y):\n        self.x = x\n        self.y = y\n        self.shell_num = None  # TODO: оставшееся на данный момент количество снарядов\n        self.direction = math.pi / 4\n\n    def aim(self, x, y):\n        \"\"\"\n        Меняет направление direction так, чтобы он из точки\n         (self.x, self.y) указывал в точку (x, y).\n        :param x: координата x, в которую целимся\n        :param y: координата y, в которую целимся\n        :return: None\n        \"\"\"\n        pass  # TODO\n\n    def fire(self, dt):\n        \"\"\"\n        Создаёт объект снаряда (если ещё не потрачены все снаряды)\n        летящий в направлении угла direction\n        со скоростью, зависящей от длительности клика мышки\n        :param dt:  длительность клика мышки, мс\n        :return: экземпляр снаряда типа Shell\n        \"\"\"\n        pass\n\n    def draw(self):\n        pygame.draw.circle(screen, self.color,\n                           (int(round(self.x)), int(round(self.y))), self.r)\n\n\nclass Shell:\n    standard_radius = 25\n\n    def __init__(self, x, y, Vx, Vy):\n        self.x, self.y = x, y\n        self.Vx, self.Vy = Vx, Vy\n        self.r = Shell.standard_radius\n\n    def move(self, dt):\n        \"\"\"\n        Сдвигает снаряд исходя из его кинематических характеристик\n        и длины кванта времени dt\n        в новое положение, а также меняет его скорость.\n        :param dt:\n        :return:\n        \"\"\"\n        ax, ay = 0, GRAVITY_ACCELERATION\n        self.x += self.Vx*dt + ax*(dt**2)/2\n        self.y += self.Vy*dt + ay*(dt**2)/2\n        self.Vx += ax*dt\n        self.Vy += ay*dt\n        # TODO: Уничтожать (в статус deleted) снаряд, когда он касается земли.\n\n    def draw(self):\n        pygame.draw.circle(screen, self.color,\n                           (int(round(self.x)), int(round(self.y))), self.r)\n\n    def detect_collision(self, other):\n        \"\"\"\n        Проверяет факт соприкосновения снаряда и объекта other\n        :param other: объект, который должен иметь поля x, y, r\n        :return: логическое значение типа bool\n        \"\"\"\n        length = ((self.x - other.x)**2 + (self.y - other.y)**2)**0.5\n        return length <= self.r + other.r\n\n\nclass Target:\n    standard_radius = 15\n\n    def __init__(self, x, y, Vx, Vy):\n        self.x, self.y = x, y\n        self.Vx, self.Vy = Vx, Vy\n        self.r = Target.standard_radius\n        self.color = COLORS[rnd.randint(0, len(COLORS) - 1)]\n\n    def move(self, dt):\n        \"\"\"\n        Сдвигает шарик-мишень исходя из его кинематических характеристик\n        и длины кванта времени dt\n        в новое положение, а также меняет его скорость.\n        :param dt:\n            :return:\n        \"\"\"\n        ax, ay = 0, GRAVITY_ACCELERATION\n        self.x += self.Vx * dt\n        self.y += self.Vy * dt\n        self.Vx += ax * dt\n        self.Vy += ay * dt\n        # TODO: Шарики-мишени должны отражаться от стенок\n\n    def draw(self):\n        pygame.draw.circle(screen, self.color,\n                           (int(round(self.x)), int(round(self.y))), self.r)\n\n    def collide(self, other):\n        \"\"\"\n        Расчёт абсолютно упругого соударения\n        :param other:\n        :return:\n        \"\"\"\n        pass  #TODO\n\n\nclass Bomb:\n    pass\n\n\ndef generate_random_targets(number: int):\n    targets = []\n    for i in range(number):\n        x = rnd.randint(0, SCREEN_HEIGHT)\n        y = rnd.randint(0, SCREEN_HEIGHT)\n        Vx = rnd.randint(-30, +30)\n        Vy = rnd.randint(-30, +30)\n        target = Target(x, y, Vx, Vy)\n        targets.append(target)\n    return targets\n\n\ndef game_main_loop():\n\n    targets = generate_random_targets(10)\n\n    clock = pygame.time.Clock()\n    finished = False\n\n    while not finished:\n        dt = clock.tick(FPS) / 1000\n        print(dt)\n        for event in pygame.event.get():\n            if event.type == pygame.QUIT:\n                finished = True\n            elif event.type == pygame.MOUSEBUTTONDOWN:\n                print('Click!')\n\n        pygame.display.update()\n        screen.fill(GRAY)\n\n        for target in targets:\n            target.move(dt)\n\n        for target in targets:\n            target.draw()\n\n    pygame.quit()\n\n\nif __name__ == \"__main__\":\n    pygame.init()\n    screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))\n    pygame.display.update()\n\n    game_main_loop()\n"
  },
  {
    "path": "python/lec_08/cannon/my_colors.py",
    "content": "RED = (255, 0, 0)\nBLUE = (0, 0, 255)\nYELLOW = (255, 255, 0)\nGREEN = (0, 255, 0)\nMAGENTA = (255, 0, 255)\nCYAN = (0, 255, 255)\nBLACK = (0, 0, 0)\nWHITE = (255, 255, 255)\nGRAY = (100, 100, 100)\nCOLORS = [RED, BLUE, YELLOW, GREEN, MAGENTA, CYAN]\n"
  },
  {
    "path": "python/lec_09/01_hierarchy.py",
    "content": "class Base:\n    def __init__(self, x):\n        self.x = x\n\n    def show(self):\n        print('Base', self.x)\n\n\nclass Derivative(Base):\n    def __init__(self):\n        super().__init__(20) # явный вызов конструктора\n        self.name = ''\n\n\na = Base(10)\nb = Derivative()\na.show()\nb.show()\n\n\n"
  },
  {
    "path": "python/lec_09/cannon.py",
    "content": "import numpy as np\nimport pygame as pg\nfrom random import randint, gauss\n\npg.init()\npg.font.init()\n\nWHITE = (255, 255, 255)\nBLACK = (0, 0, 0)\nRED = (255, 0, 0)\n\nSCREEN_SIZE = (800, 600)\n\n\ndef rand_color():\n    return (randint(0, 255), randint(0, 255), randint(0, 255))\n\n\nclass GameObject:\n    pass\n\n\nclass Shell(GameObject):\n    '''\n    The ball class. Creates a ball, controls it's movement and implement it's rendering.\n    '''\n    def __init__(self, coord, vel, rad=20, color=None):\n        '''\n        Constructor method. Initializes ball's parameters and initial values.\n        '''\n        self.coord = coord\n        self.vel = vel\n        if color == None:\n            color = rand_color()\n        self.color = color\n        self.rad = rad\n        self.is_alive = True\n\n    def check_corners(self, refl_ort=0.8, refl_par=0.9):\n        '''\n        Reflects ball's velocity when ball bumps into the screen corners. Implemetns inelastic rebounce.\n        '''\n        for i in range(2):\n            if self.coord[i] < self.rad:\n                self.coord[i] = self.rad\n                self.vel[i] = -int(self.vel[i] * refl_ort)\n                self.vel[1-i] = int(self.vel[1-i] * refl_par)\n            elif self.coord[i] > SCREEN_SIZE[i] - self.rad:\n                self.coord[i] = SCREEN_SIZE[i] - self.rad\n                self.vel[i] = -int(self.vel[i] * refl_ort)\n                self.vel[1-i] = int(self.vel[1-i] * refl_par)\n\n    def move(self, time=1, grav=0):\n        '''\n        Moves the ball according to it's velocity and time step.\n        Changes the ball's velocity due to gravitational force.\n        '''\n        self.vel[1] += grav\n        for i in range(2):\n            self.coord[i] += time * self.vel[i]\n        self.check_corners()\n        if self.vel[0]**2 + self.vel[1]**2 < 2**2 and self.coord[1] > SCREEN_SIZE[1] - 2*self.rad:\n            self.is_alive = False\n\n    def draw(self, screen):\n        '''\n        Draws the ball on appropriate surface.\n        '''\n        pg.draw.circle(screen, self.color, self.coord, self.rad)\n\n\nclass Cannon(GameObject):\n    '''\n    Cannon class. Manages it's renderring, movement and striking.\n    '''\n    def __init__(self, coord=[30, SCREEN_SIZE[1]//2], angle=0, max_pow=50, min_pow=10, color=RED):\n        '''\n        Constructor method. Sets coordinate, direction, minimum and maximum power and color of the gun.\n        '''\n        self.coord = coord\n        self.angle = angle\n        self.max_pow = max_pow\n        self.min_pow = min_pow\n        self.color = color\n        self.active = False\n        self.pow = min_pow\n    \n    def activate(self):\n        '''\n        Activates gun's charge.\n        '''\n        self.active = True\n\n    def gain(self, inc=2):\n        '''\n        Increases current gun charge power.\n        '''\n        if self.active and self.pow < self.max_pow:\n            self.pow += inc\n\n    def strike(self):\n        '''\n        Creates ball, according to gun's direction and current charge power.\n        '''\n        vel = self.pow\n        angle = self.angle\n        ball = Shell(list(self.coord), [int(vel * np.cos(angle)), int(vel * np.sin(angle))])\n        self.pow = self.min_pow\n        self.active = False\n        return ball\n        \n    def set_angle(self, target_pos):\n        '''\n        Sets gun's direction to target position.\n        '''\n        self.angle = np.arctan2(target_pos[1] - self.coord[1], target_pos[0] - self.coord[0])\n\n    def move(self, inc):\n        '''\n        Changes vertical position of the gun.\n        '''\n        if (self.coord[1] > 30 or inc > 0) and (self.coord[1] < SCREEN_SIZE[1] - 30 or inc < 0):\n            self.coord[1] += inc\n\n    def draw(self, screen):\n        '''\n        Draws the gun on the screen.\n        '''\n        gun_shape = []\n        vec_1 = np.array([int(5*np.cos(self.angle - np.pi/2)), int(5*np.sin(self.angle - np.pi/2))])\n        vec_2 = np.array([int(self.pow*np.cos(self.angle)), int(self.pow*np.sin(self.angle))])\n        gun_pos = np.array(self.coord)\n        gun_shape.append((gun_pos + vec_1).tolist())\n        gun_shape.append((gun_pos + vec_1 + vec_2).tolist())\n        gun_shape.append((gun_pos + vec_2 - vec_1).tolist())\n        gun_shape.append((gun_pos - vec_1).tolist())\n        pg.draw.polygon(screen, self.color, gun_shape)\n\n\nclass Target(GameObject):\n    '''\n    Target class. Creates target, manages it's rendering and collision with a ball event.\n    '''\n    def __init__(self, coord=None, color=None, rad=30):\n        '''\n        Constructor method. Sets coordinate, color and radius of the target.\n        '''\n        if coord == None:\n            coord = [randint(rad, SCREEN_SIZE[0] - rad), randint(rad, SCREEN_SIZE[1] - rad)]\n        self.coord = coord\n        self.rad = rad\n\n        if color == None:\n            color = rand_color()\n        self.color = color\n\n    def check_collision(self, ball):\n        '''\n        Checks whether the ball bumps into target.\n        '''\n        dist = sum([(self.coord[i] - ball.coord[i])**2 for i in range(2)])**0.5\n        min_dist = self.rad + ball.rad\n        return dist <= min_dist\n\n    def draw(self, screen):\n        '''\n        Draws the target on the screen\n        '''\n        pg.draw.circle(screen, self.color, self.coord, self.rad)\n\n    def move(self):\n        \"\"\"\n        This type of target can't move at all.\n        :return: None\n        \"\"\"\n        pass\n\n\nclass MovingTarget(Target):\n    def __init__(self, coord=None, color=None, rad=30):\n        super().__init__(coord, color, rad)\n        self.vx = randint(-2, +2)\n        self.vy = randint(-2, +2)\n\n    def move(self):\n        self.coord[0] += self.vx\n        self.coord[1] += self.vy\n\n\nclass ScoreTable:\n    '''\n    Score table class.\n    '''\n    def __init__(self, t_destr=0, b_used=0):\n        self.t_destr = t_destr\n        self.b_used = b_used\n        self.font = pg.font.SysFont(\"dejavusansmono\", 25)\n\n    def score(self):\n        '''\n        Score calculation method.\n        '''\n        return self.t_destr - self.b_used\n\n    def draw(self, screen):\n        score_surf = []\n        score_surf.append(self.font.render(\"Destroyed: {}\".format(self.t_destr), True, WHITE))\n        score_surf.append(self.font.render(\"Balls used: {}\".format(self.b_used), True, WHITE))\n        score_surf.append(self.font.render(\"Total: {}\".format(self.score()), True, RED))\n        for i in range(3):\n            screen.blit(score_surf[i], [10, 10 + 30*i])\n\n\nclass Manager:\n    '''\n    Class that manages events' handling, ball's motion and collision, target creation, etc.\n    '''\n    def __init__(self, n_targets=1):\n        self.balls = []\n        self.gun = Cannon()\n        self.targets = []\n        self.score_t = ScoreTable()\n        self.n_targets = n_targets\n        self.new_mission()\n\n    def new_mission(self):\n        '''\n        Adds new targets.\n        '''\n        for i in range(self.n_targets):\n            self.targets.append(Target(rad=randint(max(1, 30 - 2*max(0, self.score_t.score())),\n                30 - max(0, self.score_t.score()))))\n        for i in range(self.n_targets):\n            self.targets.append(MovingTarget(rad=randint(max(1, 30 - 2 * max(0, self.score_t.score())),\n                                                     30 - max(0, self.score_t.score()))))\n\n    def process(self, events, screen):\n        '''\n        Runs all necessary method for each iteration. Adds new targets, if previous are destroyed.\n        '''\n        done = self.handle_events(events)\n\n        if pg.mouse.get_focused():\n            mouse_pos = pg.mouse.get_pos()\n            self.gun.set_angle(mouse_pos)\n        \n        self.move()\n        self.collide()\n        self.draw(screen)\n\n        if len(self.targets) == 0 and len(self.balls) == 0:\n            self.new_mission()\n\n        return done\n\n    def handle_events(self, events):\n        '''\n        Handles events from keyboard, mouse, etc.\n        '''\n        done = False\n        for event in events:\n            if event.type == pg.QUIT:\n                done = True\n            elif event.type == pg.KEYDOWN:\n                if event.key == pg.K_UP:\n                    self.gun.move(-5)\n                elif event.key == pg.K_DOWN:\n                    self.gun.move(5)\n            elif event.type == pg.MOUSEBUTTONDOWN:\n                if event.button == 1:\n                    self.gun.activate()\n            elif event.type == pg.MOUSEBUTTONUP:\n                if event.button == 1:\n                    self.balls.append(self.gun.strike())\n                    self.score_t.b_used += 1\n        return done\n\n    def draw(self, screen):\n        '''\n        Runs balls', gun's, targets' and score table's drawing method.\n        '''\n        for ball in self.balls:\n            ball.draw(screen)\n        for target in self.targets:\n            target.draw(screen)\n        self.gun.draw(screen)\n        self.score_t.draw(screen)\n\n    def move(self):\n        '''\n        Runs balls' and gun's movement method, removes dead balls.\n        '''\n        dead_balls = []\n        for i, ball in enumerate(self.balls):\n            ball.move(grav=2)\n            if not ball.is_alive:\n                dead_balls.append(i)\n        for i in reversed(dead_balls):\n            self.balls.pop(i)\n        for i, target in enumerate(self.targets):\n            target.move()\n        self.gun.gain()\n\n    def collide(self):\n        '''\n        Checks whether balls bump into targets, sets balls' alive trigger.\n        '''\n        collisions = []\n        targets_c = []\n        for i, ball in enumerate(self.balls):\n            for j, target in enumerate(self.targets):\n                if target.check_collision(ball):\n                    collisions.append([i, j])\n                    targets_c.append(j)\n        targets_c.sort()\n        for j in reversed(targets_c):\n            self.score_t.t_destr += 1\n            self.targets.pop(j)\n\n\nscreen = pg.display.set_mode(SCREEN_SIZE)\npg.display.set_caption(\"The gun of Khiryanov\")\n\ndone = False\nclock = pg.time.Clock()\n\nmgr = Manager(n_targets=3)\n\nwhile not done:\n    clock.tick(15)\n    screen.fill(BLACK)\n\n    done = mgr.process(pg.event.get(), screen)\n\n    pg.display.flip()\n\n\npg.quit()\n"
  },
  {
    "path": "python/lec_10/cannon.py",
    "content": "import numpy as np\nimport pygame as pg\nfrom random import randint, gauss\n\npg.init()\npg.font.init()\n\nWHITE = (255, 255, 255)\nBLACK = (0, 0, 0)\nRED = (255, 0, 0)\n\nSCREEN_SIZE = (800, 600)\n\n\ndef rand_color():\n    return (randint(0, 255), randint(0, 255), randint(0, 255))\n\n\nclass GameObject:\n    pass\n\n\nclass Shell(GameObject):\n    '''\n    The ball class. Creates a ball, controls it's movement and implement it's rendering.\n    '''\n    def __init__(self, coord, vel, rad=20, color=None):\n        '''\n        Constructor method. Initializes ball's parameters and initial values.\n        '''\n        self.coord = coord\n        self.vel = vel\n        if color == None:\n            color = rand_color()\n        self.color = color\n        self.rad = rad\n        self.is_alive = True\n\n    def check_corners(self, refl_ort=0.8, refl_par=0.9):\n        '''\n        Reflects ball's velocity when ball bumps into the screen corners. Implemetns inelastic rebounce.\n        '''\n        for i in range(2):\n            if self.coord[i] < self.rad:\n                self.coord[i] = self.rad\n                self.vel[i] = -int(self.vel[i] * refl_ort)\n                self.vel[1-i] = int(self.vel[1-i] * refl_par)\n            elif self.coord[i] > SCREEN_SIZE[i] - self.rad:\n                self.coord[i] = SCREEN_SIZE[i] - self.rad\n                self.vel[i] = -int(self.vel[i] * refl_ort)\n                self.vel[1-i] = int(self.vel[1-i] * refl_par)\n\n    def move(self, time=1, grav=0):\n        '''\n        Moves the ball according to it's velocity and time step.\n        Changes the ball's velocity due to gravitational force.\n        '''\n        self.vel[1] += grav\n        for i in range(2):\n            self.coord[i] += time * self.vel[i]\n        self.check_corners()\n        if self.vel[0]**2 + self.vel[1]**2 < 2**2 and self.coord[1] > SCREEN_SIZE[1] - 2*self.rad:\n            self.is_alive = False\n\n    def draw(self, screen):\n        '''\n        Draws the ball on appropriate surface.\n        '''\n        pg.draw.circle(screen, self.color, self.coord, self.rad)\n\n\nclass Cannon(GameObject):\n    '''\n    Cannon class. Manages it's renderring, movement and striking.\n    '''\n    def __init__(self, coord=[30, SCREEN_SIZE[1]//2], angle=0, max_pow=50, min_pow=10, color=RED):\n        '''\n        Constructor method. Sets coordinate, direction, minimum and maximum power and color of the gun.\n        '''\n        self.coord = coord\n        self.angle = angle\n        self.max_pow = max_pow\n        self.min_pow = min_pow\n        self.color = color\n        self.active = False\n        self.pow = min_pow\n    \n    def activate(self):\n        '''\n        Activates gun's charge.\n        '''\n        self.active = True\n\n    def gain(self, inc=2):\n        '''\n        Increases current gun charge power.\n        '''\n        if self.active and self.pow < self.max_pow:\n            self.pow += inc\n\n    def strike(self):\n        '''\n        Creates ball, according to gun's direction and current charge power.\n        '''\n        vel = self.pow\n        angle = self.angle\n        ball = Shell(list(self.coord), [int(vel * np.cos(angle)), int(vel * np.sin(angle))])\n        self.pow = self.min_pow\n        self.active = False\n        return ball\n        \n    def set_angle(self, target_pos):\n        '''\n        Sets gun's direction to target position.\n        '''\n        self.angle = np.arctan2(target_pos[1] - self.coord[1], target_pos[0] - self.coord[0])\n\n    def move(self, inc):\n        '''\n        Changes vertical position of the gun.\n        '''\n        if (self.coord[1] > 30 or inc > 0) and (self.coord[1] < SCREEN_SIZE[1] - 30 or inc < 0):\n            self.coord[1] += inc\n\n    def draw(self, screen):\n        '''\n        Draws the gun on the screen.\n        '''\n        gun_shape = []\n        vec_1 = np.array([int(5*np.cos(self.angle - np.pi/2)), int(5*np.sin(self.angle - np.pi/2))])\n        vec_2 = np.array([int(self.pow*np.cos(self.angle)), int(self.pow*np.sin(self.angle))])\n        gun_pos = np.array(self.coord)\n        gun_shape.append((gun_pos + vec_1).tolist())\n        gun_shape.append((gun_pos + vec_1 + vec_2).tolist())\n        gun_shape.append((gun_pos + vec_2 - vec_1).tolist())\n        gun_shape.append((gun_pos - vec_1).tolist())\n        pg.draw.polygon(screen, self.color, gun_shape)\n\n\nclass Target(GameObject):\n    '''\n    Target class. Creates target, manages it's rendering and collision with a ball event.\n    '''\n    def __init__(self, coord=None, color=None, rad=30):\n        '''\n        Constructor method. Sets coordinate, color and radius of the target.\n        '''\n        if coord == None:\n            coord = [randint(rad, SCREEN_SIZE[0] - rad), randint(rad, SCREEN_SIZE[1] - rad)]\n        self.coord = coord\n        self.rad = rad\n\n        if color == None:\n            color = rand_color()\n        self.color = color\n\n    def check_collision(self, ball):\n        '''\n        Checks whether the ball bumps into target.\n        '''\n        dist = sum([(self.coord[i] - ball.coord[i])**2 for i in range(2)])**0.5\n        min_dist = self.rad + ball.rad\n        return dist <= min_dist\n\n    def draw(self, screen):\n        '''\n        Draws the target on the screen\n        '''\n        pg.draw.circle(screen, self.color, self.coord, self.rad)\n\n    def move(self):\n        \"\"\"\n        This type of target can't move at all.\n        :return: None\n        \"\"\"\n        pass\n\n\nclass MovingTarget(Target):\n    def __init__(self, coord=None, color=None, rad=30):\n        super().__init__(coord, color, rad)\n        self.vx = randint(-2, +2)\n        self.vy = randint(-2, +2)\n\n    def move(self):\n        self.coord[0] += self.vx\n        self.coord[1] += self.vy\n\n\nclass ScoreTable:\n    '''\n    Score table class.\n    '''\n    def __init__(self, t_destr=0, b_used=0):\n        self.t_destr = t_destr\n        self.b_used = b_used\n        self.font = pg.font.SysFont(\"dejavusansmono\", 25)\n\n    def score(self):\n        '''\n        Score calculation method.\n        '''\n        return self.t_destr - self.b_used\n\n    def draw(self, screen):\n        score_surf = []\n        score_surf.append(self.font.render(\"Destroyed: {}\".format(self.t_destr), True, WHITE))\n        score_surf.append(self.font.render(\"Balls used: {}\".format(self.b_used), True, WHITE))\n        score_surf.append(self.font.render(\"Total: {}\".format(self.score()), True, RED))\n        for i in range(3):\n            screen.blit(score_surf[i], [10, 10 + 30*i])\n\n\nclass Manager:\n    '''\n    Class that manages events' handling, ball's motion and collision, target creation, etc.\n    '''\n    def __init__(self, n_targets=1):\n        self.balls = []\n        self.gun = Cannon()\n        self.targets = []\n        self.score_t = ScoreTable()\n        self.n_targets = n_targets\n        self.new_mission()\n\n    def new_mission(self):\n        '''\n        Adds new targets.\n        '''\n        for i in range(self.n_targets):\n            self.targets.append(Target(rad=randint(max(1, 30 - 2*max(0, self.score_t.score())),\n                30 - max(0, self.score_t.score()))))\n        for i in range(self.n_targets):\n            self.targets.append(MovingTarget(rad=randint(max(1, 30 - 2 * max(0, self.score_t.score())),\n                                                     30 - max(0, self.score_t.score()))))\n\n    def process(self, events, screen):\n        '''\n        Runs all necessary method for each iteration. Adds new targets, if previous are destroyed.\n        '''\n        done = self.handle_events(events)\n\n        if pg.mouse.get_focused():\n            mouse_pos = pg.mouse.get_pos()\n            self.gun.set_angle(mouse_pos)\n        \n        self.move()\n        self.collide()\n        self.draw(screen)\n\n        if len(self.targets) == 0 and len(self.balls) == 0:\n            self.new_mission()\n\n        return done\n\n    def handle_events(self, events):\n        '''\n        Handles events from keyboard, mouse, etc.\n        '''\n        done = False\n        for event in events:\n            if event.type == pg.QUIT:\n                done = True\n            elif event.type == pg.KEYDOWN:\n                if event.key == pg.K_UP:\n                    self.gun.move(-5)\n                elif event.key == pg.K_DOWN:\n                    self.gun.move(5)\n            elif event.type == pg.MOUSEBUTTONDOWN:\n                if event.button == 1:\n                    self.gun.activate()\n            elif event.type == pg.MOUSEBUTTONUP:\n                if event.button == 1:\n                    self.balls.append(self.gun.strike())\n                    self.score_t.b_used += 1\n        return done\n\n    def draw(self, screen):\n        '''\n        Runs balls', gun's, targets' and score table's drawing method.\n        '''\n        for ball in self.balls:\n            ball.draw(screen)\n        for target in self.targets:\n            target.draw(screen)\n        self.gun.draw(screen)\n        self.score_t.draw(screen)\n\n    def move(self):\n        '''\n        Runs balls' and gun's movement method, removes dead balls.\n        '''\n        dead_balls = []\n        for i, ball in enumerate(self.balls):\n            ball.move(grav=2)\n            if not ball.is_alive:\n                dead_balls.append(i)\n        for i in reversed(dead_balls):\n            self.balls.pop(i)\n        for i, target in enumerate(self.targets):\n            target.move()\n        self.gun.gain()\n\n    def collide(self):\n        '''\n        Checks whether balls bump into targets, sets balls' alive trigger.\n        '''\n        collisions = []\n        targets_c = []\n        for i, ball in enumerate(self.balls):\n            for j, target in enumerate(self.targets):\n                if target.check_collision(ball):\n                    collisions.append([i, j])\n                    targets_c.append(j)\n        targets_c.sort()\n        for j in reversed(targets_c):\n            self.score_t.t_destr += 1\n            self.targets.pop(j)\n\n\nscreen = pg.display.set_mode(SCREEN_SIZE)\npg.display.set_caption(\"The gun of Khiryanov\")\n\ndone = False\nclock = pg.time.Clock()\n\nmgr = Manager(n_targets=3)\n\nwhile not done:\n    clock.tick(15)\n    screen.fill(BLACK)\n\n    done = mgr.process(pg.event.get(), screen)\n\n    pg.display.flip()\n\n\npg.quit()\n"
  },
  {
    "path": "python/lec_11/crosszeroes.py",
    "content": "import pygame\nfrom enum import Enum\n\n\nFPS = 60\nCELL_SIZE = 50\n\n\nclass Cell(Enum):\n    VOID = 0\n    CROSS = 1\n    ZERO = 2\n\n\nclass Player:\n    \"\"\"\n    Класс игрока, содержащий тип значков и имя.\n    \"\"\"\n    def __init__(self, name, cell_type):\n        self.name = name\n        self.cell_type = cell_type\n\n\nclass GameField:\n    def __init__(self):\n        self.height = 3\n        self.width = 3\n        self.cells = [[Cell.VOID]*self.width for i in range(self.height)]\n\n\nclass GameFieldView:\n    \"\"\"\n    Виджет игрового поля, который отображает его на экране, а также выясняет место клика.\n    \"\"\"\n    def __init__(self, field):\n        # загрузить картинки значков клеток...\n        # отобразить первичное состояние поля\n        self._field = field\n        self._height = field.height * CELL_SIZE\n        self._width = field.width * CELL_SIZE\n\n    def draw(self):\n        pass\n\n    def check_coords_correct(self, x, y):\n        return True  # TODO: self._height учесть\n\n    def get_coords(self, x, y):\n        return 0, 0  # TODO: реально вычислить клетку клика\n\n\nclass GameRoundManager:\n    \"\"\"\n    Менеджер игры, запускающий все процессы.\n    \"\"\"\n\n    def __init__(self, player1: Player, player2: Player):\n        self._players = [player1, player2]\n        self._current_player = 0\n        self.field = GameField()\n\n    def handle_click(self, i, j):\n        player = self._players[self._current_player]\n        # игрок делает клик на поле\n        print(\"click_handled\",  i, j)\n\n\nclass GameWindow:\n    \"\"\"\n    Содержит виджет поля,\n    а также менеджера игрового раунда.\n    \"\"\"\n    def __init__(self):\n        # инициализация pygame\n        pygame.init()\n\n        self._width = 800\n        self._height = 600\n        self._title = \"Crosses & Zeroes\"\n        self._screen = pygame.display.set_mode((self._width, self._height))\n        pygame.display.set_caption(self._title)\n\n        player1 = Player(\"Петя\", Cell.CROSS)\n        player2 = Player(\"Вася\", Cell.ZERO)\n        self._game_manager = GameRoundManager(player1, player2)\n        self._field_widget = GameFieldView(self._game_manager.field)\n\n    def main_loop(self):\n        finished = False\n        clock = pygame.time.Clock()\n        while not finished:\n            for event in pygame.event.get():\n                if event.type == pygame.QUIT:\n                    finished = True\n                elif event.type == pygame.MOUSEBUTTONDOWN:\n                    mouse_pos = pygame.mouse.get_pos()\n                    x, y = mouse_pos\n                    if self._field_widget.check_coords_correct(x, y):\n                        i, j = self._field_widget.get_coords(x, y)\n                        self._game_manager.handle_click(i, j)\n            pygame.display.flip()\n            clock.tick(FPS)\n\n\ndef main():\n    window = GameWindow()\n    window.main_loop()\n    print('Game over!')\n\n\nif __name__ == \"__main__\":\n    main()"
  },
  {
    "path": "python/lec_12/1_selfdoc.py",
    "content": "def hypotenuse(leg1, leg2):\n    return (leg1**2 + leg2**2)**0.5\n\n\ndef hypotenuse(leg1, leg2):\n    # Square root from sum of squares of tirangle legs.\n    # [2] Pifagor. Geometry of Euclid.\n    return (leg1**2 + leg2**2)**0.5  \n\n\ndef hypotenuse(leg1: float, leg2: float) -> float:\n    \"\"\"\n    Calculates length of hypotenuse of right triangle.\n    # Look here: [2] Pifagor. Geometry of Euclid.\n\n    :param leg1: length of the **first** triangle leg.\n    :param leg2: length of the _other_ triangle leg.\n    :return: length of the hypotenuse.\n    \"\"\"\n    # Square root from sum of squares of triangle legs.\n    return (leg1**2 + leg2**2)**0.5\n\n\ndef hypotenuse(leg1: float, leg2: float) -> float:\n    \"\"\"\n    Calculates length of hypotenuse of right triangle.\n    # Look here: [2] Pifagor. Geometry of Euclid.\n\n    :param leg1: length of the **first** triangle leg.\n    :param leg2: length of the _other_ triangle leg.\n    :return: length of the hypotenuse.\n    \"\"\"\n    # Square root from sum of squares of triangle legs.\n    length = (leg1**2 + leg2**2)**0.5\n    assert length**2 == leg1**2 + leg2**2, \"OUCH!!! Pifagor theorem doesn't work! Stopping program.\"\n    return length\n\n\ndef main():\n    x, y = [float(a) for a in input().split()]\n    print('Hypotenuse is', hypotenuse(x, y))\n\n\nif __name__ == \"__main__\":\n    # assert 2 + 2 == 5, 'Joke!'\n    main()\n"
  },
  {
    "path": "python/lec_13/fib.py",
    "content": "def fib(n):\n    \"\"\"\n    Функция вычисляет числа фибоначчи.\n\n    >>> fib(1)\n    1\n    >>> fib(2)\n    1\n    >>> fib(3)\n    2\n    >>> fib(5)\n    5\n    >>> fib(10)\n    55\n    >>> fib(20)\n    6765\n    >>> fib(-1)\n    None\n    \"\"\"\n    if n < 2:\n        return n\n    else:\n        return fib(n-1) + fib(n-2)\n\n\nif __name__ == \"__main__\":\n    import doctest\n    doctest.testmod()\n"
  },
  {
    "path": "python/lec_13/main.py",
    "content": "import fib\n\n\ndef main():\n    n = int(input(\"Введите номер числа Фибоначчи: \"))\n    f = fib.fib(n)\n    print(\"Ваше число Фибоначчи:\", f)\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "python/lec_13/test_fib.py",
    "content": "import fib\n\nall_correct = True\n\nfor n, answer in [(0, 0), (1, 1), (2, 1), (5, 5)]:\n    result = fib.fib(n)\n    correct = (result == answer)\n    if not correct:\n        print('Test case failed:', n, result, '!=', answer)\n    all_correct &= correct\n\nif all_correct:\n    print('Testing fib(): OK')\nelse:\n    print('Testing fib(): Failed.')\n\n"
  },
  {
    "path": "python/lec_14/fib.py",
    "content": "def fib(n):\n    \"\"\"\n    Вычисляет число Фибонаачи номер n.\n\n    Выбрасывает исключение TypeError, если вызвана не для целочисленного типа.\n    Выбрасыват исключение ValueError, если число отричательное или больше допустимого по контракту.\n    :param n: целое число от 0 до 9999\n    :return: целое число от 0 до ...\n    >>> fib(1)\n    1\n    >>> fib(2)\n    1\n    >>> fib(3)\n    2\n    >>> fib(5)\n    5\n    >>> fib(10)\n    55\n    >>> fib(20)\n    6765\n    \"\"\"\n    if not isinstance(n, int):\n        raise TypeError(\"Fibonacci function can work only with <class 'int'> type.\")\n    if n < 0:\n        raise ValueError(\"Fibonacci can't work with negative numbers.\")\n    if n >= 10000:\n        raise ValueError(\"Fibonacci can't work with numbers larger than 9999.\")\n    if n == 0:\n        return 0\n    f_2 = 0\n    f_1 = 1\n    for i in range(2, n + 1):\n        f_1, f_2 = (f_1 + f_2), f_1\n    return f_1\n\n\nif __name__ == \"__main__\":\n    import doctest\n    doctest.testmod()\n"
  },
  {
    "path": "python/lec_14/main.py",
    "content": "import fib\n\n\ndef main():\n    n = int(input(\"Введите номер числа Фибоначчи: \"))\n    f = fib.fib(n)\n    print(\"Ваше число Фибоначчи:\", f)\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "python/lec_14/test_first.py",
    "content": "import unittest\nfrom fib import fib\n\n\nclass TestFibonacci(unittest.TestCase):\n\n    def test_simple(self):\n        for param, result in [(0, 0), (1, 1), (2, 1), (3, 2), (10, 55)]:\n            self.assertEqual(fib(param), result)\n\n    def test_stress(self):\n        self.assertEqual(fib(9999), fib(9998) + fib(9997))\n        with self.assertRaises(ValueError):\n            fib(10000)\n\n    def test_negative(self):\n        with self.assertRaises(ValueError):\n            fib(-1)\n        with self.assertRaises(ValueError):\n            fib(-100)\n\n    def test_wrong_param_type(self):\n        with self.assertRaises(TypeError):\n            fib(2.5)\n        with self.assertRaises(TypeError):\n            fib('Hello')\n\n\nif __name__ == '__main__':\n    unittest.main()\n"
  }
]