Repository: tkhirianov/lections_2020 Branch: master Commit: 8f7e609d5d2e Files: 132 Total size: 250.0 KB Directory structure: gitextract_acwc51rz/ ├── .gitignore ├── LICENSE ├── README.md ├── cpp_algo/ │ ├── lec_01/ │ │ ├── 1_bot.cpp │ │ ├── 1_bot.py │ │ ├── 2_euclid.cpp │ │ ├── 2_euclid.py │ │ ├── 3_goto_nightmare.cpp │ │ ├── hello.cpp │ │ ├── in.txt │ │ └── out.txt │ ├── lec_02/ │ │ └── 1_bits.cpp │ ├── lec_03/ │ │ └── expressions.cpp │ ├── lec_04/ │ │ ├── 1_func_params.cpp │ │ ├── 2_func_params.cpp │ │ ├── 3_struct.cpp │ │ ├── 4_struct_to_function.cpp │ │ ├── 5_sizeof.cpp │ │ ├── 6_reinterpret.cpp │ │ ├── 7_segfault.cpp │ │ └── 8_Eratosthenes.cpp │ ├── lec_05/ │ │ ├── 1_copy.cpp │ │ ├── 2_reverse.cpp │ │ ├── 3_append.cpp │ │ ├── 4_stack.cpp │ │ ├── 4a_braces.cpp │ │ ├── 5_check_sorted.cpp │ │ ├── 6_fool.cpp │ │ ├── 6a_fool_asympotic.cpp │ │ ├── 7_bubble.cpp │ │ ├── 8_insert.cpp │ │ └── 9_choice.cpp │ ├── lec_06/ │ │ ├── 1_pointers.cpp │ │ ├── 2_structs.cpp │ │ ├── 3_malloc.c │ │ ├── 4_new.cpp │ │ └── 5_leaks.cpp │ ├── lec_07/ │ │ ├── 1_array1d.cpp │ │ ├── 2_array2d.cpp │ │ ├── 2_array2d.s │ │ ├── 2_array_param.cpp │ │ ├── 3_array_param.cpp │ │ ├── 4_array_param.cpp │ │ ├── 5_linearized_manually.cpp │ │ ├── 6_dynamical.cpp │ │ └── 7_dynamical.cpp │ ├── lec_08/ │ │ ├── bin_search.cpp │ │ ├── count_sort.cpp │ │ ├── lin_search.cpp │ │ └── radix_sort.cpp │ ├── lec_09/ │ │ ├── 1_factorial.cpp │ │ ├── 2_main.cpp │ │ ├── 3_euclid.cpp │ │ ├── 4_hanoi.cpp │ │ └── 5_bin_gen.cpp │ ├── lec_10/ │ │ ├── 1_permutations.cpp │ │ └── 2_merge_sort.cpp │ ├── lec_11/ │ │ ├── 1_fibonacci.cpp │ │ └── 2_hopper_economist.cpp │ ├── lec_12/ │ │ ├── 1_ant.cpp │ │ ├── 2_ant_array.cpp │ │ ├── 3_bagpack.cpp │ │ └── input_data.txt │ ├── lec_13/ │ │ ├── 1_strcat_problem.cpp │ │ ├── 2_strcat_solution.cpp │ │ └── 3_levenstein.cpp │ ├── lec_14/ │ │ ├── 1_vector_list.cpp │ │ └── 2_kmp.cpp │ ├── lec_15/ │ │ ├── 01_vector_usage.cpp │ │ └── 02_list_usage.cpp │ ├── lec_16/ │ │ ├── 1_simple_class.cpp │ │ ├── 2_overloading.cpp │ │ └── 3_abs_template.cpp │ ├── lec_17/ │ │ ├── 1_fin_automata_1.cpp │ │ └── 2_fin_automata_2.cpp │ ├── lec_18/ │ │ └── rabin_karp.cpp │ ├── lec_20/ │ │ ├── 1_set.cpp │ │ ├── 2_unordered_set.cpp │ │ └── set_input.txt │ ├── lec_21/ │ │ ├── 1.txt │ │ ├── 2_euclid.cpp │ │ ├── 2_euclid.s │ │ ├── cmake_project/ │ │ │ ├── CMakeLists.txt │ │ │ ├── Makefile │ │ │ ├── cmake_install.cmake │ │ │ ├── main.cpp │ │ │ ├── mylib.cpp │ │ │ └── mylib.h │ │ ├── hello.cpp │ │ └── project/ │ │ ├── Makefile │ │ ├── main.cpp │ │ ├── mylib.cpp │ │ └── mylib.h │ ├── lec_22/ │ │ └── 1_graphs_storage.cpp │ ├── lec_23/ │ │ ├── 1_dfs.cpp │ │ ├── 2_bfs.cpp │ │ ├── graph.hpp │ │ └── input1.txt │ └── lec_24/ │ ├── check_DAG.cpp │ └── graph.hpp └── python/ ├── lec_01/ │ ├── 01_input_print.py │ ├── 02_if_else.py │ └── 03_nested_for.py ├── lec_03/ │ ├── 1_function_experiments.py │ └── 2_pygame_draw_test.py ├── lec_04/ │ └── football_1.py ├── lec_05/ │ └── house.py ├── lec_06/ │ └── football_1.py ├── lec_07/ │ ├── house.py │ ├── lib.py │ └── main.py ├── lec_08/ │ ├── 01_class.py │ ├── 02_encapsulation_example.py │ ├── 2016-pacman/ │ │ ├── LICENSE │ │ ├── README.md │ │ └── pacman.py │ └── cannon/ │ ├── LICENSE │ ├── README.md │ ├── cannon.py │ └── my_colors.py ├── lec_09/ │ ├── 01_hierarchy.py │ └── cannon.py ├── lec_10/ │ └── cannon.py ├── lec_11/ │ └── crosszeroes.py ├── lec_12/ │ └── 1_selfdoc.py ├── lec_13/ │ ├── .fib.py.swp │ ├── fib.py │ ├── main.py │ └── test_fib.py └── lec_14/ ├── fib.py ├── main.py └── test_first.py ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ # Prerequisites *.d # Compiled Object files *.slo *.lo *.o *.obj # Precompiled Headers *.gch *.pch # Compiled Dynamic libraries *.so *.dylib *.dll # Fortran module files *.mod *.smod # Compiled Static libraries *.lai *.la *.a *.lib # Executables *.exe *.out *.app .idea __pycache__ ================================================ FILE: LICENSE ================================================ # Публичная лицензия Creative Commons С указанием авторства-С сохранением условий версии 4.0 Международная Осуществляя Лицензируемые права (как указано ниже), Вы принимаете и соглашаетесь соблюдать условия настоящей Публичной лицензии Creative Commons С указанием авторства-С сохранением условий версии 4.0 Международная (далее - "Публичная Лицензия"). В том объеме, в котором настоящая Публичная Лицензия может считаться договором, Вам предоставляются Лицензируемые права в качестве встречного предоставления за принятие Вами условий такого договора. Лицензиар предоставляет Вам такие права с учетом благ, которые Лицензиар получает от предоставления доступа к Лицензируемому Материалу на указанных условиях. Раздел 1 – Определения. Адаптированный Материал означает материал, охраняемый Авторским Правом И Другими Схожими Правами, производный от Лицензируемого Материала или основанный на Лицензируемом Материале, который содержит перевод, измененный вариант, аранжировку, преобразованный вариант или иную переработку Лицензируемого Материала, таким образом, который требует разрешения Лицензиара в соответствии с Авторским Правом И Другими Схожими Правами. Для целей настоящей Публичной Лицензии, в том случае, если Лицензируемый Материал является музыкальным произведением, исполнением или фонограммой, синхронизация такого Лицензируемого Материала с движущимся изображением всегда порождает "Адаптированный Материал". Лицензия на Адаптированный Материал означает лицензию, которую Вы применяете в отношении Авторского Права И Других Схожих Прав на Ваш вклад в создание Адаптированного Материала в соответствии с условиями настоящей Публичной Лицензии. Лицензия, Совместимая С Лицензией Creative Commons BY-SA означает лицензию, входящую в перечень лицензий, размещенный по адресу: creativecommons.org/compatiblelicenses, которая признается Creative Commons по существу эквивалентом настоящей Публичной Лицензии. Авторское Право И Другие Схожие Права означают авторские и/или другие аналогичные права, тесно связанные с авторскими правами, включая, но не ограничиваясь этим, права на исполнение, сообщение передач организаций вещания, фонограмму и Права Sui Generis на Базы Данных независимо от того, каким образом права обозначаются или классифицируются. Для целей настоящей Публичной Лицензии права, указанные в подпунктах 1 и 2 пункта (b) Раздела 2 не являются Авторским Правом И Другими Схожими Правами. Эффективные Технические Меры означают меры, которые при отсутствии надлежащих полномочий нельзя обойти в соответствии с законодательством, направленным на выполнение обязательств в соответствии со Статьей 11 Договора Всемирной организации интеллектуальной собственности (ВОИС) по авторскому праву, принятого 20 декабря 1996 года и/или иными подобными международными соглашениями. Исключения И Ограничения означают свободное использование (fair use, fair dealing) и/или любые иные исключения из Авторского Права И Других Схожих Прав или ограничения таких прав, которые применяются в отношении Вашего использования Лицензируемого Материала. Элементы Лицензии означают атрибуты лицензии, перечисленные в названии настоящей Публичной Лицензии Creative Commons. Элементами Лицензии настоящей Публичной Лицензии являются: С указанием авторства и С сохранением условий. Лицензируемый Материал означает произведение искусства или литературы, базу данных или другой материал, в отношении которого Лицензиар применил настоящую Публичную Лицензию. Лицензируемые Права означают права, предоставляемые Вам в соответствии с условиями настоящей Публичной Лицензии в объеме, ограниченном всеми Авторскими Правами И Другими Схожими Правами, которые применимы к Вашему использованию Лицензируемого Материала и которые Лицензиар вправе Вам предоставить. Лицензиар означает физическое лицо (физические лица) или юридическое лицо (юридические лица), предоставляющее права на условиях настоящей Публичной Лицензии. Предоставление означает предоставление материала неограниченному кругу лиц любыми средствами или способами, для использования которых требуется разрешение согласно Лицензируемых Прав, в том числе воспроизведение, публичный показ, публичное исполнение, распространение, сообщение или импорт, а также доведение материала до всеобщего сведения таким образом, при котором любое лицо может иметь доступ к нему из любого места и в любое время по собственному выбору. Права Sui Generis на Базы Данных означают права, не являющиеся авторским правом, проистекающие из Директивы 96/9/СЕ Европейского парламента и Совета от 11 марта 1996 года о правовой охране баз данных, с учетом изменений и/или исправлений, а также и другие схожие по существу права где-либо в мире. Вы означает физическое или юридическое лицо, осуществляющее Лицензируемые Права в соответствии с настоящей Публичной Лицензией. Термины "Ваш", "Ваши", "Вам", "Вами" имеют соответствующее значение. Раздел 2 – Объем лицензии. Предоставление лицензии. В соответствии с условиями настоящей Публичной Лицензии Лицензиар предоставляет Вам действующую на территории всех стран мира, безвозмездную, без права сублицензирования, неисключительную, не подлежащую отмене лицензию на осуществление Лицензируемых Прав на Лицензируемый Материал путем: воспроизведения и Предоставления Лицензируемого Материала целиком или в части; а также создания, воспроизведения и Предоставления Адаптированного Материала. Исключения И Ограничения. Во избежание неоднозначного толкования, если Исключения и Ограничения применяются в отношении Вашего способа использования Лицензируемого материала, настоящая Публичная Лицензия не применяется, и Вы не обязаны выполнять ее условия. Срок действия лицензии. Настоящая Публичная Лицензия действует в течение срока, указанного в пункте (a) Раздела 6. Носители и форматы: разрешение на внесение технических изменений. Лицензиар предоставляет Вам право осуществлять Лицензируемые Права с использованием всех известных носителей и форматов, а также носителей и форматов, которые будут созданы в будущем, и вносить с этой целью любые необходимые технические изменения. Лицензиар отказывается от и/или соглашается не осуществлять какие-либо права или полномочия, позволяющие запретить внесение Вами технических изменений, необходимых для осуществления Лицензируемых Прав, включая технические изменения, необходимые для обхода Эффективных Технических Мер. Для целей настоящей Публичной Лицензии внесение изменений, разрешенных в подпункте (4) пункта (а) Раздела 2, само по себе не является созданием Адаптированного Материала. Последующие получатели. Оферта от Лицензиара – Лицензируемый Материал. Каждый получатель Лицензируемого Материала автоматически получает оферту от Лицензиара на осуществление Лицензируемых Прав в соответствии с условиями настоящей Публичной Лицензии. Дополнительная оферта от Лицензиара – Адаптированный Материал. Каждый получатель Адаптированного Материала от Вас автоматически получает оферту от Лицензиара на осуществление Лицензируемых Прав на Адаптированный Материал в соответствии с условиями Лицензии на Адаптированный Материал, применяемой Вами. Отсутствие ограничений на последующее использование. Вы не можете предлагать или устанавливать какие-либо дополнительные или иные условия, или применять Эффективные Технические Меры в отношении Лицензируемого Материала, если это ограничивает осуществление Лицензируемых Прав любым получателем Лицензируемого Материала. Отсутствие одобрения. Никакое положение настоящей Публичной Лицензии не является разрешением и не может быть истолковано как разрешение утверждать или предполагать, что Вы или использование Вами Лицензируемого Материала каким-либо образом связаны с Лицензиаром, имеете финансовую поддержку, одобрение или официальный статус, предоставленные Лицензиаром или иными лицами, указанными Лицензиаром для указания авторства, как предусмотрено в подпункте (i) (А) (1) пункта (а) Раздела 3. Иные права. Личные неимущественные права, такие как право на неприкосновенность произведения, а также права на публичность и изображение гражданина, неприкосновенность частной жизни или иные аналогичные личные права не предоставляются на основе настоящей Публичной Лицензии. Тем не менее, в максимально возможной степени Лицензиар отказывается или соглашается не осуществлять любые такие права, принадлежащие ему, в объеме, необходимом, чтобы позволить Вам осуществлять Лицензируемые Права, но не иначе. Патентные права и права на товарные знаки и знаки обслуживания не предоставляются по настоящей Публичной Лицензии. В той мере, в которой это возможно, Лицензиар отказывается от любого права на получение от Вас вознаграждения за осуществление Вами Лицензируемых Прав, как непосредственно, так и через любые организации по коллективному управлению правами или любую добровольную, обязательную государственную или принудительную систему лицензирования. Во всех иных случаях Лицензиар сохраняет право на получение такого вознаграждения. Раздел 3 – Условия лицензии. Вы можете осуществлять Лицензируемые Права исключительно при условии соблюдения следующих условий. Указание авторства. Если Вы Предоставляете Лицензируемый Материал (в том числе в измененном виде), Вы должны: сохранить следующие сведения, если они предоставлены Лицензиаром вместе с Лицензируемым Материалом: информацию об создателе (создателях) Лицензируемого Материала, а также любых других лицах, указанных Лицензиаром, обладающих правом на указание авторства, любым разумным способом, по требованию Лицензиара (в том числе с использованием псевдонима, если таковой указан); уведомление об авторском праве; уведомление об использовании настоящей Публичной Лицензии; уведомление об отказе от гарантий; Унифицированный Идентификатор Ресурса (URI) или гиперссылку на Лицензируемый Материал, в той мере, в которой это практически выполнимо; указать, если Вами внесены изменения в Лицензируемый Материал, и сохранить указание на любые предыдущие изменения; а также указать, что Лицензируемый Материал предоставляется на условиях настоящей Публичной Лицензии, и предоставить текст, или Унифицированный Идентификатор Ресурса (URI), или гиперссылку на настоящую Публичную Лицензию. Вы можете выполнить положения подпункта (1) пункта (а) Раздела 3 любым разумным способом в зависимости от носителя, способа и контекста, посредством которых вы Предоставляете Лицензируемый Материал. Например, разумным признается выполнение данного условия путем указания Унифицированного Идентификатора Ресурса (URI) или гиперссылки на ресурс, который содержит необходимую информацию. По требованию Лицензиара Вы должны, насколько это практически выполнимо, удалить любую информацию, указанную в подпункте (А) (1) пункта (а) Раздела 3. С сохранением условий. В дополнение к условиям, указанным в пункте (а) Раздела 3, если вы Предоставляете Адаптированный Материал, созданный Вами, то применяются также следующие условия. В качестве Лицензии на Адаптированный Материал, которую Вы применяете, должна быть применена лицензия Creative Commons с теми же Элементами Лицензии, данной версии или более поздней версии, или Лицензия, Совместимая С Лицензией BY-SA. Вы должны включить текст, Унифицированный Идентификатор Ресурса (URI) или гиперссылку на Лицензию на Адаптированный Материал, которую Вы применяете. Вы можете выполнить данное условие любым разумным способом в зависимости от носителя, способа и контекста, посредством которых Вы Предоставляете Адаптированный Материал. Вы не можете предлагать или устанавливать какие-либо дополнительные или иные условия или применять Эффективные Технические Меры в отношении Адаптированного Материала, которые ограничивают осуществление прав, предоставленных в соответствии с Лицензией на Адаптированный Материал, которую Вы применяете. Раздел 4 – Права Sui Generis на Базы Данных. Если Лицензируемые Права включают Права Sui Generis на Базы Данных, которые применимы в отношении Вашего использования Лицензируемого Материала: во избежание неоднозначного толкования в соответствии с подпунктом (1) пункта (а) Раздела 2 Вам предоставляются права на извлечение, повторное использование, воспроизведение и Предоставление содержимого базы данных полностью или в существенной части; если Вы включаете содержимое базы данных полностью или его существенную часть в базу данных, в отношении которой у Вас имеются Права на содержимое баз данных, в этом случае база данных, в отношении которой у Вас имеются Права на содержимое баз данных (но не ее отдельные составляющие), является Адаптированным Материалом, в том числе в целях, указанных в пункте (b) Раздела 3; а также Вы должны соблюдать условия, изложенные в пункте (а) Раздела 3, если Вы Предоставляете содержимое базы данных полностью или его существенную часть. Во избежание неоднозначного толкования данный Раздел 4 дополняет и не заменяет Ваши обязательства в соответствии с настоящей Публичной Лицензией, если Лицензируемые Права включают другие Авторские Права И Другие Схожие Права. Раздел 5 – Отказ от гарантий и ограничение ответственности. Если иное отдельно не оговорено Лицензиаром, насколько это возможно, Лицензиар предлагает Лицензируемый Материал по принципу "как есть" и в том виде, в котором такой материал существует, и не дает никаких заверений или гарантий в отношении Лицензируемого Материала, выраженных в явном виде, предполагаемых, установленных законом или иных, включая, без ограничений, гарантии правового титула, товарной пригодности, пригодности для какой-либо определенной цели, гарантии не нарушения прав, отсутствия скрытых или других дефектов, точности, наличия или отсутствия ошибок, как известных, так и неизвестных, или как поддающихся, так и не поддающихся обнаружению. В том случае, если отказ от гарантий не разрешен полностью или частично, такой отказ может не применяться в отношении Вас. В той мере, в которой это возможно, Лицензиар не несет перед Вами никакой ответственности на основании любой правовой доктрины (в том числе, но не ограничиваясь, в результате неосторожности), за какие-либо прямые, особые, непрямые, случайные, косвенные или иные убытки и штрафные выплаты, издержки, затраты или ущерб, возникшие в результате применения настоящей Публичной Лицензии или использования Лицензируемого Материала, даже если Лицензиар был уведомлен о возможности возникновения таких затрат, издержек или убытков. В том случае если ограничение ответственности полностью или частично не допускается, настоящее ограничение может не применяться в отношении Вас. Отказ от гарантий и ограничение ответственности, изложенные выше, должны толковаться таким образом, чтобы в максимально допустимой степени соответствовать абсолютному отказу от гарантий и отказу от какой-либо ответственности. Раздел 6 – Срок действия и прекращение действия. Настоящая Публичная Лицензия действует в течение срока действия Авторского Права И Других Схожих Прав, предоставляемых в соответствии с настоящей Публичной Лицензией. При этом если Вы не соблюдаете какое-либо условие настоящей Публичной Лицензии, действие Ваших прав в соответствии с настоящей Публичной Лицензией автоматически прекращается. Если Ваше право на использование Лицензируемого Материала прекратилось в соответствии с пунктом (а) Раздела 6, оно считается восстановленным: автоматически в момент устранения Вами нарушения, если такое нарушение устранено в течение 30 дней с момента его обнаружения; или в случае четко выраженного решения Лицензиара о восстановлении права. Во избежание неоднозначного толкования пункт (b) Раздела 6 не затрагивает каких-либо прав Лицензиара на поиск средств правовой защиты от допущенных Вами нарушений условий настоящей Публичной Лицензии. Во избежание неоднозначного толкования Лицензиар может также предлагать Лицензируемый Материал на иных лицензионных условиях или остановить распространение Лицензируемого Материала в любое время; однако, это не прекращает действия Публичной Лицензии. Разделы 1, 5, 6, 7 и 8 продолжают действовать после прекращения действия настоящей Публичной Лицензии. Раздел 7 – Прочие условия. Лицензиар не должен быть связан никакими дополнительными или иными условиями, сообщенными Вами, без его согласия, выраженного в явном виде. Любые дополнительные договоренности или понимания, касающиеся Лицензируемого Материала, которые не указаны в настоящей Публичной Лицензии, являются отдельными и независимыми от условий настоящей Публичной Лицензии. Раздел 8 – Толкование. Во избежание неоднозначного толкования настоящая Публичная Лицензия не может и не должна толковаться как сокращение, ограничение или наложение условий в отношении любого использования Лицензируемого Материала, которое может быть осуществлено на законных основаниях без разрешения, предоставляемого в соответствии с настоящей Публичной Лицензией. Если какое-либо положение настоящей Публичной Лицензии считается не имеющим законной силы, оно должно быть, насколько это возможно, автоматически исправлено в минимально необходимой степени для наделения такого положения законной силой. Если такое положение невозможно исправить, оно должно быть исключено из текста настоящей Публичной Лицензии без ущерба для законной силы остальных положений лицензии. Никакое условие или положение настоящей Публичной Лицензии не будет считаться отмененным, а нарушение - согласованным, если Лицензиар в явной форме не выразит свое согласие с такой отменой или нарушением. Никакое условие или положение настоящей Публичной Лицензии не является и не может быть истолковано как ограничение или отказ от каких-либо привилегий и иммунитетов, применимых в отношении Лицензиара и/или в отношении Вас, включая отказ от судебных процессов в какой-либо юрисдикции или какой-либо подведомственности. ================================================ FILE: README.md ================================================ # Алгоритмы и структуры данных (С++), 2020 г. Программный код с лекций по информатике Хирьянова Т.Ф. на ФТШ ЛФИ МФТИ (ФОПФ) в 2020 году. Лицензия на материалы курса: ![Attribution ShareAlike CC BY-SA 4.0](https://licensebuttons.net/l/by-sa/4.0/88x31.png) Сайт курса: http://cs.mipt.ru/cpp_algo ## Рабочая программа дисциплины "Информатика": по дисциплине: Информатика по направлению: 03.03.01 «Прикладные математика и физика» физтех-школа: ЛФИ кафедра: информатики и вычислительной математики курс: 1 семестр: 2 Трудоёмкость: - лекции – 30 часов - лабораторные занятия – 60 часов - самостоятельная работа – 90 часов ВСЕГО АУДИТОРНЫХ ЧАСОВ – 90 Программу и задание составил: ст. преп. Т.Ф. Хирьянов ### Тематический план семестра 1. Ввод-вывод, ветвления и циклы. Однопроходные алгоритмы. Структура простой программы. Переменные С++: необходимость объявления, строгость типизации, присваивание. Ввод-вывод в std:: потоки cin, cout, cerr. Арифметические операции +, -, \*, /. Операторы сравнения <, <=, ==, !=. Описание простых функций. Cинхронный вызов и возврат по стеку вызовов. Метки и goto. Доводы против оператора goto Эдсгера Дейкстры. Оператор for. Генерация арифметической и геометрической прогрессий. Оператор if. Фильтрация потока чисел. Оператор while. Алгоритм Евклида на С++. Вложенные и каскадные условные конструкции. Обработка последовательностей: подсчёт, сумма, произведение, поиск максимального. Инициализация переменной при поиске максимума и минимума. 2. Целый и логический типы. Алгоритмы полного перебора. Двоичное представление данных. Двоичное кодирование. Двоичная СС и кольца вычетов. Знаковые целые: дополнительный код. Целочисленные типы С++11: intN_t. Явное приведение типа. Битовые операции с целыми: сдвиги, наложение маски. Обмен переменных значениями: универсальный и через XOR. Остаток при делении нацело: %. Разложение числа на цифры. Логический тип bool. Операции !, &&, ||, ^ и , not, and, or, xor. Индуктивные функции: поиск числа, проверка критерия. Алгоритмы полного перебора. Тест простоты числа с использованием переменной-флага. Разложение числа на множители. Управление циклом: break, continue. Определение типа struct. Функция sizeof(). 3. Плавающая точка. Математические методы. Представление вещественных чисел в памяти ПК. Cтандарт IEEE 754-2008. Типы чисел с плавающей точкой в С++ и их соответствие стандарту. Арифметика чисел с плавающей запятой (точкой). Ошибки вычислений. Машинная точность. Иерархия типов чисел в С++. Неявное приведение типа. «Грабли»: приоритет беззнаковых, деление целых. Список всех операций С++ с приоритетами. Модуль cmath. Математические функции С++: выражение аналитических функций. Суммирования ряда Тейлора. Численное интегрирование. Бисекция. Поиск корня уравнения методом двоичного поиска. 4. Одномерные массивы. Адреса и указатели. Массивы в С++. Хранение в памяти. Фиксированный размер и однотипность элементов. Скорость доступа к элементам. Решето Эратосфена. Копирование массива. Копирование с реверсом. Реверс массива и циклический сдвиг. Добавление и удаление элемента в конце и в начале массива. Стек, очередь и дек на массиве. Адреса и указатели в С++. Размер ячейки для хранения адреса. Разыменование * и взятие адреса &. Адресная арифметика в С++. Преобразование типа указателя. Тип void*. Реинтерпретация данных. Массивы структур struct и структура struct, содержащая массив. Проверка корректности скобочной последовательности. 5. Универсальные сортировки O(N2). Сортировка массива: постановка задачи. Сортировка обезьяны (без реализации). Проверка упорядоченности за O(N). Сортировка дурака. Сортировка методом пузырька. Сортировка вставками. Сортировка выбором. Устойчивость сортировок. 6. Связные списки. Динамическая память. Выделение и освобождение динамической памяти: malloc(), calloc(), free(). Операторы new и delete. Ошибки работы с памятью. Контроль за динамической памятью. Некорректные адреса. Инициализация указателей: NULL и nullptr. Создание одномерного динамического массива. Реаллокация в памяти для динамического расширения массива. Списки: односвязный, двусвязный, кольцо. Асимптотика связных списков для разных задач. Стек на односвязном списке. Дек на двусвязном списке. 7. Двумерные массивы. Обычные двумерные массивы в С++. Заполнение двумерного массива. Треугольник Паскаля. Транспонирование матрицы. Умножение матриц. Динамические двумерные массивы в С++. Линеаризация двумерного массива вручную. Функции. Синхронный вызов. Возврат по стеку вызовов. Сегмент STACK и передача параметров по значению. Модель памяти приложения. Локальные и глобальные переменные. Передача массива в функцию и возврат из функции в С++. Проблема ответственности за освобождение памяти. 8. Бинпоиск и спецсортировки. Линейный поиск в массиве. Бинарный поиск в упорядоченном массиве. Сортировка подсчётом. Поразрядная сортировка. 9. Рекурсия. Метод ветвей и границ. Прямой и обратный ход рекурсии. Факториал числа. Алгоритм Евклида. Быстрое возведение в степень. Вычисление чисел Фибоначчи. Ханойские башни. Рекурсивная генерация всех чисел длины M. Генерация всех перестановок в массиве. Перебор с возвратом: метод ветвей и границ. 10. Быстрые сортировки. Принцип «Разделяй и властвуй». Умножение Карацубы. Быстрая сортировка Тони Хоара. Сортировка слиянием. 11. Динамическое программирование. Количество траекторий на схеме дорог. Проблема повторных вычислений на примере чисел Фибоначчи. Динамическое программирование сверху и снизу. Кузнечик: количество траекторий, траектория минимальной стоимости. 12. Двумерное динамическое программирование. Алгоритм укладки рюкзака (дискретный). Наибольшая общая подпоследовательность. Наибольшая возрастающая подпоследовательность. 13. Строки и работа с файлами. Кодировки символов: ASCII, однобайтные и семейство Unicode. Строка как массив символов. Си-строки и ANSI-строки. Почему Си-строки не следует использовать для обработки текста. Проверка равенства строк. Простой и вероятностный алгоритмы. Вычисление расстояния Левенштейна. Поиск последовательности редакционных изменений. Работа с файлами в чистом Си. Два уровня API. 14. Поиск подстрок. С++ строки std::string. Поиск подстроки: наивный алгоритм. Префикс-функция. Алгоритм Кнута-Морриса-Пратта. Z-функция и Z-алгоритм. Работа с потоками ifstream, ofstream, fstream. Форматирование ввода-вывода: iomanip. 15. Параллелизм на системах с общей памятью. Ресурс параллельности. Потоки. Асинхронные вызовы. ### Методические указания обучающимся Ваша цель — запомнить классические алгоритмы и структуры данных, знать их асимптотическую сложность, уметь их описывать устно, а также программировать их на языке C++. Курс содержит три вида учебной деятельности: 1) лекции, 2) лабораторные работы и 3) самостоятельная работа. На лекциях по информатике излагается теория, разбираются алгоритмы с реализацией на C++. Посещение не обязательно, но пропуск лекций существенно усложняет выполнение лабораторных и домашних работ. Именно лекции задают содержательную линию учебного курса. Описания лабораторных работ появляются по ходу семестра на сайте http://cs.mipt.ru/cpp_algo. Очное присутствие на лабораторных обязательно. Типичная работа представляет из себя: а) текст для изучения; б) упражнения; в) контест с автоматизированной системой проверки. Автоматически проверяемые задачи допускается доделывать дома в качестве самостоятельной работы. В самостоятельную работу включается также подготовка к сдаче устного зачёта. В течение семестра на лабораторных занятиях проводится 2 контрольные работы: промежуточная и итоговая. ### Оценивание Дифференцированный зачёт сдаётся устно. Рекомендуемая итоговая оценка студента по предмету — это среднее арифметическое взвешенное оценок по лабораторным работам и контрольным. Преподаватель, экзаменующий студента, видит все эти оценки по отдельности, а также рекомендуемую итоговую оценку. Исходя из ответа студента итоговая оценка в зачётку может быть отклонена от рекомендуемой на ±2 балла (по 10-балльной шкале). Если преподаватель хочет повысить или понизить оценку на большее число баллов, он советуется со старшим преподавателем курса. Студент при несогласии с итоговой оценкой может потребовать апелляции у старшего преподавателя (в конце зачётной недели). ================================================ FILE: cpp_algo/lec_01/1_bot.cpp ================================================ #include int main() { using namespace std; string name; int age; cout << "- Hello! What is your name?" << endl; cerr << "> "; cin >> name; cout << "- I'm glad to see you, " << name << "!" << endl <<"- What is your age?" << endl; cerr << "> "; cin >> age; cout << "- I thought you are " << age + 1 << " year old. You look younger!" << endl; return 0; } ================================================ FILE: cpp_algo/lec_01/1_bot.py ================================================ print("- Hello! What is your name?") name = input("> ") print("- I'm glad to see you, ", name, "!", sep="") print("- What is your age?") age = int(input("> ")) print("- I thought you are ", age + 1, " year old. You look younger!") ================================================ FILE: cpp_algo/lec_01/2_euclid.cpp ================================================ #include int euclid_gcd(int a, int b) { // Алгоритм Евклида поиска НОД while (a != b) { if (a > b) { a -= b; } else { b -= a; } } return a; } int main() { using namespace std; int x, y; cout << "Enter integer. x = "; cin >> x; cout << "Enter integer. y = "; cin >> y; cout << "GCD(x, y) = " << euclid_gcd(x, y) << endl; return 0; } ================================================ FILE: cpp_algo/lec_01/2_euclid.py ================================================ def euclid_gcd(a: int, b: int): # Алгоритм Евклида поиска НОД while a != b: if a > b: a -= b else: b -= a return a x = int(input("Enter integer. x = ")) y = int(input("Enter integer. y = ")) print("GCD(x, y) =", euclid_gcd(x, y)) ================================================ FILE: cpp_algo/lec_01/3_goto_nightmare.cpp ================================================ #include int euclid_gcd(int a, int b) { // Алгоритм Евклида поиска НОД loop_begin: if (a == b) goto loop_end; if (!(a > b)) goto else_action; a -= b; goto after_if; else_action: b -= a; after_if: goto loop_begin; loop_end: return a; } int main() { using namespace std; int x, y; cout << "Enter integer. x = "; cin >> x; cout << "Enter integer. y = "; cin >> y; cout << "GCD(x, y) = " << euclid_gcd(x, y) << endl; return 0; } ================================================ FILE: cpp_algo/lec_01/hello.cpp ================================================ #include int main() { using namespace std; cout << "Hello, world!" << endl; return 777; } ================================================ FILE: cpp_algo/lec_01/in.txt ================================================ John 17 ================================================ FILE: cpp_algo/lec_01/out.txt ================================================ - Hello! What is your name? - I'm glad to see you, Katapulta! - What is your age? - I thought you are 2 year old. You look younger! ================================================ FILE: cpp_algo/lec_02/1_bits.cpp ================================================ #include using namespace std; int main() { uint8_t x, y; x = 10; y = 12; cout << (unsigned int) (x & y) << endl; cout << (unsigned int) (x | y) << endl; cout << (unsigned int) (x ^ y) << endl; cout << (unsigned int) (~x) << endl; y = ~x; cout << (unsigned int) (y) << endl; return 0; } ================================================ FILE: cpp_algo/lec_03/expressions.cpp ================================================ #include #include using namespace std; double f(double x); int main() { double x; cin >> x; cout << f(x) << endl; double s = 0; double factor; for(int n = 0, factor=1; n < 10; n++) { s += pow(-1, n)*pow(x, 2*n + 1)/factor; factor *= 2*n*(2*n + 1); } cout << s; return 0; } double f(double x) { return 2*sin(x); } ================================================ FILE: cpp_algo/lec_04/1_func_params.cpp ================================================ /* Аргументы в функцию передаются по значению, т.е. * при вызове функции для хранения фактических переданных значений * создаются временные переменные - ячейки памяти на сегменте STACK. * После выхода из функции эти переменные уничтожаются. * */ #include void increment(int a) // При вызове появится переменная a с копией значения b. { std::cout << a << '\n'; a = a + 1; // Значение a увеличится на 1. std::cout << a << '\n'; } // Однако, при выходе из функции переменная a уничтожится. int main() { using namespace std; int b = 3; increment(b); // Здесь число 3 будет скопировано из b во временную a. cout << b << endl; // Естественно, вызов функции inc(b) не изменил b. return 0; } ================================================ FILE: cpp_algo/lec_04/2_func_params.cpp ================================================ /* Аргументы в функцию передаются по значению, т.е. * при вызове функции для хранения фактических переданных значений * создаются временные переменные - ячейки памяти на сегменте STACK. * После выхода из функции эти переменные уничтожаются. * */ #include void increment(int* a) // При вызове появится переменная a с адресом b. { *a = *a + 1; // Значение по адресу a увеличится на 1. } // Однако, при выходе из функции указатель a уничтожится. int main() { using namespace std; int b = 3; increment(&b); // Здесь будет скопирован адрес переменной b. cout << b << endl; // Естественно, вызов функции inc(b) не изменил b. return 0; } ================================================ FILE: cpp_algo/lec_04/3_struct.cpp ================================================ #include using namespace std; struct t_Pair { // создаём новый тип t_Pair int a; int b; }; t_Pair return_pair(int x) { t_Pair result; // создаю локальный экземпляр структуры t_Pair result.a = x*x; // Заполняю его нужными значениями. result.b = x*x*x; return result; // Возвращаю его как результат. } int main() { int x; cin >> x; t_Pair y = return_pair(x); cout << y.a << ' ' << y.b << '\n'; return 0; } ================================================ FILE: cpp_algo/lec_04/4_struct_to_function.cpp ================================================ #include using namespace std; struct t_Pair { int a; int b; }; void modify_pair(t_Pair *p) { p->a += 1; (*p).b += 10; } int main() { t_Pair x; cin >> x.a >> x.b; t_Pair y; y = x; modify_pair(&x); cout << x.a << ' ' << x.b << '\n'; cout << y.a << ' ' << y.b << '\n'; return 0; } ================================================ FILE: cpp_algo/lec_04/5_sizeof.cpp ================================================ #include using namespace std; struct t_Pair { int a; int b; }; int main() { int8_t x; int y; long long int z; float a; double b; t_Pair p; cout << sizeof(x) << '\n'; cout << sizeof(int) << '\n'; cout << sizeof(int*) << '\n'; cout << sizeof(z) << '\n'; cout << sizeof(a) << '\n'; cout << sizeof(b) << '\n'; cout << sizeof(p) << '\n'; cout << sizeof(&x) << '\n'; cout << sizeof(&y) << '\n'; cout << sizeof(&z) << '\n'; cout << sizeof(&a) << '\n'; cout << sizeof(&b) << '\n'; cout << sizeof(&p) << '\n'; return 0; } ================================================ FILE: cpp_algo/lec_04/6_reinterpret.cpp ================================================ #include using namespace std; int main() { int64_t x; double y; // Я хочу "переосмыслить" сами байты double значения 1.0 как будто они - байты int64_t y = 1.0; // x = *(int64_t*)(&y); WARNING!!! Not to do this way! Use reinterpret_cast. // x = *static_cast(&y); ERROR! can't statically cast double* to int64_t* x = *reinterpret_cast(&y); cout << x << '\n'; return 0; } ================================================ FILE: cpp_algo/lec_04/7_segfault.cpp ================================================ #include int main() { int x = 2; int A[10]; int y = 256; A[10] = 1; std::cout << x << ' ' << y << '\n'; for(y = 0; y < 100; y++) // выход за границы массива - undefined behaviour { // (It's worse than Segmentation fault!!!) A[y] = (y + 1) % 5; std::cout << A[y] << '\n'; } return 0; } ================================================ FILE: cpp_algo/lec_04/8_Eratosthenes.cpp ================================================ #include using namespace std; int main() { int n; std::cin >> n; bool sieve[n+1]; // not to interpret 0 and 1-st elements - not prime numbers nor composite for(int i = 2; i < n + 1; i++) { sieve[i] = true; } int x = 2; while (x*x <= n) { if (sieve[x]) { //found new prime for (int y = x*x; y <= n; y += x) { sieve[y] = false; // composite } } x += 1; } for (int i = 2; i < n + 1; i++) { if (sieve[i]) { std::cout << i << '\t'; } } std::cout << '\n'; return 0; } ================================================ FILE: cpp_algo/lec_05/1_copy.cpp ================================================ ================================================ FILE: cpp_algo/lec_05/2_reverse.cpp ================================================ #include using namespace std; int main() { int N = 5; int A[N] = {1, 2, 3, 4, 5}; for(int i = 0; i < N / 2; ++i) { int tmp = A[i]; A[i] = A[N-1-i]; A[N-1-i] = tmp; } for(int i = 0; i < N; ++i) { cout << A[i] << '\t'; } cout << '\n'; return 0; } ================================================ FILE: cpp_algo/lec_05/3_append.cpp ================================================ #include using namespace std; const int MAX_A_SIZE = 100; int main() { int N = MAX_A_SIZE; int A[N]; int top = 0; int x; cin >> x; while (x != 0) { A[top++] = x; cin >> x; } for(int i = 0; i < top; ++i) { cout << A[i] << '\t'; } cout << '\n'; return 0; } ================================================ FILE: cpp_algo/lec_05/4_stack.cpp ================================================ #include using namespace std; const int MAX_A_SIZE = 100; int main() { int N = MAX_A_SIZE; int A[N]; int top = 0; int x; cin >> x; while (x != 0) { A[top++] = x; cin >> x; } while (top > 0) { cout << A[--top] << '\t'; } cout << '\n'; return 0; } ================================================ FILE: cpp_algo/lec_05/4a_braces.cpp ================================================ ================================================ FILE: cpp_algo/lec_05/5_check_sorted.cpp ================================================ #include using namespace std; int main() { int N = 5; int A[N] = {1, 3, 2, 4, 5}; bool is_sorted = true; int i = 0; while (i < N-1) { if (A[i] > A[i+1]) { is_sorted = false; break; } i += 1; } cout << is_sorted << '\n'; return 0; } ================================================ FILE: cpp_algo/lec_05/6_fool.cpp ================================================ #include using namespace std; int main() { int N = 5; int A[N] = {5, 4, 3, 2, 1}; int i = 0; while (i < N-1) { if (A[i] > A[i+1]) { int tmp = A[i]; A[i] = A[i+1]; A[i+1] = tmp; i = 0; } else { i += 1; } } for(int i = 0; i < N; ++i) { cout << A[i] << '\t'; } cout << '\n'; return 0; } ================================================ FILE: cpp_algo/lec_05/6a_fool_asympotic.cpp ================================================ #include using namespace std; int main() { int N = 10000; int A[N]; for(int i = 0; i < N; i++) A[i] = N-i; int i = 0; while (i < N-1) { if (A[i] > A[i+1]) { int tmp = A[i]; A[i] = A[i+1]; A[i+1] = tmp; i = 0; } else { i += 1; } } cout << "Hello!" << '\n'; return 0; } ================================================ FILE: cpp_algo/lec_05/7_bubble.cpp ================================================ #include using namespace std; int main() { int N = 5; int A[N] = {1, 3, 2, 5, 4}; bool is_sorted = false; while (not is_sorted) { int i = 0; is_sorted = true; while (i < N-1) { if (A[i] > A[i+1]) { int tmp = A[i]; A[i] = A[i+1]; A[i+1] = tmp; is_sorted = false; } i += 1; } } for(int i = 0; i < N; ++i) { cout << A[i] << '\t'; } cout << '\n'; return 0; } ================================================ FILE: cpp_algo/lec_05/8_insert.cpp ================================================ ================================================ FILE: cpp_algo/lec_05/9_choice.cpp ================================================ ================================================ FILE: cpp_algo/lec_06/1_pointers.cpp ================================================ ================================================ FILE: cpp_algo/lec_06/2_structs.cpp ================================================ #include struct node_t { int data; node_t *next; }; void go_through(node_t *p) { while (p != nullptr) { std::cout << p->data << '\n'; p = p->next; } } int main() { node_t A[5]; for(int i = 0; i < 5; i++) { A[i].data = i+1; A[i].next = A + i + 1; } A[4].next = nullptr; node_t *p_begin = A; go_through(p_begin); return 0; } ================================================ FILE: cpp_algo/lec_06/3_malloc.c ================================================ #include #include int main() { for (int i = 0; i < 100; i++) { double *pd = (double *)malloc(10 * sizeof(double)); if (pd != NULL) { //адресная арифметика обеспечит перебор адресов // от pd до pd + 9*sizeof(double) включительно for(double *p = pd; p < pd + 10; p++) *p = 0.0; //зануляем ячейку памяти типа double } else { printf("Не удалось выделить память."); } free(pd); } return 0; } ================================================ FILE: cpp_algo/lec_06/4_new.cpp ================================================ #include struct node_t { int data; node_t *next; }; void go_through(node_t *p) { while (p != nullptr) { std::cout << p->data << '\n'; p = p->next; } } int main() { node_t *p_begin = new node_t; node_t *p = p_begin; for(int i = 0; i < 5; i++) { p->data = i+1; p->next = new node_t; p = p->next; } p->data = 777; p->next = nullptr; go_through(p_begin); return 0; } ================================================ FILE: cpp_algo/lec_06/5_leaks.cpp ================================================ ================================================ FILE: cpp_algo/lec_07/1_array1d.cpp ================================================ #include using namespace std; // really it's bad to do such way! int main() { int N; N = 3; int A[N]; for(int i = 0; i < N; i++) { A[i] = i+1; } for(int i = 0; i < N; i++) { cout << A[i] << '\t'; } cout << endl; return 0; } ================================================ FILE: cpp_algo/lec_07/2_array2d.cpp ================================================ #include using namespace std; // really it's bad to do such way! int main() { int N, M; cin >> N >> M; int A[N][M]; for(int i = 0; i < N; i++) { for(int j = 0; j < M; j++) { A[i][j] = i*M + j; } } for(int i = 0; i < N; i++) { for(int j = 0; j < M; j++) { cout << A[i][j] << '\t'; } cout << '\n'; } // memory investigation int *p = reinterpret_cast(A); for(int i = 0; i < M*N; i++) { cout << *(p + i) << ' '; } return 0; } ================================================ FILE: cpp_algo/lec_07/2_array2d.s ================================================ a.out: формат файла elf64-x86-64 Дизассемблирование раздела .init: 0000000000001000 <_init>: 1000: 48 83 ec 08 sub $0x8,%rsp 1004: 48 8b 05 dd 2f 00 00 mov 0x2fdd(%rip),%rax # 3fe8 <__gmon_start__> 100b: 48 85 c0 test %rax,%rax 100e: 74 02 je 1012 <_init+0x12> 1010: ff d0 callq *%rax 1012: 48 83 c4 08 add $0x8,%rsp 1016: c3 retq Дизассемблирование раздела .plt: 0000000000001020 <.plt>: 1020: ff 35 e2 2f 00 00 pushq 0x2fe2(%rip) # 4008 <_GLOBAL_OFFSET_TABLE_+0x8> 1026: ff 25 e4 2f 00 00 jmpq *0x2fe4(%rip) # 4010 <_GLOBAL_OFFSET_TABLE_+0x10> 102c: 0f 1f 40 00 nopl 0x0(%rax) 0000000000001030 <_ZNSirsERi@plt>: 1030: ff 25 e2 2f 00 00 jmpq *0x2fe2(%rip) # 4018 <_ZNSirsERi@GLIBCXX_3.4> 1036: 68 00 00 00 00 pushq $0x0 103b: e9 e0 ff ff ff jmpq 1020 <.plt> 0000000000001040 <__cxa_atexit@plt>: 1040: ff 25 da 2f 00 00 jmpq *0x2fda(%rip) # 4020 <__cxa_atexit@GLIBC_2.2.5> 1046: 68 01 00 00 00 pushq $0x1 104b: e9 d0 ff ff ff jmpq 1020 <.plt> 0000000000001050 <_ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_c@plt>: 1050: ff 25 d2 2f 00 00 jmpq *0x2fd2(%rip) # 4028 <_ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_c@GLIBCXX_3.4> 1056: 68 02 00 00 00 pushq $0x2 105b: e9 c0 ff ff ff jmpq 1020 <.plt> 0000000000001060 <_ZNSt8ios_base4InitC1Ev@plt>: 1060: ff 25 ca 2f 00 00 jmpq *0x2fca(%rip) # 4030 <_ZNSt8ios_base4InitC1Ev@GLIBCXX_3.4> 1066: 68 03 00 00 00 pushq $0x3 106b: e9 b0 ff ff ff jmpq 1020 <.plt> 0000000000001070 <_ZNSolsEi@plt>: 1070: ff 25 c2 2f 00 00 jmpq *0x2fc2(%rip) # 4038 <_ZNSolsEi@GLIBCXX_3.4> 1076: 68 04 00 00 00 pushq $0x4 107b: e9 a0 ff ff ff jmpq 1020 <.plt> Дизассемблирование раздела .plt.got: 0000000000001080 <__cxa_finalize@plt>: 1080: ff 25 4a 2f 00 00 jmpq *0x2f4a(%rip) # 3fd0 <__cxa_finalize@GLIBC_2.2.5> 1086: 66 90 xchg %ax,%ax Дизассемблирование раздела .text: 0000000000001090 <_start>: 1090: 31 ed xor %ebp,%ebp 1092: 49 89 d1 mov %rdx,%r9 1095: 5e pop %rsi 1096: 48 89 e2 mov %rsp,%rdx 1099: 48 83 e4 f0 and $0xfffffffffffffff0,%rsp 109d: 50 push %rax 109e: 54 push %rsp 109f: 4c 8d 05 4a 04 00 00 lea 0x44a(%rip),%r8 # 14f0 <__libc_csu_fini> 10a6: 48 8d 0d e3 03 00 00 lea 0x3e3(%rip),%rcx # 1490 <__libc_csu_init> 10ad: 48 8d 3d c1 00 00 00 lea 0xc1(%rip),%rdi # 1175
10b4: ff 15 26 2f 00 00 callq *0x2f26(%rip) # 3fe0 <__libc_start_main@GLIBC_2.2.5> 10ba: f4 hlt 10bb: 0f 1f 44 00 00 nopl 0x0(%rax,%rax,1) 00000000000010c0 : 10c0: 48 8d 3d 89 2f 00 00 lea 0x2f89(%rip),%rdi # 4050 <__TMC_END__> 10c7: 48 8d 05 82 2f 00 00 lea 0x2f82(%rip),%rax # 4050 <__TMC_END__> 10ce: 48 39 f8 cmp %rdi,%rax 10d1: 74 15 je 10e8 10d3: 48 8b 05 fe 2e 00 00 mov 0x2efe(%rip),%rax # 3fd8 <_ITM_deregisterTMCloneTable> 10da: 48 85 c0 test %rax,%rax 10dd: 74 09 je 10e8 10df: ff e0 jmpq *%rax 10e1: 0f 1f 80 00 00 00 00 nopl 0x0(%rax) 10e8: c3 retq 10e9: 0f 1f 80 00 00 00 00 nopl 0x0(%rax) 00000000000010f0 : 10f0: 48 8d 3d 59 2f 00 00 lea 0x2f59(%rip),%rdi # 4050 <__TMC_END__> 10f7: 48 8d 35 52 2f 00 00 lea 0x2f52(%rip),%rsi # 4050 <__TMC_END__> 10fe: 48 29 fe sub %rdi,%rsi 1101: 48 c1 fe 03 sar $0x3,%rsi 1105: 48 89 f0 mov %rsi,%rax 1108: 48 c1 e8 3f shr $0x3f,%rax 110c: 48 01 c6 add %rax,%rsi 110f: 48 d1 fe sar %rsi 1112: 74 14 je 1128 1114: 48 8b 05 d5 2e 00 00 mov 0x2ed5(%rip),%rax # 3ff0 <_ITM_registerTMCloneTable> 111b: 48 85 c0 test %rax,%rax 111e: 74 08 je 1128 1120: ff e0 jmpq *%rax 1122: 66 0f 1f 44 00 00 nopw 0x0(%rax,%rax,1) 1128: c3 retq 1129: 0f 1f 80 00 00 00 00 nopl 0x0(%rax) 0000000000001130 <__do_global_dtors_aux>: 1130: 80 3d 61 31 00 00 00 cmpb $0x0,0x3161(%rip) # 4298 1137: 75 2f jne 1168 <__do_global_dtors_aux+0x38> 1139: 55 push %rbp 113a: 48 83 3d 8e 2e 00 00 cmpq $0x0,0x2e8e(%rip) # 3fd0 <__cxa_finalize@GLIBC_2.2.5> 1141: 00 1142: 48 89 e5 mov %rsp,%rbp 1145: 74 0c je 1153 <__do_global_dtors_aux+0x23> 1147: 48 8b 3d fa 2e 00 00 mov 0x2efa(%rip),%rdi # 4048 <__dso_handle> 114e: e8 2d ff ff ff callq 1080 <__cxa_finalize@plt> 1153: e8 68 ff ff ff callq 10c0 1158: c6 05 39 31 00 00 01 movb $0x1,0x3139(%rip) # 4298 115f: 5d pop %rbp 1160: c3 retq 1161: 0f 1f 80 00 00 00 00 nopl 0x0(%rax) 1168: c3 retq 1169: 0f 1f 80 00 00 00 00 nopl 0x0(%rax) 0000000000001170 : 1170: e9 7b ff ff ff jmpq 10f0 0000000000001175
: 1175: 55 push %rbp 1176: 48 89 e5 mov %rsp,%rbp 1179: 41 57 push %r15 117b: 41 56 push %r14 117d: 41 55 push %r13 117f: 41 54 push %r12 1181: 53 push %rbx 1182: 48 81 ec 88 00 00 00 sub $0x88,%rsp 1189: 48 89 e0 mov %rsp,%rax 118c: 48 89 85 58 ff ff ff mov %rax,-0xa8(%rbp) 1193: 48 8d 45 94 lea -0x6c(%rbp),%rax 1197: 48 89 c6 mov %rax,%rsi 119a: 48 8d 3d df 2f 00 00 lea 0x2fdf(%rip),%rdi # 4180 <_ZSt3cin@@GLIBCXX_3.4> 11a1: e8 8a fe ff ff callq 1030 <_ZNSirsERi@plt> 11a6: 48 89 c2 mov %rax,%rdx 11a9: 48 8d 45 90 lea -0x70(%rbp),%rax 11ad: 48 89 c6 mov %rax,%rsi 11b0: 48 89 d7 mov %rdx,%rdi 11b3: e8 78 fe ff ff callq 1030 <_ZNSirsERi@plt> 11b8: 8b 45 90 mov -0x70(%rbp),%eax 11bb: 48 98 cltq 11bd: 48 8d 48 ff lea -0x1(%rax),%rcx 11c1: 48 89 4d b0 mov %rcx,-0x50(%rbp) 11c5: 48 89 c8 mov %rcx,%rax 11c8: 48 83 c0 01 add $0x1,%rax 11cc: 48 89 85 60 ff ff ff mov %rax,-0xa0(%rbp) 11d3: 48 c7 85 68 ff ff ff movq $0x0,-0x98(%rbp) 11da: 00 00 00 00 11de: 48 89 c8 mov %rcx,%rax 11e1: 48 83 c0 01 add $0x1,%rax 11e5: 48 8d 1c 85 00 00 00 lea 0x0(,%rax,4),%rbx 11ec: 00 11ed: 8b 45 94 mov -0x6c(%rbp),%eax 11f0: 48 98 cltq 11f2: 48 8d 70 ff lea -0x1(%rax),%rsi 11f6: 48 89 75 a8 mov %rsi,-0x58(%rbp) 11fa: 48 89 c8 mov %rcx,%rax 11fd: 48 83 c0 01 add $0x1,%rax 1201: 48 89 45 80 mov %rax,-0x80(%rbp) 1205: 48 c7 45 88 00 00 00 movq $0x0,-0x78(%rbp) 120c: 00 120d: 48 89 f0 mov %rsi,%rax 1210: 48 83 c0 01 add $0x1,%rax 1214: 48 89 85 70 ff ff ff mov %rax,-0x90(%rbp) 121b: 48 c7 85 78 ff ff ff movq $0x0,-0x88(%rbp) 1222: 00 00 00 00 1226: 4c 8b 45 80 mov -0x80(%rbp),%r8 122a: 4c 8b 4d 88 mov -0x78(%rbp),%r9 122e: 4c 89 ca mov %r9,%rdx 1231: 4c 8b 95 70 ff ff ff mov -0x90(%rbp),%r10 1238: 4c 8b 9d 78 ff ff ff mov -0x88(%rbp),%r11 123f: 49 0f af d2 imul %r10,%rdx 1243: 4c 89 d8 mov %r11,%rax 1246: 49 0f af c0 imul %r8,%rax 124a: 48 8d 3c 02 lea (%rdx,%rax,1),%rdi 124e: 4c 89 c0 mov %r8,%rax 1251: 49 f7 e2 mul %r10 1254: 48 01 d7 add %rdx,%rdi 1257: 48 89 fa mov %rdi,%rdx 125a: 48 89 c8 mov %rcx,%rax 125d: 48 83 c0 01 add $0x1,%rax 1261: 49 89 c6 mov %rax,%r14 1264: 41 bf 00 00 00 00 mov $0x0,%r15d 126a: 48 89 f0 mov %rsi,%rax 126d: 48 83 c0 01 add $0x1,%rax 1271: 49 89 c4 mov %rax,%r12 1274: 41 bd 00 00 00 00 mov $0x0,%r13d 127a: 4c 89 fa mov %r15,%rdx 127d: 49 0f af d4 imul %r12,%rdx 1281: 4c 89 e8 mov %r13,%rax 1284: 49 0f af c6 imul %r14,%rax 1288: 48 8d 3c 02 lea (%rdx,%rax,1),%rdi 128c: 4c 89 f0 mov %r14,%rax 128f: 49 f7 e4 mul %r12 1292: 48 01 d7 add %rdx,%rdi 1295: 48 89 fa mov %rdi,%rdx 1298: 48 89 c8 mov %rcx,%rax 129b: 48 8d 50 01 lea 0x1(%rax),%rdx 129f: 48 89 f0 mov %rsi,%rax 12a2: 48 83 c0 01 add $0x1,%rax 12a6: 48 0f af c2 imul %rdx,%rax 12aa: 48 8d 14 85 00 00 00 lea 0x0(,%rax,4),%rdx 12b1: 00 12b2: b8 10 00 00 00 mov $0x10,%eax 12b7: 48 83 e8 01 sub $0x1,%rax 12bb: 48 01 d0 add %rdx,%rax 12be: b9 10 00 00 00 mov $0x10,%ecx 12c3: ba 00 00 00 00 mov $0x0,%edx 12c8: 48 f7 f1 div %rcx 12cb: 48 6b c0 10 imul $0x10,%rax,%rax 12cf: 48 29 c4 sub %rax,%rsp 12d2: 48 89 e0 mov %rsp,%rax 12d5: 48 83 c0 03 add $0x3,%rax 12d9: 48 c1 e8 02 shr $0x2,%rax 12dd: 48 c1 e0 02 shl $0x2,%rax 12e1: 48 89 45 a0 mov %rax,-0x60(%rbp) 12e5: c7 45 bc 00 00 00 00 movl $0x0,-0x44(%rbp) 12ec: 8b 45 94 mov -0x6c(%rbp),%eax 12ef: 39 45 bc cmp %eax,-0x44(%rbp) 12f2: 7d 4b jge 133f 12f4: c7 45 c0 00 00 00 00 movl $0x0,-0x40(%rbp) 12fb: 8b 45 90 mov -0x70(%rbp),%eax 12fe: 39 45 c0 cmp %eax,-0x40(%rbp) 1301: 7d 36 jge 1339 1303: 8b 45 90 mov -0x70(%rbp),%eax 1306: 0f af 45 bc imul -0x44(%rbp),%eax 130a: 89 c2 mov %eax,%edx 130c: 48 89 df mov %rbx,%rdi 130f: 48 c1 ef 02 shr $0x2,%rdi 1313: 8b 45 c0 mov -0x40(%rbp),%eax 1316: 8d 0c 02 lea (%rdx,%rax,1),%ecx 1319: 48 8b 45 a0 mov -0x60(%rbp),%rax 131d: 8b 55 c0 mov -0x40(%rbp),%edx 1320: 48 63 f2 movslq %edx,%rsi 1323: 8b 55 bc mov -0x44(%rbp),%edx 1326: 48 63 d2 movslq %edx,%rdx 1329: 48 0f af d7 imul %rdi,%rdx 132d: 48 01 f2 add %rsi,%rdx 1330: 89 0c 90 mov %ecx,(%rax,%rdx,4) 1333: 83 45 c0 01 addl $0x1,-0x40(%rbp) 1337: eb c2 jmp 12fb 1339: 83 45 bc 01 addl $0x1,-0x44(%rbp) 133d: eb ad jmp 12ec 133f: c7 45 c4 00 00 00 00 movl $0x0,-0x3c(%rbp) 1346: 8b 45 94 mov -0x6c(%rbp),%eax 1349: 39 45 c4 cmp %eax,-0x3c(%rbp) 134c: 7d 68 jge 13b6 134e: c7 45 c8 00 00 00 00 movl $0x0,-0x38(%rbp) 1355: 8b 45 90 mov -0x70(%rbp),%eax 1358: 39 45 c8 cmp %eax,-0x38(%rbp) 135b: 7d 42 jge 139f 135d: 48 89 de mov %rbx,%rsi 1360: 48 c1 ee 02 shr $0x2,%rsi 1364: 48 8b 45 a0 mov -0x60(%rbp),%rax 1368: 8b 55 c8 mov -0x38(%rbp),%edx 136b: 48 63 ca movslq %edx,%rcx 136e: 8b 55 c4 mov -0x3c(%rbp),%edx 1371: 48 63 d2 movslq %edx,%rdx 1374: 48 0f af d6 imul %rsi,%rdx 1378: 48 01 ca add %rcx,%rdx 137b: 8b 04 90 mov (%rax,%rdx,4),%eax 137e: 89 c6 mov %eax,%esi 1380: 48 8d 3d d9 2c 00 00 lea 0x2cd9(%rip),%rdi # 4060 <_ZSt4cout@@GLIBCXX_3.4> 1387: e8 e4 fc ff ff callq 1070 <_ZNSolsEi@plt> 138c: be 09 00 00 00 mov $0x9,%esi 1391: 48 89 c7 mov %rax,%rdi 1394: e8 b7 fc ff ff callq 1050 <_ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_c@plt> 1399: 83 45 c8 01 addl $0x1,-0x38(%rbp) 139d: eb b6 jmp 1355 139f: be 0a 00 00 00 mov $0xa,%esi 13a4: 48 8d 3d b5 2c 00 00 lea 0x2cb5(%rip),%rdi # 4060 <_ZSt4cout@@GLIBCXX_3.4> 13ab: e8 a0 fc ff ff callq 1050 <_ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_c@plt> 13b0: 83 45 c4 01 addl $0x1,-0x3c(%rbp) 13b4: eb 90 jmp 1346 13b6: 48 8b 45 a0 mov -0x60(%rbp),%rax 13ba: 48 89 45 98 mov %rax,-0x68(%rbp) 13be: c7 45 cc 00 00 00 00 movl $0x0,-0x34(%rbp) 13c5: 8b 55 90 mov -0x70(%rbp),%edx 13c8: 8b 45 94 mov -0x6c(%rbp),%eax 13cb: 0f af c2 imul %edx,%eax 13ce: 39 45 cc cmp %eax,-0x34(%rbp) 13d1: 7d 37 jge 140a 13d3: 8b 45 cc mov -0x34(%rbp),%eax 13d6: 48 98 cltq 13d8: 48 8d 14 85 00 00 00 lea 0x0(,%rax,4),%rdx 13df: 00 13e0: 48 8b 45 98 mov -0x68(%rbp),%rax 13e4: 48 01 d0 add %rdx,%rax 13e7: 8b 00 mov (%rax),%eax 13e9: 89 c6 mov %eax,%esi 13eb: 48 8d 3d 6e 2c 00 00 lea 0x2c6e(%rip),%rdi # 4060 <_ZSt4cout@@GLIBCXX_3.4> 13f2: e8 79 fc ff ff callq 1070 <_ZNSolsEi@plt> 13f7: be 20 00 00 00 mov $0x20,%esi 13fc: 48 89 c7 mov %rax,%rdi 13ff: e8 4c fc ff ff callq 1050 <_ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_c@plt> 1404: 83 45 cc 01 addl $0x1,-0x34(%rbp) 1408: eb bb jmp 13c5 140a: b8 00 00 00 00 mov $0x0,%eax 140f: 48 8b a5 58 ff ff ff mov -0xa8(%rbp),%rsp 1416: 48 8d 65 d8 lea -0x28(%rbp),%rsp 141a: 5b pop %rbx 141b: 41 5c pop %r12 141d: 41 5d pop %r13 141f: 41 5e pop %r14 1421: 41 5f pop %r15 1423: 5d pop %rbp 1424: c3 retq 0000000000001425 <_Z41__static_initialization_and_destruction_0ii>: 1425: 55 push %rbp 1426: 48 89 e5 mov %rsp,%rbp 1429: 48 83 ec 10 sub $0x10,%rsp 142d: 89 7d fc mov %edi,-0x4(%rbp) 1430: 89 75 f8 mov %esi,-0x8(%rbp) 1433: 83 7d fc 01 cmpl $0x1,-0x4(%rbp) 1437: 75 32 jne 146b <_Z41__static_initialization_and_destruction_0ii+0x46> 1439: 81 7d f8 ff ff 00 00 cmpl $0xffff,-0x8(%rbp) 1440: 75 29 jne 146b <_Z41__static_initialization_and_destruction_0ii+0x46> 1442: 48 8d 3d 50 2e 00 00 lea 0x2e50(%rip),%rdi # 4299 <_ZStL8__ioinit> 1449: e8 12 fc ff ff callq 1060 <_ZNSt8ios_base4InitC1Ev@plt> 144e: 48 8d 15 f3 2b 00 00 lea 0x2bf3(%rip),%rdx # 4048 <__dso_handle> 1455: 48 8d 35 3d 2e 00 00 lea 0x2e3d(%rip),%rsi # 4299 <_ZStL8__ioinit> 145c: 48 8b 05 95 2b 00 00 mov 0x2b95(%rip),%rax # 3ff8 <_ZNSt8ios_base4InitD1Ev@GLIBCXX_3.4> 1463: 48 89 c7 mov %rax,%rdi 1466: e8 d5 fb ff ff callq 1040 <__cxa_atexit@plt> 146b: 90 nop 146c: c9 leaveq 146d: c3 retq 000000000000146e <_GLOBAL__sub_I_main>: 146e: 55 push %rbp 146f: 48 89 e5 mov %rsp,%rbp 1472: be ff ff 00 00 mov $0xffff,%esi 1477: bf 01 00 00 00 mov $0x1,%edi 147c: e8 a4 ff ff ff callq 1425 <_Z41__static_initialization_and_destruction_0ii> 1481: 5d pop %rbp 1482: c3 retq 1483: 66 2e 0f 1f 84 00 00 nopw %cs:0x0(%rax,%rax,1) 148a: 00 00 00 148d: 0f 1f 00 nopl (%rax) 0000000000001490 <__libc_csu_init>: 1490: 41 57 push %r15 1492: 49 89 d7 mov %rdx,%r15 1495: 41 56 push %r14 1497: 49 89 f6 mov %rsi,%r14 149a: 41 55 push %r13 149c: 41 89 fd mov %edi,%r13d 149f: 41 54 push %r12 14a1: 4c 8d 25 00 29 00 00 lea 0x2900(%rip),%r12 # 3da8 <__frame_dummy_init_array_entry> 14a8: 55 push %rbp 14a9: 48 8d 2d 08 29 00 00 lea 0x2908(%rip),%rbp # 3db8 <__init_array_end> 14b0: 53 push %rbx 14b1: 4c 29 e5 sub %r12,%rbp 14b4: 48 83 ec 08 sub $0x8,%rsp 14b8: e8 43 fb ff ff callq 1000 <_init> 14bd: 48 c1 fd 03 sar $0x3,%rbp 14c1: 74 1b je 14de <__libc_csu_init+0x4e> 14c3: 31 db xor %ebx,%ebx 14c5: 0f 1f 00 nopl (%rax) 14c8: 4c 89 fa mov %r15,%rdx 14cb: 4c 89 f6 mov %r14,%rsi 14ce: 44 89 ef mov %r13d,%edi 14d1: 41 ff 14 dc callq *(%r12,%rbx,8) 14d5: 48 83 c3 01 add $0x1,%rbx 14d9: 48 39 dd cmp %rbx,%rbp 14dc: 75 ea jne 14c8 <__libc_csu_init+0x38> 14de: 48 83 c4 08 add $0x8,%rsp 14e2: 5b pop %rbx 14e3: 5d pop %rbp 14e4: 41 5c pop %r12 14e6: 41 5d pop %r13 14e8: 41 5e pop %r14 14ea: 41 5f pop %r15 14ec: c3 retq 14ed: 0f 1f 00 nopl (%rax) 00000000000014f0 <__libc_csu_fini>: 14f0: c3 retq Дизассемблирование раздела .fini: 00000000000014f4 <_fini>: 14f4: 48 83 ec 08 sub $0x8,%rsp 14f8: 48 83 c4 08 add $0x8,%rsp 14fc: c3 retq ================================================ FILE: cpp_algo/lec_07/2_array_param.cpp ================================================ #include using namespace std; // really it's bad to do such way! int main() { int N, M; cin >> N >> M; int A[N][M]; for(int i = 0; i < N; i++) { for(int j = 0; j < M; j++) { A[i][j] = i*M + j; } } for(int i = 0; i < N; i++) { for(int j = 0; j < M; j++) { cout << A[i][j] << '\t'; } cout << '\n'; } // memory investigation int *p = reinterpret_cast(A); for(int i = 0; i < M*N; i++) { cout << *(p + i) << ' '; } return 0; } ================================================ FILE: cpp_algo/lec_07/3_array_param.cpp ================================================ #include using namespace std; // really it's bad to do such way! const int M_MAXIMAL = 100; void print_array2d(int A[][M_MAXIMAL], int N, int M) { for(int i = 0; i < N; i++) { for(int j = 0; j < M; j++) { cout << A[i][j] << '\t'; } cout << '\n'; } } int main() { int N, M; cin >> N >> M; int A[N][M_MAXIMAL]; for(int i = 0; i < N; i++) { for(int j = 0; j < M; j++) { A[i][j] = i*M + j; } } print_array2d(A, N, M); // memory investigation int *p = reinterpret_cast(A); for(int i = 0; i < M*N; i++) { cout << *(p + i) << ' '; } return 0; } ================================================ FILE: cpp_algo/lec_07/4_array_param.cpp ================================================ #include using namespace std; // really it's bad to do such way! void print_array2d(int *p, int N, int M) { for(int i = 0; i < N; i++) { for(int j = 0; j < M; j++) { cout << p[i*M + j] << '\t'; // A[i][j] } cout << '\n'; } } int main() { int N, M; cin >> N >> M; int A[N][M]; for(int i = 0; i < N; i++) { for(int j = 0; j < M; j++) { A[i][j] = i*M + j; } } print_array2d(reinterpret_cast(A), N, M); // memory investigation int *p = reinterpret_cast(A); for(int i = 0; i < M*N; i++) { cout << *(p + i) << ' '; } return 0; } ================================================ FILE: cpp_algo/lec_07/5_linearized_manually.cpp ================================================ #include using namespace std; // really it's bad to do such way! void print_array2d(int *A, int N, int M) { for(int i = 0; i < N; i++) { for(int j = 0; j < M; j++) { cout << A[i*M + j] << '\t'; // A[i][j] } cout << '\n'; } } int main() { int N, M; cin >> N >> M; int A[N*M]; for(int i = 0; i < N; i++) { for(int j = 0; j < M; j++) { A[i*M + j] = i*M + j; } } print_array2d(A, N, M); return 0; } ================================================ FILE: cpp_algo/lec_07/6_dynamical.cpp ================================================ #include using namespace std; // really it's bad to do such way! void print_array2d(int *A, int N, int M) { for(int i = 0; i < N; i++) { for(int j = 0; j < M; j++) { cout << A[i*M + j] << '\t'; // A[i][j] } cout << '\n'; } } int main() { int N, M; cin >> N >> M; // memory allocation int **A = new int*[N]; for(int i = 0; i < N; i++) { A[i] = new int[M]; } for(int i = 0; i < N; i++) { for(int j = 0; j < M; j++) { A[i][j] = i*M + j; } } for(int i = 0; i < N; i++) { for(int j = 0; j < M; j++) { cout << A[i][j] << '\t'; } cout << '\n'; } for(int i = 0; i < N; i++) { delete[] A[i]; } delete[] A; return 0; } ================================================ FILE: cpp_algo/lec_07/7_dynamical.cpp ================================================ #include using namespace std; // really it's bad to do such way! void print_array2d(int *A, int N, int M) { for(int i = 0; i < N; i++) { for(int j = 0; j < M; j++) { cout << A[i*M + j] << '\t'; // A[i][j] } cout << '\n'; } } int main() { int N, M; cin >> N >> M; // memory allocation int **A = new int*[N]; A[0] = new int[N*M]; for(int i = 1; i < N; i++) { A[i] = A[0] + M*i; } for(int i = 0; i < N; i++) { for(int j = 0; j < M; j++) { A[i][j] = i*M + j; } } for(int i = 0; i < N; i++) { for(int j = 0; j < M; j++) { cout << A[i][j] << '\t'; } cout << '\n'; } print_array2d(A[0], M, N); delete[] A[0]; delete[] A; return 0; } ================================================ FILE: cpp_algo/lec_08/bin_search.cpp ================================================ #include using namespace std; int left_bound(int A[], int N, int x) { int left = -1; // A[left] < x int right = N; // A[right] >= x while (right - left > 1) { int middle = (left + right) / 2; if (A[middle] < x) left = middle; else right = middle; } return left; } int find(int A[], int N, int x) { int left = left_bound(A, N, x); int potential_first_index_of_x_in_A = left + 1; if (potential_first_index_of_x_in_A < N and A[potential_first_index_of_x_in_A] == x) return potential_first_index_of_x_in_A; else return -1; // x not found } int main() { int N = 10; int A[] = {1, 3, 3, 7, 7, 7, 7, 9, 10, 10}; int x; for(int i = 0; i < N; i++) cout << A[i] << '\t'; cout << '\n'; cin >> x; cout << "left boundary of x is: " << left_bound(A, N, x) << '\n'; return 0; } ================================================ FILE: cpp_algo/lec_08/count_sort.cpp ================================================ #include using namespace std; void count_sort(int A[], int N) { // Я ОБЯЗАН знать диапазон сортируемых чисел (считаю, что они от 0 до 9) int F[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; for(int i = 0; i < N; i++) { F[A[i]]++; } int i = 0; for(int x = 0; x < 10; x++) { // перебираю всевозможные значения ключа! (их M штук) for(int k = 0; k < F[x]; k++) { A[i] = x; i++; } } } void generate_random_array(int A[], int N, int M) { for(int i = 0; i < N; i++) A[i] = rand() % M; } void print_array(int A[], int N) { for(int i = 0; i < N; i++) cout << A[i] << '\t'; cout << '\n'; } int main() { int N = 10; int A[N]; generate_random_array(A, N, 10); print_array(A, N); count_sort(A, N); print_array(A, N); return 0; } ================================================ FILE: cpp_algo/lec_08/lin_search.cpp ================================================ #include using namespace std; int find(int A[], int N, int x) { for(int i = 0; i < N; i++) if (A[i] == x) return i; return -1; } int main() { int N = 10; int A[] = {1, 3, 3, 7, 7, 7, 7, 9, 10, 10}; int x; for(int i = 0; i < N; i++) cout << A[i] << '\t'; cout << '\n'; cin >> x; cout << "index of x is: " << find(A, N, x) << '\n'; return 0; } ================================================ FILE: cpp_algo/lec_08/radix_sort.cpp ================================================ #include using namespace std; void radix_sort(int *A, int N) { int *a0 = new int[N]; int *a1 = new int[N]; for(int radix = 0; radix < 32; radix++) { int a0_size = 0; int a1_size = 0; for(int i = 0; i < N; i++) { if ((A[i] & (1 << radix)) == 0) a0[a0_size++] = A[i]; else a1[a1_size++] = A[i]; } for(int i = 0; i < a0_size; i++) A[i] = a0[i]; for(int i = 0; i < a1_size; i++) A[a0_size + i] = a1[i]; } delete[] a0; delete[] a1; } void generate_random_array(int A[], int N, int M) { for(int i = 0; i < N; i++) A[i] = rand() % M; } void print_array(int A[], int N) { for(int i = 0; i < N; i++) cout << A[i] << '\t'; cout << '\n'; } int main() { int N = 10; int A[N]; generate_random_array(A, N, 1000); print_array(A, N); radix_sort(A, N); print_array(A, N); return 0; } ================================================ FILE: cpp_algo/lec_09/1_factorial.cpp ================================================ /** * Factorial really should not be writter with recursion! */ #include int64_t factorial(int16_t n) { std::cout << "factorial(" << n << ") is called. \n"; int64_t result; if (n == 0) { // base case: result = 1; } else { // recurrent case: result = factorial(n - 1)*n; } std::cout << "factorial(" << n << ") is exitting.\n"; return result; } int main() { int16_t x; std::cin >> x; std::cout << factorial(x) << '\n'; return 0; } ================================================ FILE: cpp_algo/lec_09/2_main.cpp ================================================ #include int main(int argc, char *argv[]) { if (argc > 1) return main(argc - 1, argv) * argc; else return 1; } ================================================ FILE: cpp_algo/lec_09/3_euclid.cpp ================================================ #include int gcd(int a, int b) { return (b == 0) ? a : gcd(b, a % b); } int main() { int a, b; std::cin >> a >> b; std::cout << gcd(a, b) << '\n'; return 0; } ================================================ FILE: cpp_algo/lec_09/4_hanoi.cpp ================================================ #include /** * Hanoi solution finder. * param i: start pin number * param k: finish pin number * param n: number of disks */ void hanoi(int i, int k, int n) { if (n == 1) { std::cout << "Move disk 1 from pin " << i << " to pin " << k << ".\n"; } else { int tmp = 6 - i - k; // third pin (temporary) hanoi(i, tmp, n - 1); std::cout << "Move disk " << n << " from pin " << i << " to pin " << k << ".\n"; hanoi(tmp, k, n - 1); } } int main() { hanoi(1, 2, 4); return 0; } ================================================ FILE: cpp_algo/lec_09/5_bin_gen.cpp ================================================ #include const int MAX_BINARY_DIGITS_TO_GENERATE = 100; void generate_binary_numbers(int digits_left_to_generate) { static int digits_combination[MAX_BINARY_DIGITS_TO_GENERATE]; static int top = 0; if (digits_left_to_generate == 0) { // base case for(int i = 0; i < top; i++) std::cout << digits_combination[i]; std::cout << '\n'; } else { // recursive case digits_combination[top++] = 1; generate_binary_numbers(digits_left_to_generate - 1); top--; digits_combination[top++] = 0; generate_binary_numbers(digits_left_to_generate - 1); top--; } } int main() { int n; std::cout << "Enter bin number length: "; std::cin >> n; generate_binary_numbers(n); return 0; } ================================================ FILE: cpp_algo/lec_10/1_permutations.cpp ================================================ #include const int MAX_BINARY_DIGITS_TO_GENERATE = 100; void permutations(int16_t number, int16_t current, int16_t buffer[], bool used[]) { if (current == number) { // base case for(int i = 0; i < number; i++) std::cout << buffer[i] << ' '; std::cout << '\n'; } else { // recursive case for (int16_t variant = 0; variant < number; variant++) { if (not used[variant]) { // cutting the recursive tree buffer[current] = variant; used[variant] = true; permutations(number, current + 1, buffer, used); used[variant] = false; } } } } int main() { int16_t n; std::cout << "Enter length to generate all permutations: "; std::cin >> n; if (n > 20) { std::cerr << "Your number is too big!"; return 1; } else if (n <= 0) { std::cerr << "Your number is negative!"; return 1; } int16_t buffer[n]; bool used[n] = {false}; // suspect that used will be initialized by zeroes (to be interpreted as false) permutations(n, 0, buffer, used); return 0; } ================================================ FILE: cpp_algo/lec_10/2_merge_sort.cpp ================================================ #include #include const int MAX_ARRAY_SIZE = 100000; void merge_sort(double *array, int16_t array_size) { if (array_size <= 1) return; // base case. Critical to implement it!!! int16_t middle = array_size / 2; double *left = array; double *right = array + middle; // BEWARE! Using address arithmetics: pointer + number gives shifted array begin int16_t left_size = middle; int16_t right_size = array_size - left_size; // recursion goes here: merge_sort(left, left_size); merge_sort(right, right_size); // Merge these two already sorted parts of array: double *buffer = new double[array_size]; int16_t left_i = 0; int16_t right_i = 0; int16_t buffer_i = 0; while (left_i < left_size and right_i < right_size) { if (left[left_i] <= right[right_i]) { // taking the lesser from the left part of array buffer[buffer_i] = left[left_i]; left_i += 1; buffer_i += 1; } else { // taking the lesser from the right part of array buffer[buffer_i] = right[right_i]; right_i += 1; buffer_i += 1; } } while (left_i < left_size) { // copying left elements from the left size (if there is left something) buffer[buffer_i] = left[left_i]; left_i += 1; buffer_i += 1; } while (right_i < right_size) { // copying right elements from the right size (if there is right something) buffer[buffer_i] = right[right_i]; right_i += 1; buffer_i += 1; } // copying from buffer to original array: for(int16_t i = 0; i < array_size; i++) { array[i] = buffer[i]; } delete[] buffer; } void input_array(double *array, int16_t n) { for (int i = 0; i < n; i++) { std::cin >> array[i]; } } void print_array(double *array, int16_t n) { for (int i = 0; i < n; i++) { std::cout << array[i] << ' '; } std::cout << '\n'; } int main() { int16_t array_size; std::cout << "Enter size of array: "; std::cin >> array_size; if (array_size <= 0 or array_size > MAX_ARRAY_SIZE) { std::cerr << "Your array size is unacceptable!\n"; return 1; } double *array = new double[array_size]; input_array(array, array_size); merge_sort(array, array_size); print_array(array, array_size); delete[] array; return 0; } ================================================ FILE: cpp_algo/lec_11/1_fibonacci.cpp ================================================ #include #include uint64_t fib_recursive(int n) { assert(n >= 0); if (n == 0 or n == 1) { return n; } else { return fib_recursive(n-1) + fib_recursive(n-2); } } uint64_t fib_dynamic(int n) { uint64_t result; uint64_t *fib = new uint64_t[n + 1]; fib[0] = 0; fib[1] = 1; for (int i = 2; i <= n; i++) { fib[i] = fib[i-1] + fib[i-2]; } result = fib[n]; delete[] fib; return result; } int main() { uint64_t (*fib)(int); int version = 0; std::cout << "Which version of Fibonacci function to use? (0 - recursive, 1 - dynamic)\n"; std::cin >> version; if (version == 0) { fib = fib_recursive; } else { fib = fib_dynamic; } for (int n = 0; n <= 100; n++) { std::cout << n << '\t' << fib(n) << '\n'; } return 0; } ================================================ FILE: cpp_algo/lec_11/2_hopper_economist.cpp ================================================ #include #include int min_cost(int n, int price[]) { int cost[n + 1]; // base cases: cost[1] = price[1]; cost[2] = price[1] + price[2]; for (int i = 3; i <= n; i++) { // recursive case: cost[i] = std::min(cost[i-1], cost[i-2]) + price[i]; } std::cout << "Min cost path (reversed) = ["; int current = n; std::cout << current << " "; while(current != 1) { if (cost[current - 1] == cost[current] - price[current]) current = current - 1; else if (cost[current - 2] == cost[current] - price[current]) current = current - 2; else throw -1; // Nonsence! I should never achive this line! std::cout << current << " "; } std::cout << "]\n"; return cost[n]; } int main() { int n; std::cout << "Hopper economist wants to go from point 1 to point n. Enter n:\n"; std::cin >> n; if (n > 100) { std::cout << "Your number is too big! maximum is 100.\n"; return -1; } int price[101]; std::cout << "Enter prices of visiting point (from point 1 to point n):\n"; for (int i = 1; i <= n; i++) { std::cin >> price[i]; } std::cout << "Min cost of achieving point n from point 1 is " << min_cost(n, price) << '\n'; return 0; } ================================================ FILE: cpp_algo/lec_12/1_ant.cpp ================================================ #include #include uint64_t combinations_recursive(int i, int j) { assert(i > 0 and j > 0); if (i == 1 or j == 1) { return 1; } else { return combinations_recursive(i, j-1) + combinations_recursive(i-1, j); } } uint64_t combinations_dynamic(int n, int m) { uint64_t result; // memory allocation for K function: uint64_t **K = new uint64_t*[n + 1]; for(int i = 0; i <= n; i++) { K[i] = new uint64_t[m + 1]; } // base cases: for (int i = 1; i <= n; i++) { K[i][1] = 1; } for (int j = 1; j <= m; j++) { K[1][j] = 1; } // recursive cases: for (int i = 2; i <= n; i++) { for (int j = 2; j <= m; j++) { K[i][j] = K[i-1][j] + K[i][j-1]; } } // return value with correct liberation of allocated memory result = K[n][m]; for(int i = 0; i <= n; i++) delete K[i]; delete[] K; return result; } int main() { uint64_t (*combinations)(int, int); int version = 0; std::cout << "Which version of function to use? (0 - recursive, 1 - dynamic)\n"; std::cin >> version; if (version == 0) { combinations = combinations_recursive; } else { combinations = combinations_dynamic; } for (int i = 1; i <= 30; i++) { for (int j = 1; j <= 12; j++) { std::cout << combinations(i, j) << '\t'; } std::cout << '\n'; } return 0; } ================================================ FILE: cpp_algo/lec_12/2_ant_array.cpp ================================================ #include #include #include uint64_t combinations_recursive(int i, int j) { assert(i > 0 and j > 0); if (i == 1 or j == 1) { return 1; } else { return combinations_recursive(i, j-1) + combinations_recursive(i-1, j); } } uint64_t combinations_dynamic(int n, int m) { std::vector> K; K.resize(n + 1); for (int i = 1; i <= n; i++) { K[i].resize(m + 1); } // base cases: for (int i = 1; i <= n; i++) { K[i][1] = 1; } for (int j = 1; j <= m; j++) { K[1][j] = 1; } // recursive cases: for (int i = 2; i <= n; i++) { for (int j = 2; j <= m; j++) { K[i][j] = K[i-1][j] + K[i][j-1]; } } return K[n][m]; } int main() { uint64_t (*combinations)(int, int); int version = 0; std::cout << "Which version of function to use? (0 - recursive, 1 - dynamic)\n"; std::cin >> version; if (version == 0) { combinations = combinations_recursive; } else { combinations = combinations_dynamic; } for (int i = 1; i <= 30; i++) { for (int j = 1; j <= 12; j++) { std::cout << combinations(i, j) << '\t'; } std::cout << '\n'; } return 0; } ================================================ FILE: cpp_algo/lec_12/3_bagpack.cpp ================================================ #include #include #include double max_backpack_value(std::vector> treasures, int capacity) { // 2D array of answers - to be filled in. std::vector> F; F.resize(capacity + 1); for (int i = 0; i <= capacity; i++) { F[i].resize(treasures.size() + 1); } std::cout << "DEBUG 1\n"; // base cases: for (int i = 0; i <= capacity; i++) { F[i][0] = 0; } for (int j = 0; j <= treasures.size(); j++) { F[0][j] = 0; } std::cout << "DEBUG 2\n"; // recursive cases: for (int j = 1; j <= treasures.size(); j++) { int weight = treasures[j-1].first; double value = treasures[j-1].second; for (int k = 1; k < weight; k++) { F[k][j] = F[k][j-1]; } for (int k = weight; k <= capacity; k++) { F[k][j] = std::max(F[k][j-1], value + F[k-weight][j-1]); } } return F[capacity][treasures.size()]; } int main() { int treasures_number; std::cout << "Enter number of treasures:"; std::cin >> treasures_number; std::vector> treasures; for (int i = 0; i < treasures_number; i++) { int weight; double value; std::cout << "Enter treasure[" << i << "] weight and value:"; std::cin >> weight >> value; treasures.push_back(std::make_pair(weight, value)); } int capacity; std::cout << "Enter backpack carrying capacity:"; std::cin >> capacity; std::cout << max_backpack_value(treasures, capacity) << '\n'; return 0; } ================================================ FILE: cpp_algo/lec_12/input_data.txt ================================================ 4 2 3 3 1 5 6 1 2 5 ================================================ FILE: cpp_algo/lec_13/1_strcat_problem.cpp ================================================ #include #include #include int main() { const char *s = "Hello, World! "; printf("%s\n", s); printf("strlen(s) = %d\n", strlen(s)); int times_to_concatenate; scanf("%d", ×_to_concatenate); size_t buffer_length = strlen(s) * times_to_concatenate + 1; char *buffer = (char*) malloc(buffer_length * sizeof(char)); buffer[0] = '\0'; printf("%s\n", buffer); for (int i = 0; i < times_to_concatenate; i++) { strcat(buffer, s); } //printf("%s\n", buffer); free(buffer); return 0; } ================================================ FILE: cpp_algo/lec_13/2_strcat_solution.cpp ================================================ #include #include int main() { // This is used to speedup input in automatic testing: std::ios_base::sync_with_stdio(false); std::cin.tie(nullptr); std::string hello = "Hello, World! "; std::string result; std::cout << hello << std::endl; int times_to_concatenate; std::cin >> times_to_concatenate; for (int i = 0; i < times_to_concatenate; i++) { result += hello; } //std::cout << result << std::endl; return 0; } ================================================ FILE: cpp_algo/lec_13/3_levenstein.cpp ================================================ #include #include #include int levenstein_distance(std::string a, std::string b) { // 2D array of answers - to be filled in. std::vector> L; L.resize(a.length() + 1); for (int i = 0; i <= a.length(); i++) { L[i].resize(b.length() + 1); } // base cases: for (int i = 0; i <= a.length(); i++) { L[i][0] = i; } for (int k = 0; k <= b.length(); k++) { L[0][k] = k; } // recursive cases: for (int i = 1; i <= a.length(); i++) { for (int k = 1; k <= b.length(); k++) { if (a[i-1] == b[k-1]) // Last chars are the same! L[i][k] = L[i-1][k-1]; else // Last chars are different - so we need to add or remove last in a or b. L[i][k] = std::min(std::min(L[i-1][k], L[i][k-1]), L[i-1][k-1]) + 1; } } return L[a.length()][b.length()]; } int main() { std::string a, b; std::cout << "Enter string A:"; std::cin >> a; std::cout << "Enter string B:"; std::cin >> b; std::cout << "Levenstein distance between A and B is:"; std::cout << levenstein_distance(a, b) << '\n'; return 0; } ================================================ FILE: cpp_algo/lec_14/1_vector_list.cpp ================================================ #include #include #include #include void vector_example() { std::vector words; std::string word; getline(std::cin, word); while (word != "") { words.push_back(word); getline(std::cin, word); } for(int i = 0; i < words.size(); ++i) { std::cout << words[i] << '\t'; } std::cout << std::endl; } void list_example() { std::list words; std::string word; getline(std::cin, word); while (word != "") { words.push_back(word); getline(std::cin, word); } for(std::list::iterator p = words.begin(); p != words.end(); ++p) { std::cout << *p << '\t'; } std::cout << std::endl; for(auto p = words.begin(); p != words.end(); ++p) { std::cout << *p << '\t'; } for(auto &word: words) { std::cout << word << '\t'; } std::cout << std::endl; } int main() { list_example(); return 0; } ================================================ FILE: cpp_algo/lec_14/2_kmp.cpp ================================================ #include #include #include std::vector prefix_function_kmp(std::string s) { int n = s.length(); std::vector pi(n, 0); for (int i = 1; i < n; ++i) { int k = pi[i-1]; while (k > 0 and s[i] != s[k]) { k = pi[k-1]; } if (s[i] == s[k]) k += 1; pi[i] = k; } return pi; } int main() { std::string line; getline(std::cin, line); std::string tmp; getline(std::cin, tmp); std::string summary = tmp + '#' + line; std::vector pi = prefix_function_kmp(summary); int counter = 0; for (auto x: pi) { if (x == tmp.size()) counter++; } std::cout << "Number of cases template is substring in string: " << counter << std::endl; } ================================================ FILE: cpp_algo/lec_15/01_vector_usage.cpp ================================================ #include #include #include void procedure(int x) { std::cout << x << '\n'; } int main() { std::vector A; for(int i = 0; i < 10; i++) A.push_back(i); // НЕУКЛЮЖАЯ ВЕРСИЯ: std::vector::iterator it1 = A.begin(); while (it1 != A.end()) { std::cout << *it1 << "\n"; ++it1; } // почти УКЛЮЖАЯ ВЕРСИЯ: auto it2 = A.begin(); while (it2 != A.end()) { std::cout << *it2 << "\n"; ++it2; } for (auto it3 = A.begin(); it3 != A.end(); ++it3) { std::cout << *it3 << "\n"; } std::cout << "for_each:\n"; std::for_each(A.begin(), A.end(), procedure); std::cout << "range based for:\n"; for (auto x: A) { std::cout << x << ' '; } return 0; } ================================================ FILE: cpp_algo/lec_15/02_list_usage.cpp ================================================ #include #include #include void procedure(int x) { std::cout << x << '\n'; } int main() { std::list A; for(int i = 0; i < 10; i++) A.push_back(i); // НЕУКЛЮЖАЯ ВЕРСИЯ: std::list::iterator it1 = A.begin(); while (it1 != A.end()) { std::cout << *it1 << "\n"; ++it1; } // почти УКЛЮЖАЯ ВЕРСИЯ: auto it2 = A.begin(); while (it2 != A.end()) { std::cout << *it2 << "\n"; ++it2; } for (auto it3 = A.begin(); it3 != A.end(); ++it3) { std::cout << *it3 << "\n"; } std::cout << "for_each:\n"; std::for_each(A.begin(), A.end(), procedure); std::cout << "range based for:\n"; for (auto x: A) { std::cout << x << ' '; } return 0; } ================================================ FILE: cpp_algo/lec_16/1_simple_class.cpp ================================================ #include #include // Developer #1 struct Student { private: std::string name; std::string group; int age; double *memory; public: Student(std::string name_, std::string group_, int age_) { name = name_; group = group_; age = age_; std::cout << "Hooray!!! Me " << name << " enrolled to the course!\n"; //RESOURCE ALLOCATION memory = new double[100]; } ~Student() { std::cout << "Ouch!!! Me " << name << " dismissed from the course!\n"; //RESOURCE DEALLOCATION delete[] memory; } void print() const { std::cout << name << " " << group << " "; std::cout << age << "\n"; } void ageing() { std::cout << "Hooray!!! Today is my birthday! I'm " << name << '\n'; age += 1; print(); //the same as this->print() } }; // Developer #2 int main() { Student a("Petya", "B02-991", 18); a.print(); a.ageing(); a.print(); Student b("Vasya", "B012", 17); b.print(); b = a; // RAII concept is broken HERE! b.print(); } ================================================ FILE: cpp_algo/lec_16/2_overloading.cpp ================================================ #include void foo(unsigned char x) { std::cout << " foo(unsigned char) is called\n"; } void foo(int x) { std::cout << " foo(int) is called\n"; } void foo(double x) { std::cout << " foo(double) is called\n"; } int main() { foo('A'); foo(1); foo(4.5); foo(23U); //delete to make code work return 0; } ================================================ FILE: cpp_algo/lec_16/3_abs_template.cpp ================================================ #include template T my_abs(T x) { if (x < 0) return -x; else return x; } int main() { std::cout << my_abs('A') << "\n"; std::cout << my_abs(-23) << "\n"; std::cout << my_abs(-3.5) << "\n"; return 0; } ================================================ FILE: cpp_algo/lec_17/1_fin_automata_1.cpp ================================================ #include #include inline bool is_alpha(char symbol) { return (symbol >= 'a' and symbol <= 'z') or (symbol >= 'A' and symbol <= 'Z'); } int main() { std::string s; std::getline(std::cin, s); int word_len = 0; int pos = 0; out_of_word: if (pos >= s.length()) goto the_end; if (is_alpha(s[pos])) { pos++; word_len = 1; goto in_word; } else { pos++; goto out_of_word; } in_word: if (pos >= s.length()) goto the_end; if (is_alpha(s[pos])) { pos++; word_len += 1; goto in_word; } else { pos++; std::cout << "Word length: " << word_len << '\n'; goto out_of_word; } the_end: std::cout << s << '\n'; return 0; } ================================================ FILE: cpp_algo/lec_17/2_fin_automata_2.cpp ================================================ #include #include enum AutomataState{ out_of_word = 0, in_word = 1 }; inline bool is_alpha(char symbol) { return (symbol >= 'a' and symbol <= 'z') or (symbol >= 'A' and symbol <= 'Z'); } int main() { std::string s; std::getline(std::cin, s); int word_len = 0; AutomataState state = out_of_word; for (int pos = 0; pos < s.length(); pos++) { switch(state) { case out_of_word: if (is_alpha(s[pos])) { word_len = 1; state = in_word; } else { state = out_of_word; } break; case in_word: if (is_alpha(s[pos])) { word_len += 1; state = in_word; } else { std::cout << "Word length: " << word_len << '\n'; state = out_of_word; } } } std::cout << s << '\n'; return 0; } ================================================ FILE: cpp_algo/lec_18/rabin_karp.cpp ================================================ #include #include const P = 257; uint32_t hash(std::string s) { uint32_t sum = 0; uint32_t factor = 1; for(int i = s.length() - 1; i >= 0; i--) { sum += s[i]*factor; factor *= P; } } int main() { std::string s; std::getline(std::cin, s); std::string pattern; std::getline(std::cin, pattern); uint32_t pattern_hash = hash(pattern); uint32 M = pattern.length(); uint32_t pattern_hash = hash(s); return 0; } ================================================ FILE: cpp_algo/lec_20/1_set.cpp ================================================ #include #include #include void set_example() { std::set words; std::string word; getline(std::cin, word); while (word != "") { words.insert(word); getline(std::cin, word); } for(auto &word: words) { std::cout << word << '\t'; } std::cout << std::endl; std::cout << "Enter key to find in set: "; std::cin >> word; if (words.find(word) != words.end()) { std::cout << "Found it!\n"; } else { std::cout << "Not found it...\n"; } } int main() { set_example(); return 0; } ================================================ FILE: cpp_algo/lec_20/2_unordered_set.cpp ================================================ #include #include #include void set_example() { std::unordered_set words; std::string word; getline(std::cin, word); while (word != "") { words.insert(word); getline(std::cin, word); } for(auto &word: words) { std::cout << word << '\t'; } std::cout << std::endl; std::cout << "Enter key to find in set: "; std::cin >> word; if (words.find(word) != words.end()) { std::cout << "Found it!\n"; } else { std::cout << "Not found it...\n"; } } int main() { set_example(); return 0; } ================================================ FILE: cpp_algo/lec_20/set_input.txt ================================================ pear apple carrot cabbage cucumber salad potato onion apple ================================================ FILE: cpp_algo/lec_21/1.txt ================================================ // SOme text is here. ================================================ FILE: cpp_algo/lec_21/2_euclid.cpp ================================================ #include int euclid_gcd(int a, int b) { // Алгоритм Евклида поиска НОД while (a != b) { if (a > b) { a -= b; } else { b -= a; } } return a; } int main() { using namespace std; int x, y; cout << "Enter integer. x = "; cin >> x; cout << "Enter integer. y = "; cin >> y; cout << "GCD(x, y) = " << euclid_gcd(x, y) << endl; return 0; } ================================================ FILE: cpp_algo/lec_21/2_euclid.s ================================================ .file "2_euclid.cpp" .text .section .rodata .type _ZStL19piecewise_construct, @object .size _ZStL19piecewise_construct, 1 _ZStL19piecewise_construct: .zero 1 .local _ZStL8__ioinit .comm _ZStL8__ioinit,1,1 .text .globl _Z10euclid_gcdii .type _Z10euclid_gcdii, @function _Z10euclid_gcdii: .LFB1518: .cfi_startproc pushq %rbp .cfi_def_cfa_offset 16 .cfi_offset 6, -16 movq %rsp, %rbp .cfi_def_cfa_register 6 movl %edi, -4(%rbp) movl %esi, -8(%rbp) .L5: movl -4(%rbp), %eax cmpl -8(%rbp), %eax je .L2 movl -4(%rbp), %eax cmpl -8(%rbp), %eax jle .L3 movl -8(%rbp), %eax subl %eax, -4(%rbp) jmp .L5 .L3: movl -4(%rbp), %eax subl %eax, -8(%rbp) jmp .L5 .L2: movl -4(%rbp), %eax popq %rbp .cfi_def_cfa 7, 8 ret .cfi_endproc .LFE1518: .size _Z10euclid_gcdii, .-_Z10euclid_gcdii .section .rodata .LC0: .string "Enter integer. x = " .LC1: .string "Enter integer. y = " .LC2: .string "GCD(x, y) = " .text .globl main .type main, @function main: .LFB1519: .cfi_startproc pushq %rbp .cfi_def_cfa_offset 16 .cfi_offset 6, -16 movq %rsp, %rbp .cfi_def_cfa_register 6 pushq %rbx subq $24, %rsp .cfi_offset 3, -24 leaq .LC0(%rip), %rsi leaq _ZSt4cout(%rip), %rdi call _ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_PKc@PLT leaq -20(%rbp), %rax movq %rax, %rsi leaq _ZSt3cin(%rip), %rdi call _ZNSirsERi@PLT leaq .LC1(%rip), %rsi leaq _ZSt4cout(%rip), %rdi call _ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_PKc@PLT leaq -24(%rbp), %rax movq %rax, %rsi leaq _ZSt3cin(%rip), %rdi call _ZNSirsERi@PLT leaq .LC2(%rip), %rsi leaq _ZSt4cout(%rip), %rdi call _ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_PKc@PLT movq %rax, %rbx movl -24(%rbp), %edx movl -20(%rbp), %eax movl %edx, %esi movl %eax, %edi call _Z10euclid_gcdii movl %eax, %esi movq %rbx, %rdi call _ZNSolsEi@PLT movq %rax, %rdx movq _ZSt4endlIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_@GOTPCREL(%rip), %rax movq %rax, %rsi movq %rdx, %rdi call _ZNSolsEPFRSoS_E@PLT movl $0, %eax addq $24, %rsp popq %rbx popq %rbp .cfi_def_cfa 7, 8 ret .cfi_endproc .LFE1519: .size main, .-main .type _Z41__static_initialization_and_destruction_0ii, @function _Z41__static_initialization_and_destruction_0ii: .LFB2008: .cfi_startproc pushq %rbp .cfi_def_cfa_offset 16 .cfi_offset 6, -16 movq %rsp, %rbp .cfi_def_cfa_register 6 subq $16, %rsp movl %edi, -4(%rbp) movl %esi, -8(%rbp) cmpl $1, -4(%rbp) jne .L11 cmpl $65535, -8(%rbp) jne .L11 leaq _ZStL8__ioinit(%rip), %rdi call _ZNSt8ios_base4InitC1Ev@PLT leaq __dso_handle(%rip), %rdx leaq _ZStL8__ioinit(%rip), %rsi movq _ZNSt8ios_base4InitD1Ev@GOTPCREL(%rip), %rax movq %rax, %rdi call __cxa_atexit@PLT .L11: nop leave .cfi_def_cfa 7, 8 ret .cfi_endproc .LFE2008: .size _Z41__static_initialization_and_destruction_0ii, .-_Z41__static_initialization_and_destruction_0ii .type _GLOBAL__sub_I__Z10euclid_gcdii, @function _GLOBAL__sub_I__Z10euclid_gcdii: .LFB2009: .cfi_startproc pushq %rbp .cfi_def_cfa_offset 16 .cfi_offset 6, -16 movq %rsp, %rbp .cfi_def_cfa_register 6 movl $65535, %esi movl $1, %edi call _Z41__static_initialization_and_destruction_0ii popq %rbp .cfi_def_cfa 7, 8 ret .cfi_endproc .LFE2009: .size _GLOBAL__sub_I__Z10euclid_gcdii, .-_GLOBAL__sub_I__Z10euclid_gcdii .section .init_array,"aw" .align 8 .quad _GLOBAL__sub_I__Z10euclid_gcdii .hidden __dso_handle .ident "GCC: (Debian 8.3.0-6) 8.3.0" .section .note.GNU-stack,"",@progbits ================================================ FILE: cpp_algo/lec_21/cmake_project/CMakeLists.txt ================================================ cmake_minimum_required(VERSION 2.8) # Проверка версии CMake. project(main) # Название проекта set(SOURCE_EXE main.cpp) # Установка переменной со списком исходников для исполняемого файла set(SOURCE_LIB mylib.cpp) # Тоже самое, но для библиотеки add_library(mylib STATIC ${SOURCE_LIB}) # Создание статической библиотеки с именем foo add_executable(main ${SOURCE_EXE}) # Создает исполняемый файл с именем main target_link_libraries(main mylib) # Линковка программы с библиотекой ================================================ FILE: cpp_algo/lec_21/cmake_project/Makefile ================================================ # CMAKE generated file: DO NOT EDIT! # Generated by "Unix Makefiles" Generator, CMake Version 3.13 # Default target executed when no arguments are given to make. default_target: all .PHONY : default_target # Allow only one "make -f Makefile2" at a time, but pass parallelism. .NOTPARALLEL: #============================================================================= # Special targets provided by cmake. # Disable implicit rules so canonical targets will work. .SUFFIXES: # Remove some rules from gmake that .SUFFIXES does not remove. SUFFIXES = .SUFFIXES: .hpux_make_needs_suffix_list # Suppress display of executed commands. $(VERBOSE).SILENT: # A target that is always out of date. cmake_force: .PHONY : cmake_force #============================================================================= # Set environment variables for the build. # The shell in which to execute make rules. SHELL = /bin/sh # The CMake executable. CMAKE_COMMAND = /usr/bin/cmake # The command to remove a file. RM = /usr/bin/cmake -E remove -f # Escaping for special characters. EQUALS = = # The top-level source directory on which CMake was run. CMAKE_SOURCE_DIR = /home/tkhirianov/lec_2020/cpp_algo/lec_21/cmake_project # The top-level build directory on which CMake was run. CMAKE_BINARY_DIR = /home/tkhirianov/lec_2020/cpp_algo/lec_21/cmake_project #============================================================================= # Targets provided globally by CMake. # Special rule for the target rebuild_cache rebuild_cache: @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running CMake to regenerate build system..." /usr/bin/cmake -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) .PHONY : rebuild_cache # Special rule for the target rebuild_cache rebuild_cache/fast: rebuild_cache .PHONY : rebuild_cache/fast # Special rule for the target edit_cache edit_cache: @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "No interactive CMake dialog available..." /usr/bin/cmake -E echo No\ interactive\ CMake\ dialog\ available. .PHONY : edit_cache # Special rule for the target edit_cache edit_cache/fast: edit_cache .PHONY : edit_cache/fast # The main all target all: cmake_check_build_system $(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 $(MAKE) -f CMakeFiles/Makefile2 all $(CMAKE_COMMAND) -E cmake_progress_start /home/tkhirianov/lec_2020/cpp_algo/lec_21/cmake_project/CMakeFiles 0 .PHONY : all # The main clean target clean: $(MAKE) -f CMakeFiles/Makefile2 clean .PHONY : clean # The main clean target clean/fast: clean .PHONY : clean/fast # Prepare targets for installation. preinstall: all $(MAKE) -f CMakeFiles/Makefile2 preinstall .PHONY : preinstall # Prepare targets for installation. preinstall/fast: $(MAKE) -f CMakeFiles/Makefile2 preinstall .PHONY : preinstall/fast # clear depends depend: $(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 1 .PHONY : depend #============================================================================= # Target rules for targets named mylib # Build rule for target. mylib: cmake_check_build_system $(MAKE) -f CMakeFiles/Makefile2 mylib .PHONY : mylib # fast build rule for target. mylib/fast: $(MAKE) -f CMakeFiles/mylib.dir/build.make CMakeFiles/mylib.dir/build .PHONY : mylib/fast #============================================================================= # Target rules for targets named main # Build rule for target. main: cmake_check_build_system $(MAKE) -f CMakeFiles/Makefile2 main .PHONY : main # fast build rule for target. main/fast: $(MAKE) -f CMakeFiles/main.dir/build.make CMakeFiles/main.dir/build .PHONY : main/fast main.o: main.cpp.o .PHONY : main.o # target to build an object file main.cpp.o: $(MAKE) -f CMakeFiles/main.dir/build.make CMakeFiles/main.dir/main.cpp.o .PHONY : main.cpp.o main.i: main.cpp.i .PHONY : main.i # target to preprocess a source file main.cpp.i: $(MAKE) -f CMakeFiles/main.dir/build.make CMakeFiles/main.dir/main.cpp.i .PHONY : main.cpp.i main.s: main.cpp.s .PHONY : main.s # target to generate assembly for a file main.cpp.s: $(MAKE) -f CMakeFiles/main.dir/build.make CMakeFiles/main.dir/main.cpp.s .PHONY : main.cpp.s mylib.o: mylib.cpp.o .PHONY : mylib.o # target to build an object file mylib.cpp.o: $(MAKE) -f CMakeFiles/mylib.dir/build.make CMakeFiles/mylib.dir/mylib.cpp.o .PHONY : mylib.cpp.o mylib.i: mylib.cpp.i .PHONY : mylib.i # target to preprocess a source file mylib.cpp.i: $(MAKE) -f CMakeFiles/mylib.dir/build.make CMakeFiles/mylib.dir/mylib.cpp.i .PHONY : mylib.cpp.i mylib.s: mylib.cpp.s .PHONY : mylib.s # target to generate assembly for a file mylib.cpp.s: $(MAKE) -f CMakeFiles/mylib.dir/build.make CMakeFiles/mylib.dir/mylib.cpp.s .PHONY : mylib.cpp.s # Help Target help: @echo "The following are some of the valid targets for this Makefile:" @echo "... all (the default if no target is provided)" @echo "... clean" @echo "... depend" @echo "... rebuild_cache" @echo "... mylib" @echo "... edit_cache" @echo "... main" @echo "... main.o" @echo "... main.i" @echo "... main.s" @echo "... mylib.o" @echo "... mylib.i" @echo "... mylib.s" .PHONY : help #============================================================================= # Special targets to cleanup operation of make. # Special rule to run CMake to check the build system integrity. # No rule that depends on this can have commands that come from listfiles # because they might be regenerated. cmake_check_build_system: $(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 0 .PHONY : cmake_check_build_system ================================================ FILE: cpp_algo/lec_21/cmake_project/cmake_install.cmake ================================================ # Install script for directory: /home/tkhirianov/lec_2020/cpp_algo/lec_21/cmake_project # Set the install prefix if(NOT DEFINED CMAKE_INSTALL_PREFIX) set(CMAKE_INSTALL_PREFIX "/usr/local") endif() string(REGEX REPLACE "/$" "" CMAKE_INSTALL_PREFIX "${CMAKE_INSTALL_PREFIX}") # Set the install configuration name. if(NOT DEFINED CMAKE_INSTALL_CONFIG_NAME) if(BUILD_TYPE) string(REGEX REPLACE "^[^A-Za-z0-9_]+" "" CMAKE_INSTALL_CONFIG_NAME "${BUILD_TYPE}") else() set(CMAKE_INSTALL_CONFIG_NAME "") endif() message(STATUS "Install configuration: \"${CMAKE_INSTALL_CONFIG_NAME}\"") endif() # Set the component getting installed. if(NOT CMAKE_INSTALL_COMPONENT) if(COMPONENT) message(STATUS "Install component: \"${COMPONENT}\"") set(CMAKE_INSTALL_COMPONENT "${COMPONENT}") else() set(CMAKE_INSTALL_COMPONENT) endif() endif() # Install shared libraries without execute permission? if(NOT DEFINED CMAKE_INSTALL_SO_NO_EXE) set(CMAKE_INSTALL_SO_NO_EXE "1") endif() # Is this installation the result of a crosscompile? if(NOT DEFINED CMAKE_CROSSCOMPILING) set(CMAKE_CROSSCOMPILING "FALSE") endif() if(CMAKE_INSTALL_COMPONENT) set(CMAKE_INSTALL_MANIFEST "install_manifest_${CMAKE_INSTALL_COMPONENT}.txt") else() set(CMAKE_INSTALL_MANIFEST "install_manifest.txt") endif() string(REPLACE ";" "\n" CMAKE_INSTALL_MANIFEST_CONTENT "${CMAKE_INSTALL_MANIFEST_FILES}") file(WRITE "/home/tkhirianov/lec_2020/cpp_algo/lec_21/cmake_project/${CMAKE_INSTALL_MANIFEST}" "${CMAKE_INSTALL_MANIFEST_CONTENT}") ================================================ FILE: cpp_algo/lec_21/cmake_project/main.cpp ================================================ #include #include "mylib.h" #include "mylib.h" // doesn't matter because of HEADER GUARD in library header #include "mylib.h" #include "mylib.h" int main() { using namespace std; int x, y; cout << "Enter integer. x = "; cin >> x; cout << "Enter integer. y = "; cin >> y; cout << "GCD(x, y) = " << euclid_gcd(x, y) << endl; return 0; } ================================================ FILE: cpp_algo/lec_21/cmake_project/mylib.cpp ================================================ #include "mylib.h" int euclid_gcd(int a, int b) { // Алгоритм Евклида поиска НОД while (a != b) { if (a > b) { a -= b; } else { b -= a; } } return a; } ================================================ FILE: cpp_algo/lec_21/cmake_project/mylib.h ================================================ #ifndef MYLIB_HEADER_GUARD #define MYLIB_HEADER_GUARD const int scale_x = 100; int euclid_gcd(int a, int b); #endif //MYLIB_HEADER_GUARD ================================================ FILE: cpp_algo/lec_21/hello.cpp ================================================ #include #include "1.txt" #define HELLO_MESSAGE "Hello, world!" #define MAX(x, y) x > y ? x : y using namespace std; int foo(int x) { cout << "foo(" << x << ")\n"; return x; } int main() { cout << HELLO_MESSAGE << endl; int x = 3; int z = MAX(foo(x), 2); // LOOK HERE FOR A BUG! cout << z << endl; cout << MAX(5, 2) << endl; // LOOK HERE FOR A BUG! return 0; } ================================================ FILE: cpp_algo/lec_21/project/Makefile ================================================ all: main.exe main.exe: main.o mylib.o g++ -o main.exe main.o mylib.o main.o: main.cpp mylib.h g++ -c main.cpp mylib.o: mylib.cpp mylib.h g++ -c mylib.cpp clean: rm *.o main.exe ================================================ FILE: cpp_algo/lec_21/project/main.cpp ================================================ #include #include "mylib.h" #include "mylib.h" // doesn't matter because of HEADER GUARD in library header #include "mylib.h" #include "mylib.h" int main() { using namespace std; int x, y; cout << "Enter integer. x = "; cin >> x; cout << "Enter integer. y = "; cin >> y; cout << "GCD(x, y) = " << euclid_gcd(x, y) << endl; return 0; } ================================================ FILE: cpp_algo/lec_21/project/mylib.cpp ================================================ #include "mylib.h" int euclid_gcd(int a, int b) { // Алгоритм Евклида поиска НОД while (a != b) { if (a > b) { a -= b; } else { b -= a; } } return a; } ================================================ FILE: cpp_algo/lec_21/project/mylib.h ================================================ #ifndef MYLIB_HEADER_GUARD #define MYLIB_HEADER_GUARD const int scale_x = 100; int euclid_gcd(int a, int b); #endif //MYLIB_HEADER_GUARD ================================================ FILE: cpp_algo/lec_22/1_graphs_storage.cpp ================================================ #include #include #include #include typedef int32_t vertex_t; typedef std::set SetOfVertexes; class AbstractGraph { public: int vertexes_number = 0; int edges_number = 0; virtual void input() = 0; virtual void print() const = 0; }; class Graph_type1: public AbstractGraph { public: std::set> set_of_edges; void input() { std::cin >> vertexes_number; std::cin >> edges_number; set_of_edges.clear(); for (vertex_t i = 0; i < edges_number; i++) { vertex_t a, b; std::cin >> a >> b; set_of_edges.insert(std::make_pair(a, b)); } } void print() const { std::cout << "Vertexes number = " << vertexes_number << std::endl; for(auto edge: set_of_edges) { std::cout << "(" << edge.first << ", " << edge.second << ") "; } std::cout << std::endl; } }; class Graph_type2: public AbstractGraph { public: /// Matrix of adjasency std::vector> matrix; void input() { std::cin >> vertexes_number; // Как только узнал количество вершин, создаю матрицу нужного размера matrix.resize(vertexes_number); for (auto &line: matrix) { line.resize(vertexes_number, false); } std::cin >> edges_number; for (vertex_t i = 0; i < edges_number; i++) { vertex_t a, b; std::cin >> a >> b; matrix[a][b] = 1; matrix[b][a] = 1; } } void print() const { std::cout << "Vertexes number = " << vertexes_number << std::endl; for(vertex_t a = 0; a < vertexes_number; a++) { for(vertex_t b = 0; b < vertexes_number; b++) { std::cout << matrix[a][b] << " "; } std::cout << std::endl; } std::cout << std::endl; } }; int main() { Graph_type2 g1; g1.input(); g1.print(); } ================================================ FILE: cpp_algo/lec_23/1_dfs.cpp ================================================ #include #include #include "graph.hpp" void just_dfs(const Graph_t &graph, vertex_t start, std::vector &used) { used[start] = true; std::cout << start << ' '; auto neighbours_list = graph.sets_of_neighbours[start]; for(auto neighbour: neighbours_list) { if (not used[neighbour]) just_dfs(graph, neighbour, used); } } int main() { Graph_t g; g.input(); g.print(); std::cout << "Enter start vertex: "; vertex_t start; std::cin >> start; std::vector used_vertexes; used_vertexes.resize(g.vertexes_number, false); just_dfs(g, start, used_vertexes); std::cout << "\n"; } ================================================ FILE: cpp_algo/lec_23/2_bfs.cpp ================================================ #include #include #include #include "graph.hpp" void just_bfs(const Graph_t &graph, vertex_t start, std::vector &fired) { fired[start] = true; std::deque firing_list; firing_list.push_back(start); std::cout << start << '\t'; while (not firing_list.empty()) { vertex_t current = firing_list.front(); firing_list.pop_front(); auto neighbours_list = graph.sets_of_neighbours[current]; for(auto neighbour: neighbours_list) { if (not (fired[neighbour])) { std::cout << neighbour << "\t"; fired[neighbour] = true; firing_list.push_back(neighbour); } } } std::cout << '\n'; } int main() { Graph_t g; g.input(); g.print(); std::cout << "Enter start vertex: "; vertex_t start; std::cin >> start; std::vector used_vertexes; used_vertexes.resize(g.vertexes_number, false); just_bfs(g, start, used_vertexes); std::cout << "\n"; } ================================================ FILE: cpp_algo/lec_23/graph.hpp ================================================ #ifndef _GRAPH_HPP__ #define _GRAPH_HPP__ #include #include #include #include typedef int32_t vertex_t; typedef std::set SetOfVertexes; class Graph_t { public: int vertexes_number = 0; int edges_number = 0; // списки смежности для каждой вершины графа: std::vector> sets_of_neighbours; void input() { std::cin >> vertexes_number; std::cin >> edges_number; // полная очистка массива списков смежности sets_of_neighbours.clear(); // создаю пустые списки смежности для каждой вершины: sets_of_neighbours.resize(vertexes_number); for (int i = 0; i < edges_number; i++) { vertex_t a, b; std::cin >> a >> b; sets_of_neighbours[a].insert(b); // у вершины a - сосед b sets_of_neighbours[b].insert(a); // у вершины a - сосед b } } void print() const { std::cout << "Vertexes number = " << vertexes_number << std::endl; for(vertex_t vertex = 0; vertex < vertexes_number; vertex++) { std::cout << vertex << ": ["; for(auto neighbour: sets_of_neighbours[vertex]) { std::cout << neighbour << ", "; } std::cout << "\b\b]\n"; } std::cout << std::endl; } }; #endif //_GRAPH_HPP__ ================================================ FILE: cpp_algo/lec_23/input1.txt ================================================ 5 7 0 1 1 2 2 0 0 3 3 4 0 4 1 4 0 ================================================ FILE: cpp_algo/lec_24/check_DAG.cpp ================================================ #include #include #include "graph.hpp" bool check_DAG(const OrGraph_t &graph, vertex_t start, std::vector &used) { used[start] = true; auto neighbours_list = graph.sets_of_neighbours[start]; for(auto neighbour: neighbours_list) { if (neighbour == start) { continue; } if (used[neighbour]) // Пытаемся попасть в соседнюю ранее пройденную вершину. Цикл! return false; bool is_DAG = check_DAG(graph, neighbour, used); if (not is_DAG) return false; } return true; // Достигаю этой точки, только если не случилось return false. } int main() { OrGraph_t g; g.input(); g.print(); std::vector used_vertexes; used_vertexes.resize(g.vertexes_number, false); bool is_DAG = true; for (vertex_t v = 0; v < g.vertexes_number; v++) { if (used_vertexes[v]) continue; if (not check_DAG(g, v, used_vertexes)) { is_DAG = false; break; } } if (is_DAG) std::cout << "Acyclic graph.\n"; else std::cout << "Cyclic graph.\n"; } ================================================ FILE: cpp_algo/lec_24/graph.hpp ================================================ #ifndef _GRAPH_HPP__ #define _GRAPH_HPP__ #include #include #include #include typedef int32_t vertex_t; typedef std::set SetOfVertexes; class OrGraph_t { public: int vertexes_number = 0; int edges_number = 0; // списки смежности для каждой вершины графа: std::vector> sets_of_neighbours; void input() { std::cin >> vertexes_number; std::cin >> edges_number; // полная очистка массива списков смежности sets_of_neighbours.clear(); // создаю пустые списки смежности для каждой вершины: sets_of_neighbours.resize(vertexes_number); for (int i = 0; i < edges_number; i++) { vertex_t a, b; std::cin >> a >> b; sets_of_neighbours[a].insert(b); // у вершины a - сосед b } } void print() const { std::cout << "Vertexes number = " << vertexes_number << std::endl; for(vertex_t vertex = 0; vertex < vertexes_number; vertex++) { std::cout << vertex << ": ["; for(auto neighbour: sets_of_neighbours[vertex]) { std::cout << neighbour << ", "; } std::cout << "\b\b]\n"; } std::cout << std::endl; } }; class Graph_t { public: int vertexes_number = 0; int edges_number = 0; // списки смежности для каждой вершины графа: std::vector> sets_of_neighbours; void input() { std::cin >> vertexes_number; std::cin >> edges_number; // полная очистка массива списков смежности sets_of_neighbours.clear(); // создаю пустые списки смежности для каждой вершины: sets_of_neighbours.resize(vertexes_number); for (int i = 0; i < edges_number; i++) { vertex_t a, b; std::cin >> a >> b; sets_of_neighbours[a].insert(b); // у вершины a - сосед b } } void print() const { std::cout << "Vertexes number = " << vertexes_number << std::endl; for(vertex_t vertex = 0; vertex < vertexes_number; vertex++) { std::cout << vertex << ": ["; for(auto neighbour: sets_of_neighbours[vertex]) { std::cout << neighbour << ", "; } std::cout << "\b\b]\n"; } std::cout << std::endl; } }; #endif //_GRAPH_HPP__ ================================================ FILE: python/lec_01/01_input_print.py ================================================ #!/usr/bin/env python3 name = input("Как тебя зовут? ") print(f"Привет, {name}!") name = input("Как твоя фамилия? ") print(f"Ясно, {name}!") print(name + lastname) ================================================ FILE: python/lec_01/02_if_else.py ================================================ x = int(input()) y = int(input()) if x > 0 and y > 0: print(1) elif x < 0 and y > 0: print(2) elif x < 0 and y < 0: print(3) elif x > 0 and y < 0: print(4) else: print("НИКОГДА!") ================================================ FILE: python/lec_01/03_nested_for.py ================================================ import turtle def david(): for step in range(6): turtle.begin_fill() for i in range(3): turtle.forward(50) turtle.left(360 / 3) turtle.end_fill() turtle.forward(50) turtle.right(60) turtle.shape('turtle') turtle.shapesize(2) turtle.color('green', 'yellow') turtle.speed(10) david() turtle.backward(200) david() turtle.hideturtle() ================================================ FILE: python/lec_03/1_function_experiments.py ================================================ def foo(x, y=0, z=0): return 100*x + 10*y + 1*z def bar(*args, named_parameter="bar"): for arg in args: print(named_parameter, 'arg =', arg) bar() bar(['the', 'list', 'of', 'strings']) bar(1, 2, 3) bar("jelly", "fish") bar("jelly", "fish", named_parameter='SEPARATOR') '''print(foo(1, 2, 3)) print(foo(z=1, x=2, y=3)) # named parameters print(foo(1, 2)) print(foo(7)) ''' ================================================ FILE: python/lec_03/2_pygame_draw_test.py ================================================ # Import a library of functions called 'pygame' import pygame from math import pi # Initialize the game engine pygame.init() x = 10 # Define the colors we will use in RGB format BLACK = (0, 0, 0) WHITE = (255, 255, 255) BLUE = (0, 0, 255) GREEN = (0, 255, 0) RED = (255, 0, 0) # Set the height and width of the screen size = [400, 300] screen = pygame.display.set_mode(size) pygame.display.set_caption("Example code for the draw module") # Loop until the user clicks the close button. done = False clock = pygame.time.Clock() while not done: x += 1 # global x is changing # This limits the while loop to a max of 10 times per second. # Leave this out and we will use all CPU we can. clock.tick(10) for event in pygame.event.get(): # User did something if event.type == pygame.QUIT: # If user clicked close done = True # Flag that we are done so we exit this loop # All drawing code happens after the for loop and but # inside the main while done==False loop. # Clear the screen and set the screen background screen.fill(WHITE) # Draw on the screen a GREEN line from (0, 0) to (50, 30) # 5 pixels wide. pygame.draw.line(screen, GREEN, [0, 0], [50, x], 5) # Draw on the screen 3 BLACK lines, each 5 pixels wide. # The 'False' means the first and last points are not connected. pygame.draw.lines(screen, BLACK, False, [[0, 80], [50, 90], [200, 80], [220, 30]], 5) # Draw on the screen a GREEN line from (0, 50) to (50, 80) # Because it is an antialiased line, it is 1 pixel wide. pygame.draw.aaline(screen, GREEN, [0, 50], [50, 80], True) # Draw a rectangle outline pygame.draw.rect(screen, BLACK, [75, 10+x, 50, 20+x], 2) # Draw a solid rectangle pygame.draw.rect(screen, BLACK, [150, 10+x, 50, 20]) # Draw a rectangle with rounded corners pygame.draw.rect(screen, GREEN, [115, 210, 70, 40], 10) pygame.draw.rect(screen, RED, [135, 260, 50, 30], 0) # Draw an ellipse outline, using a rectangle as the outside boundaries pygame.draw.ellipse(screen, RED, [225, 10, 50, 20], 2) # Draw an solid ellipse, using a rectangle as the outside boundaries pygame.draw.ellipse(screen, RED, [300, 10, 50, 20]) # This draws a triangle using the polygon command pygame.draw.polygon(screen, BLACK, [[100, 100], [0, 200], [200, 200]], 5) # Draw an arc as part of an ellipse. # Use radians to determine what angle to draw. pygame.draw.arc(screen, BLACK, [210, 75, 150, 125], 0, pi / 2, 2) pygame.draw.arc(screen, GREEN, [210, 75, 150, 125], pi / 2, pi, 2) pygame.draw.arc(screen, BLUE, [210, 75, 150, 125], pi, 3 * pi / 2, 2) pygame.draw.arc(screen, RED, [210, 75, 150, 125], 3 * pi / 2, 2 * pi, 2) # Draw a circle pygame.draw.circle(screen, BLUE, [60, 250], 40) # Draw only one circle quadrant pygame.draw.circle(screen, BLUE, [250, 250], 40, 0) pygame.draw.circle(screen, RED, [250, 250], 40, 30) pygame.draw.circle(screen, GREEN, [250, 250], 40, 20) pygame.draw.circle(screen, BLACK, [250, 250], 40, 10) # Go ahead and update the screen with what we've drawn. # This MUST happen after all the other drawing commands. pygame.display.flip() # Be IDLE friendly pygame.quit() ================================================ FILE: python/lec_04/football_1.py ================================================ # Original author: https://github.com/johoule/stuff/ # Imports import pygame import math import random # Initialize game engine pygame.init() # Window SIZE = (800, 600) TITLE = "Major League Soccer" screen = pygame.display.set_mode(SIZE) pygame.display.set_caption(TITLE) # Timer clock = pygame.time.Clock() refresh_rate = 60 # Colors ''' add colors you use as RGB values here ''' RED = (255, 0, 0) GREEN = (52, 166, 36) BLUE = (29, 116, 248) WHITE = (255, 255, 255) BLACK = (0, 0, 0) ORANGE = (255, 125, 0) DARK_BLUE = (18, 0, 91) DARK_GREEN = (0, 94, 0) GRAY = (130, 130, 130) YELLOW = (255, 255, 110) SILVER = (200, 200, 200) DAY_GREEN = (41, 129, 29) NIGHT_GREEN = (0, 64, 0) BRIGHT_YELLOW = (255, 244, 47) NIGHT_GRAY = (104, 98, 115) ck = (127, 33, 33) DARKNESS = pygame.Surface(SIZE) DARKNESS.set_alpha(200) DARKNESS.fill((0, 0, 0)) SEE_THROUGH = pygame.Surface((800, 180)) SEE_THROUGH.set_alpha(150) SEE_THROUGH.fill((124, 118, 135)) def draw_cloud(x, y): pygame.draw.ellipse(SEE_THROUGH, cloud_color, [x, y + 8, 10, 10]) pygame.draw.ellipse(SEE_THROUGH, cloud_color, [x + 6, y + 4, 8, 8]) pygame.draw.ellipse(SEE_THROUGH, cloud_color, [x + 10, y, 16, 16]) pygame.draw.ellipse(SEE_THROUGH, cloud_color, [x + 20, y + 8, 10, 10]) pygame.draw.rect(SEE_THROUGH, cloud_color, [x + 6, y + 8, 18, 10]) def draw_fence(): """ This function draws fence of football field in particular place. :return: """ y = 170 for x in range(5, 800, 30): pygame.draw.polygon(screen, NIGHT_GRAY, [[x + 2, y], [x + 2, y + 15], [x, y + 15], [x, y]]) y = 170 for x in range(5, 800, 3): pygame.draw.line(screen, NIGHT_GRAY, [x, y], [x, y + 15], 1) x = 0 for y in range(170, 185, 4): pygame.draw.line(screen, NIGHT_GRAY, [x, y], [x + 800, y], 1) # Config lights_on = True day = True stars = [] for n in range(200): x = random.randrange(0, 800) y = random.randrange(0, 200) r = random.randrange(1, 2) stars.append([x, y, r, r]) clouds = [] for i in range(20): x = random.randrange(-100, 1600) y = random.randrange(0, 150) clouds.append([x, y]) # Game loop done = False while not done: # Event processing (React to key presses, mouse clicks, etc.) ''' for now, we'll just check to see if the X is clicked ''' for event in pygame.event.get(): if event.type == pygame.QUIT: done = True elif event.type == pygame.KEYDOWN: if event.key == pygame.K_l: lights_on = not lights_on elif event.key == pygame.K_d: day = not day # Game logic (Check for collisions, update points, etc.) ''' leave this section alone for now ''' if lights_on: light_color = YELLOW else: light_color = SILVER if day: sky_color = BLUE field_color = GREEN stripe_color = DAY_GREEN cloud_color = WHITE else: sky_color = DARK_BLUE field_color = DARK_GREEN stripe_color = NIGHT_GREEN cloud_color = NIGHT_GRAY for c in clouds: c[0] -= 0.5 # WHAT??? if c[0] < -100: c[0] = random.randrange(800, 1600) c[1] = random.randrange(0, 150) # Drawing code (Describe the picture. It isn't actually drawn yet.) screen.fill(sky_color) SEE_THROUGH.fill(ck) SEE_THROUGH.set_colorkey(ck) if not day: # stars for s in stars: pygame.draw.ellipse(screen, WHITE, s) pygame.draw.rect(screen, field_color, [0, 180, 800, 420]) pygame.draw.rect(screen, stripe_color, [0, 180, 800, 42]) pygame.draw.rect(screen, stripe_color, [0, 264, 800, 52]) pygame.draw.rect(screen, stripe_color, [0, 368, 800, 62]) pygame.draw.rect(screen, stripe_color, [0, 492, 800, 82]) draw_fence() if day: pygame.draw.ellipse(screen, BRIGHT_YELLOW, [520, 50, 40, 40]) else: pygame.draw.ellipse(screen, WHITE, [520, 50, 40, 40]) pygame.draw.ellipse(screen, sky_color, [530, 45, 40, 40]) for c in clouds: draw_cloud(c[0], c[1]) screen.blit(SEE_THROUGH, (0, 0)) # out of bounds lines pygame.draw.line(screen, WHITE, [0, 580], [800, 580], 5) # left pygame.draw.line(screen, WHITE, [0, 360], [140, 220], 5) pygame.draw.line(screen, WHITE, [140, 220], [660, 220], 3) # right pygame.draw.line(screen, WHITE, [660, 220], [800, 360], 5) # safety circle pygame.draw.ellipse(screen, WHITE, [240, 500, 320, 160], 5) # 18 yard line goal box pygame.draw.line(screen, WHITE, [260, 220], [180, 300], 5) pygame.draw.line(screen, WHITE, [180, 300], [620, 300], 3) pygame.draw.line(screen, WHITE, [620, 300], [540, 220], 5) # arc at the top of the goal box pygame.draw.arc(screen, WHITE, [330, 280, 140, 40], math.pi, 2 * math.pi, 5) # score board pole pygame.draw.rect(screen, GRAY, [390, 120, 20, 70]) # score board pygame.draw.rect(screen, BLACK, [300, 40, 200, 90]) pygame.draw.rect(screen, WHITE, [302, 42, 198, 88], 2) # goal pygame.draw.rect(screen, WHITE, [320, 140, 160, 80], 5) pygame.draw.line(screen, WHITE, [340, 200], [460, 200], 3) pygame.draw.line(screen, WHITE, [320, 220], [340, 200], 3) pygame.draw.line(screen, WHITE, [480, 220], [460, 200], 3) pygame.draw.line(screen, WHITE, [320, 140], [340, 200], 3) pygame.draw.line(screen, WHITE, [480, 140], [460, 200], 3) # 6 yard line goal box pygame.draw.line(screen, WHITE, [310, 220], [270, 270], 3) pygame.draw.line(screen, WHITE, [270, 270], [530, 270], 2) pygame.draw.line(screen, WHITE, [530, 270], [490, 220], 3) # light pole 1 pygame.draw.rect(screen, GRAY, [150, 60, 20, 140]) pygame.draw.ellipse(screen, GRAY, [150, 195, 20, 10]) # lights pygame.draw.line(screen, GRAY, [110, 60], [210, 60], 2) pygame.draw.ellipse(screen, light_color, [110, 40, 20, 20]) pygame.draw.ellipse(screen, light_color, [130, 40, 20, 20]) pygame.draw.ellipse(screen, light_color, [150, 40, 20, 20]) pygame.draw.ellipse(screen, light_color, [170, 40, 20, 20]) pygame.draw.ellipse(screen, light_color, [190, 40, 20, 20]) pygame.draw.line(screen, GRAY, [110, 40], [210, 40], 2) pygame.draw.ellipse(screen, light_color, [110, 20, 20, 20]) pygame.draw.ellipse(screen, light_color, [130, 20, 20, 20]) pygame.draw.ellipse(screen, light_color, [150, 20, 20, 20]) pygame.draw.ellipse(screen, light_color, [170, 20, 20, 20]) pygame.draw.ellipse(screen, light_color, [190, 20, 20, 20]) pygame.draw.line(screen, GRAY, [110, 20], [210, 20], 2) # light pole 2 pygame.draw.rect(screen, GRAY, [630, 60, 20, 140]) pygame.draw.ellipse(screen, GRAY, [630, 195, 20, 10]) # lights pygame.draw.line(screen, GRAY, [590, 60], [690, 60], 2) pygame.draw.ellipse(screen, light_color, [590, 40, 20, 20]) pygame.draw.ellipse(screen, light_color, [610, 40, 20, 20]) pygame.draw.ellipse(screen, light_color, [630, 40, 20, 20]) pygame.draw.ellipse(screen, light_color, [650, 40, 20, 20]) pygame.draw.ellipse(screen, light_color, [670, 40, 20, 20]) pygame.draw.line(screen, GRAY, [590, 40], [690, 40], 2) pygame.draw.ellipse(screen, light_color, [590, 20, 20, 20]) pygame.draw.ellipse(screen, light_color, [610, 20, 20, 20]) pygame.draw.ellipse(screen, light_color, [630, 20, 20, 20]) pygame.draw.ellipse(screen, light_color, [650, 20, 20, 20]) pygame.draw.ellipse(screen, light_color, [670, 20, 20, 20]) pygame.draw.line(screen, GRAY, [590, 20], [690, 20], 2) # net pygame.draw.line(screen, WHITE, [325, 140], [341, 200], 1) pygame.draw.line(screen, WHITE, [330, 140], [344, 200], 1) pygame.draw.line(screen, WHITE, [335, 140], [347, 200], 1) pygame.draw.line(screen, WHITE, [340, 140], [350, 200], 1) pygame.draw.line(screen, WHITE, [345, 140], [353, 200], 1) pygame.draw.line(screen, WHITE, [350, 140], [356, 200], 1) pygame.draw.line(screen, WHITE, [355, 140], [359, 200], 1) pygame.draw.line(screen, WHITE, [360, 140], [362, 200], 1) pygame.draw.line(screen, WHITE, [364, 140], [365, 200], 1) pygame.draw.line(screen, WHITE, [368, 140], [369, 200], 1) pygame.draw.line(screen, WHITE, [372, 140], [373, 200], 1) pygame.draw.line(screen, WHITE, [376, 140], [377, 200], 1) pygame.draw.line(screen, WHITE, [380, 140], [380, 200], 1) pygame.draw.line(screen, WHITE, [384, 140], [384, 200], 1) pygame.draw.line(screen, WHITE, [388, 140], [388, 200], 1) pygame.draw.line(screen, WHITE, [392, 140], [392, 200], 1) pygame.draw.line(screen, WHITE, [396, 140], [396, 200], 1) pygame.draw.line(screen, WHITE, [400, 140], [400, 200], 1) pygame.draw.line(screen, WHITE, [404, 140], [404, 200], 1) pygame.draw.line(screen, WHITE, [408, 140], [408, 200], 1) pygame.draw.line(screen, WHITE, [412, 140], [412, 200], 1) pygame.draw.line(screen, WHITE, [416, 140], [416, 200], 1) pygame.draw.line(screen, WHITE, [420, 140], [420, 200], 1) pygame.draw.line(screen, WHITE, [424, 140], [423, 200], 1) pygame.draw.line(screen, WHITE, [428, 140], [427, 200], 1) pygame.draw.line(screen, WHITE, [432, 140], [431, 200], 1) pygame.draw.line(screen, WHITE, [436, 140], [435, 200], 1) pygame.draw.line(screen, WHITE, [440, 140], [438, 200], 1) pygame.draw.line(screen, WHITE, [445, 140], [441, 200], 1) pygame.draw.line(screen, WHITE, [450, 140], [444, 200], 1) pygame.draw.line(screen, WHITE, [455, 140], [447, 200], 1) pygame.draw.line(screen, WHITE, [460, 140], [450, 200], 1) pygame.draw.line(screen, WHITE, [465, 140], [453, 200], 1) pygame.draw.line(screen, WHITE, [470, 140], [456, 200], 1) pygame.draw.line(screen, WHITE, [475, 140], [459, 200], 1) # net part 2 pygame.draw.line(screen, WHITE, [320, 140], [324, 216], 1) pygame.draw.line(screen, WHITE, [320, 140], [326, 214], 1) pygame.draw.line(screen, WHITE, [320, 140], [328, 212], 1) pygame.draw.line(screen, WHITE, [320, 140], [330, 210], 1) pygame.draw.line(screen, WHITE, [320, 140], [332, 208], 1) pygame.draw.line(screen, WHITE, [320, 140], [334, 206], 1) pygame.draw.line(screen, WHITE, [320, 140], [336, 204], 1) pygame.draw.line(screen, WHITE, [320, 140], [338, 202], 1) # net part 3 pygame.draw.line(screen, WHITE, [480, 140], [476, 216], 1) pygame.draw.line(screen, WHITE, [480, 140], [474, 214], 1) pygame.draw.line(screen, WHITE, [480, 140], [472, 212], 1) pygame.draw.line(screen, WHITE, [480, 140], [470, 210], 1) pygame.draw.line(screen, WHITE, [480, 140], [468, 208], 1) pygame.draw.line(screen, WHITE, [480, 140], [466, 206], 1) pygame.draw.line(screen, WHITE, [480, 140], [464, 204], 1) pygame.draw.line(screen, WHITE, [480, 140], [462, 202], 1) # net part 4 pygame.draw.line(screen, WHITE, [324, 144], [476, 144], 1) pygame.draw.line(screen, WHITE, [324, 148], [476, 148], 1) pygame.draw.line(screen, WHITE, [324, 152], [476, 152], 1) pygame.draw.line(screen, WHITE, [324, 156], [476, 156], 1) pygame.draw.line(screen, WHITE, [324, 160], [476, 160], 1) pygame.draw.line(screen, WHITE, [324, 164], [476, 164], 1) pygame.draw.line(screen, WHITE, [324, 168], [476, 168], 1) pygame.draw.line(screen, WHITE, [324, 172], [476, 172], 1) pygame.draw.line(screen, WHITE, [324, 176], [476, 176], 1) pygame.draw.line(screen, WHITE, [335, 180], [470, 180], 1) pygame.draw.line(screen, WHITE, [335, 184], [465, 184], 1) pygame.draw.line(screen, WHITE, [335, 188], [465, 188], 1) pygame.draw.line(screen, WHITE, [335, 192], [465, 192], 1) pygame.draw.line(screen, WHITE, [335, 196], [465, 196], 1) # stands right pygame.draw.polygon(screen, RED, [[680, 220], [800, 340], [800, 290], [680, 180]]) pygame.draw.polygon(screen, WHITE, [[680, 180], [800, 100], [800, 290]]) # stands left pygame.draw.polygon(screen, RED, [[120, 220], [0, 340], [0, 290], [120, 180]]) pygame.draw.polygon(screen, WHITE, [[120, 180], [0, 100], [0, 290]]) # people # corner flag right pygame.draw.line(screen, BRIGHT_YELLOW, [140, 220], [135, 190], 3) pygame.draw.polygon(screen, RED, [[132, 190], [125, 196], [135, 205]]) # corner flag left pygame.draw.line(screen, BRIGHT_YELLOW, [660, 220], [665, 190], 3) pygame.draw.polygon(screen, RED, [[668, 190], [675, 196], [665, 205]]) # DARKNESS if not day and not lights_on: screen.blit(DARKNESS, (0, 0)) # WHAT??? # pygame.draw.polygon(screen, BLACK, [[200, 200], [50,400], [600, 500]], 10) ''' angles for arcs are measured in radians (a pre-cal topic) ''' # pygame.draw.arc(screen, ORANGE, [100, 100, 100, 100], 0, math.pi/2, 1) # pygame.draw.arc(screen, BLACK, [100, 100, 100, 100], 0, math.pi/2, 50) # Update screen (Actually draw the picture in the window.) pygame.display.flip() # Limit refresh rate of game loop clock.tick(refresh_rate) # Close window and quit pygame.quit() ================================================ FILE: python/lec_05/house.py ================================================ def main(): x, y = 300, 400 width, height = 200, 300 draw_house(x, y, width, height) def draw_house(x, y, width, height): """ Нарисовать домик ширины width и высоты height от опорной точки (x, y), которая находится в середине нижней точки фундамента. :param x: координата x середины домика :param y: координата y низа фундамента :param width: полная ширина домика (фундамен или вылеты крыши включены) :param height: полная высота домика :return: None """ print('Типа рисую домик...', x, y, width, height) foundation_height = 0.05 * height walls_width = 0.9 * width walls_height = 0.5 * height roof_height = height - foundation_height - walls_height draw_house_foundation(x, y, width, foundation_height) draw_house_walls(x, y - foundation_height, walls_width, walls_height) draw_house_roof(x, y - foundation_height - walls_height, width, roof_height) def draw_house_foundation(x, y, width, height): """ Нарисовать основание домика ширины width и высоты height от опорной точки (x, y), которая находится в середине нижней точки фундамента. :param x: координата x середины фундамента :param y: координата y низа фундамента :param width: полная ширина фундамена :param height: полная высота фундамента :return: None """ print('Типа рисую основание...', x, y, width, height) pass def draw_house_walls(x, y, width, height): print('Типа рисую стены...', x, y, width, height) pass def draw_house_roof(x, y, width, height): print('Типа рисую крышу...', x, y, width, height) pass main() ================================================ FILE: python/lec_06/football_1.py ================================================ # Original author: https://github.com/johoule/stuff/ # Imports import pygame import math import random # Initialize game engine pygame.init() # Window SIZE = (800, 600) TITLE = "Major League Soccer" screen = pygame.display.set_mode(SIZE) pygame.display.set_caption(TITLE) # Timer clock = pygame.time.Clock() refresh_rate = 60 # Colors ''' add colors you use as RGB values here ''' RED = (235, 0, 0) GREEN = (52, 169, 36) BLUE = (29, 116, 248) WHITE = (255, 255, 255) BLACK = (0, 0, 0) ORANGE = (255, 125, 0) DARK_BLUE = (18, 0, 91) DARK_GREEN = (0, 94, 0) GRAY = (130, 130, 130) YELLOW = (255, 255, 110) SILVER = (200, 200, 200) DAY_GREEN = (41, 129, 29) NIGHT_GREEN = (0, 64, 0) BRIGHT_YELLOW = (255, 244, 47) NIGHT_GRAY = (104, 98, 115) ck = (127, 33, 33) DARKNESS = pygame.Surface(SIZE) DARKNESS.set_alpha(200) DARKNESS.fill((0, 0, 0)) SEE_THROUGH = pygame.Surface((800, 180)) SEE_THROUGH.set_alpha(150) SEE_THROUGH.fill((124, 118, 135)) def draw_cloud(x, y): pygame.draw.ellipse(SEE_THROUGH, cloud_color, [x, y + 8, 10, 10]) pygame.draw.ellipse(SEE_THROUGH, cloud_color, [x + 6, y + 4, 8, 8]) pygame.draw.ellipse(SEE_THROUGH, cloud_color, [x + 10, y, 16, 16]) pygame.draw.ellipse(SEE_THROUGH, cloud_color, [x + 20, y + 8, 10, 10]) pygame.draw.rect(SEE_THROUGH, cloud_color, [x + 6, y + 8, 18, 10]) def draw_fence(): """ This function draws fence of football field in particular place. :return: """ y = 170 for x in range(5, 800, 30): pygame.draw.polygon(screen, NIGHT_GRAY, [[x + 2, y], [x + 2, y + 15], [x, y + 15], [x, y]]) y = 170 for x in range(5, 800, 3): pygame.draw.line(screen, NIGHT_GRAY, [x, y], [x, y + 15], 1) x = 0 for y in range(170, 185, 4): pygame.draw.line(screen, NIGHT_GRAY, [x, y], [x + 800, y], 1) def key_down_handler(event): global lights_on, day if event.key == pygame.K_l: lights_on = not lights_on elif event.key == pygame.K_d: day = not day # Config lights_on = True day = True stars = [] for n in range(200): x = random.randrange(0, 800) y = random.randrange(0, 200) r = random.randrange(1, 2) stars.append([x, y, r, r]) clouds = [] for i in range(20): x = random.randrange(-100, 1600) y = random.randrange(0, 150) clouds.append([x, y]) # Game loop done = False while not done: # Event processing (React to key presses, mouse clicks, etc.) ''' for now, we'll just check to see if the X is clicked ''' for event in pygame.event.get(): if event.type == pygame.QUIT: done = True elif event.type == pygame.KEYDOWN: key_down_handler(event) # Game logic (Check for collisions, update points, etc.) ''' leave this section alone for now ''' if lights_on: light_color = YELLOW else: light_color = SILVER if day: sky_color = BLUE field_color = GREEN stripe_color = DAY_GREEN cloud_color = WHITE else: sky_color = DARK_BLUE field_color = DARK_GREEN stripe_color = NIGHT_GREEN cloud_color = NIGHT_GRAY for c in clouds: c[0] -= 0.5 # WHAT??? if c[0] < -100: c[0] = random.randrange(800, 1600) c[1] = random.randrange(0, 150) # Drawing code (Describe the picture. It isn't actually drawn yet.) screen.fill(sky_color) SEE_THROUGH.fill(ck) SEE_THROUGH.set_colorkey(ck) if not day: # stars for s in stars: pygame.draw.ellipse(screen, WHITE, s) pygame.draw.rect(screen, field_color, [0, 180, 800, 420]) pygame.draw.rect(screen, stripe_color, [0, 180, 800, 42]) pygame.draw.rect(screen, stripe_color, [0, 264, 800, 52]) pygame.draw.rect(screen, stripe_color, [0, 368, 800, 62]) pygame.draw.rect(screen, stripe_color, [0, 492, 800, 82]) draw_fence() if day: pygame.draw.ellipse(screen, BRIGHT_YELLOW, [520, 50, 40, 40]) else: pygame.draw.ellipse(screen, WHITE, [520, 50, 40, 40]) pygame.draw.ellipse(screen, sky_color, [530, 45, 40, 40]) for c in clouds: draw_cloud(c[0], c[1]) screen.blit(SEE_THROUGH, (0, 0)) # out of bounds lines pygame.draw.line(screen, WHITE, [0, 580], [800, 580], 5) # left pygame.draw.line(screen, WHITE, [0, 360], [140, 220], 5) pygame.draw.line(screen, WHITE, [140, 220], [660, 220], 3) # right pygame.draw.line(screen, WHITE, [660, 220], [800, 360], 5) # safety circle pygame.draw.ellipse(screen, WHITE, [240, 500, 320, 160], 5) # 18 yard line goal box pygame.draw.line(screen, WHITE, [260, 220], [180, 300], 5) pygame.draw.line(screen, WHITE, [180, 300], [620, 300], 3) pygame.draw.line(screen, WHITE, [620, 300], [540, 220], 5) # arc at the top of the goal box pygame.draw.arc(screen, WHITE, [330, 280, 140, 40], math.pi, 2 * math.pi, 5) # score board pole pygame.draw.rect(screen, GRAY, [390, 120, 20, 70]) # score board pygame.draw.rect(screen, BLACK, [300, 40, 200, 90]) pygame.draw.rect(screen, WHITE, [302, 42, 198, 88], 2) # goal pygame.draw.rect(screen, WHITE, [320, 140, 160, 80], 5) pygame.draw.line(screen, WHITE, [340, 200], [460, 200], 3) pygame.draw.line(screen, WHITE, [320, 220], [340, 200], 3) pygame.draw.line(screen, WHITE, [480, 220], [460, 200], 3) pygame.draw.line(screen, WHITE, [320, 140], [340, 200], 3) pygame.draw.line(screen, WHITE, [480, 140], [460, 200], 3) # 6 yard line goal box pygame.draw.line(screen, WHITE, [310, 220], [270, 270], 3) pygame.draw.line(screen, WHITE, [270, 270], [530, 270], 2) pygame.draw.line(screen, WHITE, [530, 270], [490, 220], 3) # light pole 1 pygame.draw.rect(screen, GRAY, [150, 60, 20, 140]) pygame.draw.ellipse(screen, GRAY, [150, 195, 20, 10]) # lights pygame.draw.line(screen, GRAY, [110, 60], [210, 60], 2) pygame.draw.ellipse(screen, light_color, [110, 40, 20, 20]) pygame.draw.ellipse(screen, light_color, [130, 40, 20, 20]) pygame.draw.ellipse(screen, light_color, [150, 40, 20, 20]) pygame.draw.ellipse(screen, light_color, [170, 40, 20, 20]) pygame.draw.ellipse(screen, light_color, [190, 40, 20, 20]) pygame.draw.line(screen, GRAY, [110, 40], [210, 40], 2) pygame.draw.ellipse(screen, light_color, [110, 20, 20, 20]) pygame.draw.ellipse(screen, light_color, [130, 20, 20, 20]) pygame.draw.ellipse(screen, light_color, [150, 20, 20, 20]) pygame.draw.ellipse(screen, light_color, [170, 20, 20, 20]) pygame.draw.ellipse(screen, light_color, [190, 20, 20, 20]) pygame.draw.line(screen, GRAY, [110, 20], [210, 20], 2) # light pole 2 pygame.draw.rect(screen, GRAY, [630, 60, 20, 140]) pygame.draw.ellipse(screen, GRAY, [630, 195, 20, 10]) # lights pygame.draw.line(screen, GRAY, [590, 60], [690, 60], 2) pygame.draw.ellipse(screen, light_color, [590, 40, 20, 20]) pygame.draw.ellipse(screen, light_color, [610, 40, 20, 20]) pygame.draw.ellipse(screen, light_color, [630, 40, 20, 20]) pygame.draw.ellipse(screen, light_color, [650, 40, 20, 20]) pygame.draw.ellipse(screen, light_color, [670, 40, 20, 20]) pygame.draw.line(screen, GRAY, [590, 40], [690, 40], 2) pygame.draw.ellipse(screen, light_color, [590, 20, 20, 20]) pygame.draw.ellipse(screen, light_color, [610, 20, 20, 20]) pygame.draw.ellipse(screen, light_color, [630, 20, 20, 20]) pygame.draw.ellipse(screen, light_color, [650, 20, 20, 20]) pygame.draw.ellipse(screen, light_color, [670, 20, 20, 20]) pygame.draw.line(screen, GRAY, [590, 20], [690, 20], 2) # net pygame.draw.line(screen, WHITE, [325, 140], [341, 200], 1) pygame.draw.line(screen, WHITE, [330, 140], [344, 200], 1) pygame.draw.line(screen, WHITE, [335, 140], [347, 200], 1) pygame.draw.line(screen, WHITE, [340, 140], [350, 200], 1) pygame.draw.line(screen, WHITE, [345, 140], [353, 200], 1) pygame.draw.line(screen, WHITE, [350, 140], [356, 200], 1) pygame.draw.line(screen, WHITE, [355, 140], [359, 200], 1) pygame.draw.line(screen, WHITE, [360, 140], [362, 200], 1) pygame.draw.line(screen, WHITE, [364, 140], [365, 200], 1) pygame.draw.line(screen, WHITE, [368, 140], [369, 200], 1) pygame.draw.line(screen, WHITE, [372, 140], [373, 200], 1) pygame.draw.line(screen, WHITE, [376, 140], [377, 200], 1) pygame.draw.line(screen, WHITE, [380, 140], [380, 200], 1) pygame.draw.line(screen, WHITE, [384, 140], [384, 200], 1) pygame.draw.line(screen, WHITE, [388, 140], [388, 200], 1) pygame.draw.line(screen, WHITE, [392, 140], [392, 200], 1) pygame.draw.line(screen, WHITE, [396, 140], [396, 200], 1) pygame.draw.line(screen, WHITE, [400, 140], [400, 200], 1) pygame.draw.line(screen, WHITE, [404, 140], [404, 200], 1) pygame.draw.line(screen, WHITE, [408, 140], [408, 200], 1) pygame.draw.line(screen, WHITE, [412, 140], [412, 200], 1) pygame.draw.line(screen, WHITE, [416, 140], [416, 200], 1) pygame.draw.line(screen, WHITE, [420, 140], [420, 200], 1) pygame.draw.line(screen, WHITE, [424, 140], [423, 200], 1) pygame.draw.line(screen, WHITE, [428, 140], [427, 200], 1) pygame.draw.line(screen, WHITE, [432, 140], [431, 200], 1) pygame.draw.line(screen, WHITE, [436, 140], [435, 200], 1) pygame.draw.line(screen, WHITE, [440, 140], [438, 200], 1) pygame.draw.line(screen, WHITE, [445, 140], [441, 200], 1) pygame.draw.line(screen, WHITE, [450, 140], [444, 200], 1) pygame.draw.line(screen, WHITE, [455, 140], [447, 200], 1) pygame.draw.line(screen, WHITE, [460, 140], [450, 200], 1) pygame.draw.line(screen, WHITE, [465, 140], [453, 200], 1) pygame.draw.line(screen, WHITE, [470, 140], [456, 200], 1) pygame.draw.line(screen, WHITE, [475, 140], [459, 200], 1) # net part 2 pygame.draw.line(screen, WHITE, [320, 140], [324, 216], 1) pygame.draw.line(screen, WHITE, [320, 140], [326, 214], 1) pygame.draw.line(screen, WHITE, [320, 140], [328, 212], 1) pygame.draw.line(screen, WHITE, [320, 140], [330, 210], 1) pygame.draw.line(screen, WHITE, [320, 140], [332, 208], 1) pygame.draw.line(screen, WHITE, [320, 140], [334, 206], 1) pygame.draw.line(screen, WHITE, [320, 140], [336, 204], 1) pygame.draw.line(screen, WHITE, [320, 140], [338, 202], 1) # net part 3 pygame.draw.line(screen, WHITE, [480, 140], [476, 216], 1) pygame.draw.line(screen, WHITE, [480, 140], [474, 214], 1) pygame.draw.line(screen, WHITE, [480, 140], [472, 212], 1) pygame.draw.line(screen, WHITE, [480, 140], [470, 210], 1) pygame.draw.line(screen, WHITE, [480, 140], [468, 208], 1) pygame.draw.line(screen, WHITE, [480, 140], [466, 206], 1) pygame.draw.line(screen, WHITE, [480, 140], [464, 204], 1) pygame.draw.line(screen, WHITE, [480, 140], [462, 202], 1) # net part 4 pygame.draw.line(screen, WHITE, [324, 144], [476, 144], 1) pygame.draw.line(screen, WHITE, [324, 148], [476, 148], 1) pygame.draw.line(screen, WHITE, [324, 152], [476, 152], 1) pygame.draw.line(screen, WHITE, [324, 156], [476, 156], 1) pygame.draw.line(screen, WHITE, [324, 160], [476, 160], 1) pygame.draw.line(screen, WHITE, [324, 164], [476, 164], 1) pygame.draw.line(screen, WHITE, [324, 168], [476, 168], 1) pygame.draw.line(screen, WHITE, [324, 172], [476, 172], 1) pygame.draw.line(screen, WHITE, [324, 176], [476, 176], 1) pygame.draw.line(screen, WHITE, [335, 180], [470, 180], 1) pygame.draw.line(screen, WHITE, [335, 184], [465, 184], 1) pygame.draw.line(screen, WHITE, [335, 188], [465, 188], 1) pygame.draw.line(screen, WHITE, [335, 192], [465, 192], 1) pygame.draw.line(screen, WHITE, [335, 196], [465, 196], 1) # stands right pygame.draw.polygon(screen, RED, [[680, 220], [800, 340], [800, 290], [680, 180]]) pygame.draw.polygon(screen, WHITE, [[680, 180], [800, 100], [800, 290]]) # stands left pygame.draw.polygon(screen, RED, [[120, 220], [0, 340], [0, 290], [120, 180]]) pygame.draw.polygon(screen, WHITE, [[120, 180], [0, 100], [0, 290]]) # people # corner flag right pygame.draw.line(screen, BRIGHT_YELLOW, [140, 220], [135, 190], 3) pygame.draw.polygon(screen, RED, [[132, 190], [125, 196], [135, 205]]) # corner flag left pygame.draw.line(screen, BRIGHT_YELLOW, [660, 220], [665, 190], 3) pygame.draw.polygon(screen, RED, [[668, 190], [675, 196], [665, 205]]) # DARKNESS if not day and not lights_on: screen.blit(DARKNESS, (0, 0)) # WHAT??? # pygame.draw.polygon(screen, BLACK, [[200, 200], [50,400], [600, 500]], 10) ''' angles for arcs are measured in radians (a pre-cal topic) ''' # pygame.draw.arc(screen, ORANGE, [100, 100, 100, 100], 0, math.pi/2, 1) # pygame.draw.arc(screen, BLACK, [100, 100, 100, 100], 0, math.pi/2, 50) # Update screen (Actually draw the picture in the window.) pygame.display.flip() # Limit refresh rate of game loop clock.tick(refresh_rate) # Close window and quit pygame.quit() ================================================ FILE: python/lec_07/house.py ================================================ def main(): x, y = 300, 400 width, height = 200, 300 draw_house(x, y, width, height) def draw_house(x, y, width, height): """ Нарисовать домик ширины width и высоты height от опорной точки (x, y), которая находится в середине нижней точки фундамента. :param x: координата x середины домика :param y: координата y низа фундамента :param width: полная ширина домика (фундамен или вылеты крыши включены) :param height: полная высота домика :return: None """ print('Типа рисую домик...', x, y, width, height) foundation_height = 0.05 * height walls_width = 0.9 * width walls_height = 0.5 * height roof_height = height - foundation_height - walls_height draw_house_foundation(x, y, width, foundation_height) draw_house_walls(x, y - foundation_height, walls_width, walls_height) draw_house_roof(x, y - foundation_height - walls_height, width, roof_height) def draw_house_foundation(x, y, width, height): """ Нарисовать основание домика ширины width и высоты height от опорной точки (x, y), которая находится в середине нижней точки фундамента. :param x: координата x середины фундамента :param y: координата y низа фундамента :param width: полная ширина фундамена :param height: полная высота фундамента :return: None """ print('Типа рисую основание...', x, y, width, height) pass def draw_house_walls(x, y, width, height): print('Типа рисую стены...', x, y, width, height) pass def draw_house_roof(x, y, width, height): print('Типа рисую крышу...', x, y, width, height) pass if __name__ == "__main__": main() ================================================ FILE: python/lec_07/lib.py ================================================ def foo(x): print('foo(', x, ') is called') def bar(x, y): print(x + y) def print_name(): print(__name__) print_name() ================================================ FILE: python/lec_07/main.py ================================================ import lib lib.foo(5) lib.bar(2, 3) print('from module main.py __name__ ==', __name__) ================================================ FILE: python/lec_08/01_class.py ================================================ class Dragon: def __init__(self, name): self.name = name self.health = 100 def is_alive(self): return self.health > 0 def get_damage(self, damage): self.health -= damage if self.health < 0: self.health = 0 def talk(self): print(self.name, 'health', self.health, '. Hit me!') def final_cry(self): print(self.name, 'is dead...') def main(): enemy_list = [Dragon('Smog'), Dragon('Hidra')] finish = False while not finish: enemy = enemy_list[0] enemy.talk() damage = int(input()) enemy.get_damage(damage) if not enemy.is_alive(): # удалить из списка мёртвого врага enemy.final_cry() enemy_list.pop(0) if not enemy_list: # проверить пуст ли список врагов finish = True print('You win!') main() ================================================ FILE: python/lec_08/02_encapsulation_example.py ================================================ # coding=UTF-8 class PositiveInt: __a = 0 __counter = 0 def set_a(self, a): self.__counter += 1 if a >= 0: self.__a = int(a) else: print("Wrong parameter, an internal state won't change." ) def get_a(self): print("Was set", self.__counter, "times.") return self.__a if __name__ == "__main__": value = PositiveInt() print(value.get_a()) value.set_a(10) print(value.get_a()) value.set_a(-10) print(value.get_a()) ================================================ FILE: python/lec_08/2016-pacman/LICENSE ================================================ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. {one line to give the program's name and a brief idea of what it does.} Copyright (C) {year} {name of author} This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: {project} Copyright (C) {year} {fullname} This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ================================================ FILE: python/lec_08/2016-pacman/README.md ================================================ # pacman Преподавательская версия проекта Pacman ================================================ FILE: python/lec_08/2016-pacman/pacman.py ================================================ import sys import pygame from pygame.locals import * from math import floor import random def init_window(): pygame.init() pygame.display.set_mode((512, 512)) pygame.display.set_caption('Pacman') def draw_background(scr, img=None): if img: scr.blit(img, (0, 0)) else: bg = pygame.Surface(scr.get_size()) bg.fill((128, 128, 128)) scr.blit(bg, (0, 0)) class GameObject(pygame.sprite.Sprite): def __init__(self, img, x, y, tile_size, map_size): pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load(img) self.screen_rect = None self.x = 0 self.y = 0 self.tick = 0 self.tile_size = tile_size self.map_size = map_size self.set_coord(x, y) def set_coord(self, x, y): self.x = x self.y = y self.screen_rect = Rect(floor(x) * self.tile_size, floor(y) * self.tile_size, self.tile_size, self.tile_size ) def game_tick(self): self.tick += 1 def draw(self, scr): scr.blit(self.image, (self.screen_rect.x, self.screen_rect.y)) class Ghost(GameObject): def __init__(self, x, y, tile_size, map_size): GameObject.__init__(self, './resources/ghost.png', x, y, tile_size, map_size) self.direction = 0 self.velocity = 4.0 / 10.0 def game_tick(self): super(Ghost, self).game_tick() if self.tick % 20 == 0 or self.direction == 0: self.direction = random.randint(1, 4) if self.direction == 1: self.x += self.velocity if self.x >= self.map_size-1: self.x = self.map_size-1 self.direction = random.randint(1, 4) elif self.direction == 2: self.y += self.velocity if self.y >= self.map_size-1: self.y = self.map_size-1 self.direction = random.randint(1, 4) elif self.direction == 3: self.x -= self.velocity if self.x <= 0: self.x = 0 self.direction = random.randint(1, 4) elif self.direction == 4: self.y -= self.velocity if self.y <= 0: self.y = 0 self.direction = random.randint(1, 4) self.set_coord(self.x, self.y) class Pacman(GameObject): def __init__(self, x, y, tile_size, map_size): GameObject.__init__(self, './resources/pacman.png', x, y, tile_size, map_size) self.direction = 0 self.velocity = 4.0 / 10.0 def game_tick(self): super(Pacman, self).game_tick() if self.direction == 1: self.x += self.velocity if self.x >= self.map_size-1: self.x = self.map_size-1 elif self.direction == 2: self.y += self.velocity if self.y >= self.map_size-1: self.y = self.map_size-1 elif self.direction == 3: self.x -= self.velocity if self.x <= 0: self.x = 0 elif self.direction == 4: self.y -= self.velocity if self.y <= 0: self.y = 0 self.set_coord(self.x, self.y) def process_events(events, packman): for event in events: if (event.type == QUIT) or (event.type == KEYDOWN and event.key == K_ESCAPE): sys.exit(0) elif event.type == KEYDOWN: if event.key == K_LEFT: packman.direction = 3 elif event.key == K_RIGHT: packman.direction = 1 elif event.key == K_UP: packman.direction = 4 elif event.key == K_DOWN: packman.direction = 2 elif event.key == K_SPACE: packman.direction = 0 if __name__ == '__main__': init_window() tile_size = 32 map_size = 16 ghost = Ghost(0, 0, tile_size, map_size) pacman = Pacman(5, 5, tile_size, map_size) background = None #pygame.image.load("./resources/background.png") screen = pygame.display.get_surface() while True: process_events(pygame.event.get(), pacman) pygame.time.delay(100) ghost.game_tick() pacman.game_tick() draw_background(screen, background) pacman.draw(screen) ghost.draw(screen) pygame.display.update() ================================================ FILE: python/lec_08/cannon/LICENSE ================================================ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ================================================ FILE: python/lec_08/cannon/README.md ================================================ # cannon Набросок игры "Пушка" Реализация ООП. Ссылка на старую игру пушка: http://judge.mipt.ru/mipt_cs_on_python3_2016/labs/lab10.html#id4 ================================================ FILE: python/lec_08/cannon/cannon.py ================================================ import random as rnd import math import pygame from my_colors import * FPS = 20 GRAVITY_ACCELERATION = 9.8 # Ускорение свободного падения для снаряда. SCREEN_WIDTH, SCREEN_HEIGHT = 800, 600 class Cannon: max_velocity = 10 def __init__(self, x, y): self.x = x self.y = y self.shell_num = None # TODO: оставшееся на данный момент количество снарядов self.direction = math.pi / 4 def aim(self, x, y): """ Меняет направление direction так, чтобы он из точки (self.x, self.y) указывал в точку (x, y). :param x: координата x, в которую целимся :param y: координата y, в которую целимся :return: None """ pass # TODO def fire(self, dt): """ Создаёт объект снаряда (если ещё не потрачены все снаряды) летящий в направлении угла direction со скоростью, зависящей от длительности клика мышки :param dt: длительность клика мышки, мс :return: экземпляр снаряда типа Shell """ pass def draw(self): pygame.draw.circle(screen, self.color, (int(round(self.x)), int(round(self.y))), self.r) class Shell: standard_radius = 25 def __init__(self, x, y, Vx, Vy): self.x, self.y = x, y self.Vx, self.Vy = Vx, Vy self.r = Shell.standard_radius def move(self, dt): """ Сдвигает снаряд исходя из его кинематических характеристик и длины кванта времени dt в новое положение, а также меняет его скорость. :param dt: :return: """ ax, ay = 0, GRAVITY_ACCELERATION self.x += self.Vx*dt + ax*(dt**2)/2 self.y += self.Vy*dt + ay*(dt**2)/2 self.Vx += ax*dt self.Vy += ay*dt # TODO: Уничтожать (в статус deleted) снаряд, когда он касается земли. def draw(self): pygame.draw.circle(screen, self.color, (int(round(self.x)), int(round(self.y))), self.r) def detect_collision(self, other): """ Проверяет факт соприкосновения снаряда и объекта other :param other: объект, который должен иметь поля x, y, r :return: логическое значение типа bool """ length = ((self.x - other.x)**2 + (self.y - other.y)**2)**0.5 return length <= self.r + other.r class Target: standard_radius = 15 def __init__(self, x, y, Vx, Vy): self.x, self.y = x, y self.Vx, self.Vy = Vx, Vy self.r = Target.standard_radius self.color = COLORS[rnd.randint(0, len(COLORS) - 1)] def move(self, dt): """ Сдвигает шарик-мишень исходя из его кинематических характеристик и длины кванта времени dt в новое положение, а также меняет его скорость. :param dt: :return: """ ax, ay = 0, GRAVITY_ACCELERATION self.x += self.Vx * dt self.y += self.Vy * dt self.Vx += ax * dt self.Vy += ay * dt # TODO: Шарики-мишени должны отражаться от стенок def draw(self): pygame.draw.circle(screen, self.color, (int(round(self.x)), int(round(self.y))), self.r) def collide(self, other): """ Расчёт абсолютно упругого соударения :param other: :return: """ pass #TODO class Bomb: pass def generate_random_targets(number: int): targets = [] for i in range(number): x = rnd.randint(0, SCREEN_HEIGHT) y = rnd.randint(0, SCREEN_HEIGHT) Vx = rnd.randint(-30, +30) Vy = rnd.randint(-30, +30) target = Target(x, y, Vx, Vy) targets.append(target) return targets def game_main_loop(): targets = generate_random_targets(10) clock = pygame.time.Clock() finished = False while not finished: dt = clock.tick(FPS) / 1000 print(dt) for event in pygame.event.get(): if event.type == pygame.QUIT: finished = True elif event.type == pygame.MOUSEBUTTONDOWN: print('Click!') pygame.display.update() screen.fill(GRAY) for target in targets: target.move(dt) for target in targets: target.draw() pygame.quit() if __name__ == "__main__": pygame.init() screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) pygame.display.update() game_main_loop() ================================================ FILE: python/lec_08/cannon/my_colors.py ================================================ RED = (255, 0, 0) BLUE = (0, 0, 255) YELLOW = (255, 255, 0) GREEN = (0, 255, 0) MAGENTA = (255, 0, 255) CYAN = (0, 255, 255) BLACK = (0, 0, 0) WHITE = (255, 255, 255) GRAY = (100, 100, 100) COLORS = [RED, BLUE, YELLOW, GREEN, MAGENTA, CYAN] ================================================ FILE: python/lec_09/01_hierarchy.py ================================================ class Base: def __init__(self, x): self.x = x def show(self): print('Base', self.x) class Derivative(Base): def __init__(self): super().__init__(20) # явный вызов конструктора self.name = '' a = Base(10) b = Derivative() a.show() b.show() ================================================ FILE: python/lec_09/cannon.py ================================================ import numpy as np import pygame as pg from random import randint, gauss pg.init() pg.font.init() WHITE = (255, 255, 255) BLACK = (0, 0, 0) RED = (255, 0, 0) SCREEN_SIZE = (800, 600) def rand_color(): return (randint(0, 255), randint(0, 255), randint(0, 255)) class GameObject: pass class Shell(GameObject): ''' The ball class. Creates a ball, controls it's movement and implement it's rendering. ''' def __init__(self, coord, vel, rad=20, color=None): ''' Constructor method. Initializes ball's parameters and initial values. ''' self.coord = coord self.vel = vel if color == None: color = rand_color() self.color = color self.rad = rad self.is_alive = True def check_corners(self, refl_ort=0.8, refl_par=0.9): ''' Reflects ball's velocity when ball bumps into the screen corners. Implemetns inelastic rebounce. ''' for i in range(2): if self.coord[i] < self.rad: self.coord[i] = self.rad self.vel[i] = -int(self.vel[i] * refl_ort) self.vel[1-i] = int(self.vel[1-i] * refl_par) elif self.coord[i] > SCREEN_SIZE[i] - self.rad: self.coord[i] = SCREEN_SIZE[i] - self.rad self.vel[i] = -int(self.vel[i] * refl_ort) self.vel[1-i] = int(self.vel[1-i] * refl_par) def move(self, time=1, grav=0): ''' Moves the ball according to it's velocity and time step. Changes the ball's velocity due to gravitational force. ''' self.vel[1] += grav for i in range(2): self.coord[i] += time * self.vel[i] self.check_corners() if self.vel[0]**2 + self.vel[1]**2 < 2**2 and self.coord[1] > SCREEN_SIZE[1] - 2*self.rad: self.is_alive = False def draw(self, screen): ''' Draws the ball on appropriate surface. ''' pg.draw.circle(screen, self.color, self.coord, self.rad) class Cannon(GameObject): ''' Cannon class. Manages it's renderring, movement and striking. ''' def __init__(self, coord=[30, SCREEN_SIZE[1]//2], angle=0, max_pow=50, min_pow=10, color=RED): ''' Constructor method. Sets coordinate, direction, minimum and maximum power and color of the gun. ''' self.coord = coord self.angle = angle self.max_pow = max_pow self.min_pow = min_pow self.color = color self.active = False self.pow = min_pow def activate(self): ''' Activates gun's charge. ''' self.active = True def gain(self, inc=2): ''' Increases current gun charge power. ''' if self.active and self.pow < self.max_pow: self.pow += inc def strike(self): ''' Creates ball, according to gun's direction and current charge power. ''' vel = self.pow angle = self.angle ball = Shell(list(self.coord), [int(vel * np.cos(angle)), int(vel * np.sin(angle))]) self.pow = self.min_pow self.active = False return ball def set_angle(self, target_pos): ''' Sets gun's direction to target position. ''' self.angle = np.arctan2(target_pos[1] - self.coord[1], target_pos[0] - self.coord[0]) def move(self, inc): ''' Changes vertical position of the gun. ''' if (self.coord[1] > 30 or inc > 0) and (self.coord[1] < SCREEN_SIZE[1] - 30 or inc < 0): self.coord[1] += inc def draw(self, screen): ''' Draws the gun on the screen. ''' gun_shape = [] vec_1 = np.array([int(5*np.cos(self.angle - np.pi/2)), int(5*np.sin(self.angle - np.pi/2))]) vec_2 = np.array([int(self.pow*np.cos(self.angle)), int(self.pow*np.sin(self.angle))]) gun_pos = np.array(self.coord) gun_shape.append((gun_pos + vec_1).tolist()) gun_shape.append((gun_pos + vec_1 + vec_2).tolist()) gun_shape.append((gun_pos + vec_2 - vec_1).tolist()) gun_shape.append((gun_pos - vec_1).tolist()) pg.draw.polygon(screen, self.color, gun_shape) class Target(GameObject): ''' Target class. Creates target, manages it's rendering and collision with a ball event. ''' def __init__(self, coord=None, color=None, rad=30): ''' Constructor method. Sets coordinate, color and radius of the target. ''' if coord == None: coord = [randint(rad, SCREEN_SIZE[0] - rad), randint(rad, SCREEN_SIZE[1] - rad)] self.coord = coord self.rad = rad if color == None: color = rand_color() self.color = color def check_collision(self, ball): ''' Checks whether the ball bumps into target. ''' dist = sum([(self.coord[i] - ball.coord[i])**2 for i in range(2)])**0.5 min_dist = self.rad + ball.rad return dist <= min_dist def draw(self, screen): ''' Draws the target on the screen ''' pg.draw.circle(screen, self.color, self.coord, self.rad) def move(self): """ This type of target can't move at all. :return: None """ pass class MovingTarget(Target): def __init__(self, coord=None, color=None, rad=30): super().__init__(coord, color, rad) self.vx = randint(-2, +2) self.vy = randint(-2, +2) def move(self): self.coord[0] += self.vx self.coord[1] += self.vy class ScoreTable: ''' Score table class. ''' def __init__(self, t_destr=0, b_used=0): self.t_destr = t_destr self.b_used = b_used self.font = pg.font.SysFont("dejavusansmono", 25) def score(self): ''' Score calculation method. ''' return self.t_destr - self.b_used def draw(self, screen): score_surf = [] score_surf.append(self.font.render("Destroyed: {}".format(self.t_destr), True, WHITE)) score_surf.append(self.font.render("Balls used: {}".format(self.b_used), True, WHITE)) score_surf.append(self.font.render("Total: {}".format(self.score()), True, RED)) for i in range(3): screen.blit(score_surf[i], [10, 10 + 30*i]) class Manager: ''' Class that manages events' handling, ball's motion and collision, target creation, etc. ''' def __init__(self, n_targets=1): self.balls = [] self.gun = Cannon() self.targets = [] self.score_t = ScoreTable() self.n_targets = n_targets self.new_mission() def new_mission(self): ''' Adds new targets. ''' for i in range(self.n_targets): self.targets.append(Target(rad=randint(max(1, 30 - 2*max(0, self.score_t.score())), 30 - max(0, self.score_t.score())))) for i in range(self.n_targets): self.targets.append(MovingTarget(rad=randint(max(1, 30 - 2 * max(0, self.score_t.score())), 30 - max(0, self.score_t.score())))) def process(self, events, screen): ''' Runs all necessary method for each iteration. Adds new targets, if previous are destroyed. ''' done = self.handle_events(events) if pg.mouse.get_focused(): mouse_pos = pg.mouse.get_pos() self.gun.set_angle(mouse_pos) self.move() self.collide() self.draw(screen) if len(self.targets) == 0 and len(self.balls) == 0: self.new_mission() return done def handle_events(self, events): ''' Handles events from keyboard, mouse, etc. ''' done = False for event in events: if event.type == pg.QUIT: done = True elif event.type == pg.KEYDOWN: if event.key == pg.K_UP: self.gun.move(-5) elif event.key == pg.K_DOWN: self.gun.move(5) elif event.type == pg.MOUSEBUTTONDOWN: if event.button == 1: self.gun.activate() elif event.type == pg.MOUSEBUTTONUP: if event.button == 1: self.balls.append(self.gun.strike()) self.score_t.b_used += 1 return done def draw(self, screen): ''' Runs balls', gun's, targets' and score table's drawing method. ''' for ball in self.balls: ball.draw(screen) for target in self.targets: target.draw(screen) self.gun.draw(screen) self.score_t.draw(screen) def move(self): ''' Runs balls' and gun's movement method, removes dead balls. ''' dead_balls = [] for i, ball in enumerate(self.balls): ball.move(grav=2) if not ball.is_alive: dead_balls.append(i) for i in reversed(dead_balls): self.balls.pop(i) for i, target in enumerate(self.targets): target.move() self.gun.gain() def collide(self): ''' Checks whether balls bump into targets, sets balls' alive trigger. ''' collisions = [] targets_c = [] for i, ball in enumerate(self.balls): for j, target in enumerate(self.targets): if target.check_collision(ball): collisions.append([i, j]) targets_c.append(j) targets_c.sort() for j in reversed(targets_c): self.score_t.t_destr += 1 self.targets.pop(j) screen = pg.display.set_mode(SCREEN_SIZE) pg.display.set_caption("The gun of Khiryanov") done = False clock = pg.time.Clock() mgr = Manager(n_targets=3) while not done: clock.tick(15) screen.fill(BLACK) done = mgr.process(pg.event.get(), screen) pg.display.flip() pg.quit() ================================================ FILE: python/lec_10/cannon.py ================================================ import numpy as np import pygame as pg from random import randint, gauss pg.init() pg.font.init() WHITE = (255, 255, 255) BLACK = (0, 0, 0) RED = (255, 0, 0) SCREEN_SIZE = (800, 600) def rand_color(): return (randint(0, 255), randint(0, 255), randint(0, 255)) class GameObject: pass class Shell(GameObject): ''' The ball class. Creates a ball, controls it's movement and implement it's rendering. ''' def __init__(self, coord, vel, rad=20, color=None): ''' Constructor method. Initializes ball's parameters and initial values. ''' self.coord = coord self.vel = vel if color == None: color = rand_color() self.color = color self.rad = rad self.is_alive = True def check_corners(self, refl_ort=0.8, refl_par=0.9): ''' Reflects ball's velocity when ball bumps into the screen corners. Implemetns inelastic rebounce. ''' for i in range(2): if self.coord[i] < self.rad: self.coord[i] = self.rad self.vel[i] = -int(self.vel[i] * refl_ort) self.vel[1-i] = int(self.vel[1-i] * refl_par) elif self.coord[i] > SCREEN_SIZE[i] - self.rad: self.coord[i] = SCREEN_SIZE[i] - self.rad self.vel[i] = -int(self.vel[i] * refl_ort) self.vel[1-i] = int(self.vel[1-i] * refl_par) def move(self, time=1, grav=0): ''' Moves the ball according to it's velocity and time step. Changes the ball's velocity due to gravitational force. ''' self.vel[1] += grav for i in range(2): self.coord[i] += time * self.vel[i] self.check_corners() if self.vel[0]**2 + self.vel[1]**2 < 2**2 and self.coord[1] > SCREEN_SIZE[1] - 2*self.rad: self.is_alive = False def draw(self, screen): ''' Draws the ball on appropriate surface. ''' pg.draw.circle(screen, self.color, self.coord, self.rad) class Cannon(GameObject): ''' Cannon class. Manages it's renderring, movement and striking. ''' def __init__(self, coord=[30, SCREEN_SIZE[1]//2], angle=0, max_pow=50, min_pow=10, color=RED): ''' Constructor method. Sets coordinate, direction, minimum and maximum power and color of the gun. ''' self.coord = coord self.angle = angle self.max_pow = max_pow self.min_pow = min_pow self.color = color self.active = False self.pow = min_pow def activate(self): ''' Activates gun's charge. ''' self.active = True def gain(self, inc=2): ''' Increases current gun charge power. ''' if self.active and self.pow < self.max_pow: self.pow += inc def strike(self): ''' Creates ball, according to gun's direction and current charge power. ''' vel = self.pow angle = self.angle ball = Shell(list(self.coord), [int(vel * np.cos(angle)), int(vel * np.sin(angle))]) self.pow = self.min_pow self.active = False return ball def set_angle(self, target_pos): ''' Sets gun's direction to target position. ''' self.angle = np.arctan2(target_pos[1] - self.coord[1], target_pos[0] - self.coord[0]) def move(self, inc): ''' Changes vertical position of the gun. ''' if (self.coord[1] > 30 or inc > 0) and (self.coord[1] < SCREEN_SIZE[1] - 30 or inc < 0): self.coord[1] += inc def draw(self, screen): ''' Draws the gun on the screen. ''' gun_shape = [] vec_1 = np.array([int(5*np.cos(self.angle - np.pi/2)), int(5*np.sin(self.angle - np.pi/2))]) vec_2 = np.array([int(self.pow*np.cos(self.angle)), int(self.pow*np.sin(self.angle))]) gun_pos = np.array(self.coord) gun_shape.append((gun_pos + vec_1).tolist()) gun_shape.append((gun_pos + vec_1 + vec_2).tolist()) gun_shape.append((gun_pos + vec_2 - vec_1).tolist()) gun_shape.append((gun_pos - vec_1).tolist()) pg.draw.polygon(screen, self.color, gun_shape) class Target(GameObject): ''' Target class. Creates target, manages it's rendering and collision with a ball event. ''' def __init__(self, coord=None, color=None, rad=30): ''' Constructor method. Sets coordinate, color and radius of the target. ''' if coord == None: coord = [randint(rad, SCREEN_SIZE[0] - rad), randint(rad, SCREEN_SIZE[1] - rad)] self.coord = coord self.rad = rad if color == None: color = rand_color() self.color = color def check_collision(self, ball): ''' Checks whether the ball bumps into target. ''' dist = sum([(self.coord[i] - ball.coord[i])**2 for i in range(2)])**0.5 min_dist = self.rad + ball.rad return dist <= min_dist def draw(self, screen): ''' Draws the target on the screen ''' pg.draw.circle(screen, self.color, self.coord, self.rad) def move(self): """ This type of target can't move at all. :return: None """ pass class MovingTarget(Target): def __init__(self, coord=None, color=None, rad=30): super().__init__(coord, color, rad) self.vx = randint(-2, +2) self.vy = randint(-2, +2) def move(self): self.coord[0] += self.vx self.coord[1] += self.vy class ScoreTable: ''' Score table class. ''' def __init__(self, t_destr=0, b_used=0): self.t_destr = t_destr self.b_used = b_used self.font = pg.font.SysFont("dejavusansmono", 25) def score(self): ''' Score calculation method. ''' return self.t_destr - self.b_used def draw(self, screen): score_surf = [] score_surf.append(self.font.render("Destroyed: {}".format(self.t_destr), True, WHITE)) score_surf.append(self.font.render("Balls used: {}".format(self.b_used), True, WHITE)) score_surf.append(self.font.render("Total: {}".format(self.score()), True, RED)) for i in range(3): screen.blit(score_surf[i], [10, 10 + 30*i]) class Manager: ''' Class that manages events' handling, ball's motion and collision, target creation, etc. ''' def __init__(self, n_targets=1): self.balls = [] self.gun = Cannon() self.targets = [] self.score_t = ScoreTable() self.n_targets = n_targets self.new_mission() def new_mission(self): ''' Adds new targets. ''' for i in range(self.n_targets): self.targets.append(Target(rad=randint(max(1, 30 - 2*max(0, self.score_t.score())), 30 - max(0, self.score_t.score())))) for i in range(self.n_targets): self.targets.append(MovingTarget(rad=randint(max(1, 30 - 2 * max(0, self.score_t.score())), 30 - max(0, self.score_t.score())))) def process(self, events, screen): ''' Runs all necessary method for each iteration. Adds new targets, if previous are destroyed. ''' done = self.handle_events(events) if pg.mouse.get_focused(): mouse_pos = pg.mouse.get_pos() self.gun.set_angle(mouse_pos) self.move() self.collide() self.draw(screen) if len(self.targets) == 0 and len(self.balls) == 0: self.new_mission() return done def handle_events(self, events): ''' Handles events from keyboard, mouse, etc. ''' done = False for event in events: if event.type == pg.QUIT: done = True elif event.type == pg.KEYDOWN: if event.key == pg.K_UP: self.gun.move(-5) elif event.key == pg.K_DOWN: self.gun.move(5) elif event.type == pg.MOUSEBUTTONDOWN: if event.button == 1: self.gun.activate() elif event.type == pg.MOUSEBUTTONUP: if event.button == 1: self.balls.append(self.gun.strike()) self.score_t.b_used += 1 return done def draw(self, screen): ''' Runs balls', gun's, targets' and score table's drawing method. ''' for ball in self.balls: ball.draw(screen) for target in self.targets: target.draw(screen) self.gun.draw(screen) self.score_t.draw(screen) def move(self): ''' Runs balls' and gun's movement method, removes dead balls. ''' dead_balls = [] for i, ball in enumerate(self.balls): ball.move(grav=2) if not ball.is_alive: dead_balls.append(i) for i in reversed(dead_balls): self.balls.pop(i) for i, target in enumerate(self.targets): target.move() self.gun.gain() def collide(self): ''' Checks whether balls bump into targets, sets balls' alive trigger. ''' collisions = [] targets_c = [] for i, ball in enumerate(self.balls): for j, target in enumerate(self.targets): if target.check_collision(ball): collisions.append([i, j]) targets_c.append(j) targets_c.sort() for j in reversed(targets_c): self.score_t.t_destr += 1 self.targets.pop(j) screen = pg.display.set_mode(SCREEN_SIZE) pg.display.set_caption("The gun of Khiryanov") done = False clock = pg.time.Clock() mgr = Manager(n_targets=3) while not done: clock.tick(15) screen.fill(BLACK) done = mgr.process(pg.event.get(), screen) pg.display.flip() pg.quit() ================================================ FILE: python/lec_11/crosszeroes.py ================================================ import pygame from enum import Enum FPS = 60 CELL_SIZE = 50 class Cell(Enum): VOID = 0 CROSS = 1 ZERO = 2 class Player: """ Класс игрока, содержащий тип значков и имя. """ def __init__(self, name, cell_type): self.name = name self.cell_type = cell_type class GameField: def __init__(self): self.height = 3 self.width = 3 self.cells = [[Cell.VOID]*self.width for i in range(self.height)] class GameFieldView: """ Виджет игрового поля, который отображает его на экране, а также выясняет место клика. """ def __init__(self, field): # загрузить картинки значков клеток... # отобразить первичное состояние поля self._field = field self._height = field.height * CELL_SIZE self._width = field.width * CELL_SIZE def draw(self): pass def check_coords_correct(self, x, y): return True # TODO: self._height учесть def get_coords(self, x, y): return 0, 0 # TODO: реально вычислить клетку клика class GameRoundManager: """ Менеджер игры, запускающий все процессы. """ def __init__(self, player1: Player, player2: Player): self._players = [player1, player2] self._current_player = 0 self.field = GameField() def handle_click(self, i, j): player = self._players[self._current_player] # игрок делает клик на поле print("click_handled", i, j) class GameWindow: """ Содержит виджет поля, а также менеджера игрового раунда. """ def __init__(self): # инициализация pygame pygame.init() self._width = 800 self._height = 600 self._title = "Crosses & Zeroes" self._screen = pygame.display.set_mode((self._width, self._height)) pygame.display.set_caption(self._title) player1 = Player("Петя", Cell.CROSS) player2 = Player("Вася", Cell.ZERO) self._game_manager = GameRoundManager(player1, player2) self._field_widget = GameFieldView(self._game_manager.field) def main_loop(self): finished = False clock = pygame.time.Clock() while not finished: for event in pygame.event.get(): if event.type == pygame.QUIT: finished = True elif event.type == pygame.MOUSEBUTTONDOWN: mouse_pos = pygame.mouse.get_pos() x, y = mouse_pos if self._field_widget.check_coords_correct(x, y): i, j = self._field_widget.get_coords(x, y) self._game_manager.handle_click(i, j) pygame.display.flip() clock.tick(FPS) def main(): window = GameWindow() window.main_loop() print('Game over!') if __name__ == "__main__": main() ================================================ FILE: python/lec_12/1_selfdoc.py ================================================ def hypotenuse(leg1, leg2): return (leg1**2 + leg2**2)**0.5 def hypotenuse(leg1, leg2): # Square root from sum of squares of tirangle legs. # [2] Pifagor. Geometry of Euclid. return (leg1**2 + leg2**2)**0.5 def hypotenuse(leg1: float, leg2: float) -> float: """ Calculates length of hypotenuse of right triangle. # Look here: [2] Pifagor. Geometry of Euclid. :param leg1: length of the **first** triangle leg. :param leg2: length of the _other_ triangle leg. :return: length of the hypotenuse. """ # Square root from sum of squares of triangle legs. return (leg1**2 + leg2**2)**0.5 def hypotenuse(leg1: float, leg2: float) -> float: """ Calculates length of hypotenuse of right triangle. # Look here: [2] Pifagor. Geometry of Euclid. :param leg1: length of the **first** triangle leg. :param leg2: length of the _other_ triangle leg. :return: length of the hypotenuse. """ # Square root from sum of squares of triangle legs. length = (leg1**2 + leg2**2)**0.5 assert length**2 == leg1**2 + leg2**2, "OUCH!!! Pifagor theorem doesn't work! Stopping program." return length def main(): x, y = [float(a) for a in input().split()] print('Hypotenuse is', hypotenuse(x, y)) if __name__ == "__main__": # assert 2 + 2 == 5, 'Joke!' main() ================================================ FILE: python/lec_13/fib.py ================================================ def fib(n): """ Функция вычисляет числа фибоначчи. >>> fib(1) 1 >>> fib(2) 1 >>> fib(3) 2 >>> fib(5) 5 >>> fib(10) 55 >>> fib(20) 6765 >>> fib(-1) None """ if n < 2: return n else: return fib(n-1) + fib(n-2) if __name__ == "__main__": import doctest doctest.testmod() ================================================ FILE: python/lec_13/main.py ================================================ import fib def main(): n = int(input("Введите номер числа Фибоначчи: ")) f = fib.fib(n) print("Ваше число Фибоначчи:", f) if __name__ == "__main__": main() ================================================ FILE: python/lec_13/test_fib.py ================================================ import fib all_correct = True for n, answer in [(0, 0), (1, 1), (2, 1), (5, 5)]: result = fib.fib(n) correct = (result == answer) if not correct: print('Test case failed:', n, result, '!=', answer) all_correct &= correct if all_correct: print('Testing fib(): OK') else: print('Testing fib(): Failed.') ================================================ FILE: python/lec_14/fib.py ================================================ def fib(n): """ Вычисляет число Фибонаачи номер n. Выбрасывает исключение TypeError, если вызвана не для целочисленного типа. Выбрасыват исключение ValueError, если число отричательное или больше допустимого по контракту. :param n: целое число от 0 до 9999 :return: целое число от 0 до ... >>> fib(1) 1 >>> fib(2) 1 >>> fib(3) 2 >>> fib(5) 5 >>> fib(10) 55 >>> fib(20) 6765 """ if not isinstance(n, int): raise TypeError("Fibonacci function can work only with type.") if n < 0: raise ValueError("Fibonacci can't work with negative numbers.") if n >= 10000: raise ValueError("Fibonacci can't work with numbers larger than 9999.") if n == 0: return 0 f_2 = 0 f_1 = 1 for i in range(2, n + 1): f_1, f_2 = (f_1 + f_2), f_1 return f_1 if __name__ == "__main__": import doctest doctest.testmod() ================================================ FILE: python/lec_14/main.py ================================================ import fib def main(): n = int(input("Введите номер числа Фибоначчи: ")) f = fib.fib(n) print("Ваше число Фибоначчи:", f) if __name__ == "__main__": main() ================================================ FILE: python/lec_14/test_first.py ================================================ import unittest from fib import fib class TestFibonacci(unittest.TestCase): def test_simple(self): for param, result in [(0, 0), (1, 1), (2, 1), (3, 2), (10, 55)]: self.assertEqual(fib(param), result) def test_stress(self): self.assertEqual(fib(9999), fib(9998) + fib(9997)) with self.assertRaises(ValueError): fib(10000) def test_negative(self): with self.assertRaises(ValueError): fib(-1) with self.assertRaises(ValueError): fib(-100) def test_wrong_param_type(self): with self.assertRaises(TypeError): fib(2.5) with self.assertRaises(TypeError): fib('Hello') if __name__ == '__main__': unittest.main()