├── .gitignore
├── LICENSE
├── README.md
├── sem01_intro
├── README.md
├── sem01_211.ipynb
└── sem01_intro.ipynb
├── sem02_for
├── README.md
├── flowchart.png
├── sem02_211.ipynb
├── sem02_2113.ipynb
├── sem02_218.ipynb
├── sem02_219.ipynb
├── sem02_forif.ipynb
├── sem02_forif_come_back_212.ipynb
├── sem02_forif_come_back_217.ipynb
├── sem_02_213.ipynb
└── sem_02_214.ipynb
├── sem03_list
├── README.md
├── images
│ ├── comod.jpg
│ ├── comod_open.jpg
│ └── oooh.jpg
├── sem03_211.ipynb
├── sem03_2110.ipynb
├── sem03_218.ipynb
├── sem03_219.ipynb
├── sem_03_2113.ipynb
├── sem_03_213.ipynb
├── sem_03_214.ipynb
├── sem_03_memory.ipynb
├── sem_03_memory_come_back_212.ipynb
└── sem_03_memory_come_back_217.ipynb
├── sem04_functions
├── README.md
├── sem04_211.ipynb
├── sem04_2113.ipynb
├── sem04_218.ipynb
├── sem04_come_back_212.ipynb
├── sem04_come_back_217.ipynb
├── sem04_functions.ipynb
├── sem04_functions_2111.ipynb
├── sem04_functions_bec215.ipynb
├── sem_04_213.ipynb
└── sem_04_214.ipynb
├── sem05_dict
├── README.md
├── sem05&06_218.ipynb
├── sem05-216.ipynb
├── sem05_211.ipynb
├── sem05_2110_func.ipynb
├── sem05_2111.ipynb
├── sem05_2113.ipynb
├── sem05_219_bsr.ipynb
├── sem05_set_dict.ipynb
├── sem05_set_dict_come_back.ipynb
├── sem05_set_dict_solutions.ipynb
├── sem05_set_dict_tutorial_part1_come_back.ipynb
├── sem_05_213.ipynb
├── sem_05_213_214_lection.ipynb
└── sem_05_214.ipynb
├── sem06_dict
├── README.md
├── come_back.ipynb
├── sem06_2113.ipynb
├── sem06_211_from_sem.ipynb
├── sem06_211_init.ipynb
├── sem06_218.ipynb
├── sem06_219_2110_set_dict_problem_solutions.ipynb
├── sem06_219_2110_set_dict_problems.ipynb
├── sem06_set_dict_problem_set-215.ipynb
├── sem06_set_dict_problem_set-216.ipynb
├── sem06_set_dict_problem_set.ipynb
├── sem06_set_dict_problem_set_come_back.ipynb
├── sem06_set_dict_tutorial_part2.ipynb
├── sem06_set_dict_tutorial_part2_come_back.ipynb
├── sem_06_213.ipynb
└── sem_06_214.ipynb
├── sem07_wow
├── README.md
├── sem07_211
│ ├── cheat.py
│ ├── cheating
│ │ ├── 1.py
│ │ ├── 10.py
│ │ ├── 11.py
│ │ ├── 12.py
│ │ ├── 13.py
│ │ ├── 14.py
│ │ ├── 15.py
│ │ ├── 16.py
│ │ ├── 17.py
│ │ ├── 18.py
│ │ ├── 19.py
│ │ ├── 2.py
│ │ ├── 20.py
│ │ ├── 21.py
│ │ ├── 22.py
│ │ ├── 23.py
│ │ ├── 24.py
│ │ ├── 25.py
│ │ ├── 26.py
│ │ ├── 27.py
│ │ ├── 28.py
│ │ ├── 29.py
│ │ ├── 3.py
│ │ ├── 30.py
│ │ ├── 31.py
│ │ ├── 32.py
│ │ ├── 33.py
│ │ ├── 34.py
│ │ ├── 35.py
│ │ ├── 36.py
│ │ ├── 37.py
│ │ ├── 38.py
│ │ ├── 39.py
│ │ ├── 4.py
│ │ ├── 40.py
│ │ ├── 41.py
│ │ ├── 42.py
│ │ ├── 43.py
│ │ ├── 44.py
│ │ ├── 45.py
│ │ ├── 46.py
│ │ ├── 47.py
│ │ ├── 48.py
│ │ ├── 49.py
│ │ ├── 5.py
│ │ ├── 50.py
│ │ ├── 51.py
│ │ ├── 52.py
│ │ ├── 53.py
│ │ ├── 54.py
│ │ ├── 55.py
│ │ ├── 56.py
│ │ ├── 57.py
│ │ ├── 58.py
│ │ ├── 59.py
│ │ ├── 6.py
│ │ ├── 60.py
│ │ ├── 61.py
│ │ ├── 62.py
│ │ ├── 63.py
│ │ ├── 64.py
│ │ ├── 65.py
│ │ ├── 66.py
│ │ ├── 67.py
│ │ ├── 68.py
│ │ ├── 69.py
│ │ ├── 7.py
│ │ ├── 70.py
│ │ ├── 71.py
│ │ ├── 72.py
│ │ ├── 73.py
│ │ ├── 8.py
│ │ └── 9.py
│ ├── file.txt
│ ├── function_g.pickle
│ ├── lst.pickle
│ ├── marks.tsv
│ ├── markup.json
│ └── sem07_211.ipynb
├── sem07_2113
│ ├── cheat.py
│ ├── cheating
│ │ ├── 1.py
│ │ ├── 10.py
│ │ ├── 11.py
│ │ ├── 12.py
│ │ ├── 13.py
│ │ ├── 14.py
│ │ ├── 15.py
│ │ ├── 16.py
│ │ ├── 17.py
│ │ ├── 18.py
│ │ ├── 19.py
│ │ ├── 2.py
│ │ ├── 20.py
│ │ ├── 21.py
│ │ ├── 22.py
│ │ ├── 23.py
│ │ ├── 24.py
│ │ ├── 25.py
│ │ ├── 26.py
│ │ ├── 27.py
│ │ ├── 28.py
│ │ ├── 29.py
│ │ ├── 3.py
│ │ ├── 30.py
│ │ ├── 31.py
│ │ ├── 32.py
│ │ ├── 33.py
│ │ ├── 34.py
│ │ ├── 35.py
│ │ ├── 36.py
│ │ ├── 37.py
│ │ ├── 38.py
│ │ ├── 39.py
│ │ ├── 4.py
│ │ ├── 40.py
│ │ ├── 41.py
│ │ ├── 42.py
│ │ ├── 43.py
│ │ ├── 44.py
│ │ ├── 45.py
│ │ ├── 46.py
│ │ ├── 47.py
│ │ ├── 48.py
│ │ ├── 49.py
│ │ ├── 5.py
│ │ ├── 50.py
│ │ ├── 51.py
│ │ ├── 52.py
│ │ ├── 53.py
│ │ ├── 54.py
│ │ ├── 55.py
│ │ ├── 56.py
│ │ ├── 57.py
│ │ ├── 58.py
│ │ ├── 59.py
│ │ ├── 6.py
│ │ ├── 60.py
│ │ ├── 61.py
│ │ ├── 62.py
│ │ ├── 63.py
│ │ ├── 64.py
│ │ ├── 65.py
│ │ ├── 66.py
│ │ ├── 67.py
│ │ ├── 68.py
│ │ ├── 69.py
│ │ ├── 7.py
│ │ ├── 70.py
│ │ ├── 71.py
│ │ ├── 72.py
│ │ ├── 73.py
│ │ ├── 8.py
│ │ └── 9.py
│ ├── file.txt
│ ├── function_g.pickle
│ ├── lst.pickle
│ ├── marks.tsv
│ ├── markup.json
│ ├── my_important_dict.pkl
│ ├── my_important_function.pkl
│ ├── my_library
│ │ ├── my_module
│ │ │ ├── __init__.py
│ │ │ └── my_module.py
│ │ └── setup.py
│ ├── sem07_211.ipynb
│ └── some_folder
│ │ └── test.txt
├── sem07_218
│ ├── file.txt
│ ├── lst.pickle
│ ├── markup.json
│ ├── markup.pickle
│ ├── sem07_218.ipynb
│ ├── table.tsv
│ ├── test.json
│ └── test.pickle
├── sem07_219_2110_ie_problems.ipynb
├── sem_07_213.ipynb
└── sem_07_214.ipynb
├── sem08_write
├── README.md
├── data
│ ├── filtered-apartments.csv
│ ├── apartments.csv
│ ├── data.txt
│ ├── grades.tsv
│ ├── input.json
│ ├── msr_summary.tsv
│ ├── skating.txt
│ ├── users.txt
│ └── users_.txt
├── markup.json
├── sem08_218.ipynb
├── sem08_219_2110_ie_examples_csv_etc.ipynb
├── sem_08_213.ipynb
├── sem_08_214.ipynb
└── txt_files
│ ├── bill.txt
│ ├── ilon.txt
│ └── sasha.txt
├── sem09_parsers
├── README.md
├── sem05_parsing_215.ipynb
├── sem05_parsing_full.ipynb
├── sem05_parsing_full_2111.ipynb
├── sem05_parsing_full_2112.ipynb
├── sem05_parsing_full_216.ipynb
├── sem09_219_2110.ipynb
├── sem10_211.ipynb
├── sem10_213.ipynb
└── sem10_214.ipynb
├── sem10_API
├── 2111.ipynb
├── README.md
├── Untitled.ipynb
├── bot_utils
│ ├── Procfile
│ ├── main.py
│ └── requirements.txt
├── images
│ ├── client-server.png
│ └── scheme.png
├── sem10_218.ipynb
├── sem10_219_2110_telegram_bot.ipynb
└── sem10_bot_tutorial.ipynb
└── utils
├── eds_test_contest.pdf
├── input.json
├── input.txt
├── install_conda_mac.pdf
└── install_conda_windows.pdf
/.gitignore:
--------------------------------------------------------------------------------
1 | .DS_Store
2 |
3 |
4 | # Byte-compiled / optimized / DLL files
5 | __pycache__/
6 | *.py[cod]
7 | *$py.class
8 |
9 | # C extensions
10 | *.so
11 |
12 | # Distribution / packaging
13 | .Python
14 | build/
15 | develop-eggs/
16 | dist/
17 | downloads/
18 | eggs/
19 | .eggs/
20 | lib/
21 | lib64/
22 | parts/
23 | sdist/
24 | var/
25 | wheels/
26 | pip-wheel-metadata/
27 | share/python-wheels/
28 | *.egg-info/
29 | .installed.cfg
30 | *.egg
31 | MANIFEST
32 |
33 | # PyInstaller
34 | # Usually these files are written by a python script from a template
35 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
36 | *.manifest
37 | *.spec
38 |
39 | # Installer logs
40 | pip-log.txt
41 | pip-delete-this-directory.txt
42 |
43 | # Unit test / coverage reports
44 | htmlcov/
45 | .tox/
46 | .nox/
47 | .coverage
48 | .coverage.*
49 | .cache
50 | nosetests.xml
51 | coverage.xml
52 | *.cover
53 | *.py,cover
54 | .hypothesis/
55 | .pytest_cache/
56 |
57 | # Translations
58 | *.mo
59 | *.pot
60 |
61 | # Django stuff:
62 | *.log
63 | local_settings.py
64 | db.sqlite3
65 | db.sqlite3-journal
66 |
67 | # Flask stuff:
68 | instance/
69 | .webassets-cache
70 |
71 | # Scrapy stuff:
72 | .scrapy
73 |
74 | # Sphinx documentation
75 | docs/_build/
76 |
77 | # PyBuilder
78 | target/
79 |
80 | # Jupyter Notebook
81 | .ipynb_checkpoints
82 |
83 | # IPython
84 | profile_default/
85 | ipython_config.py
86 |
87 | # pyenv
88 | .python-version
89 |
90 | # pipenv
91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
94 | # install all needed dependencies.
95 | #Pipfile.lock
96 |
97 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow
98 | __pypackages__/
99 |
100 | # Celery stuff
101 | celerybeat-schedule
102 | celerybeat.pid
103 |
104 | # SageMath parsed files
105 | *.sage.py
106 |
107 | # Environments
108 | .env
109 | .venv
110 | env/
111 | venv/
112 | ENV/
113 | env.bak/
114 | venv.bak/
115 |
116 | # Spyder project settings
117 | .spyderproject
118 | .spyproject
119 |
120 | # Rope project settings
121 | .ropeproject
122 |
123 | # mkdocs documentation
124 | /site
125 |
126 | # mypy
127 | .mypy_cache/
128 | .dmypy.json
129 | dmypy.json
130 |
131 | # Pyre type checker
132 | .pyre/
133 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2022 hse-econ-data-science
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Data Analysis with Python, Анализ данных на python, коллекция весна 2022 и весна 2023
2 |
3 | Этой весной вас ждёт курс по python. Следующей весной будет курс про анализ данных. После каждого из этих курсов будет независимый экзамен от ФКН. Будет, страшно, сложно и весело.
4 |
5 | # Python
6 |
7 | - Wiki-страница курса - ???
8 | - Youtube-каналы с записями семинаров: [канал Филиппа](https://www.youtube.com/playlist?list=PLNKXA-74YGLi5tYgh2yuvstoMIRcEgWPk)
9 | - [Таблица с вашими оценками](https://docs.google.com/spreadsheets/d/1yAHDJ9wWWYjuEADHdQOxzHo_IMKxINLHAuWICTpJAO0/edit?usp=sharing)
10 | - Материалы для каждого семинара лежат в папках `/sem*`
11 | - Если вы хотите скачать из репозитория конкретную папку, просто вставьте ссылку на неё [в сервис для скачки.](https://minhaskamal.github.io/DownGit/#/home)
12 | - Любые вопросы можно задавать в общий чат. Там можно найти поддержку и пофлудить. [](https://t.me/+_2BivfQyHHYxMzJi)
13 | - Канал с основными объявлениями [](https://t.me/+VyQGUa12HZg4MjAy)
14 | - [Материалы прошлого курса (весна 2021)](https://github.com/hse-econ-data-science/dap_2021_spring)
15 |
16 |
17 |
18 | ## Идеология курса
19 |
20 | Основная цель курса - научить вас скриптованию. По его итогам вы должны __смело__ уметь открывать python и писать гору кода для решения всех своих проблем.
21 |
22 | Курс представляет из себя сочетания онлайн и офлайн частей. В офлайн-части, мы на семинарах вместе что-то делаем. В основном решаем задачи. В онлайн-части, вы изучаете курс на Coursera и дополнительные материалы, которые мы выкладываем.
23 |
24 | Проверять то, как вы делаете онлайновую часть, мы не будем. Тем не менее, единственный способ научиться программировать - это много программировать. Если вы будете игнорировать онлайновую часть, довольно большой кусок практики выпадет из вашей жизни, а впоследствии на ср и экзамине возникнут проблемы.
25 |
26 |
27 |
28 | ## Домашние задания и контрольные
29 |
30 | __Домашки:__
31 |
32 | - [Домашняя работа №1](https://official.contest.yandex.ru/contest/37490/enter/?retPage=problems)
33 | - [Домашняя работа №2](https://official.contest.yandex.ru/contest/38029/enter/?retPage=problems)
34 | - [Домашняя работа №3](https://official.contest.yandex.ru/contest/38029/enter/?retPage=problems)
35 | - [Домашняя работа №4](https://t.me/c/1154842830/100). Сдавать [сюда](https://forms.gle/va18jMuVSQV9ncWb6)
36 |
37 |
38 | __Контрольные:__
39 |
40 | - [Самостоятельная работа 1](https://official.contest.yandex.ru/contest/37927/enter/?retPage=problems)
41 | - [Самостоятельная работа 2](https://official.contest.yandex.ru/contest/38157/enter/?retPage=problems)
42 | - [Самостоятельная работа 3](https://official.contest.yandex.ru/contest/38495/enter/?retPage=problems)
43 |
44 |
45 | Примеры мини-самостоялок:
46 |
47 | - Мини-ср 1: [вариант 1,](https://docs.google.com/forms/d/e/1FAIpQLSeiSHS5ZbjfOwSZ1gRnwv4dRAu4ldeimXI6QjV208XGh1n1bg/viewform?usp=sf_link) [вариант 2](https://docs.google.com/forms/d/e/1FAIpQLSdzBKLF4TjXq_jEYWT8ApxzVcvG9mSBcbIXUYN38M-dSyTUxQ/viewform?usp=sf_link)
48 | - Мини-ср 2: [вариант 1,](https://docs.google.com/forms/d/e/1FAIpQLSea6UXtW2C3LHVvFBGpRFyE6klyz568_526AcZLOyZcjUUqHg/viewform?usp=sf_link) [вариант 2](https://docs.google.com/forms/d/e/1FAIpQLSdXs8kv8nxyvJdV9ESSmZqw3NV955EswiOBt7ZupnWcrXTD5w/viewform?usp=sf_link)
49 | - Мини-ср 3: [вариант 1,](https://docs.google.com/forms/d/e/1FAIpQLSffQuoMUKKozLRIcdf_TKWr8hTmmG2FG_cbwNcoAbWNFWUFbw/viewform?usp=sf_link) [вариант 2](https://docs.google.com/forms/d/e/1FAIpQLScnnl1DlVfrpmZ8IO2fxIqAQzME1ln18vLB1wOCWLKCm06QOQ/viewform?usp=sf_link)
50 | - Мини-ср 4: [вариант 1,](https://docs.google.com/forms/d/e/1FAIpQLSf7uXZJ3Ca3VKMIzwCBLyLtCzKUYTIeGjMOxOtuPwNdFgiGTQ/viewform?usp=sf_link) [вариант 2](https://docs.google.com/forms/d/e/1FAIpQLSe_RFqA-ya1RsVnRDg9XgZRwdcsOWfDxvyF5t4sIhm2EKVhdw/viewform?usp=sf_link)
51 | - Мини-ср 5: [вариант 1,](https://docs.google.com/forms/d/e/1FAIpQLSfySBkHYA_rUXfCS0IXATMAm4rf4vkyv1iIaKXF0Eyr8eNO1w/viewform?usp=sf_link) [вариант 2](https://docs.google.com/forms/d/e/1FAIpQLSd9JIHploK9kNRH-ezNkZbHXdMFrUa8o-YOJaZnQj9s6nAa5A/viewform?usp=sf_link)
52 | - Мини-ср 6: [вариант](https://docs.google.com/forms/d/e/1FAIpQLSdF-Mkyc2pmTHaGuS00qNOWtyepKQn4FGB4dQtw60yvULjPcQ/viewform?usp=sf_link)
53 |
54 |
55 | ## Большой план маленьких побед
56 |
57 | Установите перед первым семинаром Anaconda. [Инструкция для windows](https://github.com/hse-econ-data-science/dap_2020_fall/blob/master/utils/install_conda_windows.pdf) и [инструкция для мака.](https://github.com/hse-econ-data-science/dap_2020_fall/blob/master/utils/install_conda_mac.pdf)
58 |
59 | Anaconda - это дистрибутив для новичка. Обычно рано или поздно от него отказываются. Если вы жёсткий и вам знакомо слово терминал, можно поставить python и всё необходимое через него. Желательно сразу же делать это [через pyenv.](https://github.com/pyenv/pyenv)
60 |
61 |
62 | - [__sem01__](./sem01_intro) ~~Тратим полтора часа на то, чтобы запустить анаконду.~~ Вводимся в python, git и делаем import this.
63 | - [__sem02__](./sem02_for) Говорим про циклы, условия, списки, что такое range (концепция генераторов на пальцах).
64 | - [__sem03__](./sem03_list) Говорим про изменяемые и незименяемые типы данных: списки, кортежи, строки и методы работы с ними. Обсуждаем как питон работает с памятью и где можно из-за этого накосячить.
65 | - [__sem04__](./sem04_functions) Говорим о функциях и рекурсии. Решаем задачи на циклы и оформляем их в виде функций.
66 | - [__sem05__](./sem05_dict) Говорим про словарики и множества
67 | - [__sem06__](./sem06_dict) Решаем задачи на словари и множества. Немного говорим про collections.
68 | - [__sem07__](./sem07_wow) Полезный функционал: list comprehension, map, lambda-функции, all, any, max, sorted, lambda внутри них как key и т.п. Мб про operator, collections и itertools
69 | - [__sem08__](./sem08_write) Чтение и запись в файлы. Типы файлов: txt, json, csv, tsv, pickle. Введение в pandas: подгрузили табличку и сделали минимальное её шатание. Сразу забыли про пандас до следующего года. На экзамене им пользоваться нельзя.
70 | - [__sem09__](./sem09_parsers) Учимся собирать данные, пишем парсеры.
71 | - [__sem10__](./sem10_API) Работа с API
72 |
73 |
74 | ## Сдача домашек и контрольных
75 |
76 | Сдача части домашних заданий и контрольных будет происходить через Яндекс.Контест. На почты вам будут разосланы логины и пароли от него.
77 |
78 | - [инструкция как зайти в контест и решить тествое соревнование](https://github.com/hse-econ-data-science/dap_2020_fall/blob/master/utils/eds_test_contest.pdf)
79 | - [ссылка на тестовое соревнование](https://official.contest.yandex.ru/contest/17883/enter)
80 |
81 | Другая часть будет сдаваться через github. А может быть и через Anytask. Мы ещё не решили. До этой части домашек ещё дожить надо.
82 |
83 |
84 | ## Самый важный раздел
85 |
86 | Вы поулчаете две оценки. Одну за курс, вторую за независимый экзамен. Оценка за курс ставится по формуле:
87 |
88 |
89 | ```
90 | Min(10, 0.1*МСР + 0.4*БСР + 0.5*ДЗ),
91 | ```
92 |
93 | где ДЗ — средняя оценка за все домашние задания (4 штуки), МСР — средняя оценка за все мини-самостоятельные работы на семинарах (около 6 штук), БСР — средняя оценка за все большие самостоятельные работы (3 штуки). Округление арифметическое.
94 |
95 | Независимый экзамен вы пишите в конце курса и получаете по его итогам отдельную оценку. Будет пробный вариант.
96 |
97 |
98 |
99 | ## Контрибьюторы и создатели
100 |
101 | * [Максимовская Настя](https://github.com/AnastasiyaMax)
102 | * [Зарманбетов Ахмед](https://github.com/ahmedushka7)
103 | * [Зехов Матвей](https://github.com/Pyatachokk)
104 | * [Мидюкин Максим](https://github.com/MidiukinM)
105 | * [Илья Аброскин](https://github.com/ilyaaaaaaaa)
106 | * [Ульянкин Ппилиф](https://github.com/FUlyankin)
107 |
108 |
109 | Ментально с нами <3:
110 |
111 | * [Демешев Борис aka ББ](https://github.com/bdemeshev)
112 | * [Ананьева Марина](https://github.com/anamarina)
113 | * [Петросян Артур](https://github.com/pet67)
114 | * [Филатов Артём](https://github.com/FilatovArtm)
115 | * [Карпов Макс](https://github.com/karpovmax)
116 |
117 |
118 |
119 | ## Лицензия
120 |
121 | Весь контент, созданный для этого курса распространяются на правах лицензии [MIT License](https://github.com/hse-econ-data-science/dap_2020_fall/blob/master/LICENSE) Материалы публикуются как общественное достояние.
122 |
--------------------------------------------------------------------------------
/sem01_intro/README.md:
--------------------------------------------------------------------------------
1 | ## Материалы к первой неделе
2 |
3 | * [Материалы семинара sem01](https://github.com/hse-econ-data-science/dap_2021_spring/tree/main/sem01_intro)
4 | * Тетрадка для семинара в колабе: [](https://colab.research.google.com/github/hse-econ-data-science/dap_2022-23/blob/main/sem01_intro/sem01_intro.ipynb)
5 | * [Задачи для семинара](https://official.contest.yandex.ru/contest/24363/enter/)
6 | * Прочитать про то [как писать код красиво (PEP 8)](https://pythonworld.ru/osnovy/pep-8-rukovodstvo-po-napisaniyu-koda-na-python.html)
7 |
8 | __Задание:__
9 |
10 | * Пройдите первые уроки [с pythontutor](https://pythontutor.ru/lessons/inout_and_arithmetic_operations/)
11 | * Попытаться дорешать все задачи из [первого контеста.](https://official.contest.yandex.ru/contest/24363/enter/) Постарайтесь решить половину их них. Задачи, где нужно включать логику и придумывать формулы, можно пропускать.
12 |
13 |
14 | __Если хотите мастерски писать в ноутбуках текст на маркдауне:__
15 |
16 | * [10-минутный урок по markdown синтаксису](https://www.markdowntutorial.com/)
17 | * [Короткий гайд по markdown синтаксису](https://guides.github.com/features/mastering-markdown/)
18 |
--------------------------------------------------------------------------------
/sem02_for/README.md:
--------------------------------------------------------------------------------
1 | ## Материалы к неделям 2-3 (циклы и условия)
2 |
3 | * [Материалы семинара sem02](https://github.com/hse-econ-data-science/dap_2022-23/blob/main/sem02_for/sem02_forif.ipynb)
4 |
5 | * Тетрадка для семинара в колабе: [](https://colab.research.google.com/github/hse-econ-data-science/dap_2022-23/blob/sem02_for/sem02_forif.ipynb)
6 |
7 |
8 | __Задачи для семинаров и самостоятельного решения:__
9 |
10 | Постарайтесь решить из каждого набора хотябы 50%. Если возникают сложности, требуйте консультаций у асистентов и семинаристов с разбором задач.
11 |
12 | * [Задачи на условия](https://official.contest.yandex.ru/contest/24441/enter/) (первая половина 2 недели курса)
13 | * [Задачи на цикл while (можно решать и через for)](https://official.contest.yandex.ru/contest/24442/enter/) (вторая половина 2 недели курса)
14 | * [Задачи на цикл for (можно решать и через while)](https://official.contest.yandex.ru/contest/24443/enter/) (первая половина 5 недели курса)
15 | * [Задачи на действительные числа и строки](https://official.contest.yandex.ru/contest/24444/enter/) (3 неделя курса)
16 | * [Задачи на списки и циклы](https://official.contest.yandex.ru/contest/24445/enter/) (вторая половина 5 недели курса)
17 |
18 | Похожие задачи ждут вас на первой самостоятельной работе.
19 |
20 | __Ещё материалы:__
21 |
22 | * Объяснения и задачки на pythontutor по [условиям](https://pythontutor.ru/lessons/ifelse/) и циклам [for](https://pythontutor.ru/lessons/for_loop/) и [while](https://pythontutor.ru/lessons/while/).
23 | * Совсем краткий конспект на pythonworld по [циклам](https://pythonworld.ru/osnovy/cikly-for-i-while-operatory-break-i-continue-volshebnoe-slovo-else.html) и [условиям](https://pythonworld.ru/osnovy/instrukciya-if-elif-else-proverka-istinnosti-trexmestnoe-vyrazhenie-ifelse.html).
24 |
--------------------------------------------------------------------------------
/sem02_for/flowchart.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hse-econ-data-science/dap_2022-23/1e23952959de15a2f17b63dd48523a62245c74fc/sem02_for/flowchart.png
--------------------------------------------------------------------------------
/sem02_for/sem02_219.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "id": "7e16eb5e",
6 | "metadata": {
7 | "toc": true
8 | },
9 | "source": [
10 | "
Table of Contents
\n",
11 | ""
12 | ]
13 | },
14 | {
15 | "cell_type": "code",
16 | "execution_count": 3,
17 | "id": "6b6bb850",
18 | "metadata": {},
19 | "outputs": [
20 | {
21 | "name": "stdout",
22 | "output_type": "stream",
23 | "text": [
24 | "10\n",
25 | "Отлично\n"
26 | ]
27 | }
28 | ],
29 | "source": [
30 | "# пример 1\n",
31 | "mark = int(input())\n",
32 | "\n",
33 | "if mark<10:\n",
34 | " print('Это нормально!')\n",
35 | "else:\n",
36 | " print('Отлично')"
37 | ]
38 | },
39 | {
40 | "cell_type": "code",
41 | "execution_count": 10,
42 | "id": "988fb30e",
43 | "metadata": {},
44 | "outputs": [
45 | {
46 | "name": "stdout",
47 | "output_type": "stream",
48 | "text": [
49 | "3\n",
50 | "Недовлетворительно\n"
51 | ]
52 | }
53 | ],
54 | "source": [
55 | "# пример 2\n",
56 | "mark = int(input())\n",
57 | "\n",
58 | "if mark>=8:\n",
59 | " text = 'Отлично'\n",
60 | "else:\n",
61 | " if mark>=6:\n",
62 | " text = 'Хорошо'\n",
63 | " else:\n",
64 | " if mark>=4:\n",
65 | " text = 'Удовлетворительно'\n",
66 | " else:\n",
67 | " text = 'Неудовлетворительно'\n",
68 | " \n",
69 | "print(text)"
70 | ]
71 | },
72 | {
73 | "cell_type": "code",
74 | "execution_count": 14,
75 | "id": "4ad518fa",
76 | "metadata": {},
77 | "outputs": [
78 | {
79 | "name": "stdout",
80 | "output_type": "stream",
81 | "text": [
82 | "8\n",
83 | "Отлично\n"
84 | ]
85 | }
86 | ],
87 | "source": [
88 | "# пример 3\n",
89 | "mark = int(input())\n",
90 | "if mark>=8:\n",
91 | " text = 'Отлично'\n",
92 | "elif mark>=6:\n",
93 | " text = 'Хорошо'\n",
94 | "elif mark>=4:\n",
95 | " text = 'Удовлетворительно'\n",
96 | "else:\n",
97 | " text = 'Неудовлетворительно'\n",
98 | "print(text)"
99 | ]
100 | },
101 | {
102 | "cell_type": "code",
103 | "execution_count": 16,
104 | "id": "34425680",
105 | "metadata": {},
106 | "outputs": [
107 | {
108 | "name": "stdout",
109 | "output_type": "stream",
110 | "text": [
111 | "1\n",
112 | "2\n",
113 | "2\n"
114 | ]
115 | }
116 | ],
117 | "source": [
118 | "# Задача A\n",
119 | "\n",
120 | "a = int(input())\n",
121 | "b = int(input())\n",
122 | "\n",
123 | "if a>b:\n",
124 | " print(1)\n",
125 | "elif a=b and a>=c:\n",
217 | " print(a)\n",
218 | "elif b>=a and b>=c:\n",
219 | " print(b)\n",
220 | "else:\n",
221 | " print(c)"
222 | ]
223 | },
224 | {
225 | "cell_type": "code",
226 | "execution_count": 24,
227 | "id": "b89c5ab6",
228 | "metadata": {},
229 | "outputs": [
230 | {
231 | "name": "stdout",
232 | "output_type": "stream",
233 | "text": [
234 | "2022\n",
235 | "NO\n"
236 | ]
237 | }
238 | ],
239 | "source": [
240 | "# Задача C\n",
241 | "year = int(input())\n",
242 | "# кратен 4, но не кратен 100, а также если он кратен 400\n",
243 | "\n",
244 | "if (year%4==0 and year%100!=0) or (year%400==0):\n",
245 | " print('YES')\n",
246 | "else:\n",
247 | " print('NO')"
248 | ]
249 | },
250 | {
251 | "cell_type": "code",
252 | "execution_count": 26,
253 | "id": "918039c9",
254 | "metadata": {},
255 | "outputs": [
256 | {
257 | "name": "stdout",
258 | "output_type": "stream",
259 | "text": [
260 | "2021\n",
261 | "NO\n"
262 | ]
263 | }
264 | ],
265 | "source": [
266 | "year = int(input())\n",
267 | "condition = (year%4==0 and year%100!=0) or (year%400==0)\n",
268 | "# тенарный оператор: if-else конструкция в одну строку\n",
269 | "print('YES'if condition else 'NO')"
270 | ]
271 | },
272 | {
273 | "cell_type": "markdown",
274 | "id": "90b21714",
275 | "metadata": {},
276 | "source": [
277 | ""
278 | ]
279 | },
280 | {
281 | "cell_type": "code",
282 | "execution_count": 32,
283 | "id": "b905630b",
284 | "metadata": {},
285 | "outputs": [
286 | {
287 | "name": "stdout",
288 | "output_type": "stream",
289 | "text": [
290 | "1\n",
291 | "1\n",
292 | "10000\n",
293 | "impossible\n"
294 | ]
295 | }
296 | ],
297 | "source": [
298 | "a = int(input())\n",
299 | "b = int(input())\n",
300 | "c = int(input())\n",
301 | "\n",
302 | "if a+b>c and a+c>b and b+c>a:\n",
303 | " if (b**2 + c**2 == a**2) or (b**2 + a**2 == b**2) or (b**2 + a**2 == c**2):\n",
304 | " print('rectangular')\n",
305 | " elif (b**2 + c**2 > a**2) or (b**2 + a**2 > b**2) or (b**2 + a**2 > c**2):\n",
306 | " print('acute')\n",
307 | " elif (b**2 + c**2 < a**2) or (b**2 + a**2 < b**2) or (b**2 + a**2 < c**2):\n",
308 | " print('obtuse')\n",
309 | "else:\n",
310 | " print('impossible')"
311 | ]
312 | },
313 | {
314 | "cell_type": "code",
315 | "execution_count": null,
316 | "id": "1b8f021a",
317 | "metadata": {},
318 | "outputs": [],
319 | "source": []
320 | }
321 | ],
322 | "metadata": {
323 | "kernelspec": {
324 | "display_name": "Python 3",
325 | "language": "python",
326 | "name": "python3"
327 | },
328 | "language_info": {
329 | "codemirror_mode": {
330 | "name": "ipython",
331 | "version": 3
332 | },
333 | "file_extension": ".py",
334 | "mimetype": "text/x-python",
335 | "name": "python",
336 | "nbconvert_exporter": "python",
337 | "pygments_lexer": "ipython3",
338 | "version": "3.9.4"
339 | },
340 | "toc": {
341 | "base_numbering": 1,
342 | "nav_menu": {},
343 | "number_sections": true,
344 | "sideBar": true,
345 | "skip_h1_title": false,
346 | "title_cell": "Table of Contents",
347 | "title_sidebar": "Contents",
348 | "toc_cell": true,
349 | "toc_position": {},
350 | "toc_section_display": true,
351 | "toc_window_display": false
352 | }
353 | },
354 | "nbformat": 4,
355 | "nbformat_minor": 5
356 | }
357 |
--------------------------------------------------------------------------------
/sem03_list/README.md:
--------------------------------------------------------------------------------
1 | ## Материалы к неделям 3 (методы строк, списков + работа с памятью)
2 |
3 | * [Материалы семинара sem03](https://github.com/hse-econ-data-science/dap_2022-23/blob/main/sem03_list/sem_03_memory.ipynb)
4 |
5 | * Тетрадка для семинара в колабе: [](https://colab.research.google.com/github/hse-econ-data-science/dap_2022-23/blob/main/sem03_list/sem_03_memory.ipynb)
6 |
7 | __Задачи для семинаров и самостоятельного решения:__
8 |
9 | Постарайтесь решить из каждого набора хотябы 50%. Если возникают сложности, требуйте консультаций у асистентов и семинаристов с разбором задач.
10 |
11 | * [Задачи на условия](https://official.contest.yandex.ru/contest/24441/enter/)
12 | * [Задачи на цикл while (можно решать и через for)](https://official.contest.yandex.ru/contest/24442/enter/)
13 | * [Задачи на цикл for (можно решать и через while)](https://official.contest.yandex.ru/contest/24443/enter/)
14 | * [Задачи на действительные числа и строки](https://official.contest.yandex.ru/contest/24444/enter/)
15 | * [Задачи на списки и циклы](https://official.contest.yandex.ru/contest/24445/enter/)
16 |
--------------------------------------------------------------------------------
/sem03_list/images/comod.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hse-econ-data-science/dap_2022-23/1e23952959de15a2f17b63dd48523a62245c74fc/sem03_list/images/comod.jpg
--------------------------------------------------------------------------------
/sem03_list/images/comod_open.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hse-econ-data-science/dap_2022-23/1e23952959de15a2f17b63dd48523a62245c74fc/sem03_list/images/comod_open.jpg
--------------------------------------------------------------------------------
/sem03_list/images/oooh.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hse-econ-data-science/dap_2022-23/1e23952959de15a2f17b63dd48523a62245c74fc/sem03_list/images/oooh.jpg
--------------------------------------------------------------------------------
/sem03_list/sem03_219.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "id": "6db39f65",
6 | "metadata": {},
7 | "source": [
8 | "# while"
9 | ]
10 | },
11 | {
12 | "cell_type": "code",
13 | "execution_count": 1,
14 | "id": "31f908c4",
15 | "metadata": {},
16 | "outputs": [
17 | {
18 | "name": "stdout",
19 | "output_type": "stream",
20 | "text": [
21 | "0\n",
22 | "1\n",
23 | "2\n",
24 | "3\n",
25 | "4\n"
26 | ]
27 | }
28 | ],
29 | "source": [
30 | "i = 0\n",
31 | "while i < 10:\n",
32 | " print(i)\n",
33 | " # i = i + 1\n",
34 | " i += 1\n",
35 | " if i == 5:\n",
36 | " break"
37 | ]
38 | },
39 | {
40 | "cell_type": "code",
41 | "execution_count": 2,
42 | "id": "87948b74",
43 | "metadata": {},
44 | "outputs": [
45 | {
46 | "name": "stdout",
47 | "output_type": "stream",
48 | "text": [
49 | "9\n"
50 | ]
51 | }
52 | ],
53 | "source": [
54 | "x = 10\n",
55 | "y = 20\n",
56 | "days = 1\n",
57 | "while x <= y:\n",
58 | " days += 1\n",
59 | " x *= 1.1\n",
60 | " # print(days, x)\n",
61 | "print(days)"
62 | ]
63 | },
64 | {
65 | "cell_type": "code",
66 | "execution_count": 3,
67 | "id": "d63ffb85",
68 | "metadata": {},
69 | "outputs": [
70 | {
71 | "name": "stdout",
72 | "output_type": "stream",
73 | "text": [
74 | "10\n",
75 | "1000\n",
76 | "50\n",
77 | "20\n",
78 | "6730.86\n"
79 | ]
80 | }
81 | ],
82 | "source": [
83 | "p = int(input())\n",
84 | "rubles = int(input())\n",
85 | "kopeyka = int(input())\n",
86 | "years = int(input())\n",
87 | "i = 1\n",
88 | "money = rubles+(kopeyka/100)\n",
89 | "while i<=years:\n",
90 | " money*= (p/100+1)\n",
91 | " #money = round(money, 2)\n",
92 | " i+=1\n",
93 | "money *= 10000\n",
94 | "money = money // 100\n",
95 | "money /= 100\n",
96 | "print(money)\n",
97 | "# 36360285 50"
98 | ]
99 | },
100 | {
101 | "cell_type": "markdown",
102 | "id": "01e8f8dc",
103 | "metadata": {},
104 | "source": [
105 | "# range"
106 | ]
107 | },
108 | {
109 | "cell_type": "code",
110 | "execution_count": 4,
111 | "id": "913e9851",
112 | "metadata": {},
113 | "outputs": [
114 | {
115 | "name": "stdout",
116 | "output_type": "stream",
117 | "text": [
118 | "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n",
119 | "[5, 6, 7, 8, 9]\n",
120 | "[5, 7, 9]\n",
121 | "[10, 9, 8, 7, 6, 5, 4, 3, 2]\n",
122 | "[10, 8, 6, 4, 2]\n"
123 | ]
124 | }
125 | ],
126 | "source": [
127 | "print(list(range(10)))\n",
128 | "print(list(range(5,10)))\n",
129 | "print(list(range(5,10,2)))\n",
130 | "print(list(range(10,1,-1)))\n",
131 | "print(list(range(10,1,-2)))"
132 | ]
133 | },
134 | {
135 | "cell_type": "markdown",
136 | "id": "86faa323",
137 | "metadata": {},
138 | "source": [
139 | "# for"
140 | ]
141 | },
142 | {
143 | "cell_type": "code",
144 | "execution_count": 5,
145 | "id": "08864da2",
146 | "metadata": {},
147 | "outputs": [
148 | {
149 | "name": "stdout",
150 | "output_type": "stream",
151 | "text": [
152 | "0\n",
153 | "1\n",
154 | "2\n",
155 | "3\n",
156 | "4\n",
157 | "5\n",
158 | "6\n",
159 | "7\n",
160 | "8\n",
161 | "9\n"
162 | ]
163 | }
164 | ],
165 | "source": [
166 | "for i in range(10):\n",
167 | " print(i)"
168 | ]
169 | },
170 | {
171 | "cell_type": "markdown",
172 | "id": "7abe9dbe",
173 | "metadata": {},
174 | "source": [
175 | "# lists"
176 | ]
177 | },
178 | {
179 | "cell_type": "code",
180 | "execution_count": 6,
181 | "id": "cce78690",
182 | "metadata": {},
183 | "outputs": [
184 | {
185 | "name": "stdout",
186 | "output_type": "stream",
187 | "text": [
188 | "под номером 0 идет студент маша 10\n",
189 | "под номером 1 идет студент паша 4\n",
190 | "под номером 2 идет студент саша 9\n"
191 | ]
192 | }
193 | ],
194 | "source": [
195 | "a = ['маша 10', \n",
196 | " 'паша 4', \n",
197 | " 'саша 9']\n",
198 | "\n",
199 | "for index in range(len(a)):\n",
200 | " print(f'под номером {index} идет студент {a[index]}')"
201 | ]
202 | },
203 | {
204 | "cell_type": "code",
205 | "execution_count": 7,
206 | "id": "255cea0e",
207 | "metadata": {},
208 | "outputs": [
209 | {
210 | "name": "stdout",
211 | "output_type": "stream",
212 | "text": [
213 | "маша 10\n",
214 | "паша 4\n",
215 | "саша 9\n"
216 | ]
217 | }
218 | ],
219 | "source": [
220 | "for element in a:\n",
221 | " print(element)"
222 | ]
223 | },
224 | {
225 | "cell_type": "code",
226 | "execution_count": 8,
227 | "id": "963a166d",
228 | "metadata": {},
229 | "outputs": [
230 | {
231 | "name": "stdout",
232 | "output_type": "stream",
233 | "text": [
234 | "0 маша 10\n",
235 | "1 паша 4\n",
236 | "2 саша 9\n"
237 | ]
238 | }
239 | ],
240 | "source": [
241 | "for index, element in enumerate(a):\n",
242 | " print(index, element)"
243 | ]
244 | },
245 | {
246 | "cell_type": "code",
247 | "execution_count": 9,
248 | "id": "692f9324",
249 | "metadata": {},
250 | "outputs": [
251 | {
252 | "name": "stdout",
253 | "output_type": "stream",
254 | "text": [
255 | "1 2 3 4 5\n"
256 | ]
257 | }
258 | ],
259 | "source": [
260 | "a = input()"
261 | ]
262 | },
263 | {
264 | "cell_type": "code",
265 | "execution_count": 10,
266 | "id": "98ea9898",
267 | "metadata": {},
268 | "outputs": [
269 | {
270 | "data": {
271 | "text/plain": [
272 | "'1 2 3 4 5'"
273 | ]
274 | },
275 | "execution_count": 10,
276 | "metadata": {},
277 | "output_type": "execute_result"
278 | }
279 | ],
280 | "source": [
281 | "a"
282 | ]
283 | },
284 | {
285 | "cell_type": "code",
286 | "execution_count": 11,
287 | "id": "07a07300",
288 | "metadata": {},
289 | "outputs": [
290 | {
291 | "data": {
292 | "text/plain": [
293 | "[1, 2, 3, 4, 5]"
294 | ]
295 | },
296 | "execution_count": 11,
297 | "metadata": {},
298 | "output_type": "execute_result"
299 | }
300 | ],
301 | "source": [
302 | "a = list(map(int, a.split()))\n",
303 | "a"
304 | ]
305 | },
306 | {
307 | "cell_type": "code",
308 | "execution_count": 12,
309 | "id": "e00a0556",
310 | "metadata": {},
311 | "outputs": [
312 | {
313 | "name": "stdout",
314 | "output_type": "stream",
315 | "text": [
316 | "1\n"
317 | ]
318 | }
319 | ],
320 | "source": [
321 | "min_ = 1000\n",
322 | "for i in range(len(a)):\n",
323 | " if a[i]>0 and a[i]0 and element0:\n",
370 | " b.append(element)\n",
371 | "b"
372 | ]
373 | },
374 | {
375 | "cell_type": "code",
376 | "execution_count": 15,
377 | "id": "ebd4257e",
378 | "metadata": {},
379 | "outputs": [
380 | {
381 | "data": {
382 | "text/plain": [
383 | "1"
384 | ]
385 | },
386 | "execution_count": 15,
387 | "metadata": {},
388 | "output_type": "execute_result"
389 | }
390 | ],
391 | "source": [
392 | "min(b)"
393 | ]
394 | }
395 | ],
396 | "metadata": {
397 | "kernelspec": {
398 | "display_name": "Python 3 (ipykernel)",
399 | "language": "python",
400 | "name": "python3"
401 | },
402 | "language_info": {
403 | "codemirror_mode": {
404 | "name": "ipython",
405 | "version": 3
406 | },
407 | "file_extension": ".py",
408 | "mimetype": "text/x-python",
409 | "name": "python",
410 | "nbconvert_exporter": "python",
411 | "pygments_lexer": "ipython3",
412 | "version": "3.10.4"
413 | },
414 | "toc": {
415 | "base_numbering": 1,
416 | "nav_menu": {},
417 | "number_sections": true,
418 | "sideBar": true,
419 | "skip_h1_title": false,
420 | "title_cell": "Table of Contents",
421 | "title_sidebar": "Contents",
422 | "toc_cell": false,
423 | "toc_position": {},
424 | "toc_section_display": true,
425 | "toc_window_display": false
426 | }
427 | },
428 | "nbformat": 4,
429 | "nbformat_minor": 5
430 | }
431 |
--------------------------------------------------------------------------------
/sem04_functions/README.md:
--------------------------------------------------------------------------------
1 | ## Материалы к неделе 4 (функции)
2 |
3 | * [Материалы семинара sem04](https://github.com/hse-econ-data-science/dap_2022-23/blob/main/sem04_functions/sem04_functions.ipynb)
4 |
5 | * Тетрадка для семинара в колабе: [](https://colab.research.google.com/github/hse-econ-data-science/dap_2022-23/blob/main/sem04_functions/sem04_functions.ipynb)
6 |
7 | __Задачи для семинаров и самостоятельного решения:__
8 |
9 | Постарайтесь решить из каждого набора хотябы 50%. Если возникают сложности, требуйте консультаций у асистентов и семинаристов с разбором задач.
10 |
11 | * [Задачи на написание функций](https://official.contest.yandex.ru/contest/24446/enter/) (4 неделя курса)
12 | * Если хочется задачек чуть сложнее, посмотрите [набор задач на сортировку](https://official.contest.yandex.ru/contest/24448/enter/) (6 неделя курса)
13 |
14 | Похожие задачи ждут вас на второй самостоятельной работе.
15 |
16 | __Ещё материалы:__
17 |
18 | * Урок про функции и рекурсию на [pythontutor](http://pythontutor.ru/lessons/functions/)
19 | * Краткие конспекты [про функции](https://pythonworld.ru/tipy-dannyx-v-python/vse-o-funkciyax-i-ix-argumentax.html) на pythonworld
20 | * Ещё более сложные задачи с литкода:
21 | - https://leetcode.com/problems/longest-palindromic-substring/
22 | - https://leetcode.com/problems/last-stone-weight/
23 | - https://leetcode.com/problems/max-consecutive-ones/
24 | - https://leetcode.com/problems/merge-two-sorted-lists/
25 | - https://leetcode.com/problems/3sum-closest/
26 |
27 |
--------------------------------------------------------------------------------
/sem04_functions/sem04_functions.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "# Анализ данных на Python \n",
8 | "\n",
9 | "## Семинар 4. Функции"
10 | ]
11 | },
12 | {
13 | "cell_type": "markdown",
14 | "metadata": {},
15 | "source": [
16 | "
"
17 | ]
18 | },
19 | {
20 | "cell_type": "markdown",
21 | "metadata": {},
22 | "source": [
23 | "### Пример even_odd\n",
24 | "\n",
25 | "Напишите функцию, которая возвращает \"even\", если число четное и \"odd\" в противном случае"
26 | ]
27 | },
28 | {
29 | "cell_type": "code",
30 | "execution_count": null,
31 | "metadata": {},
32 | "outputs": [],
33 | "source": [
34 | "def even_odd(integer):\n",
35 | " if integer % 2 == 0:\n",
36 | " return \"even\"\n",
37 | " else:\n",
38 | " return \"odd\"\n",
39 | "\n",
40 | "print(3, \"is\", even_odd(3))\n",
41 | "print(10, \"is\", even_odd(10))"
42 | ]
43 | },
44 | {
45 | "cell_type": "markdown",
46 | "metadata": {},
47 | "source": [
48 | "### Лямбда функции\n",
49 | " Функции можно определять еще короче, если функция простая\n",
50 | "\n",
51 | "\n",
52 | "
"
53 | ]
54 | },
55 | {
56 | "cell_type": "code",
57 | "execution_count": null,
58 | "metadata": {},
59 | "outputs": [],
60 | "source": [
61 | "even_odd_lambda = lambda integer: \"even\" if integer % 2 == 0 else \"odd\"\n",
62 | "\n",
63 | "print(3, \"is\", even_odd_lambda(3))\n",
64 | "print(10, \"is\", even_odd_lambda(10))"
65 | ]
66 | },
67 | {
68 | "cell_type": "markdown",
69 | "metadata": {},
70 | "source": [
71 | "## Ремарка о print и return\n",
72 | "\n",
73 | "До этого момента, чтобы посмотреть на результат нашей программы мы использовали print. Из-за этого, как показывает практика, могло показаться, что print возвращает результат"
74 | ]
75 | },
76 | {
77 | "cell_type": "markdown",
78 | "metadata": {},
79 | "source": [
80 | "\n",
81 | "
"
82 | ]
83 | },
84 | {
85 | "cell_type": "markdown",
86 | "metadata": {},
87 | "source": [
88 | "Но это не так. Сравните:"
89 | ]
90 | },
91 | {
92 | "cell_type": "code",
93 | "execution_count": null,
94 | "metadata": {},
95 | "outputs": [],
96 | "source": [
97 | "def my_function_return(x):\n",
98 | " return x\n",
99 | "\n",
100 | "def my_function_print(x):\n",
101 | " print(\"print inside function:\", x)\n",
102 | " \n",
103 | "print(\"my_function_return:\", str(my_function_return(67)))\n",
104 | "print(\"my_function_print:\", str(my_function_print(67)))"
105 | ]
106 | },
107 | {
108 | "cell_type": "markdown",
109 | "metadata": {},
110 | "source": [
111 | "Поэтому, когда вы пишете функции:"
112 | ]
113 | },
114 | {
115 | "cell_type": "markdown",
116 | "metadata": {},
117 | "source": [
118 | "
"
119 | ]
120 | },
121 | {
122 | "cell_type": "markdown",
123 | "metadata": {},
124 | "source": [
125 | "## Задачи"
126 | ]
127 | },
128 | {
129 | "cell_type": "code",
130 | "execution_count": null,
131 | "metadata": {},
132 | "outputs": [],
133 | "source": [
134 | "# simple tool for tests\n",
135 | "def test_problem(func, test_data):\n",
136 | " for inputs, true_answer in test_data:\n",
137 | " answer = func(inputs)\n",
138 | " assert answer == true_answer, f'Expected {true_answer}, got {answer}. Input: {inputs}'\n",
139 | " print(\"OK!\")"
140 | ]
141 | },
142 | {
143 | "cell_type": "markdown",
144 | "metadata": {},
145 | "source": [
146 | "### Задача 0. Чтение и запись в файл\n",
147 | "\n",
148 | "Часто в задачах (не в этот раз) на вход вам будут подаваться файлы, и из них нужно уметь считывать данные."
149 | ]
150 | },
151 | {
152 | "cell_type": "markdown",
153 | "metadata": {},
154 | "source": [
155 | "Иногда случается так, что файл со входными данными содержит лишние символы, пустые строки и тд. Давайте разберем несколько случаев."
156 | ]
157 | },
158 | {
159 | "cell_type": "code",
160 | "execution_count": null,
161 | "metadata": {},
162 | "outputs": [],
163 | "source": [
164 | "FILENAME = \"myfile.txt\""
165 | ]
166 | },
167 | {
168 | "cell_type": "markdown",
169 | "metadata": {},
170 | "source": [
171 | "#### Пример 1\n",
172 | "\n",
173 | "На вход программы поступает 4 числа с новой строки. Считайте их из файла и положите в переменную answer."
174 | ]
175 | },
176 | {
177 | "cell_type": "code",
178 | "execution_count": null,
179 | "metadata": {},
180 | "outputs": [],
181 | "source": [
182 | "content = \"\"\"\n",
183 | "1\n",
184 | "\n",
185 | "2\n",
186 | "3 \n",
187 | "\n",
188 | "4\n",
189 | "\"\"\"\n",
190 | "\n",
191 | "answer = []\n",
192 | "\n",
193 | "with open(FILENAME, \"w\") as out_file:\n",
194 | " out_file.write(content)\n",
195 | " \n",
196 | "\n",
197 | "with open(FILENAME, \"r\") as input_file:\n",
198 | " for row in input_file:\n",
199 | " # YOUR CODE HERE\n",
200 | "\n",
201 | "assert answer == [1, 2, 3, 4] "
202 | ]
203 | },
204 | {
205 | "cell_type": "markdown",
206 | "metadata": {},
207 | "source": [
208 | "#### Пример 2\n",
209 | "\n",
210 | "На вход программы поступает 4 числа разбитых пробелами. Считайте их из файла и положите в переменную answer "
211 | ]
212 | },
213 | {
214 | "cell_type": "code",
215 | "execution_count": null,
216 | "metadata": {},
217 | "outputs": [],
218 | "source": [
219 | "content = \"1 2 3 4\"\n",
220 | "\n",
221 | "answer = []\n",
222 | "\n",
223 | "with open(FILENAME, \"w\") as out_file:\n",
224 | " out_file.write(content)\n",
225 | " \n",
226 | "\n",
227 | "with open(FILENAME, \"r\") as input_file:\n",
228 | " row = next(input_file)\n",
229 | " # YOUR CODE HERE\n",
230 | "\n",
231 | "assert answer == [1, 2, 3, 4] "
232 | ]
233 | },
234 | {
235 | "cell_type": "markdown",
236 | "metadata": {},
237 | "source": [
238 | "### Задача 1.Fizz Buzz \n",
239 | "\n",
240 | "Напишите программу, которая выводит строковое представление чисел от 1 до n.\n",
241 | "\n",
242 | "Но для чисел кратных трем он должен выводить «Fizz» вместо числа, а для кратных пяти - «Buzz». Для чисел, кратных трем и пяти, выведите «FizzBuzz».\n"
243 | ]
244 | },
245 | {
246 | "cell_type": "code",
247 | "execution_count": null,
248 | "metadata": {},
249 | "outputs": [],
250 | "source": [
251 | "def fizz_buzz(n):\n",
252 | " # YOUR CODE HERE\n",
253 | " return answer"
254 | ]
255 | },
256 | {
257 | "cell_type": "code",
258 | "execution_count": null,
259 | "metadata": {},
260 | "outputs": [],
261 | "source": [
262 | "FIZZ_BUZZ_TESTS_DATA = [\n",
263 | " (1, [\"1\"]),\n",
264 | " (2, [\"1\", \"2\"]),\n",
265 | " (15, [\"1\", \"2\", \"Fizz\", \"4\", \"Buzz\", \"Fizz\", \"7\", \"8\", \"Fizz\", \"Buzz\", \"11\", \"Fizz\", \"13\", \"14\", \"FizzBuzz\"]),\n",
266 | "]\n",
267 | "test_problem(fizz_buzz, FIZZ_BUZZ_TESTS_DATA)"
268 | ]
269 | },
270 | {
271 | "cell_type": "markdown",
272 | "metadata": {},
273 | "source": [
274 | "### Задача 2. Fibonacci \n",
275 | "\n",
276 | "Напишите программу, которая выводить числа Фибоначчи.\n",
277 | "(Подсказка: последовательность Фибоначчи - это последовательность чисел, в которой каждое следующее число в последовательности - это сумма двух предыдущих чисел. Последовательность выглядит так: 1, 1, 2, 3, 5, 8, 13, …)"
278 | ]
279 | },
280 | {
281 | "cell_type": "code",
282 | "execution_count": null,
283 | "metadata": {},
284 | "outputs": [],
285 | "source": [
286 | "def fibonacci(n):\n",
287 | " # YOUR CODE HERE\n",
288 | " return answer\n"
289 | ]
290 | },
291 | {
292 | "cell_type": "code",
293 | "execution_count": null,
294 | "metadata": {},
295 | "outputs": [],
296 | "source": [
297 | "FIBONACCI_TESTS_DATA = [\n",
298 | " (1, 1),\n",
299 | " (2, 1),\n",
300 | " (3, 2),\n",
301 | " (4, 3),\n",
302 | " (5, 5),\n",
303 | " (10, 55),\n",
304 | " (40, 102334155),\n",
305 | "]\n",
306 | "test_problem(fibonacci, FIBONACCI_TESTS_DATA)"
307 | ]
308 | },
309 | {
310 | "cell_type": "markdown",
311 | "metadata": {},
312 | "source": [
313 | "### Задача 3. Найти все дубли в списке\n",
314 | "\n",
315 | "В массиве целых чисел некоторые элементы появляются дважды, а другие - один раз.\n",
316 | "\n",
317 | "Найдите все элементы, которые встречаются дважды в этом массиве.\n",
318 | "\n",
319 | "Выводить елементы нужно в том же порядке, в котором они первый раз встретились в листе."
320 | ]
321 | },
322 | {
323 | "cell_type": "code",
324 | "execution_count": null,
325 | "metadata": {},
326 | "outputs": [],
327 | "source": [
328 | "def find_duplicates(arr):\n",
329 | " # YOUR CODE HERE\n",
330 | " return answer\n"
331 | ]
332 | },
333 | {
334 | "cell_type": "code",
335 | "execution_count": null,
336 | "metadata": {
337 | "scrolled": true
338 | },
339 | "outputs": [],
340 | "source": [
341 | "FIND_DUPLICATES_TESTS_DATA = [\n",
342 | " ([1], []),\n",
343 | " ([1, 1], [1]),\n",
344 | " ([1, 1, 2, 2], [1, 2]),\n",
345 | "]\n",
346 | "test_problem(find_duplicates, FIND_DUPLICATES_TESTS_DATA)"
347 | ]
348 | },
349 | {
350 | "cell_type": "markdown",
351 | "metadata": {},
352 | "source": [
353 | "### Задача 4. Палиндром\n",
354 | " \n",
355 | "Определите, является ли строка палиндромом. Палиндром - это число или текст, одинаково читающееся в обоих направлениях."
356 | ]
357 | },
358 | {
359 | "cell_type": "code",
360 | "execution_count": null,
361 | "metadata": {},
362 | "outputs": [],
363 | "source": [
364 | "def is_palindrome(string):\n",
365 | " # YOUR CODE HERE\n",
366 | " return answer"
367 | ]
368 | },
369 | {
370 | "cell_type": "code",
371 | "execution_count": null,
372 | "metadata": {},
373 | "outputs": [],
374 | "source": [
375 | "IS_PALINDROME_TESTS_DATA = [\n",
376 | " (\"\", True),\n",
377 | " (\"a\", True),\n",
378 | " (\"ab\", False),\n",
379 | " (\"aba\", True),\n",
380 | " (\"malayalam\", True),\n",
381 | "]\n",
382 | "test_problem(is_palindrome, IS_PALINDROME_TESTS_DATA)"
383 | ]
384 | }
385 | ],
386 | "metadata": {
387 | "kernelspec": {
388 | "display_name": "Python 3",
389 | "language": "python",
390 | "name": "python3"
391 | },
392 | "language_info": {
393 | "codemirror_mode": {
394 | "name": "ipython",
395 | "version": 3
396 | },
397 | "file_extension": ".py",
398 | "mimetype": "text/x-python",
399 | "name": "python",
400 | "nbconvert_exporter": "python",
401 | "pygments_lexer": "ipython3",
402 | "version": "3.6.9"
403 | }
404 | },
405 | "nbformat": 4,
406 | "nbformat_minor": 2
407 | }
408 |
--------------------------------------------------------------------------------
/sem05_dict/README.md:
--------------------------------------------------------------------------------
1 | ## Материалы к неделям 5-6 (словари и множества)
2 |
3 | * [Материалы семинара sem05](https://github.com/hse-econ-data-science/dap_2021_spring/tree/main/sem05_dict)
4 | * [Материалы семинара sem06](https://github.com/hse-econ-data-science/dap_2021_spring/tree/main/sem06_dict)
5 |
6 | __Задачи для семинаров и самостоятельного решения:__
7 |
8 | Обратите внимание, что эти наборы задач практически полностью соответствуют [рекомендованному вам курсу с Coursera.](https://www.coursera.org/learn/python-osnovy-programmirovaniya#syllabus) Постарайтесь решить из каждого набора хотябы 50%. Если вам удобнее решать задачи на Coursera, тогда делайте это там.
9 |
10 | * [Задачи на множества](https://official.contest.yandex.ru/contest/24447/enter/) (первая половина 7 недели курса)
11 | * [Задачи на словари](https://official.contest.yandex.ru/contest/24449/enter/) (вторая половина 7 недели курса)
12 |
13 | Похожие задачи ждут вас на второй самостоятельной работе.
14 |
15 | __Ещё материалы:__
16 |
17 | * Уроки про [множества](http://pythontutor.ru/lessons/sets/) и [словари](http://pythontutor.ru/lessons/dicts/) на pythontutor
18 | * Краткие коспекты на pythonworld про [словари](https://pythonworld.ru/tipy-dannyx-v-python/slovari-dict-funkcii-i-metody-slovarej.html) и [множества](https://pythonworld.ru/tipy-dannyx-v-python/mnozhestva-set-i-frozenset.html)
19 | * Если вы хотите немного углубиться в алгоритмическую составляющую, прочитайте книгу Грокаем Алгоритмы с примерами кода на python, она великолепная и очень просто написана с примерами на python
20 |
21 |
--------------------------------------------------------------------------------
/sem05_dict/sem_05_213.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "code",
5 | "execution_count": 3,
6 | "metadata": {},
7 | "outputs": [],
8 | "source": [
9 | "x = [1, 10, 24, 4, 5]\n",
10 | "k = 4"
11 | ]
12 | },
13 | {
14 | "cell_type": "code",
15 | "execution_count": 4,
16 | "metadata": {},
17 | "outputs": [
18 | {
19 | "data": {
20 | "text/plain": [
21 | "True"
22 | ]
23 | },
24 | "execution_count": 4,
25 | "metadata": {},
26 | "output_type": "execute_result"
27 | }
28 | ],
29 | "source": [
30 | "4 in x"
31 | ]
32 | },
33 | {
34 | "cell_type": "code",
35 | "execution_count": 12,
36 | "metadata": {},
37 | "outputs": [],
38 | "source": [
39 | "def linear_search(x, k):\n",
40 | " for i in range(len(x)):\n",
41 | " if x[i] == k:\n",
42 | " return i\n",
43 | " return 'NA'"
44 | ]
45 | },
46 | {
47 | "cell_type": "code",
48 | "execution_count": 18,
49 | "metadata": {},
50 | "outputs": [
51 | {
52 | "data": {
53 | "text/plain": [
54 | "0"
55 | ]
56 | },
57 | "execution_count": 18,
58 | "metadata": {},
59 | "output_type": "execute_result"
60 | }
61 | ],
62 | "source": [
63 | "linear_search([1, 10, 4, 22, 42], 4)"
64 | ]
65 | },
66 | {
67 | "cell_type": "code",
68 | "execution_count": null,
69 | "metadata": {},
70 | "outputs": [],
71 | "source": [
72 | "for i in range(len(x)):\n",
73 | " for j in range(len(x)):\n",
74 | " x[i, j] == k"
75 | ]
76 | },
77 | {
78 | "cell_type": "code",
79 | "execution_count": null,
80 | "metadata": {},
81 | "outputs": [],
82 | "source": []
83 | },
84 | {
85 | "cell_type": "code",
86 | "execution_count": null,
87 | "metadata": {},
88 | "outputs": [],
89 | "source": [
90 | "x = [1, 4, 5, 10, 5900]\n",
91 | "k = 4"
92 | ]
93 | },
94 | {
95 | "cell_type": "markdown",
96 | "metadata": {},
97 | "source": []
98 | },
99 | {
100 | "cell_type": "code",
101 | "execution_count": null,
102 | "metadata": {},
103 | "outputs": [],
104 | "source": [
105 | "a = 1 \n",
106 | "b = 2\n",
107 | "\n",
108 | "if a * b > a + b:\n",
109 | " print('*')\n",
110 | "else:\n",
111 | " print('+')"
112 | ]
113 | },
114 | {
115 | "cell_type": "code",
116 | "execution_count": null,
117 | "metadata": {},
118 | "outputs": [],
119 | "source": [
120 | "for i in range(len(x)): # O(n)\n",
121 | " a = i + 4 # O(1)\n",
122 | " b = x[a] + 100 # O(1)\n",
123 | " c = b * 100 # O(1)\n",
124 | "\n",
125 | " \n",
126 | "for i in range(len(x)): # O(n)\n",
127 | " for j in range(len(x)): # O(n)\n",
128 | " fasdfsac # O(1)\n",
129 | " sdfasd # O(1)\n",
130 | " dfasd # O(1)"
131 | ]
132 | },
133 | {
134 | "cell_type": "code",
135 | "execution_count": 21,
136 | "metadata": {},
137 | "outputs": [],
138 | "source": [
139 | "def linear_search(x, k):\n",
140 | " for i in range(len(x)):\n",
141 | " if x[i] == k:\n",
142 | " return i\n",
143 | " return 'NA'"
144 | ]
145 | },
146 | {
147 | "cell_type": "code",
148 | "execution_count": 28,
149 | "metadata": {},
150 | "outputs": [],
151 | "source": [
152 | "def binary_search(lst, search):\n",
153 | " low = 0\n",
154 | " high = len(lst) - 1\n",
155 | " \n",
156 | " while low <= high:\n",
157 | " mid = (low + high) // 2\n",
158 | " guess = lst[mid]\n",
159 | " \n",
160 | " if guess == search:\n",
161 | " return mid\n",
162 | " elif guess > search:\n",
163 | " high = mid - 1\n",
164 | " else:\n",
165 | " low = mid + 1\n",
166 | " return 'NA' "
167 | ]
168 | },
169 | {
170 | "cell_type": "code",
171 | "execution_count": 29,
172 | "metadata": {},
173 | "outputs": [
174 | {
175 | "name": "stdout",
176 | "output_type": "stream",
177 | "text": [
178 | "444 ns ± 20.7 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)\n"
179 | ]
180 | }
181 | ],
182 | "source": [
183 | "%%timeit\n",
184 | "linear_search([1, 5, 42, 414, 1000], 1000)"
185 | ]
186 | },
187 | {
188 | "cell_type": "code",
189 | "execution_count": 31,
190 | "metadata": {},
191 | "outputs": [
192 | {
193 | "name": "stdout",
194 | "output_type": "stream",
195 | "text": [
196 | "CPU times: user 5 µs, sys: 1e+03 ns, total: 6 µs\n",
197 | "Wall time: 8.11 µs\n"
198 | ]
199 | },
200 | {
201 | "data": {
202 | "text/plain": [
203 | "4"
204 | ]
205 | },
206 | "execution_count": 31,
207 | "metadata": {},
208 | "output_type": "execute_result"
209 | }
210 | ],
211 | "source": [
212 | "%%timeit\n",
213 | "binary_search(lst=[1, 5, 42, 414, 1000], search=1000)"
214 | ]
215 | },
216 | {
217 | "cell_type": "code",
218 | "execution_count": 32,
219 | "metadata": {},
220 | "outputs": [],
221 | "source": [
222 | "import numpy as np"
223 | ]
224 | },
225 | {
226 | "cell_type": "code",
227 | "execution_count": 35,
228 | "metadata": {},
229 | "outputs": [],
230 | "source": [
231 | "x = np.linspace(0, 2, 100000)"
232 | ]
233 | },
234 | {
235 | "cell_type": "code",
236 | "execution_count": 36,
237 | "metadata": {},
238 | "outputs": [
239 | {
240 | "name": "stdout",
241 | "output_type": "stream",
242 | "text": [
243 | "28.5 ms ± 856 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)\n"
244 | ]
245 | }
246 | ],
247 | "source": [
248 | "%%timeit\n",
249 | "linear_search(x, 1000)"
250 | ]
251 | },
252 | {
253 | "cell_type": "code",
254 | "execution_count": 37,
255 | "metadata": {},
256 | "outputs": [
257 | {
258 | "name": "stdout",
259 | "output_type": "stream",
260 | "text": [
261 | "9.16 µs ± 128 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)\n"
262 | ]
263 | }
264 | ],
265 | "source": [
266 | "%%timeit\n",
267 | "binary_search(x, search=1000)"
268 | ]
269 | },
270 | {
271 | "cell_type": "code",
272 | "execution_count": 43,
273 | "metadata": {},
274 | "outputs": [],
275 | "source": [
276 | "d = {'паша': 792693251124, 'спасательная': 911, 'максим': 79269325823}"
277 | ]
278 | },
279 | {
280 | "cell_type": "code",
281 | "execution_count": 46,
282 | "metadata": {},
283 | "outputs": [
284 | {
285 | "data": {
286 | "text/plain": [
287 | "dict_keys(['паша', 'спасательная', 'максим'])"
288 | ]
289 | },
290 | "execution_count": 46,
291 | "metadata": {},
292 | "output_type": "execute_result"
293 | }
294 | ],
295 | "source": [
296 | "d.keys()"
297 | ]
298 | },
299 | {
300 | "cell_type": "code",
301 | "execution_count": 48,
302 | "metadata": {},
303 | "outputs": [
304 | {
305 | "data": {
306 | "text/plain": [
307 | "dict_values([792693251124, 911, 79269325823])"
308 | ]
309 | },
310 | "execution_count": 48,
311 | "metadata": {},
312 | "output_type": "execute_result"
313 | }
314 | ],
315 | "source": [
316 | "d.values()"
317 | ]
318 | },
319 | {
320 | "cell_type": "code",
321 | "execution_count": 49,
322 | "metadata": {},
323 | "outputs": [
324 | {
325 | "data": {
326 | "text/plain": [
327 | "dict_items([('паша', 792693251124), ('спасательная', 911), ('максим', 79269325823)])"
328 | ]
329 | },
330 | "execution_count": 49,
331 | "metadata": {},
332 | "output_type": "execute_result"
333 | }
334 | ],
335 | "source": [
336 | "d.items()"
337 | ]
338 | },
339 | {
340 | "cell_type": "code",
341 | "execution_count": 40,
342 | "metadata": {},
343 | "outputs": [
344 | {
345 | "data": {
346 | "text/plain": [
347 | "911"
348 | ]
349 | },
350 | "execution_count": 40,
351 | "metadata": {},
352 | "output_type": "execute_result"
353 | }
354 | ],
355 | "source": [
356 | "d['спасательная']"
357 | ]
358 | },
359 | {
360 | "cell_type": "code",
361 | "execution_count": 42,
362 | "metadata": {},
363 | "outputs": [],
364 | "source": [
365 | "d = {(1, 2): 'sdfasd'}"
366 | ]
367 | },
368 | {
369 | "cell_type": "code",
370 | "execution_count": null,
371 | "metadata": {},
372 | "outputs": [],
373 | "source": []
374 | }
375 | ],
376 | "metadata": {
377 | "kernelspec": {
378 | "display_name": "Python 3",
379 | "language": "python",
380 | "name": "python3"
381 | },
382 | "language_info": {
383 | "codemirror_mode": {
384 | "name": "ipython",
385 | "version": 3
386 | },
387 | "file_extension": ".py",
388 | "mimetype": "text/x-python",
389 | "name": "python",
390 | "nbconvert_exporter": "python",
391 | "pygments_lexer": "ipython3",
392 | "version": "3.8.5"
393 | }
394 | },
395 | "nbformat": 4,
396 | "nbformat_minor": 4
397 | }
398 |
--------------------------------------------------------------------------------
/sem06_dict/README.md:
--------------------------------------------------------------------------------
1 | ## Материалы к неделям 5-6 (словари и множества)
2 |
3 | * [Материалы семинара sem05](https://github.com/hse-econ-data-science/dap_2022-23/tree/main/sem05_dict)
4 | * [Материалы семинара sem06](https://github.com/hse-econ-data-science/dap_2022-23/tree/main/sem06_dict)
5 |
6 | __Задачи для семинаров и самостоятельного решения:__
7 |
8 | Обратите внимание, что эти наборы задач практически полностью соответствуют [рекомендованному вам курсу с Coursera.](https://www.coursera.org/learn/python-osnovy-programmirovaniya#syllabus) Постарайтесь решить из каждого набора хотябы 50%. Если вам удобнее решать задачи на Coursera, тогда делайте это там.
9 |
10 | * [Задачи на множества](https://official.contest.yandex.ru/contest/24447/enter/) (первая половина 7 недели курса)
11 | * [Задачи на словари](https://official.contest.yandex.ru/contest/24449/enter/) (вторая половина 7 недели курса)
12 |
13 | Похожие задачи ждут вас на второй самостоятельной работе.
14 |
15 | __Ещё материалы:__
16 |
17 | * Уроки про [множества](http://pythontutor.ru/lessons/sets/) и [словари](http://pythontutor.ru/lessons/dicts/) на pythontutor
18 | * Краткие коспекты на pythonworld про [словари](https://pythonworld.ru/tipy-dannyx-v-python/slovari-dict-funkcii-i-metody-slovarej.html) и [множества](https://pythonworld.ru/tipy-dannyx-v-python/mnozhestva-set-i-frozenset.html)
19 | * Если вы хотите немного углубиться в алгоритмическую составляющую, прочитайте книгу Грокаем Алгоритмы с примерами кода на python, она великолепная и очень просто написана с примерами на python
20 |
--------------------------------------------------------------------------------
/sem06_dict/sem06_set_dict_problem_set.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "# Анализ данных на Python\n",
8 | "\n",
9 | "### Семинар 6. Множества и словари. Задачи."
10 | ]
11 | },
12 | {
13 | "cell_type": "code",
14 | "execution_count": null,
15 | "metadata": {},
16 | "outputs": [],
17 | "source": [
18 | "def test_problem(func, test_data):\n",
19 | " for inputs, true_answer in test_data:\n",
20 | " answer = func(inputs)\n",
21 | " assert answer == true_answer, f'Expected {true_answer}, got {answer}. Input: {inputs}'\n",
22 | " print(\"OK!\")\n",
23 | " \n",
24 | "def test_problem_13(func, test_data):\n",
25 | " for inputs, true_answer in test_data:\n",
26 | " answer = func(*inputs)\n",
27 | " assert answer == true_answer, f'Expected {true_answer}, got {answer}. Input: {inputs}'\n",
28 | " print(\"OK!\")"
29 | ]
30 | },
31 | {
32 | "cell_type": "markdown",
33 | "metadata": {},
34 | "source": [
35 | "## Задачка 1: магазин\n",
36 | "Вам предостоит обработать базу данных о продажах некоторого интернет-магазина. База данных представляет собой набор кортежей, в каждом кортеже три элемента: (Покупатель, товар, количество), где Покупатель — имя покупателя (строка без пробелов), товар — название товара (строка без пробелов), количество — количество приобретенных единиц товара.\n",
37 | "Создайте словарь, ключами которого являются имена покупателей, а значениями — словари, ключами которых являются названия товаров, а значениями — количество единиц этого товара, которые купил этот покупатель.\n",
38 | "Напишите функцию aggregate, принимающую некоторое количество набор кортежей из базы данных и возвращающую сводную информацию в виде словаря."
39 | ]
40 | },
41 | {
42 | "cell_type": "code",
43 | "execution_count": null,
44 | "metadata": {},
45 | "outputs": [],
46 | "source": [
47 | "def aggregate(names):\n",
48 | " \n",
49 | " # ┬─┬ ノ( ゜-゜ノ)\n",
50 | " \n",
51 | " # (╯° □°)╯︵ ┻━┻\n",
52 | "\n",
53 | " return ..."
54 | ]
55 | },
56 | {
57 | "cell_type": "code",
58 | "execution_count": null,
59 | "metadata": {},
60 | "outputs": [],
61 | "source": [
62 | "AGG_TESTS_DATA = [\n",
63 | " ([(\"Petrov\",\"pens\",5), (\"Ivanov\",\"marker\",3), (\"Ivanov\",\"paper\",7), \n",
64 | " (\"Petrov\",\"envelope\",20), (\"Ivanov\",\"envelope\",5)], \n",
65 | " {'Petrov': {'pens': 5, 'envelope': 20}, \n",
66 | " 'Ivanov': {'marker': 3, 'paper': 7, 'envelope': 5}}),\n",
67 | " \n",
68 | " ([(\"Ivanov\",\"aaa\",1), (\"Petrov\",\"aaa\",2), (\"Sidorov\",\"aaa\",3), (\"Ivanov\",\"aaa\",6), \n",
69 | " (\"Petrov\",\"aaa\",7), (\"Sidorov\",\"aaa\",8), (\"Ivanov\",\"bbb\",3), (\"Petrov\",\"bbb\",7), \n",
70 | " (\"Sidorov\",\"aaa\",345), (\"Ivanov\",\"ccc\",45), (\"Petrov\",\"ddd\",34), \n",
71 | " (\"Ziborov\",\"eee\",234), (\"Ivanov\",\"aaa\",45)],\n",
72 | " {'Ivanov': {'aaa': 52, 'bbb': 3, 'ccc': 45},\n",
73 | " 'Petrov': {'aaa': 9, 'bbb': 7, 'ddd': 34},\n",
74 | " 'Sidorov': {'aaa': 356},\n",
75 | " 'Ziborov': {'eee': 234}})\n",
76 | "]\n",
77 | "test_problem(aggregate, AGG_TESTS_DATA)"
78 | ]
79 | },
80 | {
81 | "cell_type": "markdown",
82 | "metadata": {},
83 | "source": [
84 | "## Задачка 2: одинаковые строки\n",
85 | "\n",
86 | "Напишите функцию, которая приенимает на вход две строки и возвращает True, если перестановкой символов можно получить вторую строку из первой."
87 | ]
88 | },
89 | {
90 | "cell_type": "code",
91 | "execution_count": null,
92 | "metadata": {},
93 | "outputs": [],
94 | "source": [
95 | "def is_isomorphic(a, b):\n",
96 | " return True"
97 | ]
98 | },
99 | {
100 | "cell_type": "code",
101 | "execution_count": null,
102 | "metadata": {},
103 | "outputs": [],
104 | "source": [
105 | "TEST_DATA = [\n",
106 | " (('foo', 'bar'), False),\n",
107 | " (('foo', 'oof'), True),\n",
108 | " (('a', 'a'), True),\n",
109 | " (('aaa', 'aaab'), False),\n",
110 | " (('140', '041'), True),\n",
111 | "]\n",
112 | "\n",
113 | "test_problem_13(is_isomorphic, TEST_DATA)"
114 | ]
115 | },
116 | {
117 | "cell_type": "markdown",
118 | "metadata": {},
119 | "source": [
120 | "## Задачка 3. Парковка\n",
121 | "\n",
122 | "Напишите функцию, которая принимает на вход словарь, где ключом является индекс парковочного места, а значением True/False (занято/свободно). Вторым аргументом функция должна принимать индекс места, которое хочется занять.\n",
123 | "Функция должна возращать True, если место можно занять и модифицировать словарь, занимая место. Функция возвращает False, если место уже занято."
124 | ]
125 | },
126 | {
127 | "cell_type": "code",
128 | "execution_count": null,
129 | "metadata": {},
130 | "outputs": [],
131 | "source": [
132 | "def parking_lot(data, index):\n",
133 | " return True"
134 | ]
135 | },
136 | {
137 | "cell_type": "code",
138 | "execution_count": null,
139 | "metadata": {},
140 | "outputs": [],
141 | "source": [
142 | "parking = {0: False, 1: False, 2: False, 3: False}\n",
143 | "\n",
144 | "TEST_DATA = [\n",
145 | " ((parking, 0), True),\n",
146 | " ((parking, 0), False),\n",
147 | " ((parking, 1), True),\n",
148 | " ((parking, 3), True),\n",
149 | "]\n",
150 | "\n",
151 | "test_problem_13(parking_lot, TEST_DATA)"
152 | ]
153 | },
154 | {
155 | "cell_type": "markdown",
156 | "metadata": {},
157 | "source": [
158 | "## Задачка 4. Последовательность ДНК.\n",
159 | "\n",
160 | "Последовательность ДНК содержит четыре вида символов: 'A', 'C', 'G', и 'T'.\n",
161 | "Напишите функцию, которая будет возращать все подпоследовательности длины 10, которые встретились чаще одного раза."
162 | ]
163 | },
164 | {
165 | "cell_type": "code",
166 | "execution_count": null,
167 | "metadata": {},
168 | "outputs": [],
169 | "source": [
170 | "def repeated_dna(s):\n",
171 | " return []"
172 | ]
173 | },
174 | {
175 | "cell_type": "code",
176 | "execution_count": null,
177 | "metadata": {},
178 | "outputs": [],
179 | "source": [
180 | "TEST_DATA = [\n",
181 | " ('AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT', ['AAAAACCCCC','CCCCCAAAAA']),\n",
182 | " ('AAAAAAAAAAAAA', ['AAAAAAAAAA']),\n",
183 | "]\n",
184 | "\n",
185 | "test_problem(repeated_dna, TEST_DATA)"
186 | ]
187 | }
188 | ],
189 | "metadata": {
190 | "kernelspec": {
191 | "display_name": "Python 3",
192 | "language": "python",
193 | "name": "python3"
194 | },
195 | "language_info": {
196 | "codemirror_mode": {
197 | "name": "ipython",
198 | "version": 3
199 | },
200 | "file_extension": ".py",
201 | "mimetype": "text/x-python",
202 | "name": "python",
203 | "nbconvert_exporter": "python",
204 | "pygments_lexer": "ipython3",
205 | "version": "3.9.2"
206 | }
207 | },
208 | "nbformat": 4,
209 | "nbformat_minor": 2
210 | }
211 |
--------------------------------------------------------------------------------
/sem07_wow/README.md:
--------------------------------------------------------------------------------
1 | # Cudly sniffle
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheat.py:
--------------------------------------------------------------------------------
1 | import os
2 | from shutil import copyfile
3 |
4 | def repl(s1):
5 | s2 = []
6 | for line in s1:
7 | if line.startswith('#'):
8 | continue
9 | if line.find('//') != -1:
10 | line = line[:line.find('//')]
11 | s2.append(line)
12 | syms = set('+-*/%^:;"\'<>!=[](){}&|.,?')
13 | prev = ''
14 | ans = []
15 | s = ''.join(s2).replace('\n', '')
16 | s = s.replace(' ', '')
17 | s = s.replace('\t', '')
18 | for c in s:
19 | if c not in syms and prev != '#':
20 | ans.append('#')
21 | prev = '#'
22 | elif c in syms:
23 | ans.append(c)
24 | prev = c
25 | return ''.join(ans)
26 |
27 | def check(s1, s2):
28 | return repl(s1) == repl(s2)
29 |
30 | dirs = os.listdir()
31 | sols = {}
32 | badass = {}
33 | stop = 10**9
34 | for ndir in range(len(dirs)):
35 | if stop <= 0:
36 | break
37 |
38 | if dirs[ndir] == 'cheat.py' or dirs[ndir] == 'log.txt' or dirs[ndir] == 'lex_cheat.py':
39 | continue
40 | tfiles = os.listdir(dirs[ndir])
41 | files = []
42 | for file in tfiles:
43 | if True:#file.find('OK') != -1:
44 | files.append(file)
45 |
46 | for pdir in range(ndir):
47 | if stop <= 0:
48 | break
49 | if dirs[pdir] == 'cheat.py' or dirs[pdir] == 'log.txt' or dirs[pdir] == 'lex_cheat.py':
50 | continue
51 | pfiles = sols[dirs[pdir]]
52 | for nfn in files:
53 | p1 = dirs[ndir] + '/' + nfn
54 | #print(p1)
55 | s1 = os.path.getsize(p1)
56 | for pfn in pfiles:
57 | if nfn[0] == pfn[0]:
58 | p2 = dirs[pdir] + '/' + pfn
59 | #print(p2)
60 | s2 = os.path.getsize(p2)
61 | fn = open(p1, 'r', encoding = 'utf8')
62 | fp = open(p2, 'r', encoding = 'utf8')
63 | st1 = fn.readlines()
64 | st2 = fp.readlines()
65 | fn.close()
66 | fp.close()
67 | if s1 == s2:
68 | flag = False
69 | if len(st1) == len(st2):
70 | flag = True
71 | for i in range(len(st1)):
72 | if st1[i].strip() != st2[i].strip():
73 | flag = False
74 |
75 | if flag:
76 | pair = dirs[ndir], dirs[pdir]
77 | if pair not in badass:
78 | badass[pair] = set()
79 | badass[pair].add(pfn[0])
80 | print('146%', dirs[ndir], dirs[pdir], pfn[0], sep = '\t')
81 | stop -= 1
82 | #if check(st1, st2):
83 | # print('prob', dirs[ndir], dirs[pdir], pfn[0], sep = '\t')
84 |
85 |
86 | sols[dirs[ndir]] = files
87 | pass
88 | pass
89 | ans = []
90 | for pair in badass:
91 | ans.append((badass[pair], pair))
92 | ans.sort(reverse=True, key=lambda x: (len(x[0]), x[1]))
93 | fout = open('log.txt', 'w', encoding='utf8')
94 | for now in ans:
95 | print(now[1][0], now[1][1], len(now[0]), ''.join(sorted(now[0])), sep='\t', file=fout)
96 | fout.close()
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/1.py:
--------------------------------------------------------------------------------
1 | s = input()
2 | if not(s.find('f') == -1):
3 | if s.find('f') == s.rfind('f'):
4 | print(s.find('f'))
5 | else:
6 | print(s.find('f'), end=' ')
7 | print(s.rfind('f'))
8 |
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/10.py:
--------------------------------------------------------------------------------
1 | n = int(input())
2 | partial_factorial = 1
3 | partial_sum = 0
4 | for i in range(1, n + 1):
5 | partial_factorial *= i
6 | partial_sum += partial_factorial
7 | print(partial_sum)
8 |
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/11.py:
--------------------------------------------------------------------------------
1 | n = 8
2 | x = []
3 | y = []
4 | for i in range(n):
5 | new_x, new_y = [int(s) for s in input().split()]
6 | x.append(new_x)
7 | y.append(new_y)
8 |
9 | correct = True
10 | for i in range(n):
11 | for j in range(i + 1, n):
12 | if x[i] == x[j] or y[i] == y[j]:
13 | correct = False
14 | if abs(x[i] - x[j]) == abs(y[i] - y[j]):
15 | correct = False
16 |
17 | if correct:
18 | print('NO')
19 | else:
20 | print('YES')
21 |
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/12.py:
--------------------------------------------------------------------------------
1 | a = [int(s) for s in input().split()]
2 | k = int(input())
3 | for i in range(k + 1, len(a)):
4 | a[i - 1] = a[i]
5 | a.pop()
6 | print(' '.join([str(i) for i in a]))
7 |
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/13.py:
--------------------------------------------------------------------------------
1 | myList = list(map(int, input().split()))
2 | count = 0
3 | for i in range(1, len(myList) - 1):
4 | if myList[i] > myList[i - 1] and myList[i] > myList[i + 1]:
5 | count += 1
6 | print(count)
7 |
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/14.py:
--------------------------------------------------------------------------------
1 | tot_cont = []
2 | grade9 = []
3 | grade10 = []
4 | grade11 = []
5 | tot_point = []
6 | file = open('input.txt', 'r', encoding='utf-8')
7 | for line in file:
8 | cont = list(line.split())
9 | tot_cont.append(cont)
10 | tot_cont.sort(key=lambda x: int(x[2]))
11 | max9 = 80
12 | for i in tot_cont:
13 | if int(i[2]) == 9:
14 | grade9.append(i[3])
15 | elif int(i[2]) == 10:
16 | grade10.append(i[3])
17 | elif int(i[2]) == 11:
18 | grade11.append(i[3])
19 | grade9.sort()
20 | grade10.sort()
21 | grade11.sort()
22 | grade9 = grade9[::-1]
23 | grade10 = grade10[::-1]
24 | grade11 = grade11[::-1]
25 | max9 = grade9[0]
26 | max10 = grade10[0]
27 | max11 = grade11[0]
28 | kol9 = 0
29 | kol10 = 0
30 | kol11 = 0
31 | for i in range(0, len(grade9)):
32 | if grade9[i] == max9:
33 | kol9 += 1
34 | for i in range(0, len(grade10)):
35 | if grade10[i] == max10:
36 | kol10 += 1
37 | for i in range(0, len(grade11)):
38 | if grade11[i] == max11:
39 | kol11 += 1
40 | print(kol9, kol10, kol11)
41 |
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/15.py:
--------------------------------------------------------------------------------
1 | yes = set(map(str, range(1, int(input()) + 1)))
2 | for line in iter(input, 'HELP'):
3 | guesses = yes.intersection(line.split())
4 | if len(guesses) > (len(yes) - len(guesses)):
5 | print('YES')
6 | yes = guesses
7 | else:
8 | print('NO')
9 | yes -= guesses
10 | print(*sorted(yes, key=int))
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/16.py:
--------------------------------------------------------------------------------
1 | yes_pile = set(map(str, range(1, int(input()) + 1)))
2 | for line in iter(input, 'HELP'):
3 | guesses = yes_pile.intersection(line.split())
4 | if len(guesses) > (len(yes_pile) - len(guesses)):
5 | print('YES')
6 | yes_pile = guesses
7 | else:
8 | print('NO')
9 | yes_pile -= guesses
10 | print(*sorted(yes_pile, key=int))
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/17.py:
--------------------------------------------------------------------------------
1 | k = int(input())
2 | n = set(i for i in range(1, k + 1))
3 | while True:
4 | s = input()
5 | if s == "HELP":
6 | break
7 | s = set(map(int, s.split()))
8 | if len(n & s) > len(n) / 2:
9 | print("YES")
10 | n &= s
11 | else:
12 | print("NO")
13 | n -= s
14 | print(*sorted(n))
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/18.py:
--------------------------------------------------------------------------------
1 | n = int(input())
2 | k = set(i for i in range(1, n + 1))
3 | while True:
4 | s = input()
5 | if s == "HELP":
6 | break
7 | s = set(map(int, s.split()))
8 | if len(k & s) > len(k) / 2:
9 | print("YES")
10 | k &= s
11 | else:
12 | print("NO")
13 | k -= s
14 | print(*sorted(k))
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/19.py:
--------------------------------------------------------------------------------
1 | n = int(input())
2 | sres = set(range(1, n + 1))
3 | while True:
4 | cur = input()
5 | if cur == 'HELP':
6 | break
7 | cur = {int(x) for x in cur.split()}
8 | if len(sres & cur) > len(sres) / 2:
9 | print('YES')
10 | sres &= cur
11 | else:
12 | print('NO')
13 | sres -= cur
14 | print(' '.join([str(x) for x in sorted(sres)]))
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/2.py:
--------------------------------------------------------------------------------
1 | s = input()
2 | if not(s.find('f') == -1):
3 | if s.find('f') == s.rfind('f'):
4 | print(s.find('f'))
5 | else:
6 | print(s.find('f'), end=' ')
7 | print(s.rfind('f'))
8 |
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/20.py:
--------------------------------------------------------------------------------
1 | n = int(input())
2 | a = set(range(1, n + 1))
3 | b = a
4 | while True:
5 | c = input()
6 | if c == 'HELP':
7 | break
8 | c = {int(x) for x in c.split()}
9 | if len(b & c) > len(b) / 2:
10 | print('YES')
11 | b &= c
12 | else:
13 | print('NO')
14 | b -= c
15 |
16 | print(' '.join([str(x) for x in sorted(b)]))
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/21.py:
--------------------------------------------------------------------------------
1 | n = int(input())
2 | pn = set(range(1, n + 1))
3 | while True:
4 | g = input()
5 | if g == 'HELP':
6 | break
7 | g = {int(x) for x in g.split()}
8 | if len(pn & g) > len(pn) / 2:
9 | print('YES')
10 | pn &= g
11 | else:
12 | pn -= g
13 | print('NO')
14 | print(' '.join([str(x) for x in sorted(pn)]))
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/22.py:
--------------------------------------------------------------------------------
1 | n = int(input())
2 | accents = {}
3 | for i in range(n):
4 | word = input()
5 | base_form = word.lower()
6 | if base_form not in accents:
7 | accents[base_form] = set()
8 | accents[base_form].add(word)
9 | errors = 0
10 | sent = input().split()
11 | for word in sent:
12 | base_form = word.lower()
13 | if base_form in accents and word not in accents[base_form] \
14 | or len([l for l in word if l.isupper()]) != 1:
15 | errors += 1
16 | print(errors)
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/23.py:
--------------------------------------------------------------------------------
1 | n = int(input())
2 | acnts = {}
3 | for i in range(n):
4 | word = input()
5 | base_frm = word.lower()
6 | if base_frm not in acnts:
7 | acnts[base_frm] = set()
8 | acnts[base_frm].add(word)
9 |
10 | errors = 0
11 | sent = input().split()
12 | for word in sent:
13 | base_frm = word.lower()
14 | if (not (not (base_frm in acnts and word not in acnts[base_frm]) and not (
15 | len([l for l in word if l.isupper()]) != 1))):
16 | errors += 1
17 | print(errors)
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/24.py:
--------------------------------------------------------------------------------
1 | n = int(input())
2 | accents = {}
3 | for i in range(n):
4 | word = input()
5 | form = word.lower()
6 | if form not in accents:
7 | accents[form] = set()
8 | accents[form].add(word)
9 | mistakes = 0
10 | line = input().strip().split()
11 | for word in line:
12 | form = word.lower()
13 | if form in accents and word not in accents[form] or \
14 | len([elem for elem in word if elem.isupper()]) != 1:
15 | mistakes += 1
16 | print(mistakes)
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/25.py:
--------------------------------------------------------------------------------
1 | n = int(input())
2 | a = {}
3 | for i in range(n):
4 | word = input()
5 | b = word.lower()
6 | if b not in a:
7 | a[b] = set()
8 | a[b].add(word)
9 | errors = 0
10 | s = input().split()
11 | for word in s:
12 | b = word.lower()
13 | le = len([l for l in word if l.isupper()])
14 | if (b in a and word not in a[b] or le != 1):
15 | errors += 1
16 | print(errors)
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/26.py:
--------------------------------------------------------------------------------
1 | n = int(input())
2 | a = {}
3 | for i in range(n):
4 | word = input()
5 | b = word.lower()
6 | if b not in a:
7 | a[b] = set()
8 | a[b].add(word)
9 | errors = 0
10 | s = input().split()
11 | for word in s:
12 | b = word.lower()
13 | le = len([l for l in word if l.isupper()])
14 | if (b in a and word not in a[b] or le != 1):
15 | errors += 1
16 | print(errors)
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/27.py:
--------------------------------------------------------------------------------
1 | n = int(input())
2 | a = {}
3 | for i in range(n):
4 | word = input()
5 | base = word.lower()
6 | if base not in a:
7 | a[base] = set()
8 | a[base].add(word)
9 |
10 | mistakes = 0
11 | sent = input().split()
12 | for word in sent:
13 | base = word.lower()
14 | if base in a and word not in a[base]:
15 | mistakes += 1
16 | elif len([l for l in word if l.isupper()]) != 1:
17 | mistakes += 1
18 | print(mistakes)
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/28.py:
--------------------------------------------------------------------------------
1 | n = int(input())
2 | a = dict()
3 | for i in range(n):
4 | word = input()
5 | base_form = word.lower()
6 | if base_form not in a:
7 | a[base_form] = set()
8 | a[base_form].add(word)
9 | errors = 0
10 | s = input().split()
11 | for word in s:
12 | base_form = word.lower()
13 | if base_form in a and word not in a[base_form]:
14 | errors += 1
15 | elif len([l for l in word if l.isupper()]) != 1:
16 | errors += 1
17 | print(errors)
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/29.py:
--------------------------------------------------------------------------------
1 | n = int(input())
2 | accents = {}
3 | for i in range(n):
4 | word = input()
5 | base_form = word.lower()
6 | if base_form not in accents:
7 | accents[base_form] = set()
8 | accents[base_form].add(word)
9 | errors = 0
10 | sent = input().split()
11 | for word in sent:
12 | base_form = word.lower()
13 | if base_form in accents and word not in accents[base_form] \
14 | or len([l for l in word if l.isupper()]) != 1:
15 | errors += 1
16 | print(errors)
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/3.py:
--------------------------------------------------------------------------------
1 | s = input()
2 | a = s[:s.find('h') + 1]
3 | b = s[s.find('h') + 1:s.rfind('h')]
4 | c = s[s.rfind('h'):]
5 | s = a + b.replace('h', 'H') + c
6 | print(s)
7 |
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/30.py:
--------------------------------------------------------------------------------
1 | k = int(input())
2 | accents = {}
3 | for i in range(k):
4 | word = input()
5 | base_form = word.lower()
6 | if base_form not in accents:
7 | accents[base_form] = set()
8 | accents[base_form].add(word)
9 |
10 | errors = 0
11 | sent = input().split()
12 | for word in sent:
13 | base_form = word.lower()
14 | if (base_form in accents and word not in accents[base_form] or
15 | len([l for l in word if l.isupper()]) != 1):
16 | errors += 1
17 | print(errors)
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/31.py:
--------------------------------------------------------------------------------
1 | n = int(input())
2 | acnts = {}
3 | for i in range(n):
4 | word = input()
5 | base_frm = word.lower()
6 | if base_frm not in acnts:
7 | acnts[base_frm] = set()
8 | acnts[base_frm].add(word)
9 |
10 | errors = 0
11 | sent = input().split()
12 | for word in sent:
13 | base_frm = word.lower()
14 | if (not (not (base_frm in acnts and word not in acnts[base_frm]) and not (
15 | len([l for l in word if l.isupper()]) != 1))):
16 | errors += 1
17 | print(errors)
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/32.py:
--------------------------------------------------------------------------------
1 | n = int(input())
2 | accents = {}
3 | for i in range(n):
4 | word = input()
5 | base_form = word.lower()
6 | if base_form not in accents:
7 | accents[base_form] = set()
8 | accents[base_form].add(word)
9 |
10 | errors = 0
11 | sent = input().split()
12 | for word in sent:
13 | base_form = word.lower()
14 | if base_form in accents and word not in accents[base_form] \
15 | or len([l for l in word if l.isupper()]) != 1:
16 | errors += 1
17 | print(errors)
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/33.py:
--------------------------------------------------------------------------------
1 | n = int(input())
2 | a = {}
3 | for i in range(n):
4 | word = input()
5 | b = word.lower()
6 | if b not in a:
7 | a[b] = set()
8 | a[b].add(word)
9 |
10 | err = 0
11 | sent = input().split()
12 | for word in sent:
13 | b = word.lower()
14 | if b in a and word not in a[b] \
15 | or len([l for l in word if l.isupper()]) != 1:
16 | err += 1
17 | print(err)
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/34.py:
--------------------------------------------------------------------------------
1 | inp = open('input.txt', 'r', encoding='utf-8')
2 | out = open('output.txt', 'w', encoding='utf-8')
3 |
4 |
5 | def count_uppercase(s):
6 | count = 0
7 | for letter in s:
8 | if letter.isupper():
9 | count += 1
10 | return count
11 |
12 |
13 | dict = set()
14 | n = int(input())
15 | for i in range(n):
16 | word = input()
17 | dict.add(word)
18 | dict.add(word.upper())
19 | to_check = input().split()
20 | count_mistakes = 0
21 | for word in to_check:
22 | if word in dict and count_uppercase(word) == 1:
23 | continue
24 | if count_uppercase(word) == 1:
25 | if not word.upper() in dict:
26 | continue
27 | count_mistakes += 1
28 | print(count_mistakes)
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/35.py:
--------------------------------------------------------------------------------
1 | infile = open('input.txt', 'r', encoding='utf-8')
2 | oufile = open('output.txt', 'w', encoding='utf-8')
3 |
4 |
5 | def count_upper(s):
6 | count = 0
7 | for letter in s:
8 | if letter.isupper():
9 | count += 1
10 | return count
11 |
12 |
13 | dict = set()
14 | n = int(input())
15 | for i in range(n):
16 | slovo = str(input())
17 | dict.add(slovo)
18 | dict.add(slovo.upper())
19 | check = input().split()
20 | mistakes = 0
21 | for slovo in check:
22 | if slovo in dict and count_upper(slovo) == 1:
23 | continue
24 | if count_upper(slovo) == 1:
25 | if not slovo.upper() in dict:
26 | continue
27 | mistakes += 1
28 | print(mistakes)
29 | # finally)) 0:40 a.m.
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/36.py:
--------------------------------------------------------------------------------
1 | names = list()
2 | votes = list()
3 | sumVotes = 0
4 | file = open('input.txt', 'r', encoding='utf-8')
5 | for line in file:
6 | line = line.split()
7 | partyName = ' '.join(line[:-1])
8 | partyVotes = int(line[-1])
9 | names.append(partyName)
10 | votes.append(partyVotes)
11 | sumVotes += partyVotes
12 | file.close()
13 | mandates = list()
14 | fracPart = []
15 | sumMandates = 0
16 | for i in range(len(names)):
17 | partyMandates = (votes[i] * 450) / sumVotes
18 | sumMandates += int(partyMandates)
19 | mandates.append(int(partyMandates))
20 | fracPart.append(partyMandates - int(partyMandates))
21 | while sumMandates < 450:
22 | i = 0
23 | for j in range(1, len(fracPart)):
24 | if (fracPart[j] > fracPart[i]) or \
25 | (fracPart[j] == fracPart[i] and votes[j] > votes[i]):
26 | i = j
27 | mandates[i] += 1
28 | sumMandates += 1
29 | fracPart[i] = 0
30 | for k in range(len(names)):
31 | print(names[k], mandates[k])
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/37.py:
--------------------------------------------------------------------------------
1 | names = list()
2 | votes = list()
3 | sumVotes = 0
4 | inFile = open('input.txt')
5 | for line in inFile:
6 | line = line.split()
7 | partyName = ' '.join(line[:-1])
8 | partyVotes = int(line[-1])
9 | names.append(partyName)
10 | votes.append(partyVotes)
11 | sumVotes += partyVotes
12 | inFile.close()
13 |
14 | mandates = list()
15 | fracPart = []
16 | sumMandates = 0
17 | for i in range(len(names)):
18 | partyMandates = (votes[i] * 450) / sumVotes
19 | sumMandates += int(partyMandates)
20 | mandates.append(int(partyMandates))
21 | fracPart.append(partyMandates - int(partyMandates))
22 |
23 | while sumMandates < 450:
24 | i = 0
25 | for j in range(1, len(fracPart)):
26 | if (
27 | (fracPart[j] > fracPart[i]) or
28 | (fracPart[j] == fracPart[i] and votes[j] > votes[i])
29 | ):
30 | i = j
31 | mandates[i] += 1
32 | sumMandates += 1
33 | fracPart[i] = 0
34 |
35 | for k in range(len(names)):
36 | print(names[k], mandates[k])
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/38.py:
--------------------------------------------------------------------------------
1 | parties = list()
2 | votes = list()
3 | sumVotes = 0
4 | with open('input.txt', 'r', encoding='utf-8') as f:
5 | for line in f:
6 | line = line.split()
7 | partyName = ' '.join(line[:-1])
8 | partyVotes = int(line[-1])
9 | parties.append(partyName)
10 | votes.append(partyVotes)
11 | sumVotes += partyVotes
12 | mandates = list()
13 | frac = []
14 | sum_mandates = 0
15 | for i in range(len(parties)):
16 | partyMandates = (votes[i] * 450) / sumVotes
17 | sum_mandates += int(partyMandates)
18 | mandates.append(int(partyMandates))
19 | frac.append(partyMandates - int(partyMandates))
20 | while sum_mandates < 450:
21 | i = 0
22 | for j in range(1, len(frac)):
23 | if (frac[j] > frac[i]) or\
24 | (frac[j] == frac[i] and votes[j] > votes[i]):
25 | i = j
26 | mandates[i] += 1
27 | sum_mandates += 1
28 | frac[i] = 0
29 |
30 | for k in range(len(parties)):
31 | print(parties[k], mandates[k])
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/39.py:
--------------------------------------------------------------------------------
1 | names = list()
2 | votes = list()
3 | sumVotes = 0
4 | inFile = open('input.txt')
5 | for line in inFile:
6 | line = line.split()
7 | partyName = ' '.join(line[:-1])
8 | partyVotes = int(line[-1])
9 | names.append(partyName)
10 | votes.append(partyVotes)
11 | sumVotes += partyVotes
12 | inFile.close()
13 | mandates = list()
14 | fracPart = []
15 | sumMandates = 0
16 | for i in range(len(names)):
17 | partyMandates = (votes[i] * 450) / sumVotes
18 | sumMandates += int(partyMandates)
19 | mandates.append(int(partyMandates))
20 | fracPart.append(partyMandates - int(partyMandates))
21 | while sumMandates < 450:
22 | i = 0
23 | for j in range(1, len(fracPart)):
24 | if (fracPart[j] > fracPart[i]) or \
25 | (fracPart[j] == fracPart[i] and votes[j] > votes[i]):
26 | i = j
27 | mandates[i] += 1
28 | sumMandates += 1
29 | fracPart[i] = 0
30 | for k in range(len(names)):
31 | print(names[k], mandates[k])
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/4.py:
--------------------------------------------------------------------------------
1 | def power(a, n):
2 | if n == 0:
3 | return 1
4 | elif n > 0:
5 | i = 2
6 | b = a
7 | while i <= n:
8 | a = a * b
9 | i += 1
10 | return a
11 | else:
12 | i = 0
13 | b = a
14 | a = 1
15 | while i > n:
16 | a = a / b
17 | i -= 1
18 | return a
19 |
20 |
21 | a = float(input())
22 | n = int(input())
23 | print(power(a, n))
24 |
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/40.py:
--------------------------------------------------------------------------------
1 | import sys
2 |
3 |
4 | def A(inputsource, output):
5 | w = dict()
6 | for l in inputsource:
7 | for word in l.split():
8 | if word not in w:
9 | w[word] = 1
10 | else:
11 | w[word] += 1
12 | for i in sorted(w.items(), key=lambda x: (-x[1], x[0])):
13 | output.write(i[0] + '\n')
14 | return
15 |
16 |
17 | def main():
18 | A(sys.stdin, sys.stdout)
19 |
20 |
21 | main()
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/41.py:
--------------------------------------------------------------------------------
1 | import sys
2 |
3 |
4 | def Solving(inputsource, output):
5 | words = dict()
6 | for line in inputsource:
7 | for word in line.split():
8 | if word not in words:
9 | words[word] = 1
10 | else:
11 | words[word] += 1
12 | for i in sorted(words.items(), key=lambda x: (-x[1], x[0])):
13 | output.write(i[0] + '\n')
14 | return
15 |
16 |
17 | def main():
18 | Solving(sys.stdin, sys.stdout)
19 |
20 |
21 | main()
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/42.py:
--------------------------------------------------------------------------------
1 | inFile = open('input.txt', 'r', encoding='utf-8')
2 | lines = inFile.readlines()
3 | counter = {}
4 | for line in lines:
5 | line = line.split()
6 | for word in line:
7 | counter[word] = counter.get(word, 0) + 1
8 | items = (counter.items())
9 |
10 |
11 | def sorter(a):
12 | for number in a:
13 | return -a[1], a[0]
14 |
15 |
16 | for word in sorted(items, key=sorter):
17 | print(word[0])
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/43.py:
--------------------------------------------------------------------------------
1 | inFile = open('input.txt', 'r', encoding='utf=8')
2 | line_set = inFile.readlines()
3 | temp = {}
4 | for line in line_set:
5 | line = line.split()
6 | for word in line:
7 | temp[word] = temp.get(word, 0) + 1
8 | subj = (temp.items())
9 |
10 |
11 | def sort(a):
12 | for i in a:
13 | return -a[1], a[0]
14 |
15 |
16 | for word in sorted(subj, key=sort):
17 | print(word[0])
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/44.py:
--------------------------------------------------------------------------------
1 | t = input()
2 | t1 = int(t[0])
3 | t2 = int(t[1])
4 | m1 = int(t[3])
5 | m2 = int(t[4])
6 | h = 10 * t1 + t2
7 | if h <= 11:
8 | if h == 0:
9 | h += 12
10 | print(h, ':', m1, m2, ' a.m.', end='', sep='')
11 | else:
12 | if h > 12:
13 | h -= 12
14 | print(h, ':', m1, m2, ' p.m.', end='', sep='')
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/45.py:
--------------------------------------------------------------------------------
1 | s = input()
2 | h1 = int(s[0])
3 | h2 = int(s[1])
4 | h = 10 * h1 + h2
5 |
6 | m1 = int(s[3])
7 | m2 = int(s[4])
8 | m = 10 * m1 + m2
9 | if 11 >= h >= 0:
10 | if h == 0:
11 | h += 12
12 | print(h, ':', m1, m2, ' a.m.', end='', sep='')
13 | else:
14 | if h > 12:
15 | h -= 12
16 | print(h, ':', m1, m2, ' p.m.', end='', sep='')
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/46.py:
--------------------------------------------------------------------------------
1 | x = int(input())
2 | a = x // 100000 * 2
3 | b = x // 10000 % 10
4 | c = x // 1000 % 10 * 2
5 | d = x % 1000 // 100
6 | e = x % 100 // 10 * 2
7 | f = x % 10
8 | if a >= 9:
9 | a = a - 9
10 | if c >= 9:
11 | c = c - 9
12 | if e >= 9:
13 | e = e - 9
14 | sum = a + b + c + d + e + f
15 | if sum % 10 == 0:
16 | print('YES')
17 | else:
18 | print('NO')
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/47.py:
--------------------------------------------------------------------------------
1 | n = int(input())
2 | a = n // 100000 * 2
3 | b = n // 10000 % 10
4 | c = n // 1000 % 10 * 2
5 | d = n % 1000 // 100
6 | e = n % 100 // 10 * 2
7 | f = n % 10
8 | if (a >= 9):
9 | a = a - 9
10 | if (c >= 9):
11 | c = c - 9
12 | if (e >= 9):
13 | e = e - 9
14 | sum = a + b + c + d + e + f
15 | if (sum % 10 == 0):
16 | print('YES')
17 | else:
18 | print('NO')
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/48.py:
--------------------------------------------------------------------------------
1 | n = int(input())
2 | a = list(map(int, input().split()))
3 | ans = []
4 | mun = n + 1
5 | mux = 0
6 | top = []
7 | for i in range(n):
8 | if (a[i] % 10 == 5):
9 | ans.append((a[i], i))
10 | if (a[i] > mux):
11 | mux = a[i]
12 | muni = i
13 | elif (a[i] == mux):
14 | muni = min(muni, i)
15 | mux = -1
16 | for i in range(len(ans)):
17 | if (ans[i][1] == n - 1):
18 | continue
19 | if (a[ans[i][1] + 1] >= ans[i][0]):
20 | continue
21 | if (muni < ans[i][1]):
22 | mux = max(mux, ans[i][0])
23 | if (mux == -1):
24 | print(0)
25 | else:
26 | kol = 0
27 | for i in range(n):
28 | if (a[i] > mux):
29 | kol += 1
30 | print(kol + 1)
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/49.py:
--------------------------------------------------------------------------------
1 | n = int(input())
2 | l = list(map(int, input().split()))
3 | res = []
4 | am = n + 1
5 | mx = 0
6 | orl = []
7 | for i in range(n):
8 | if (l[i] % 10 == 5):
9 | res.append((l[i], i))
10 | if (l[i] > mx):
11 | mx = l[i]
12 | mn = i
13 | elif (l[i] == mx):
14 | mn = min(mn, i)
15 | mx = -1
16 | for i in range(len(res)):
17 | if (res[i][1] == n - 1):
18 | continue
19 | if (l[res[i][1] + 1] >= res[i][0]):
20 | continue
21 | if (mn < res[i][1]):
22 | mx = max(mx, res[i][0])
23 | if mx == -1:
24 | print(0)
25 | else:
26 | mount = 0
27 | for i in range(n):
28 | if l[i] > mx:
29 | mount += 1
30 | print(mount + 1)
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/5.py:
--------------------------------------------------------------------------------
1 | def power(a, n):
2 | if n == 0:
3 | return 1
4 | elif n > 0:
5 | i = 2
6 | b = a
7 | while i <= n:
8 | a = a * b
9 | i += 1
10 | return a
11 | else:
12 | i = 0
13 | b = a
14 | a = 1
15 | while i > n:
16 | a = a / b
17 | i -= 1
18 | return a
19 |
20 |
21 | a = float(input())
22 | n = int(input())
23 | print(power(a, n))
24 |
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/50.py:
--------------------------------------------------------------------------------
1 | n = int(input())
2 | s = ''
3 | summa = 0
4 | for i in range(1, n):
5 | s = s + str(i) + '*' + str(i + 1) + '+'
6 | summa = summa + i * (i + 1)
7 | s = s[:-1]
8 | print(s, summa, sep='=')
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/51.py:
--------------------------------------------------------------------------------
1 | n = int(input())
2 | s = ''
3 | suma = 0
4 | for i in range(1, n):
5 | s = s + str(i) + '*' + str(i + 1) + '+'
6 | suma = suma + i * (i + 1)
7 | s = s[:-1]
8 | print(s, suma, sep='=')
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/52.py:
--------------------------------------------------------------------------------
1 | n = int(input())
2 | s = ''
3 | summ = 0
4 | for i in range(1, n):
5 | s = s + str(i) + '*' + str(i + 1) + '+'
6 | summ = summ + i * (i + 1)
7 | s = s[:-1]
8 | print(s, summ, sep='=')
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/53.py:
--------------------------------------------------------------------------------
1 | def transpose(matrix, n):
2 | for i in range(n):
3 | for j in range(n):
4 | if i < j:
5 | matrix[i][j], matrix[j][i] =\
6 | matrix[j][i], matrix[i][j]
7 |
8 |
9 | n, k = map(int, input().split())
10 | matrix = [list(map(int, input().split())) for _ in range(n)]
11 | transpose(matrix, n)
12 | for i in range(n):
13 | matrix[i] = sorted(matrix[i], key=lambda x: [abs(x - k), x])
14 | transpose(matrix, n)
15 | for i in range(n):
16 | for j in range(n):
17 | print(matrix[i][j], end=' ')
18 | print()
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/54.py:
--------------------------------------------------------------------------------
1 | N, K = map(int, input().split())
2 | mat = [list(map(int, input().split())) for i in range(N)]
3 | for i in range(N):
4 | for j in range(N):
5 | if i < j:
6 | mat[i][j], mat[j][i] = mat[j][i], mat[i][j]
7 | for i in range(N):
8 | mat[i] = sorted(mat[i], key=lambda X: [abs(X - K), X])
9 | for i in range(N):
10 | for j in range(N):
11 | if i < j:
12 | mat[i][j], mat[j][i] = mat[j][i], mat[i][j]
13 | for i in range(N):
14 | for j in range(N):
15 | print(mat[i][j], end=' ')
16 | print()
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/55.py:
--------------------------------------------------------------------------------
1 | L, K = map(int, input().split())
2 | sr = (L - 1) / 2
3 | s = list(map(int, input().split()))
4 | i = 0
5 | max1 = 0
6 | while i < len(s) and s[i] < sr:
7 | max1 = s[i]
8 | i += 1
9 | max2 = s[len(s) - 1]
10 | i = len(s) - 1
11 | while s[i] > sr:
12 | max2 = s[i]
13 | i -= 1
14 | if (L - 1) % 2 == 0 and int((L - 1) / 2) in s:
15 | print(int((L - 1) / 2))
16 | else:
17 | print(max1, max2)
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/56.py:
--------------------------------------------------------------------------------
1 | l, k = map(int, input().split())
2 | m = (l - 1) / 2
3 | s = [int(x) for x in input().split()]
4 | i = 0
5 | max1 = 0
6 | while i < len(s) and s[i] < m:
7 | max1 = s[i]
8 | i += 1
9 | max2 = s[len(s) - 1]
10 | i = len(s) - 1
11 | while s[i] > m:
12 | max2 = s[i]
13 | i -= 1
14 | if (l - 1) % 2 == 0 and int((l - 1) / 2) in s:
15 | print(int((l - 1) / 2))
16 | else:
17 | print(max1, max2)
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/57.py:
--------------------------------------------------------------------------------
1 | l, k = map(int, input().split())
2 | a = list(map(int, input().split()))
3 | p = 0
4 | for i in range(len(a)):
5 | if l % 2 == 1 and k > 1 and a[i] != l // 2:
6 | p += 1
7 | one = 0
8 | two = 0
9 | five = 0
10 | first = []
11 | sec = []
12 | thrd = []
13 | six = 0
14 | forth = []
15 | if k > 1 and l % 2 == 0:
16 | for i in range(len(a)):
17 | if a[i] < l // 2:
18 | one = one + 1
19 | first.append(a[i])
20 | else:
21 | two = two + 1
22 | thrd.append(a[i])
23 | if one > 0 and two > 0:
24 | print(max(first), min(thrd))
25 | if k > 1 and l % 2 == 1:
26 | for i in range(len(a)):
27 | if a[i] == l // 2:
28 | w = a[i]
29 | print(w)
30 | if k > 1 and l % 2 == 1:
31 | for i in range(len(a)):
32 | if p == len(a):
33 | for i in range(len(a)):
34 | if a[i] < l // 2:
35 | six = six + 1
36 | sec.append(a[i])
37 | else:
38 | five = five + 1
39 | forth.append(a[i])
40 | if six > 0 and five > 0:
41 | print(max(sec), min(forth))
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/58.py:
--------------------------------------------------------------------------------
1 | l, k = map(int, input().split())
2 | a = list(map(int, input().split()))
3 | p = 0
4 | for i in range(len(a)):
5 | if l % 2 == 1 and k > 1 and a[i] != l // 2:
6 | p += 1
7 | one = 0
8 | two = 0
9 | five = 0
10 | ar1 = []
11 | ar2 = []
12 | ar3 = []
13 | six = 0
14 | ar4 = []
15 | if k > 1 and l % 2 == 0:
16 | for i in range(len(a)):
17 | if a[i] < l // 2:
18 | one = one + 1
19 | ar1.append(a[i])
20 | else:
21 | two = two + 1
22 | ar3.append(a[i])
23 | if one > 0 and two > 0:
24 | print(max(ar1), min(ar3))
25 | if k > 1 and l % 2 == 1:
26 | for i in range(len(a)):
27 | if a[i] == l // 2:
28 | w = a[i]
29 | print(w)
30 | if k > 1 and l % 2 == 1:
31 | for i in range(len(a)):
32 | if p == len(a):
33 | for i in range(len(a)):
34 | if a[i] < l // 2:
35 | six = six + 1
36 | ar2.append(a[i])
37 | else:
38 | five = five + 1
39 | ar4.append(a[i])
40 | if six > 0 and five > 0:
41 | print(max(ar2), min(ar4))
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/59.py:
--------------------------------------------------------------------------------
1 | n, m = map(int, input().split())
2 | a = list(map(int, input().split()))
3 | b = 0
4 | for i in range(len(a)):
5 | if n % 2 == 1 and m > 1 and a[i] != n // 2:
6 | b = b + 1
7 | s = 0
8 | d = 0
9 | q = 0
10 | v = 0
11 | g = 0
12 | l = []
13 | f = []
14 | p = []
15 | d = 0
16 | h = 0
17 | x = []
18 | if m > 1 and n % 2 == 0:
19 | for i in range(len(a)):
20 | if a[i] < n // 2:
21 | s = s + 1
22 | l.append(a[i])
23 | else:
24 | d = d + 1
25 | p.append(a[i])
26 | if s > 0 and d > 0:
27 | print(max(l), min(p))
28 | if m > 1 and n % 2 == 1:
29 | for i in range(len(a)):
30 | if a[i] == n // 2:
31 | w = a[i]
32 | print(w)
33 | if m > 1 and n % 2 == 1:
34 | for i in range(len(a)):
35 | if b == len(a):
36 | for i in range(len(a)):
37 | if a[i] < n // 2:
38 | h = h + 1
39 | f.append(a[i])
40 | else:
41 | g = g + 1
42 | x.append(a[i])
43 | if h > 0 and g > 0:
44 | print(max(f), min(x))
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/6.py:
--------------------------------------------------------------------------------
1 | def power(a, n):
2 | if n == 0:
3 | return 1
4 | elif n > 0:
5 | i = 2
6 | b = a
7 | while i <= n:
8 | a = a * b
9 | i += 1
10 | return a
11 | else:
12 | i = 0
13 | b = a
14 | a = 1
15 | while i > n:
16 | a = a / b
17 | i -= 1
18 | return a
19 |
20 |
21 | a = float(input())
22 | n = int(input())
23 | print(power(a, n))
24 |
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/60.py:
--------------------------------------------------------------------------------
1 | m, n = map(int, input().split())
2 | blocks = list(map(int, input().split()))
3 | less = blocks[0]
4 | more = blocks[-1]
5 | k = 0
6 | for i in range(n):
7 | if blocks[i] < (m / 2):
8 | less = blocks[i]
9 |
10 | for i in sorted(blocks, reverse=True):
11 | if i + 1 > (m / 2):
12 | more = i
13 |
14 | if more == less and m % 2 == 1:
15 | print(more)
16 | else:
17 | print(less, more)
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/61.py:
--------------------------------------------------------------------------------
1 | a, b = map(int, input().split())
2 | k = [int(i) for i in input().split()]
3 | left = k[0]
4 | right = k[-1]
5 | for i in range(b):
6 | if k[i] < (a / 2):
7 | left = k[i]
8 |
9 | for i in sorted(k, reverse=True):
10 | if i + 1 > (a / 2):
11 | right = i
12 |
13 | if right == left and a % 2 == 1:
14 | print(right)
15 | else:
16 | print(left, right)
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/62.py:
--------------------------------------------------------------------------------
1 | l, n = map(int, input().split())
2 | myl = list(map(int, input().split()))
3 | a = myl[0]
4 | b = myl[-1]
5 | for i in range(n):
6 | if myl[i] < (l / 2):
7 | a = myl[i]
8 |
9 | for i in sorted(myl, reverse=True):
10 | if i + 1 > (l / 2):
11 | b = i
12 |
13 | if b == a and l % 2 == 1:
14 | print(b)
15 | else:
16 | print(a, b)
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/63.py:
--------------------------------------------------------------------------------
1 | lst1 = input().split()
2 | leng = int(lst1[0])
3 | n = int(lst1[1])
4 |
5 | x1 = 0
6 | x2 = -1
7 |
8 | data = []
9 | data1 = input().split()
10 | for i in range(n):
11 | data.append(int(data1[i]))
12 | for i in range(n):
13 | if 2 * data[i] < leng:
14 | x1 = data[i]
15 | if (2 * data[i] + 2 > leng) and (x2 == -1):
16 | x2 = data[i]
17 | if x1 == x2:
18 | print(x1)
19 | else:
20 | print(x1, x2)
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/64.py:
--------------------------------------------------------------------------------
1 | dt = input().split()
2 | length = int(dt[0])
3 | n = int(dt[1])
4 |
5 |
6 | ans1 = 0
7 | ans2 = -1
8 |
9 |
10 | data = []
11 |
12 | data_ = input().split()
13 |
14 |
15 | for i in range(n):
16 | data.append(int(data_[i]))
17 |
18 | for i in range(n):
19 | if 2 * data[i] < length:
20 | ans1 = data[i]
21 | if 2 * data[i] + 2 > length and ans2 == -1:
22 | ans2 = data[i]
23 |
24 | if ans1 == ans2:
25 | print(ans1)
26 | else:
27 | print(ans1, ans2)
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/65.py:
--------------------------------------------------------------------------------
1 | l, k = map(int, input().split())
2 | blok = list(map(int, input().split()))
3 | a = [0] * l
4 | k1 = k2 = 0
5 | for i in range(len(blok)):
6 | a[blok[i]] += 1
7 | if l % 2 == 0:
8 | g1 = l // 2 - 1
9 | g2 = l // 2
10 | for i in range(len(a)):
11 | if a[i] != 0 and i <= g1:
12 | k1 = i
13 | if a[i] != 0 and i >= g2 and k2 == 0:
14 | k2 = i
15 | print(k1, k2)
16 | else:
17 | g = l // 2
18 | if a[g] == 1:
19 | print(g)
20 | else:
21 | for i in range(len(a)):
22 | if a[i] != 0 and i < g:
23 | k1 = i
24 | if a[i] != 0 and i > g and k2 == 0:
25 | k2 = i
26 | print(k1, k2)
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/66.py:
--------------------------------------------------------------------------------
1 | l, k = list(map(int, input().split()))
2 | n = list(map(int, input().split()))
3 | right = 0
4 | left = 0
5 | nearL = -1
6 | nearR = l + 1
7 | a = [0] * l
8 | for i in range(len(n)):
9 | a[n[i]] = a[n[i]] + 1
10 | if l % 2 == 0:
11 | nearL = l // 2 - 1
12 | nearR = l // 2
13 | for i in range(l):
14 | if i <= nearL and a[i] != 0:
15 | left = i
16 | if i >= nearR and right == 0 and a[i] != 0:
17 | right = i
18 | print(left, right)
19 | else:
20 | near = l // 2
21 | if a[near] == 1:
22 | print(near)
23 | else:
24 | for i in range(l):
25 | if i < near and a[i] != 0:
26 | left = i
27 | if i > near and right == 0 and a[i] != 0:
28 | right = i
29 | print(left, right)
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/67.py:
--------------------------------------------------------------------------------
1 | l, k = map(int, input().split())
2 | legs = list(map(int, input().split()))
3 | middle = -1
4 | legs_number = set()
5 | legs_number1 = set()
6 | for i in range(len(legs)):
7 | if (l - 1) / 2 == legs[i]:
8 | middle = legs[i]
9 | elif (l - 1) / 2 > legs[i]:
10 | legs_number.add(legs[i])
11 | elif (l - 1) / 2 < legs[i]:
12 | legs_number1.add(legs[i])
13 | if middle != -1:
14 | print(middle)
15 | else:
16 | print(max(legs_number), min(legs_number1))
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/68.py:
--------------------------------------------------------------------------------
1 | l, k = map(int, input().split())
2 | block = list(map(int, input().split()))
3 | mid = -1
4 | block_num1 = set()
5 | block_num2 = set()
6 | for i in range(len(block)):
7 | if (l - 1) / 2 == block[i]:
8 | mid = block[i]
9 | elif (l - 1) / 2 > block[i]:
10 | block_num1.add(block[i])
11 | elif (l - 1) / 2 < block[i]:
12 | block_num2.add(block[i])
13 | if mid != -1:
14 | print(mid)
15 | else:
16 | left = max(block_num1)
17 | right = min(block_num2)
18 | print(left, right)
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/69.py:
--------------------------------------------------------------------------------
1 | P_23, D_23 = list(map(int, input().split()))
2 | n_23 = list(map(int, input().split()))
3 | x_23 = n_23[0]
4 | y_23 = n_23[len(n_23) - 1]
5 | for k in range(len(n_23)):
6 | if n_23[k] < P_23 / 2:
7 | x_23 = n_23[k]
8 | for i in range(len(n_23) - 1, -1, -1):
9 | if n_23[i] >= P_23 / 2:
10 | y_23 = n_23[i]
11 | if x_23 == P_23 // 2:
12 | print(x_23)
13 | else:
14 | print(x_23)
15 | print(y_23)
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/7.py:
--------------------------------------------------------------------------------
1 | import math
2 |
3 |
4 | def rev():
5 | n = int(input())
6 | if n != 0:
7 | rev()
8 | if (math.sqrt(n).is_integer()):
9 | global flag
10 | flag = 1
11 | print(n)
12 |
13 | flag = 0
14 | rev()
15 | if flag == 0:
16 | print(0)
17 |
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/70.py:
--------------------------------------------------------------------------------
1 | L, K = list(map(int, input().split()))
2 | N = list(map(int, input().split()))
3 | a = N[0]
4 | b = N[len(N) - 1]
5 | for i in range(len(N)):
6 | if N[i] < L / 2:
7 | a = N[i]
8 | for j in range(len(N) - 1, -1, -1):
9 | if N[j] >= L / 2:
10 | b = N[j]
11 | if a == L // 2:
12 | print(a)
13 | else:
14 | print(a)
15 | print(b)
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/71.py:
--------------------------------------------------------------------------------
1 | n, k = map(int, input().split())
2 | mas = []
3 | s = list(map(int, input().split()))
4 | for i in range(n):
5 | mas.append([[abs(s[i]-k), s[i]]])
6 | for f in range(1, n):
7 | s = list(map(int, input().split()))
8 | for j in range(n):
9 | mas[j].append([abs(s[j]-k), s[j]])
10 |
11 | for e in range(n):
12 | mas[e].sort()
13 |
14 | for i in range(n):
15 | for j in range(n-1):
16 | print(mas[j][i][1], ' ', sep='', end='')
17 | print(mas[n-1][i][1])
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/72.py:
--------------------------------------------------------------------------------
1 | n, k = map(int, input().split())
2 | a = []
3 | s = list(map(int, input().split()))
4 | for i in range(n):
5 | a.append([[abs(s[i]-k), s[i]]])
6 | for i in range(1, n):
7 | s = list(map(int, input().split()))
8 | for j in range(n):
9 | a[j].append([abs(s[j]-k), s[j]])
10 |
11 | for i in range(n):
12 | a[i].sort()
13 |
14 | for i in range(n):
15 | for j in range(n-1):
16 | print(a[j][i][1], ' ', sep='', end='')
17 | print(a[n-1][i][1])
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/73.py:
--------------------------------------------------------------------------------
1 | x = list(map(int, input().split()))
2 | n = x[0]
3 | k = x[1]
4 | lst = list(map(int, input().split()))
5 | arr = []
6 | for i in range(n):
7 | arr.append([[abs(lst[i] - k), lst[i]]])
8 | for f in range(1, n):
9 | lst = list(map(int, input().split()))
10 | for j in range(n):
11 | arr[j].append([abs(lst[j] - k), lst[j]])
12 | for i in range(n):
13 | arr[i].sort()
14 | for i in range(n):
15 | for j in range(n - 1):
16 | print(arr[j][i][1], ' ', sep='', end='')
17 | print(arr[n - 1][i][1])
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/8.py:
--------------------------------------------------------------------------------
1 | import math
2 |
3 |
4 | def rev():
5 | n = int(input())
6 | if n != 0:
7 | rev()
8 | if (math.sqrt(n).is_integer()):
9 | global flag
10 | flag = 1
11 | print(n)
12 |
13 | flag = 0
14 | rev()
15 | if flag == 0:
16 | print(0)
17 |
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/cheating/9.py:
--------------------------------------------------------------------------------
1 | n = int(input())
2 | partial_factorial = 1
3 | partial_sum = 0
4 | for i in range(1, n + 1):
5 | partial_factorial *= i
6 | partial_sum += partial_factorial
7 | print(partial_sum)
8 |
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/file.txt:
--------------------------------------------------------------------------------
1 | ахаха=азащзазащахах
2 | ахах
3 | ахах
4 | ахахlkwfjfwejfwel
5 | ахаха
6 | Я фанатею
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/function_g.pickle:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hse-econ-data-science/dap_2022-23/1e23952959de15a2f17b63dd48523a62245c74fc/sem07_wow/sem07_211/function_g.pickle
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/lst.pickle:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hse-econ-data-science/dap_2022-23/1e23952959de15a2f17b63dd48523a62245c74fc/sem07_wow/sem07_211/lst.pickle
--------------------------------------------------------------------------------
/sem07_wow/sem07_211/marks.tsv:
--------------------------------------------------------------------------------
1 | fio login group email 1 2 3 4 ДЗ итог 1 2 3 4 5 6 МСР итог 1 2 3 БСР итог Итог Итог округл Проверяющий ассистент
2 | Новицкая Алина Дмитриевна dap_econ_2022_358 БЭК196 adnovitskaya@edu.hse.ru 11 2.8 4.3 8.0 2.0 9 3.0 2.78 3
3 | Мунхтур Эгшиглэн dap_econ_2022_359 БЭК197 emunkhtur@edu.hse.ru 2 0.5 0.0 0.0 0.25 0
4 | Майданов Бекнур dap_econ_2022_360 БЭК198 bmaydanov@edu.hse.ru 11 2.8 0.0 0.0 0 0.0 1.38 1
5 | Мукамбеков Бектур dap_econ_2022_361 БЭК199 bmukambekov@edu.hse.ru 11 2.8 0.0 10 3.3 2.71 3
6 | Цветкова Алёна Алексеевна dap_econ_2022_353 БЭК2011 aatsvetkova_3@edu.hse.ru 11 2.8 10.0 10.0 3.3 10 3.3 3.04 3
7 | Артеменко Мария Игоревна dap_econ_2022_354 БЭК2012 miartemenko@edu.hse.ru 11 2.8 0.0 0.0 1.38 1
8 | Котляренко Владислав Викторович dap_econ_2022_355 БЭК2012 vvkotlyarenko@edu.hse.ru 10.3 2.6 8.0 10.0 3.0 0 0.0 1.59 2
9 | Хафизов Шохрух Обиджон угли dap_econ_2022_357 БЭК209 shokhafizov@edu.hse.ru 0 0.0 0.0 0.0 0.00 0
10 | Адмайкин Артём Евгеньевич dap_econ_2022_11 БЭК211 aeadmaykin@edu.hse.ru 3.5 0.9 6.0 10.0 2.7 7.5 2.5 1.70 2
11 | Багаутдинов Эрнест Ришатович dap_econ_2022_12 БЭК211 erbagautdinov@edu.hse.ru 11 2.8 0.0 10.0 1.7 9 3.0 2.74 3
12 | Баландин Егор Максимович dap_econ_2022_13 БЭК211 embalandin@edu.hse.ru 11 2.8 4.0 4.0 1.3 10 3.3 2.84 3
13 | Березин Даниил Сергеевич dap_econ_2022_14 БЭК211 dsberezin_1@edu.hse.ru 11 2.8 10.0 10.0 3.3 4.6 1.5 2.32 2
14 | Богоявленский Максим Сергеевич dap_econ_2022_15 БЭК211 msbogoyavlenskiy@edu.hse.ru 11 2.8 8.0 8.0 2.7 9.6 3.2 2.92 3
15 | Гарифуллов Тимур Гамилевич dap_econ_2022_16 БЭК211 tggarifullov@edu.hse.ru 10.8 2.7 10.0 8.0 3.0 9 3.0 2.85 3
16 | Гельмиза Арсений Андреевич dap_econ_2022_17 БЭК211 aagelmiza@edu.hse.ru 0 0.0 8.0 10.0 3.0 6.6 2.2 1.18 1
17 | Горбенко Игорь Денисович dap_econ_2022_18 БЭК211 idgorbenko@edu.hse.ru 11 2.8 10.0 8.0 3.0 10 3.3 3.01 3
18 | Грязнов Михаил Александрович dap_econ_2022_19 БЭК211 magryaznov@edu.hse.ru 11 2.8 0.0 10.0 1.7 4 1.3 2.08 2
19 | Гусева Екатерина Евгеньевна dap_econ_2022_20 БЭК211 eeguseva_1@edu.hse.ru 11 2.8 7.0 8.0 2.5 10 3.3 2.96 3
20 | Ермаков Тимур Сергеевич dap_econ_2022_21 БЭК211 tsermakov@edu.hse.ru 9.8 2.5 0.0 0.0 0.0 9 3.0 2.43 2
21 | Казаков Михаил Станиславович dap_econ_2022_22 БЭК211 mskazakov@edu.hse.ru 11 2.8 0.0 0.0 0.0 0.5 0.2 1.44 1
22 | Карлова Ульяна Юрьевна dap_econ_2022_23 БЭК211 uyukarlova@edu.hse.ru 0 0.0 8.0 8.0 2.7 0 0.0 0.27 0
23 | Каюмова Карина Ринатовна dap_econ_2022_24 БЭК211 krkayumova_1@edu.hse.ru 0 0.0 10.0 10.0 3.3 10 3.3 1.67 2
24 | Комарова Серафима Николаевна dap_econ_2022_25 БЭК211 snkomarova@edu.hse.ru 0.1 0.0 0.0 6.0 1.0 9 3.0 1.31 1
25 | Котяков Даниил Антонович dap_econ_2022_26 БЭК211 dakotyakov@edu.hse.ru 10.8 2.7 0.0 2.0 0.3 6 2.0 2.18 2
26 | Кривоносов Андрей Дмитриевич dap_econ_2022_27 БЭК211 adkrivonosov@edu.hse.ru 11 2.8 10.0 8.0 3.0 9.6 3.2 2.96 3
27 | Куцев Владимир Максимович dap_econ_2022_28 БЭК211 vmkutsev@edu.hse.ru 0.0 0.0 0.0 0.0 10 3.3 1.33 1
28 | Левакова Оксана Сергеевна dap_econ_2022_29 БЭК211 oslevakova@edu.hse.ru 11 2.8 10.0 8.0 3.0 0 0.0 1.68 2
29 | Маслов Кирилл Олегович dap_econ_2022_30 БЭК211 komaslov@edu.hse.ru 0.0 0.0 6.0 1.0 6 2.0 0.90 1
30 | Микаелян Арман Арменович dap_econ_2022_31 БЭК211 aamikaelyan@edu.hse.ru 10.1 2.5 8.0 10.0 3.0 4 1.3 2.10 2
31 | Мовсисян Артём Алексеевич dap_econ_2022_32 БЭК211 aamovsisyan_1@edu.hse.ru 8.5 2.1 10.0 8.0 3.0 0 0.0 1.36 1
32 | Москвина Анастасия Олеговна dap_econ_2022_33 БЭК211 aomoskvina_1@edu.hse.ru 11 2.8 10.0 8.0 3.0 10 3.3 3.01 3
33 | Пахомов Иван Андреевич dap_econ_2022_34 БЭК211 iapakhomov@edu.hse.ru 11 2.8 8.0 8.0 2.7 5 1.7 2.31 2
34 | Полищук Мария Вячеславовна dap_econ_2022_35 БЭК211 mvpolischuk@edu.hse.ru 0 0.0 10.0 10.0 3.3 2.5 0.8 0.67 1
35 | Шакирова Эльмира Фаридовна dap_econ_2022_36 БЭК211 efshakirova@edu.hse.ru 10 2.5 8.0 10.0 3.0 10 3.3 2.88 3
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheat.py:
--------------------------------------------------------------------------------
1 | import os
2 | from shutil import copyfile
3 |
4 | def repl(s1):
5 | s2 = []
6 | for line in s1:
7 | if line.startswith('#'):
8 | continue
9 | if line.find('//') != -1:
10 | line = line[:line.find('//')]
11 | s2.append(line)
12 | syms = set('+-*/%^:;"\'<>!=[](){}&|.,?')
13 | prev = ''
14 | ans = []
15 | s = ''.join(s2).replace('\n', '')
16 | s = s.replace(' ', '')
17 | s = s.replace('\t', '')
18 | for c in s:
19 | if c not in syms and prev != '#':
20 | ans.append('#')
21 | prev = '#'
22 | elif c in syms:
23 | ans.append(c)
24 | prev = c
25 | return ''.join(ans)
26 |
27 | def check(s1, s2):
28 | return repl(s1) == repl(s2)
29 |
30 | dirs = os.listdir()
31 | sols = {}
32 | badass = {}
33 | stop = 10**9
34 | for ndir in range(len(dirs)):
35 | if stop <= 0:
36 | break
37 |
38 | if dirs[ndir] == 'cheat.py' or dirs[ndir] == 'log.txt' or dirs[ndir] == 'lex_cheat.py':
39 | continue
40 | tfiles = os.listdir(dirs[ndir])
41 | files = []
42 | for file in tfiles:
43 | if True:#file.find('OK') != -1:
44 | files.append(file)
45 |
46 | for pdir in range(ndir):
47 | if stop <= 0:
48 | break
49 | if dirs[pdir] == 'cheat.py' or dirs[pdir] == 'log.txt' or dirs[pdir] == 'lex_cheat.py':
50 | continue
51 | pfiles = sols[dirs[pdir]]
52 | for nfn in files:
53 | p1 = dirs[ndir] + '/' + nfn
54 | #print(p1)
55 | s1 = os.path.getsize(p1)
56 | for pfn in pfiles:
57 | if nfn[0] == pfn[0]:
58 | p2 = dirs[pdir] + '/' + pfn
59 | #print(p2)
60 | s2 = os.path.getsize(p2)
61 | fn = open(p1, 'r', encoding = 'utf8')
62 | fp = open(p2, 'r', encoding = 'utf8')
63 | st1 = fn.readlines()
64 | st2 = fp.readlines()
65 | fn.close()
66 | fp.close()
67 | if s1 == s2:
68 | flag = False
69 | if len(st1) == len(st2):
70 | flag = True
71 | for i in range(len(st1)):
72 | if st1[i].strip() != st2[i].strip():
73 | flag = False
74 |
75 | if flag:
76 | pair = dirs[ndir], dirs[pdir]
77 | if pair not in badass:
78 | badass[pair] = set()
79 | badass[pair].add(pfn[0])
80 | print('146%', dirs[ndir], dirs[pdir], pfn[0], sep = '\t')
81 | stop -= 1
82 | #if check(st1, st2):
83 | # print('prob', dirs[ndir], dirs[pdir], pfn[0], sep = '\t')
84 |
85 |
86 | sols[dirs[ndir]] = files
87 | pass
88 | pass
89 | ans = []
90 | for pair in badass:
91 | ans.append((badass[pair], pair))
92 | ans.sort(reverse=True, key=lambda x: (len(x[0]), x[1]))
93 | fout = open('log.txt', 'w', encoding='utf8')
94 | for now in ans:
95 | print(now[1][0], now[1][1], len(now[0]), ''.join(sorted(now[0])), sep='\t', file=fout)
96 | fout.close()
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/1.py:
--------------------------------------------------------------------------------
1 | s = input()
2 | if not(s.find('f') == -1):
3 | if s.find('f') == s.rfind('f'):
4 | print(s.find('f'))
5 | else:
6 | print(s.find('f'), end=' ')
7 | print(s.rfind('f'))
8 |
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/10.py:
--------------------------------------------------------------------------------
1 | n = int(input())
2 | partial_factorial = 1
3 | partial_sum = 0
4 | for i in range(1, n + 1):
5 | partial_factorial *= i
6 | partial_sum += partial_factorial
7 | print(partial_sum)
8 |
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/11.py:
--------------------------------------------------------------------------------
1 | n = 8
2 | x = []
3 | y = []
4 | for i in range(n):
5 | new_x, new_y = [int(s) for s in input().split()]
6 | x.append(new_x)
7 | y.append(new_y)
8 |
9 | correct = True
10 | for i in range(n):
11 | for j in range(i + 1, n):
12 | if x[i] == x[j] or y[i] == y[j]:
13 | correct = False
14 | if abs(x[i] - x[j]) == abs(y[i] - y[j]):
15 | correct = False
16 |
17 | if correct:
18 | print('NO')
19 | else:
20 | print('YES')
21 |
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/12.py:
--------------------------------------------------------------------------------
1 | a = [int(s) for s in input().split()]
2 | k = int(input())
3 | for i in range(k + 1, len(a)):
4 | a[i - 1] = a[i]
5 | a.pop()
6 | print(' '.join([str(i) for i in a]))
7 |
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/13.py:
--------------------------------------------------------------------------------
1 | myList = list(map(int, input().split()))
2 | count = 0
3 | for i in range(1, len(myList) - 1):
4 | if myList[i] > myList[i - 1] and myList[i] > myList[i + 1]:
5 | count += 1
6 | print(count)
7 |
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/14.py:
--------------------------------------------------------------------------------
1 | tot_cont = []
2 | grade9 = []
3 | grade10 = []
4 | grade11 = []
5 | tot_point = []
6 | file = open('input.txt', 'r', encoding='utf-8')
7 | for line in file:
8 | cont = list(line.split())
9 | tot_cont.append(cont)
10 | tot_cont.sort(key=lambda x: int(x[2]))
11 | max9 = 80
12 | for i in tot_cont:
13 | if int(i[2]) == 9:
14 | grade9.append(i[3])
15 | elif int(i[2]) == 10:
16 | grade10.append(i[3])
17 | elif int(i[2]) == 11:
18 | grade11.append(i[3])
19 | grade9.sort()
20 | grade10.sort()
21 | grade11.sort()
22 | grade9 = grade9[::-1]
23 | grade10 = grade10[::-1]
24 | grade11 = grade11[::-1]
25 | max9 = grade9[0]
26 | max10 = grade10[0]
27 | max11 = grade11[0]
28 | kol9 = 0
29 | kol10 = 0
30 | kol11 = 0
31 | for i in range(0, len(grade9)):
32 | if grade9[i] == max9:
33 | kol9 += 1
34 | for i in range(0, len(grade10)):
35 | if grade10[i] == max10:
36 | kol10 += 1
37 | for i in range(0, len(grade11)):
38 | if grade11[i] == max11:
39 | kol11 += 1
40 | print(kol9, kol10, kol11)
41 |
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/15.py:
--------------------------------------------------------------------------------
1 | yes = set(map(str, range(1, int(input()) + 1)))
2 | for line in iter(input, 'HELP'):
3 | guesses = yes.intersection(line.split())
4 | if len(guesses) > (len(yes) - len(guesses)):
5 | print('YES')
6 | yes = guesses
7 | else:
8 | print('NO')
9 | yes -= guesses
10 | print(*sorted(yes, key=int))
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/16.py:
--------------------------------------------------------------------------------
1 | yes_pile = set(map(str, range(1, int(input()) + 1)))
2 | for line in iter(input, 'HELP'):
3 | guesses = yes_pile.intersection(line.split())
4 | if len(guesses) > (len(yes_pile) - len(guesses)):
5 | print('YES')
6 | yes_pile = guesses
7 | else:
8 | print('NO')
9 | yes_pile -= guesses
10 | print(*sorted(yes_pile, key=int))
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/17.py:
--------------------------------------------------------------------------------
1 | k = int(input())
2 | n = set(i for i in range(1, k + 1))
3 | while True:
4 | s = input()
5 | if s == "HELP":
6 | break
7 | s = set(map(int, s.split()))
8 | if len(n & s) > len(n) / 2:
9 | print("YES")
10 | n &= s
11 | else:
12 | print("NO")
13 | n -= s
14 | print(*sorted(n))
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/18.py:
--------------------------------------------------------------------------------
1 | n = int(input())
2 | k = set(i for i in range(1, n + 1))
3 | while True:
4 | s = input()
5 | if s == "HELP":
6 | break
7 | s = set(map(int, s.split()))
8 | if len(k & s) > len(k) / 2:
9 | print("YES")
10 | k &= s
11 | else:
12 | print("NO")
13 | k -= s
14 | print(*sorted(k))
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/19.py:
--------------------------------------------------------------------------------
1 | n = int(input())
2 | sres = set(range(1, n + 1))
3 | while True:
4 | cur = input()
5 | if cur == 'HELP':
6 | break
7 | cur = {int(x) for x in cur.split()}
8 | if len(sres & cur) > len(sres) / 2:
9 | print('YES')
10 | sres &= cur
11 | else:
12 | print('NO')
13 | sres -= cur
14 | print(' '.join([str(x) for x in sorted(sres)]))
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/2.py:
--------------------------------------------------------------------------------
1 | s = input()
2 | if not(s.find('f') == -1):
3 | if s.find('f') == s.rfind('f'):
4 | print(s.find('f'))
5 | else:
6 | print(s.find('f'), end=' ')
7 | print(s.rfind('f'))
8 |
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/20.py:
--------------------------------------------------------------------------------
1 | n = int(input())
2 | a = set(range(1, n + 1))
3 | b = a
4 | while True:
5 | c = input()
6 | if c == 'HELP':
7 | break
8 | c = {int(x) for x in c.split()}
9 | if len(b & c) > len(b) / 2:
10 | print('YES')
11 | b &= c
12 | else:
13 | print('NO')
14 | b -= c
15 |
16 | print(' '.join([str(x) for x in sorted(b)]))
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/21.py:
--------------------------------------------------------------------------------
1 | n = int(input())
2 | pn = set(range(1, n + 1))
3 | while True:
4 | g = input()
5 | if g == 'HELP':
6 | break
7 | g = {int(x) for x in g.split()}
8 | if len(pn & g) > len(pn) / 2:
9 | print('YES')
10 | pn &= g
11 | else:
12 | pn -= g
13 | print('NO')
14 | print(' '.join([str(x) for x in sorted(pn)]))
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/22.py:
--------------------------------------------------------------------------------
1 | n = int(input())
2 | accents = {}
3 | for i in range(n):
4 | word = input()
5 | base_form = word.lower()
6 | if base_form not in accents:
7 | accents[base_form] = set()
8 | accents[base_form].add(word)
9 | errors = 0
10 | sent = input().split()
11 | for word in sent:
12 | base_form = word.lower()
13 | if base_form in accents and word not in accents[base_form] \
14 | or len([l for l in word if l.isupper()]) != 1:
15 | errors += 1
16 | print(errors)
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/23.py:
--------------------------------------------------------------------------------
1 | n = int(input())
2 | acnts = {}
3 | for i in range(n):
4 | word = input()
5 | base_frm = word.lower()
6 | if base_frm not in acnts:
7 | acnts[base_frm] = set()
8 | acnts[base_frm].add(word)
9 |
10 | errors = 0
11 | sent = input().split()
12 | for word in sent:
13 | base_frm = word.lower()
14 | if (not (not (base_frm in acnts and word not in acnts[base_frm]) and not (
15 | len([l for l in word if l.isupper()]) != 1))):
16 | errors += 1
17 | print(errors)
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/24.py:
--------------------------------------------------------------------------------
1 | n = int(input())
2 | accents = {}
3 | for i in range(n):
4 | word = input()
5 | form = word.lower()
6 | if form not in accents:
7 | accents[form] = set()
8 | accents[form].add(word)
9 | mistakes = 0
10 | line = input().strip().split()
11 | for word in line:
12 | form = word.lower()
13 | if form in accents and word not in accents[form] or \
14 | len([elem for elem in word if elem.isupper()]) != 1:
15 | mistakes += 1
16 | print(mistakes)
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/25.py:
--------------------------------------------------------------------------------
1 | n = int(input())
2 | a = {}
3 | for i in range(n):
4 | word = input()
5 | b = word.lower()
6 | if b not in a:
7 | a[b] = set()
8 | a[b].add(word)
9 | errors = 0
10 | s = input().split()
11 | for word in s:
12 | b = word.lower()
13 | le = len([l for l in word if l.isupper()])
14 | if (b in a and word not in a[b] or le != 1):
15 | errors += 1
16 | print(errors)
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/26.py:
--------------------------------------------------------------------------------
1 | n = int(input())
2 | a = {}
3 | for i in range(n):
4 | word = input()
5 | b = word.lower()
6 | if b not in a:
7 | a[b] = set()
8 | a[b].add(word)
9 | errors = 0
10 | s = input().split()
11 | for word in s:
12 | b = word.lower()
13 | le = len([l for l in word if l.isupper()])
14 | if (b in a and word not in a[b] or le != 1):
15 | errors += 1
16 | print(errors)
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/27.py:
--------------------------------------------------------------------------------
1 | n = int(input())
2 | a = {}
3 | for i in range(n):
4 | word = input()
5 | base = word.lower()
6 | if base not in a:
7 | a[base] = set()
8 | a[base].add(word)
9 |
10 | mistakes = 0
11 | sent = input().split()
12 | for word in sent:
13 | base = word.lower()
14 | if base in a and word not in a[base]:
15 | mistakes += 1
16 | elif len([l for l in word if l.isupper()]) != 1:
17 | mistakes += 1
18 | print(mistakes)
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/28.py:
--------------------------------------------------------------------------------
1 | n = int(input())
2 | a = dict()
3 | for i in range(n):
4 | word = input()
5 | base_form = word.lower()
6 | if base_form not in a:
7 | a[base_form] = set()
8 | a[base_form].add(word)
9 | errors = 0
10 | s = input().split()
11 | for word in s:
12 | base_form = word.lower()
13 | if base_form in a and word not in a[base_form]:
14 | errors += 1
15 | elif len([l for l in word if l.isupper()]) != 1:
16 | errors += 1
17 | print(errors)
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/29.py:
--------------------------------------------------------------------------------
1 | n = int(input())
2 | accents = {}
3 | for i in range(n):
4 | word = input()
5 | base_form = word.lower()
6 | if base_form not in accents:
7 | accents[base_form] = set()
8 | accents[base_form].add(word)
9 | errors = 0
10 | sent = input().split()
11 | for word in sent:
12 | base_form = word.lower()
13 | if base_form in accents and word not in accents[base_form] \
14 | or len([l for l in word if l.isupper()]) != 1:
15 | errors += 1
16 | print(errors)
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/3.py:
--------------------------------------------------------------------------------
1 | s = input()
2 | a = s[:s.find('h') + 1]
3 | b = s[s.find('h') + 1:s.rfind('h')]
4 | c = s[s.rfind('h'):]
5 | s = a + b.replace('h', 'H') + c
6 | print(s)
7 |
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/30.py:
--------------------------------------------------------------------------------
1 | k = int(input())
2 | accents = {}
3 | for i in range(k):
4 | word = input()
5 | base_form = word.lower()
6 | if base_form not in accents:
7 | accents[base_form] = set()
8 | accents[base_form].add(word)
9 |
10 | errors = 0
11 | sent = input().split()
12 | for word in sent:
13 | base_form = word.lower()
14 | if (base_form in accents and word not in accents[base_form] or
15 | len([l for l in word if l.isupper()]) != 1):
16 | errors += 1
17 | print(errors)
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/31.py:
--------------------------------------------------------------------------------
1 | n = int(input())
2 | acnts = {}
3 | for i in range(n):
4 | word = input()
5 | base_frm = word.lower()
6 | if base_frm not in acnts:
7 | acnts[base_frm] = set()
8 | acnts[base_frm].add(word)
9 |
10 | errors = 0
11 | sent = input().split()
12 | for word in sent:
13 | base_frm = word.lower()
14 | if (not (not (base_frm in acnts and word not in acnts[base_frm]) and not (
15 | len([l for l in word if l.isupper()]) != 1))):
16 | errors += 1
17 | print(errors)
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/32.py:
--------------------------------------------------------------------------------
1 | n = int(input())
2 | accents = {}
3 | for i in range(n):
4 | word = input()
5 | base_form = word.lower()
6 | if base_form not in accents:
7 | accents[base_form] = set()
8 | accents[base_form].add(word)
9 |
10 | errors = 0
11 | sent = input().split()
12 | for word in sent:
13 | base_form = word.lower()
14 | if base_form in accents and word not in accents[base_form] \
15 | or len([l for l in word if l.isupper()]) != 1:
16 | errors += 1
17 | print(errors)
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/33.py:
--------------------------------------------------------------------------------
1 | n = int(input())
2 | a = {}
3 | for i in range(n):
4 | word = input()
5 | b = word.lower()
6 | if b not in a:
7 | a[b] = set()
8 | a[b].add(word)
9 |
10 | err = 0
11 | sent = input().split()
12 | for word in sent:
13 | b = word.lower()
14 | if b in a and word not in a[b] \
15 | or len([l for l in word if l.isupper()]) != 1:
16 | err += 1
17 | print(err)
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/34.py:
--------------------------------------------------------------------------------
1 | inp = open('input.txt', 'r', encoding='utf-8')
2 | out = open('output.txt', 'w', encoding='utf-8')
3 |
4 |
5 | def count_uppercase(s):
6 | count = 0
7 | for letter in s:
8 | if letter.isupper():
9 | count += 1
10 | return count
11 |
12 |
13 | dict = set()
14 | n = int(input())
15 | for i in range(n):
16 | word = input()
17 | dict.add(word)
18 | dict.add(word.upper())
19 | to_check = input().split()
20 | count_mistakes = 0
21 | for word in to_check:
22 | if word in dict and count_uppercase(word) == 1:
23 | continue
24 | if count_uppercase(word) == 1:
25 | if not word.upper() in dict:
26 | continue
27 | count_mistakes += 1
28 | print(count_mistakes)
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/35.py:
--------------------------------------------------------------------------------
1 | infile = open('input.txt', 'r', encoding='utf-8')
2 | oufile = open('output.txt', 'w', encoding='utf-8')
3 |
4 |
5 | def count_upper(s):
6 | count = 0
7 | for letter in s:
8 | if letter.isupper():
9 | count += 1
10 | return count
11 |
12 |
13 | dict = set()
14 | n = int(input())
15 | for i in range(n):
16 | slovo = str(input())
17 | dict.add(slovo)
18 | dict.add(slovo.upper())
19 | check = input().split()
20 | mistakes = 0
21 | for slovo in check:
22 | if slovo in dict and count_upper(slovo) == 1:
23 | continue
24 | if count_upper(slovo) == 1:
25 | if not slovo.upper() in dict:
26 | continue
27 | mistakes += 1
28 | print(mistakes)
29 | # finally)) 0:40 a.m.
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/36.py:
--------------------------------------------------------------------------------
1 | names = list()
2 | votes = list()
3 | sumVotes = 0
4 | file = open('input.txt', 'r', encoding='utf-8')
5 | for line in file:
6 | line = line.split()
7 | partyName = ' '.join(line[:-1])
8 | partyVotes = int(line[-1])
9 | names.append(partyName)
10 | votes.append(partyVotes)
11 | sumVotes += partyVotes
12 | file.close()
13 | mandates = list()
14 | fracPart = []
15 | sumMandates = 0
16 | for i in range(len(names)):
17 | partyMandates = (votes[i] * 450) / sumVotes
18 | sumMandates += int(partyMandates)
19 | mandates.append(int(partyMandates))
20 | fracPart.append(partyMandates - int(partyMandates))
21 | while sumMandates < 450:
22 | i = 0
23 | for j in range(1, len(fracPart)):
24 | if (fracPart[j] > fracPart[i]) or \
25 | (fracPart[j] == fracPart[i] and votes[j] > votes[i]):
26 | i = j
27 | mandates[i] += 1
28 | sumMandates += 1
29 | fracPart[i] = 0
30 | for k in range(len(names)):
31 | print(names[k], mandates[k])
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/37.py:
--------------------------------------------------------------------------------
1 | names = list()
2 | votes = list()
3 | sumVotes = 0
4 | inFile = open('input.txt')
5 | for line in inFile:
6 | line = line.split()
7 | partyName = ' '.join(line[:-1])
8 | partyVotes = int(line[-1])
9 | names.append(partyName)
10 | votes.append(partyVotes)
11 | sumVotes += partyVotes
12 | inFile.close()
13 |
14 | mandates = list()
15 | fracPart = []
16 | sumMandates = 0
17 | for i in range(len(names)):
18 | partyMandates = (votes[i] * 450) / sumVotes
19 | sumMandates += int(partyMandates)
20 | mandates.append(int(partyMandates))
21 | fracPart.append(partyMandates - int(partyMandates))
22 |
23 | while sumMandates < 450:
24 | i = 0
25 | for j in range(1, len(fracPart)):
26 | if (
27 | (fracPart[j] > fracPart[i]) or
28 | (fracPart[j] == fracPart[i] and votes[j] > votes[i])
29 | ):
30 | i = j
31 | mandates[i] += 1
32 | sumMandates += 1
33 | fracPart[i] = 0
34 |
35 | for k in range(len(names)):
36 | print(names[k], mandates[k])
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/38.py:
--------------------------------------------------------------------------------
1 | parties = list()
2 | votes = list()
3 | sumVotes = 0
4 | with open('input.txt', 'r', encoding='utf-8') as f:
5 | for line in f:
6 | line = line.split()
7 | partyName = ' '.join(line[:-1])
8 | partyVotes = int(line[-1])
9 | parties.append(partyName)
10 | votes.append(partyVotes)
11 | sumVotes += partyVotes
12 | mandates = list()
13 | frac = []
14 | sum_mandates = 0
15 | for i in range(len(parties)):
16 | partyMandates = (votes[i] * 450) / sumVotes
17 | sum_mandates += int(partyMandates)
18 | mandates.append(int(partyMandates))
19 | frac.append(partyMandates - int(partyMandates))
20 | while sum_mandates < 450:
21 | i = 0
22 | for j in range(1, len(frac)):
23 | if (frac[j] > frac[i]) or\
24 | (frac[j] == frac[i] and votes[j] > votes[i]):
25 | i = j
26 | mandates[i] += 1
27 | sum_mandates += 1
28 | frac[i] = 0
29 |
30 | for k in range(len(parties)):
31 | print(parties[k], mandates[k])
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/39.py:
--------------------------------------------------------------------------------
1 | names = list()
2 | votes = list()
3 | sumVotes = 0
4 | inFile = open('input.txt')
5 | for line in inFile:
6 | line = line.split()
7 | partyName = ' '.join(line[:-1])
8 | partyVotes = int(line[-1])
9 | names.append(partyName)
10 | votes.append(partyVotes)
11 | sumVotes += partyVotes
12 | inFile.close()
13 | mandates = list()
14 | fracPart = []
15 | sumMandates = 0
16 | for i in range(len(names)):
17 | partyMandates = (votes[i] * 450) / sumVotes
18 | sumMandates += int(partyMandates)
19 | mandates.append(int(partyMandates))
20 | fracPart.append(partyMandates - int(partyMandates))
21 | while sumMandates < 450:
22 | i = 0
23 | for j in range(1, len(fracPart)):
24 | if (fracPart[j] > fracPart[i]) or \
25 | (fracPart[j] == fracPart[i] and votes[j] > votes[i]):
26 | i = j
27 | mandates[i] += 1
28 | sumMandates += 1
29 | fracPart[i] = 0
30 | for k in range(len(names)):
31 | print(names[k], mandates[k])
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/4.py:
--------------------------------------------------------------------------------
1 | def power(a, n):
2 | if n == 0:
3 | return 1
4 | elif n > 0:
5 | i = 2
6 | b = a
7 | while i <= n:
8 | a = a * b
9 | i += 1
10 | return a
11 | else:
12 | i = 0
13 | b = a
14 | a = 1
15 | while i > n:
16 | a = a / b
17 | i -= 1
18 | return a
19 |
20 |
21 | a = float(input())
22 | n = int(input())
23 | print(power(a, n))
24 |
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/40.py:
--------------------------------------------------------------------------------
1 | import sys
2 |
3 |
4 | def A(inputsource, output):
5 | w = dict()
6 | for l in inputsource:
7 | for word in l.split():
8 | if word not in w:
9 | w[word] = 1
10 | else:
11 | w[word] += 1
12 | for i in sorted(w.items(), key=lambda x: (-x[1], x[0])):
13 | output.write(i[0] + '\n')
14 | return
15 |
16 |
17 | def main():
18 | A(sys.stdin, sys.stdout)
19 |
20 |
21 | main()
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/41.py:
--------------------------------------------------------------------------------
1 | import sys
2 |
3 |
4 | def Solving(inputsource, output):
5 | words = dict()
6 | for line in inputsource:
7 | for word in line.split():
8 | if word not in words:
9 | words[word] = 1
10 | else:
11 | words[word] += 1
12 | for i in sorted(words.items(), key=lambda x: (-x[1], x[0])):
13 | output.write(i[0] + '\n')
14 | return
15 |
16 |
17 | def main():
18 | Solving(sys.stdin, sys.stdout)
19 |
20 |
21 | main()
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/42.py:
--------------------------------------------------------------------------------
1 | inFile = open('input.txt', 'r', encoding='utf-8')
2 | lines = inFile.readlines()
3 | counter = {}
4 | for line in lines:
5 | line = line.split()
6 | for word in line:
7 | counter[word] = counter.get(word, 0) + 1
8 | items = (counter.items())
9 |
10 |
11 | def sorter(a):
12 | for number in a:
13 | return -a[1], a[0]
14 |
15 |
16 | for word in sorted(items, key=sorter):
17 | print(word[0])
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/43.py:
--------------------------------------------------------------------------------
1 | inFile = open('input.txt', 'r', encoding='utf=8')
2 | line_set = inFile.readlines()
3 | temp = {}
4 | for line in line_set:
5 | line = line.split()
6 | for word in line:
7 | temp[word] = temp.get(word, 0) + 1
8 | subj = (temp.items())
9 |
10 |
11 | def sort(a):
12 | for i in a:
13 | return -a[1], a[0]
14 |
15 |
16 | for word in sorted(subj, key=sort):
17 | print(word[0])
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/44.py:
--------------------------------------------------------------------------------
1 | t = input()
2 | t1 = int(t[0])
3 | t2 = int(t[1])
4 | m1 = int(t[3])
5 | m2 = int(t[4])
6 | h = 10 * t1 + t2
7 | if h <= 11:
8 | if h == 0:
9 | h += 12
10 | print(h, ':', m1, m2, ' a.m.', end='', sep='')
11 | else:
12 | if h > 12:
13 | h -= 12
14 | print(h, ':', m1, m2, ' p.m.', end='', sep='')
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/45.py:
--------------------------------------------------------------------------------
1 | s = input()
2 | h1 = int(s[0])
3 | h2 = int(s[1])
4 | h = 10 * h1 + h2
5 |
6 | m1 = int(s[3])
7 | m2 = int(s[4])
8 | m = 10 * m1 + m2
9 | if 11 >= h >= 0:
10 | if h == 0:
11 | h += 12
12 | print(h, ':', m1, m2, ' a.m.', end='', sep='')
13 | else:
14 | if h > 12:
15 | h -= 12
16 | print(h, ':', m1, m2, ' p.m.', end='', sep='')
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/46.py:
--------------------------------------------------------------------------------
1 | x = int(input())
2 | a = x // 100000 * 2
3 | b = x // 10000 % 10
4 | c = x // 1000 % 10 * 2
5 | d = x % 1000 // 100
6 | e = x % 100 // 10 * 2
7 | f = x % 10
8 | if a >= 9:
9 | a = a - 9
10 | if c >= 9:
11 | c = c - 9
12 | if e >= 9:
13 | e = e - 9
14 | sum = a + b + c + d + e + f
15 | if sum % 10 == 0:
16 | print('YES')
17 | else:
18 | print('NO')
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/47.py:
--------------------------------------------------------------------------------
1 | n = int(input())
2 | a = n // 100000 * 2
3 | b = n // 10000 % 10
4 | c = n // 1000 % 10 * 2
5 | d = n % 1000 // 100
6 | e = n % 100 // 10 * 2
7 | f = n % 10
8 | if (a >= 9):
9 | a = a - 9
10 | if (c >= 9):
11 | c = c - 9
12 | if (e >= 9):
13 | e = e - 9
14 | sum = a + b + c + d + e + f
15 | if (sum % 10 == 0):
16 | print('YES')
17 | else:
18 | print('NO')
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/48.py:
--------------------------------------------------------------------------------
1 | n = int(input())
2 | a = list(map(int, input().split()))
3 | ans = []
4 | mun = n + 1
5 | mux = 0
6 | top = []
7 | for i in range(n):
8 | if (a[i] % 10 == 5):
9 | ans.append((a[i], i))
10 | if (a[i] > mux):
11 | mux = a[i]
12 | muni = i
13 | elif (a[i] == mux):
14 | muni = min(muni, i)
15 | mux = -1
16 | for i in range(len(ans)):
17 | if (ans[i][1] == n - 1):
18 | continue
19 | if (a[ans[i][1] + 1] >= ans[i][0]):
20 | continue
21 | if (muni < ans[i][1]):
22 | mux = max(mux, ans[i][0])
23 | if (mux == -1):
24 | print(0)
25 | else:
26 | kol = 0
27 | for i in range(n):
28 | if (a[i] > mux):
29 | kol += 1
30 | print(kol + 1)
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/49.py:
--------------------------------------------------------------------------------
1 | n = int(input())
2 | l = list(map(int, input().split()))
3 | res = []
4 | am = n + 1
5 | mx = 0
6 | orl = []
7 | for i in range(n):
8 | if (l[i] % 10 == 5):
9 | res.append((l[i], i))
10 | if (l[i] > mx):
11 | mx = l[i]
12 | mn = i
13 | elif (l[i] == mx):
14 | mn = min(mn, i)
15 | mx = -1
16 | for i in range(len(res)):
17 | if (res[i][1] == n - 1):
18 | continue
19 | if (l[res[i][1] + 1] >= res[i][0]):
20 | continue
21 | if (mn < res[i][1]):
22 | mx = max(mx, res[i][0])
23 | if mx == -1:
24 | print(0)
25 | else:
26 | mount = 0
27 | for i in range(n):
28 | if l[i] > mx:
29 | mount += 1
30 | print(mount + 1)
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/5.py:
--------------------------------------------------------------------------------
1 | def power(a, n):
2 | if n == 0:
3 | return 1
4 | elif n > 0:
5 | i = 2
6 | b = a
7 | while i <= n:
8 | a = a * b
9 | i += 1
10 | return a
11 | else:
12 | i = 0
13 | b = a
14 | a = 1
15 | while i > n:
16 | a = a / b
17 | i -= 1
18 | return a
19 |
20 |
21 | a = float(input())
22 | n = int(input())
23 | print(power(a, n))
24 |
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/50.py:
--------------------------------------------------------------------------------
1 | n = int(input())
2 | s = ''
3 | summa = 0
4 | for i in range(1, n):
5 | s = s + str(i) + '*' + str(i + 1) + '+'
6 | summa = summa + i * (i + 1)
7 | s = s[:-1]
8 | print(s, summa, sep='=')
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/51.py:
--------------------------------------------------------------------------------
1 | n = int(input())
2 | s = ''
3 | suma = 0
4 | for i in range(1, n):
5 | s = s + str(i) + '*' + str(i + 1) + '+'
6 | suma = suma + i * (i + 1)
7 | s = s[:-1]
8 | print(s, suma, sep='=')
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/52.py:
--------------------------------------------------------------------------------
1 | n = int(input())
2 | s = ''
3 | summ = 0
4 | for i in range(1, n):
5 | s = s + str(i) + '*' + str(i + 1) + '+'
6 | summ = summ + i * (i + 1)
7 | s = s[:-1]
8 | print(s, summ, sep='=')
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/53.py:
--------------------------------------------------------------------------------
1 | def transpose(matrix, n):
2 | for i in range(n):
3 | for j in range(n):
4 | if i < j:
5 | matrix[i][j], matrix[j][i] =\
6 | matrix[j][i], matrix[i][j]
7 |
8 |
9 | n, k = map(int, input().split())
10 | matrix = [list(map(int, input().split())) for _ in range(n)]
11 | transpose(matrix, n)
12 | for i in range(n):
13 | matrix[i] = sorted(matrix[i], key=lambda x: [abs(x - k), x])
14 | transpose(matrix, n)
15 | for i in range(n):
16 | for j in range(n):
17 | print(matrix[i][j], end=' ')
18 | print()
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/54.py:
--------------------------------------------------------------------------------
1 | N, K = map(int, input().split())
2 | mat = [list(map(int, input().split())) for i in range(N)]
3 | for i in range(N):
4 | for j in range(N):
5 | if i < j:
6 | mat[i][j], mat[j][i] = mat[j][i], mat[i][j]
7 | for i in range(N):
8 | mat[i] = sorted(mat[i], key=lambda X: [abs(X - K), X])
9 | for i in range(N):
10 | for j in range(N):
11 | if i < j:
12 | mat[i][j], mat[j][i] = mat[j][i], mat[i][j]
13 | for i in range(N):
14 | for j in range(N):
15 | print(mat[i][j], end=' ')
16 | print()
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/55.py:
--------------------------------------------------------------------------------
1 | L, K = map(int, input().split())
2 | sr = (L - 1) / 2
3 | s = list(map(int, input().split()))
4 | i = 0
5 | max1 = 0
6 | while i < len(s) and s[i] < sr:
7 | max1 = s[i]
8 | i += 1
9 | max2 = s[len(s) - 1]
10 | i = len(s) - 1
11 | while s[i] > sr:
12 | max2 = s[i]
13 | i -= 1
14 | if (L - 1) % 2 == 0 and int((L - 1) / 2) in s:
15 | print(int((L - 1) / 2))
16 | else:
17 | print(max1, max2)
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/56.py:
--------------------------------------------------------------------------------
1 | l, k = map(int, input().split())
2 | m = (l - 1) / 2
3 | s = [int(x) for x in input().split()]
4 | i = 0
5 | max1 = 0
6 | while i < len(s) and s[i] < m:
7 | max1 = s[i]
8 | i += 1
9 | max2 = s[len(s) - 1]
10 | i = len(s) - 1
11 | while s[i] > m:
12 | max2 = s[i]
13 | i -= 1
14 | if (l - 1) % 2 == 0 and int((l - 1) / 2) in s:
15 | print(int((l - 1) / 2))
16 | else:
17 | print(max1, max2)
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/57.py:
--------------------------------------------------------------------------------
1 | l, k = map(int, input().split())
2 | a = list(map(int, input().split()))
3 | p = 0
4 | for i in range(len(a)):
5 | if l % 2 == 1 and k > 1 and a[i] != l // 2:
6 | p += 1
7 | one = 0
8 | two = 0
9 | five = 0
10 | first = []
11 | sec = []
12 | thrd = []
13 | six = 0
14 | forth = []
15 | if k > 1 and l % 2 == 0:
16 | for i in range(len(a)):
17 | if a[i] < l // 2:
18 | one = one + 1
19 | first.append(a[i])
20 | else:
21 | two = two + 1
22 | thrd.append(a[i])
23 | if one > 0 and two > 0:
24 | print(max(first), min(thrd))
25 | if k > 1 and l % 2 == 1:
26 | for i in range(len(a)):
27 | if a[i] == l // 2:
28 | w = a[i]
29 | print(w)
30 | if k > 1 and l % 2 == 1:
31 | for i in range(len(a)):
32 | if p == len(a):
33 | for i in range(len(a)):
34 | if a[i] < l // 2:
35 | six = six + 1
36 | sec.append(a[i])
37 | else:
38 | five = five + 1
39 | forth.append(a[i])
40 | if six > 0 and five > 0:
41 | print(max(sec), min(forth))
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/58.py:
--------------------------------------------------------------------------------
1 | l, k = map(int, input().split())
2 | a = list(map(int, input().split()))
3 | p = 0
4 | for i in range(len(a)):
5 | if l % 2 == 1 and k > 1 and a[i] != l // 2:
6 | p += 1
7 | one = 0
8 | two = 0
9 | five = 0
10 | ar1 = []
11 | ar2 = []
12 | ar3 = []
13 | six = 0
14 | ar4 = []
15 | if k > 1 and l % 2 == 0:
16 | for i in range(len(a)):
17 | if a[i] < l // 2:
18 | one = one + 1
19 | ar1.append(a[i])
20 | else:
21 | two = two + 1
22 | ar3.append(a[i])
23 | if one > 0 and two > 0:
24 | print(max(ar1), min(ar3))
25 | if k > 1 and l % 2 == 1:
26 | for i in range(len(a)):
27 | if a[i] == l // 2:
28 | w = a[i]
29 | print(w)
30 | if k > 1 and l % 2 == 1:
31 | for i in range(len(a)):
32 | if p == len(a):
33 | for i in range(len(a)):
34 | if a[i] < l // 2:
35 | six = six + 1
36 | ar2.append(a[i])
37 | else:
38 | five = five + 1
39 | ar4.append(a[i])
40 | if six > 0 and five > 0:
41 | print(max(ar2), min(ar4))
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/59.py:
--------------------------------------------------------------------------------
1 | n, m = map(int, input().split())
2 | a = list(map(int, input().split()))
3 | b = 0
4 | for i in range(len(a)):
5 | if n % 2 == 1 and m > 1 and a[i] != n // 2:
6 | b = b + 1
7 | s = 0
8 | d = 0
9 | q = 0
10 | v = 0
11 | g = 0
12 | l = []
13 | f = []
14 | p = []
15 | d = 0
16 | h = 0
17 | x = []
18 | if m > 1 and n % 2 == 0:
19 | for i in range(len(a)):
20 | if a[i] < n // 2:
21 | s = s + 1
22 | l.append(a[i])
23 | else:
24 | d = d + 1
25 | p.append(a[i])
26 | if s > 0 and d > 0:
27 | print(max(l), min(p))
28 | if m > 1 and n % 2 == 1:
29 | for i in range(len(a)):
30 | if a[i] == n // 2:
31 | w = a[i]
32 | print(w)
33 | if m > 1 and n % 2 == 1:
34 | for i in range(len(a)):
35 | if b == len(a):
36 | for i in range(len(a)):
37 | if a[i] < n // 2:
38 | h = h + 1
39 | f.append(a[i])
40 | else:
41 | g = g + 1
42 | x.append(a[i])
43 | if h > 0 and g > 0:
44 | print(max(f), min(x))
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/6.py:
--------------------------------------------------------------------------------
1 | def power(a, n):
2 | if n == 0:
3 | return 1
4 | elif n > 0:
5 | i = 2
6 | b = a
7 | while i <= n:
8 | a = a * b
9 | i += 1
10 | return a
11 | else:
12 | i = 0
13 | b = a
14 | a = 1
15 | while i > n:
16 | a = a / b
17 | i -= 1
18 | return a
19 |
20 |
21 | a = float(input())
22 | n = int(input())
23 | print(power(a, n))
24 |
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/60.py:
--------------------------------------------------------------------------------
1 | m, n = map(int, input().split())
2 | blocks = list(map(int, input().split()))
3 | less = blocks[0]
4 | more = blocks[-1]
5 | k = 0
6 | for i in range(n):
7 | if blocks[i] < (m / 2):
8 | less = blocks[i]
9 |
10 | for i in sorted(blocks, reverse=True):
11 | if i + 1 > (m / 2):
12 | more = i
13 |
14 | if more == less and m % 2 == 1:
15 | print(more)
16 | else:
17 | print(less, more)
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/61.py:
--------------------------------------------------------------------------------
1 | a, b = map(int, input().split())
2 | k = [int(i) for i in input().split()]
3 | left = k[0]
4 | right = k[-1]
5 | for i in range(b):
6 | if k[i] < (a / 2):
7 | left = k[i]
8 |
9 | for i in sorted(k, reverse=True):
10 | if i + 1 > (a / 2):
11 | right = i
12 |
13 | if right == left and a % 2 == 1:
14 | print(right)
15 | else:
16 | print(left, right)
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/62.py:
--------------------------------------------------------------------------------
1 | l, n = map(int, input().split())
2 | myl = list(map(int, input().split()))
3 | a = myl[0]
4 | b = myl[-1]
5 | for i in range(n):
6 | if myl[i] < (l / 2):
7 | a = myl[i]
8 |
9 | for i in sorted(myl, reverse=True):
10 | if i + 1 > (l / 2):
11 | b = i
12 |
13 | if b == a and l % 2 == 1:
14 | print(b)
15 | else:
16 | print(a, b)
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/63.py:
--------------------------------------------------------------------------------
1 | lst1 = input().split()
2 | leng = int(lst1[0])
3 | n = int(lst1[1])
4 |
5 | x1 = 0
6 | x2 = -1
7 |
8 | data = []
9 | data1 = input().split()
10 | for i in range(n):
11 | data.append(int(data1[i]))
12 | for i in range(n):
13 | if 2 * data[i] < leng:
14 | x1 = data[i]
15 | if (2 * data[i] + 2 > leng) and (x2 == -1):
16 | x2 = data[i]
17 | if x1 == x2:
18 | print(x1)
19 | else:
20 | print(x1, x2)
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/64.py:
--------------------------------------------------------------------------------
1 | dt = input().split()
2 | length = int(dt[0])
3 | n = int(dt[1])
4 |
5 |
6 | ans1 = 0
7 | ans2 = -1
8 |
9 |
10 | data = []
11 |
12 | data_ = input().split()
13 |
14 |
15 | for i in range(n):
16 | data.append(int(data_[i]))
17 |
18 | for i in range(n):
19 | if 2 * data[i] < length:
20 | ans1 = data[i]
21 | if 2 * data[i] + 2 > length and ans2 == -1:
22 | ans2 = data[i]
23 |
24 | if ans1 == ans2:
25 | print(ans1)
26 | else:
27 | print(ans1, ans2)
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/65.py:
--------------------------------------------------------------------------------
1 | l, k = map(int, input().split())
2 | blok = list(map(int, input().split()))
3 | a = [0] * l
4 | k1 = k2 = 0
5 | for i in range(len(blok)):
6 | a[blok[i]] += 1
7 | if l % 2 == 0:
8 | g1 = l // 2 - 1
9 | g2 = l // 2
10 | for i in range(len(a)):
11 | if a[i] != 0 and i <= g1:
12 | k1 = i
13 | if a[i] != 0 and i >= g2 and k2 == 0:
14 | k2 = i
15 | print(k1, k2)
16 | else:
17 | g = l // 2
18 | if a[g] == 1:
19 | print(g)
20 | else:
21 | for i in range(len(a)):
22 | if a[i] != 0 and i < g:
23 | k1 = i
24 | if a[i] != 0 and i > g and k2 == 0:
25 | k2 = i
26 | print(k1, k2)
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/66.py:
--------------------------------------------------------------------------------
1 | l, k = list(map(int, input().split()))
2 | n = list(map(int, input().split()))
3 | right = 0
4 | left = 0
5 | nearL = -1
6 | nearR = l + 1
7 | a = [0] * l
8 | for i in range(len(n)):
9 | a[n[i]] = a[n[i]] + 1
10 | if l % 2 == 0:
11 | nearL = l // 2 - 1
12 | nearR = l // 2
13 | for i in range(l):
14 | if i <= nearL and a[i] != 0:
15 | left = i
16 | if i >= nearR and right == 0 and a[i] != 0:
17 | right = i
18 | print(left, right)
19 | else:
20 | near = l // 2
21 | if a[near] == 1:
22 | print(near)
23 | else:
24 | for i in range(l):
25 | if i < near and a[i] != 0:
26 | left = i
27 | if i > near and right == 0 and a[i] != 0:
28 | right = i
29 | print(left, right)
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/67.py:
--------------------------------------------------------------------------------
1 | l, k = map(int, input().split())
2 | legs = list(map(int, input().split()))
3 | middle = -1
4 | legs_number = set()
5 | legs_number1 = set()
6 | for i in range(len(legs)):
7 | if (l - 1) / 2 == legs[i]:
8 | middle = legs[i]
9 | elif (l - 1) / 2 > legs[i]:
10 | legs_number.add(legs[i])
11 | elif (l - 1) / 2 < legs[i]:
12 | legs_number1.add(legs[i])
13 | if middle != -1:
14 | print(middle)
15 | else:
16 | print(max(legs_number), min(legs_number1))
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/68.py:
--------------------------------------------------------------------------------
1 | l, k = map(int, input().split())
2 | block = list(map(int, input().split()))
3 | mid = -1
4 | block_num1 = set()
5 | block_num2 = set()
6 | for i in range(len(block)):
7 | if (l - 1) / 2 == block[i]:
8 | mid = block[i]
9 | elif (l - 1) / 2 > block[i]:
10 | block_num1.add(block[i])
11 | elif (l - 1) / 2 < block[i]:
12 | block_num2.add(block[i])
13 | if mid != -1:
14 | print(mid)
15 | else:
16 | left = max(block_num1)
17 | right = min(block_num2)
18 | print(left, right)
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/69.py:
--------------------------------------------------------------------------------
1 | P_23, D_23 = list(map(int, input().split()))
2 | n_23 = list(map(int, input().split()))
3 | x_23 = n_23[0]
4 | y_23 = n_23[len(n_23) - 1]
5 | for k in range(len(n_23)):
6 | if n_23[k] < P_23 / 2:
7 | x_23 = n_23[k]
8 | for i in range(len(n_23) - 1, -1, -1):
9 | if n_23[i] >= P_23 / 2:
10 | y_23 = n_23[i]
11 | if x_23 == P_23 // 2:
12 | print(x_23)
13 | else:
14 | print(x_23)
15 | print(y_23)
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/7.py:
--------------------------------------------------------------------------------
1 | import math
2 |
3 |
4 | def rev():
5 | n = int(input())
6 | if n != 0:
7 | rev()
8 | if (math.sqrt(n).is_integer()):
9 | global flag
10 | flag = 1
11 | print(n)
12 |
13 | flag = 0
14 | rev()
15 | if flag == 0:
16 | print(0)
17 |
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/70.py:
--------------------------------------------------------------------------------
1 | L, K = list(map(int, input().split()))
2 | N = list(map(int, input().split()))
3 | a = N[0]
4 | b = N[len(N) - 1]
5 | for i in range(len(N)):
6 | if N[i] < L / 2:
7 | a = N[i]
8 | for j in range(len(N) - 1, -1, -1):
9 | if N[j] >= L / 2:
10 | b = N[j]
11 | if a == L // 2:
12 | print(a)
13 | else:
14 | print(a)
15 | print(b)
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/71.py:
--------------------------------------------------------------------------------
1 | n, k = map(int, input().split())
2 | mas = []
3 | s = list(map(int, input().split()))
4 | for i in range(n):
5 | mas.append([[abs(s[i]-k), s[i]]])
6 | for f in range(1, n):
7 | s = list(map(int, input().split()))
8 | for j in range(n):
9 | mas[j].append([abs(s[j]-k), s[j]])
10 |
11 | for e in range(n):
12 | mas[e].sort()
13 |
14 | for i in range(n):
15 | for j in range(n-1):
16 | print(mas[j][i][1], ' ', sep='', end='')
17 | print(mas[n-1][i][1])
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/72.py:
--------------------------------------------------------------------------------
1 | n, k = map(int, input().split())
2 | a = []
3 | s = list(map(int, input().split()))
4 | for i in range(n):
5 | a.append([[abs(s[i]-k), s[i]]])
6 | for i in range(1, n):
7 | s = list(map(int, input().split()))
8 | for j in range(n):
9 | a[j].append([abs(s[j]-k), s[j]])
10 |
11 | for i in range(n):
12 | a[i].sort()
13 |
14 | for i in range(n):
15 | for j in range(n-1):
16 | print(a[j][i][1], ' ', sep='', end='')
17 | print(a[n-1][i][1])
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/73.py:
--------------------------------------------------------------------------------
1 | x = list(map(int, input().split()))
2 | n = x[0]
3 | k = x[1]
4 | lst = list(map(int, input().split()))
5 | arr = []
6 | for i in range(n):
7 | arr.append([[abs(lst[i] - k), lst[i]]])
8 | for f in range(1, n):
9 | lst = list(map(int, input().split()))
10 | for j in range(n):
11 | arr[j].append([abs(lst[j] - k), lst[j]])
12 | for i in range(n):
13 | arr[i].sort()
14 | for i in range(n):
15 | for j in range(n - 1):
16 | print(arr[j][i][1], ' ', sep='', end='')
17 | print(arr[n - 1][i][1])
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/8.py:
--------------------------------------------------------------------------------
1 | import math
2 |
3 |
4 | def rev():
5 | n = int(input())
6 | if n != 0:
7 | rev()
8 | if (math.sqrt(n).is_integer()):
9 | global flag
10 | flag = 1
11 | print(n)
12 |
13 | flag = 0
14 | rev()
15 | if flag == 0:
16 | print(0)
17 |
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/cheating/9.py:
--------------------------------------------------------------------------------
1 | n = int(input())
2 | partial_factorial = 1
3 | partial_sum = 0
4 | for i in range(1, n + 1):
5 | partial_factorial *= i
6 | partial_sum += partial_factorial
7 | print(partial_sum)
8 |
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/file.txt:
--------------------------------------------------------------------------------
1 | ахаха=азащзазащ
2 | ахах
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/function_g.pickle:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hse-econ-data-science/dap_2022-23/1e23952959de15a2f17b63dd48523a62245c74fc/sem07_wow/sem07_2113/function_g.pickle
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/lst.pickle:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hse-econ-data-science/dap_2022-23/1e23952959de15a2f17b63dd48523a62245c74fc/sem07_wow/sem07_2113/lst.pickle
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/marks.tsv:
--------------------------------------------------------------------------------
1 | fio login group email 1 2 3 4 ДЗ итог 1 2 3 4 5 6 МСР итог 1 2 3 БСР итог Итог Итог округл Проверяющий ассистент
2 | Новицкая Алина Дмитриевна dap_econ_2022_358 БЭК196 adnovitskaya@edu.hse.ru 11 2.8 4.3 8.0 2.0 9 3.0 2.78 3
3 | Мунхтур Эгшиглэн dap_econ_2022_359 БЭК197 emunkhtur@edu.hse.ru 2 0.5 0.0 0.0 0.25 0
4 | Майданов Бекнур dap_econ_2022_360 БЭК198 bmaydanov@edu.hse.ru 11 2.8 0.0 0.0 0 0.0 1.38 1
5 | Мукамбеков Бектур dap_econ_2022_361 БЭК199 bmukambekov@edu.hse.ru 11 2.8 0.0 10 3.3 2.71 3
6 | Цветкова Алёна Алексеевна dap_econ_2022_353 БЭК2011 aatsvetkova_3@edu.hse.ru 11 2.8 10.0 10.0 3.3 10 3.3 3.04 3
7 | Артеменко Мария Игоревна dap_econ_2022_354 БЭК2012 miartemenko@edu.hse.ru 11 2.8 0.0 0.0 1.38 1
8 | Котляренко Владислав Викторович dap_econ_2022_355 БЭК2012 vvkotlyarenko@edu.hse.ru 10.3 2.6 8.0 10.0 3.0 0 0.0 1.59 2
9 | Хафизов Шохрух Обиджон угли dap_econ_2022_357 БЭК209 shokhafizov@edu.hse.ru 0 0.0 0.0 0.0 0.00 0
10 | Адмайкин Артём Евгеньевич dap_econ_2022_11 БЭК211 aeadmaykin@edu.hse.ru 3.5 0.9 6.0 10.0 2.7 7.5 2.5 1.70 2
11 | Багаутдинов Эрнест Ришатович dap_econ_2022_12 БЭК211 erbagautdinov@edu.hse.ru 11 2.8 0.0 10.0 1.7 9 3.0 2.74 3
12 | Баландин Егор Максимович dap_econ_2022_13 БЭК211 embalandin@edu.hse.ru 11 2.8 4.0 4.0 1.3 10 3.3 2.84 3
13 | Березин Даниил Сергеевич dap_econ_2022_14 БЭК211 dsberezin_1@edu.hse.ru 11 2.8 10.0 10.0 3.3 4.6 1.5 2.32 2
14 | Богоявленский Максим Сергеевич dap_econ_2022_15 БЭК211 msbogoyavlenskiy@edu.hse.ru 11 2.8 8.0 8.0 2.7 9.6 3.2 2.92 3
15 | Гарифуллов Тимур Гамилевич dap_econ_2022_16 БЭК211 tggarifullov@edu.hse.ru 10.8 2.7 10.0 8.0 3.0 9 3.0 2.85 3
16 | Гельмиза Арсений Андреевич dap_econ_2022_17 БЭК211 aagelmiza@edu.hse.ru 0 0.0 8.0 10.0 3.0 6.6 2.2 1.18 1
17 | Горбенко Игорь Денисович dap_econ_2022_18 БЭК211 idgorbenko@edu.hse.ru 11 2.8 10.0 8.0 3.0 10 3.3 3.01 3
18 | Грязнов Михаил Александрович dap_econ_2022_19 БЭК211 magryaznov@edu.hse.ru 11 2.8 0.0 10.0 1.7 4 1.3 2.08 2
19 | Гусева Екатерина Евгеньевна dap_econ_2022_20 БЭК211 eeguseva_1@edu.hse.ru 11 2.8 7.0 8.0 2.5 10 3.3 2.96 3
20 | Ермаков Тимур Сергеевич dap_econ_2022_21 БЭК211 tsermakov@edu.hse.ru 9.8 2.5 0.0 0.0 0.0 9 3.0 2.43 2
21 | Казаков Михаил Станиславович dap_econ_2022_22 БЭК211 mskazakov@edu.hse.ru 11 2.8 0.0 0.0 0.0 0.5 0.2 1.44 1
22 | Карлова Ульяна Юрьевна dap_econ_2022_23 БЭК211 uyukarlova@edu.hse.ru 0 0.0 8.0 8.0 2.7 0 0.0 0.27 0
23 | Каюмова Карина Ринатовна dap_econ_2022_24 БЭК211 krkayumova_1@edu.hse.ru 0 0.0 10.0 10.0 3.3 10 3.3 1.67 2
24 | Комарова Серафима Николаевна dap_econ_2022_25 БЭК211 snkomarova@edu.hse.ru 0.1 0.0 0.0 6.0 1.0 9 3.0 1.31 1
25 | Котяков Даниил Антонович dap_econ_2022_26 БЭК211 dakotyakov@edu.hse.ru 10.8 2.7 0.0 2.0 0.3 6 2.0 2.18 2
26 | Кривоносов Андрей Дмитриевич dap_econ_2022_27 БЭК211 adkrivonosov@edu.hse.ru 11 2.8 10.0 8.0 3.0 9.6 3.2 2.96 3
27 | Куцев Владимир Максимович dap_econ_2022_28 БЭК211 vmkutsev@edu.hse.ru 0.0 0.0 0.0 0.0 10 3.3 1.33 1
28 | Левакова Оксана Сергеевна dap_econ_2022_29 БЭК211 oslevakova@edu.hse.ru 11 2.8 10.0 8.0 3.0 0 0.0 1.68 2
29 | Маслов Кирилл Олегович dap_econ_2022_30 БЭК211 komaslov@edu.hse.ru 0.0 0.0 6.0 1.0 6 2.0 0.90 1
30 | Микаелян Арман Арменович dap_econ_2022_31 БЭК211 aamikaelyan@edu.hse.ru 10.1 2.5 8.0 10.0 3.0 4 1.3 2.10 2
31 | Мовсисян Артём Алексеевич dap_econ_2022_32 БЭК211 aamovsisyan_1@edu.hse.ru 8.5 2.1 10.0 8.0 3.0 0 0.0 1.36 1
32 | Москвина Анастасия Олеговна dap_econ_2022_33 БЭК211 aomoskvina_1@edu.hse.ru 11 2.8 10.0 8.0 3.0 10 3.3 3.01 3
33 | Пахомов Иван Андреевич dap_econ_2022_34 БЭК211 iapakhomov@edu.hse.ru 11 2.8 8.0 8.0 2.7 5 1.7 2.31 2
34 | Полищук Мария Вячеславовна dap_econ_2022_35 БЭК211 mvpolischuk@edu.hse.ru 0 0.0 10.0 10.0 3.3 2.5 0.8 0.67 1
35 | Шакирова Эльмира Фаридовна dap_econ_2022_36 БЭК211 efshakirova@edu.hse.ru 10 2.5 8.0 10.0 3.0 10 3.3 2.88 3
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/my_important_dict.pkl:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hse-econ-data-science/dap_2022-23/1e23952959de15a2f17b63dd48523a62245c74fc/sem07_wow/sem07_2113/my_important_dict.pkl
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/my_important_function.pkl:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hse-econ-data-science/dap_2022-23/1e23952959de15a2f17b63dd48523a62245c74fc/sem07_wow/sem07_2113/my_important_function.pkl
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/my_library/my_module/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hse-econ-data-science/dap_2022-23/1e23952959de15a2f17b63dd48523a62245c74fc/sem07_wow/sem07_2113/my_library/my_module/__init__.py
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/my_library/my_module/my_module.py:
--------------------------------------------------------------------------------
1 | def foo():
2 | print('I\'m from module!')
3 |
4 | def boo():
5 | print(1+1)
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/my_library/setup.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hse-econ-data-science/dap_2022-23/1e23952959de15a2f17b63dd48523a62245c74fc/sem07_wow/sem07_2113/my_library/setup.py
--------------------------------------------------------------------------------
/sem07_wow/sem07_2113/some_folder/test.txt:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hse-econ-data-science/dap_2022-23/1e23952959de15a2f17b63dd48523a62245c74fc/sem07_wow/sem07_2113/some_folder/test.txt
--------------------------------------------------------------------------------
/sem07_wow/sem07_218/file.txt:
--------------------------------------------------------------------------------
1 | азазазаахахахаахахаха
2 | ахахахаlkwfjfwejfwelахахаЯ фанатеюlkwfjfwejfwelахахаЯ фанатеюlkwfjfwejfwel
3 | ахаха
4 | Я фанатею
--------------------------------------------------------------------------------
/sem07_wow/sem07_218/lst.pickle:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hse-econ-data-science/dap_2022-23/1e23952959de15a2f17b63dd48523a62245c74fc/sem07_wow/sem07_218/lst.pickle
--------------------------------------------------------------------------------
/sem07_wow/sem07_218/markup.pickle:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hse-econ-data-science/dap_2022-23/1e23952959de15a2f17b63dd48523a62245c74fc/sem07_wow/sem07_218/markup.pickle
--------------------------------------------------------------------------------
/sem07_wow/sem07_218/table.tsv:
--------------------------------------------------------------------------------
1 | fio login group email 1 2 3 4 ДЗ итог 1 2 3 4 5 6 МСР итог 1 2 3 БСР итог Итог Итог округл Проверяющий ассистент
2 | Новицкая Алина Дмитриевна dap_econ_2022_358 БЭК196 adnovitskaya@edu.hse.ru 11 2.8 4.3 8.0 2.0 9 3.0 2.78 3
3 | Мунхтур Эгшиглэн dap_econ_2022_359 БЭК197 emunkhtur@edu.hse.ru 2 0.5 0.0 0.0 0.25 0
4 | Майданов Бекнур dap_econ_2022_360 БЭК198 bmaydanov@edu.hse.ru 11 2.8 0.0 0.0 0 0.0 1.38 1
5 | Мукамбеков Бектур dap_econ_2022_361 БЭК199 bmukambekov@edu.hse.ru 11 2.8 0.0 10 3.3 2.71 3
6 | Цветкова Алёна Алексеевна dap_econ_2022_353 БЭК2011 aatsvetkova_3@edu.hse.ru 11 2.8 10.0 10.0 3.3 10 3.3 3.04 3
7 | Артеменко Мария Игоревна dap_econ_2022_354 БЭК2012 miartemenko@edu.hse.ru 11 2.8 0.0 0.0 1.38 1
8 | Котляренко Владислав Викторович dap_econ_2022_355 БЭК2012 vvkotlyarenko@edu.hse.ru 10.3 2.6 8.0 10.0 3.0 0 0.0 1.59 2
9 | Хафизов Шохрух Обиджон угли dap_econ_2022_357 БЭК209 shokhafizov@edu.hse.ru 0 0.0 0.0 0.0 0.00 0
--------------------------------------------------------------------------------
/sem07_wow/sem07_218/test.json:
--------------------------------------------------------------------------------
1 | [{"a": 0}, {"a": 1}, {"a": 2}]
--------------------------------------------------------------------------------
/sem07_wow/sem07_218/test.pickle:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hse-econ-data-science/dap_2022-23/1e23952959de15a2f17b63dd48523a62245c74fc/sem07_wow/sem07_218/test.pickle
--------------------------------------------------------------------------------
/sem07_wow/sem_07_213.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "id": "coated-linux",
6 | "metadata": {},
7 | "source": [
8 | "## План\n",
9 | "\n",
10 | "1. Поговорим про оценки\n",
11 | "2. Повторим конструкции (5-7 мин)\n",
12 | "3. Порешаем задачу с литкода \n",
13 | "4. Рассмотрим всякие приколы в питоне\n",
14 | "5. МСР"
15 | ]
16 | },
17 | {
18 | "cell_type": "markdown",
19 | "id": "crude-warehouse",
20 | "metadata": {},
21 | "source": [
22 | "## Структуры данных\n",
23 | "\n",
24 | "* Список\n",
25 | "* Кортеж\n",
26 | "* Множество\n",
27 | "* Словарь"
28 | ]
29 | },
30 | {
31 | "cell_type": "markdown",
32 | "id": "twelve-crazy",
33 | "metadata": {},
34 | "source": [
35 | "## Немного о сложностях"
36 | ]
37 | },
38 | {
39 | "cell_type": "code",
40 | "execution_count": 1,
41 | "id": "treated-harassment",
42 | "metadata": {},
43 | "outputs": [
44 | {
45 | "data": {
46 | "text/plain": [
47 | "True"
48 | ]
49 | },
50 | "execution_count": 1,
51 | "metadata": {},
52 | "output_type": "execute_result"
53 | }
54 | ],
55 | "source": [
56 | "x = [1, 2, 3, 4]\n",
57 | "\n",
58 | "3 in x # O(n)"
59 | ]
60 | },
61 | {
62 | "cell_type": "code",
63 | "execution_count": 5,
64 | "id": "processed-adjustment",
65 | "metadata": {},
66 | "outputs": [
67 | {
68 | "name": "stdout",
69 | "output_type": "stream",
70 | "text": [
71 | "{1, 2, 3, 4}\n"
72 | ]
73 | },
74 | {
75 | "data": {
76 | "text/plain": [
77 | "True"
78 | ]
79 | },
80 | "execution_count": 5,
81 | "metadata": {},
82 | "output_type": "execute_result"
83 | }
84 | ],
85 | "source": [
86 | "x = [1, 2, 3, 4, 4]\n",
87 | "\n",
88 | "x_set = set(x) # O(n)\n",
89 | "\n",
90 | "print(x_set)\n",
91 | "\n",
92 | "3 in x_set # O(1)"
93 | ]
94 | },
95 | {
96 | "cell_type": "code",
97 | "execution_count": 7,
98 | "id": "amazing-uganda",
99 | "metadata": {},
100 | "outputs": [
101 | {
102 | "data": {
103 | "text/plain": [
104 | "14"
105 | ]
106 | },
107 | "execution_count": 7,
108 | "metadata": {},
109 | "output_type": "execute_result"
110 | }
111 | ],
112 | "source": [
113 | "x = [1, 2, 3, 4, 4]\n",
114 | "\n",
115 | "sum(x) # O(n)\n",
116 | "\n",
117 | "\n",
118 | "#def my_sum(x):\n",
119 | "# summa = 0\n",
120 | "# for el in x:\n",
121 | "# summa += el\n",
122 | "# return summa"
123 | ]
124 | },
125 | {
126 | "cell_type": "code",
127 | "execution_count": 8,
128 | "id": "economic-annotation",
129 | "metadata": {},
130 | "outputs": [
131 | {
132 | "data": {
133 | "text/plain": [
134 | "5"
135 | ]
136 | },
137 | "execution_count": 8,
138 | "metadata": {},
139 | "output_type": "execute_result"
140 | }
141 | ],
142 | "source": [
143 | "x = [1, 2, 3, 4, 4]\n",
144 | "\n",
145 | "len(x) # O(1)"
146 | ]
147 | },
148 | {
149 | "cell_type": "markdown",
150 | "id": "comic-universal",
151 | "metadata": {},
152 | "source": [
153 | "## Задачку с литкода (2sum)"
154 | ]
155 | },
156 | {
157 | "cell_type": "code",
158 | "execution_count": 17,
159 | "id": "decimal-duncan",
160 | "metadata": {},
161 | "outputs": [
162 | {
163 | "data": {
164 | "text/plain": [
165 | "(3, 4)"
166 | ]
167 | },
168 | "execution_count": 17,
169 | "metadata": {},
170 | "output_type": "execute_result"
171 | }
172 | ],
173 | "source": [
174 | "x = [1, 100, 50, 40, 2] \n",
175 | "target = 42\n",
176 | "\n",
177 | "def slow_2sum(x, target):\n",
178 | " for i in range(len(x)): # O(n)\n",
179 | " for j in range(i+1, len(x)): # O(n)\n",
180 | " if x[i] + x[j] == target: # O(1)\n",
181 | " return (i, j)\n",
182 | " \n",
183 | "\n",
184 | "slow_2sum(x, target)\n",
185 | "\n",
186 | "# O(n^2)"
187 | ]
188 | },
189 | {
190 | "cell_type": "code",
191 | "execution_count": 20,
192 | "id": "nutritional-plaza",
193 | "metadata": {},
194 | "outputs": [
195 | {
196 | "data": {
197 | "text/plain": [
198 | "(40, 2)"
199 | ]
200 | },
201 | "execution_count": 20,
202 | "metadata": {},
203 | "output_type": "execute_result"
204 | }
205 | ],
206 | "source": [
207 | "x = [1, 100, 50, 40, 2] \n",
208 | "target = 42\n",
209 | "\n",
210 | "def slow_2sum(x, target):\n",
211 | " for i in range(len(x)): # O(n)\n",
212 | " k = target - x[i] # O(1)\n",
213 | " if k in x: # O(n)\n",
214 | " return (x[i], k)\n",
215 | " \n",
216 | "slow_2sum(x, target)\n",
217 | "\n",
218 | "# O(n^2)"
219 | ]
220 | },
221 | {
222 | "cell_type": "code",
223 | "execution_count": 22,
224 | "id": "civilian-buffalo",
225 | "metadata": {},
226 | "outputs": [
227 | {
228 | "data": {
229 | "text/plain": [
230 | "(40, 2)"
231 | ]
232 | },
233 | "execution_count": 22,
234 | "metadata": {},
235 | "output_type": "execute_result"
236 | }
237 | ],
238 | "source": [
239 | "x = [1, 100, 50, 40, 2, 2] \n",
240 | "target = 4\n",
241 | "\n",
242 | "def fast_2sum(x, target):\n",
243 | " x_set = set(x) # O(n)\n",
244 | " \n",
245 | " for i in range(len(x)): # O(n)\n",
246 | " k = target - x[i] # O(1)\n",
247 | " if k in x_set: # O(1)\n",
248 | " return (x[i], k)\n",
249 | " \n",
250 | "fast_2sum(x, target)\n",
251 | "\n",
252 | "# O(n + n) = O(2n) = O(n)\n",
253 | "\n"
254 | ]
255 | },
256 | {
257 | "cell_type": "code",
258 | "execution_count": null,
259 | "id": "presidential-rebound",
260 | "metadata": {},
261 | "outputs": [],
262 | "source": []
263 | }
264 | ],
265 | "metadata": {
266 | "kernelspec": {
267 | "display_name": "Python 3",
268 | "language": "python",
269 | "name": "python3"
270 | },
271 | "language_info": {
272 | "codemirror_mode": {
273 | "name": "ipython",
274 | "version": 3
275 | },
276 | "file_extension": ".py",
277 | "mimetype": "text/x-python",
278 | "name": "python",
279 | "nbconvert_exporter": "python",
280 | "pygments_lexer": "ipython3",
281 | "version": "3.9.2"
282 | },
283 | "varInspector": {
284 | "cols": {
285 | "lenName": 16,
286 | "lenType": 16,
287 | "lenVar": 40
288 | },
289 | "kernels_config": {
290 | "python": {
291 | "delete_cmd_postfix": "",
292 | "delete_cmd_prefix": "del ",
293 | "library": "var_list.py",
294 | "varRefreshCmd": "print(var_dic_list())"
295 | },
296 | "r": {
297 | "delete_cmd_postfix": ") ",
298 | "delete_cmd_prefix": "rm(",
299 | "library": "var_list.r",
300 | "varRefreshCmd": "cat(var_dic_list()) "
301 | }
302 | },
303 | "types_to_exclude": [
304 | "module",
305 | "function",
306 | "builtin_function_or_method",
307 | "instance",
308 | "_Feature"
309 | ],
310 | "window_display": false
311 | }
312 | },
313 | "nbformat": 4,
314 | "nbformat_minor": 5
315 | }
316 |
--------------------------------------------------------------------------------
/sem07_wow/sem_07_214.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "id": "whole-trash",
6 | "metadata": {},
7 | "source": [
8 | "## План\n",
9 | "\n",
10 | "1. Вспомним структуры данных\n",
11 | "2. Поговорим про сложности\n",
12 | "3. Решим задачку с литкода\n",
13 | "4. МСР (за 10 мин)"
14 | ]
15 | },
16 | {
17 | "cell_type": "markdown",
18 | "id": "fatty-reputation",
19 | "metadata": {},
20 | "source": [
21 | "## Структуры данных\n",
22 | "\n",
23 | "* Списки\n",
24 | "* Кортежи\n",
25 | "* Множества\n",
26 | "* Словари"
27 | ]
28 | },
29 | {
30 | "cell_type": "markdown",
31 | "id": "introductory-brook",
32 | "metadata": {},
33 | "source": [
34 | "## Сложности"
35 | ]
36 | },
37 | {
38 | "cell_type": "code",
39 | "execution_count": 33,
40 | "id": "divided-yeast",
41 | "metadata": {},
42 | "outputs": [
43 | {
44 | "data": {
45 | "text/plain": [
46 | "dict_keys([])"
47 | ]
48 | },
49 | "execution_count": 33,
50 | "metadata": {},
51 | "output_type": "execute_result"
52 | }
53 | ],
54 | "source": [
55 | "d = {}\n",
56 | "\n",
57 | "d.keys()"
58 | ]
59 | },
60 | {
61 | "cell_type": "code",
62 | "execution_count": 2,
63 | "id": "protecting-stomach",
64 | "metadata": {},
65 | "outputs": [
66 | {
67 | "data": {
68 | "text/plain": [
69 | "False"
70 | ]
71 | },
72 | "execution_count": 2,
73 | "metadata": {},
74 | "output_type": "execute_result"
75 | }
76 | ],
77 | "source": [
78 | "x = [1, 2, 3, 4]\n",
79 | "\n",
80 | "3 in x # O(n)"
81 | ]
82 | },
83 | {
84 | "cell_type": "code",
85 | "execution_count": 6,
86 | "id": "nominated-kansas",
87 | "metadata": {},
88 | "outputs": [
89 | {
90 | "data": {
91 | "text/plain": [
92 | "True"
93 | ]
94 | },
95 | "execution_count": 6,
96 | "metadata": {},
97 | "output_type": "execute_result"
98 | }
99 | ],
100 | "source": [
101 | "x = [1, 2, 3, 4]\n",
102 | "\n",
103 | "x_set = set(x) # O(n)\n",
104 | "\n",
105 | "3 in x_set # O(1)"
106 | ]
107 | },
108 | {
109 | "cell_type": "code",
110 | "execution_count": 7,
111 | "id": "durable-container",
112 | "metadata": {},
113 | "outputs": [
114 | {
115 | "data": {
116 | "text/plain": [
117 | "10"
118 | ]
119 | },
120 | "execution_count": 7,
121 | "metadata": {},
122 | "output_type": "execute_result"
123 | }
124 | ],
125 | "source": [
126 | "x = [1, 2, 3, 4]\n",
127 | "\n",
128 | "sum(x) # O(n)"
129 | ]
130 | },
131 | {
132 | "cell_type": "code",
133 | "execution_count": 8,
134 | "id": "closed-chain",
135 | "metadata": {},
136 | "outputs": [],
137 | "source": [
138 | "#def my_sum(x): # O(n)\n",
139 | "# summa = 0\n",
140 | "# for el in x: # O(n)\n",
141 | "# summa += el\n",
142 | "# return summa"
143 | ]
144 | },
145 | {
146 | "cell_type": "code",
147 | "execution_count": 9,
148 | "id": "lucky-staff",
149 | "metadata": {},
150 | "outputs": [
151 | {
152 | "data": {
153 | "text/plain": [
154 | "4"
155 | ]
156 | },
157 | "execution_count": 9,
158 | "metadata": {},
159 | "output_type": "execute_result"
160 | }
161 | ],
162 | "source": [
163 | "x = [1, 2, 3, 4]\n",
164 | "\n",
165 | "len(x) # O(1)"
166 | ]
167 | },
168 | {
169 | "cell_type": "markdown",
170 | "id": "sexual-error",
171 | "metadata": {},
172 | "source": [
173 | "## Задачка с литкода (2sum)"
174 | ]
175 | },
176 | {
177 | "cell_type": "code",
178 | "execution_count": 13,
179 | "id": "received-humor",
180 | "metadata": {},
181 | "outputs": [
182 | {
183 | "data": {
184 | "text/plain": [
185 | "(2, 7)"
186 | ]
187 | },
188 | "execution_count": 13,
189 | "metadata": {},
190 | "output_type": "execute_result"
191 | }
192 | ],
193 | "source": [
194 | "nums = [2, 7, 11, 15]\n",
195 | "target = 9\n",
196 | "\n",
197 | "def slow_2sum(x, target):\n",
198 | " for i in range(len(x)): # O(n)\n",
199 | " for j in range(i+1, len(x)): # O(n)\n",
200 | " if x[i] + x[j] == target: # O(1)\n",
201 | " return (x[i], x[j]) # O(1)\n",
202 | "\n",
203 | "\n",
204 | "# O(n^2) \n",
205 | "slow_2sum(nums, target)"
206 | ]
207 | },
208 | {
209 | "cell_type": "code",
210 | "execution_count": 21,
211 | "id": "russian-affect",
212 | "metadata": {},
213 | "outputs": [
214 | {
215 | "data": {
216 | "text/plain": [
217 | "(2, 7)"
218 | ]
219 | },
220 | "execution_count": 21,
221 | "metadata": {},
222 | "output_type": "execute_result"
223 | }
224 | ],
225 | "source": [
226 | "nums = [2, 7, 11, 15]\n",
227 | "target = 9\n",
228 | "\n",
229 | "def slow_2sum(x, target):\n",
230 | " for i in range(len(x)): # O(n)\n",
231 | " k = target - x[i] # O(1)\n",
232 | " if (k in x) and (x[i] != k): # O(n)\n",
233 | " return (x[i], k) # O(1) \n",
234 | " \n",
235 | "# O(n^2)\n",
236 | "slow_2sum(nums, target)"
237 | ]
238 | },
239 | {
240 | "cell_type": "code",
241 | "execution_count": null,
242 | "id": "accredited-tactics",
243 | "metadata": {},
244 | "outputs": [],
245 | "source": [
246 | "nums = [2, 7, 11, 15]\n",
247 | "target = 9\n",
248 | "\n",
249 | "def slow_2sum(x, target):\n",
250 | " for i in range(len(x)): # O(n)\n",
251 | " k = target - x[i] # O(1)\n",
252 | " if (k in x) and (x[i] != k): # O(n)\n",
253 | " return (x[i], k) # O(1) \n",
254 | " \n",
255 | "# O(n^2)\n",
256 | "slow_2sum(nums, target)"
257 | ]
258 | },
259 | {
260 | "cell_type": "code",
261 | "execution_count": 25,
262 | "id": "center-society",
263 | "metadata": {},
264 | "outputs": [
265 | {
266 | "data": {
267 | "text/plain": [
268 | "(2, 7)"
269 | ]
270 | },
271 | "execution_count": 25,
272 | "metadata": {},
273 | "output_type": "execute_result"
274 | }
275 | ],
276 | "source": [
277 | "nums = [2, 7, 11, 15]\n",
278 | "target = 9\n",
279 | "\n",
280 | "def fast_2sum(x, target):\n",
281 | " x_set = set(x) # O(n)\n",
282 | " \n",
283 | " for i in range(len(x)): # O(n)\n",
284 | " k = target - x[i] # O(1)\n",
285 | " if (k in x_set) and (x[i] != k): # O(1)\n",
286 | " return (x[i], k) # O(1) \n",
287 | " \n",
288 | "# O(n+n) = O(2n) = O(n)\n",
289 | "fast_2sum(nums, target)"
290 | ]
291 | },
292 | {
293 | "cell_type": "code",
294 | "execution_count": 32,
295 | "id": "computational-desktop",
296 | "metadata": {},
297 | "outputs": [
298 | {
299 | "data": {
300 | "text/plain": [
301 | "(0, 2)"
302 | ]
303 | },
304 | "execution_count": 32,
305 | "metadata": {},
306 | "output_type": "execute_result"
307 | }
308 | ],
309 | "source": [
310 | "nums = [2, 7, 2]\n",
311 | "target = 4\n",
312 | "\n",
313 | "def fast_2sum(x, target):\n",
314 | " d = {}\n",
315 | " for i in range(len(nums)):\n",
316 | " k = target - x[i]\n",
317 | " if k in d:\n",
318 | " return (d[k], i)\n",
319 | " d[x[i]] = i\n",
320 | " \n",
321 | "# O(n)\n",
322 | "fast_2sum(nums, target)"
323 | ]
324 | },
325 | {
326 | "cell_type": "code",
327 | "execution_count": null,
328 | "id": "hearing-shadow",
329 | "metadata": {},
330 | "outputs": [],
331 | "source": []
332 | }
333 | ],
334 | "metadata": {
335 | "kernelspec": {
336 | "display_name": "Python 3",
337 | "language": "python",
338 | "name": "python3"
339 | },
340 | "language_info": {
341 | "codemirror_mode": {
342 | "name": "ipython",
343 | "version": 3
344 | },
345 | "file_extension": ".py",
346 | "mimetype": "text/x-python",
347 | "name": "python",
348 | "nbconvert_exporter": "python",
349 | "pygments_lexer": "ipython3",
350 | "version": "3.9.2"
351 | },
352 | "varInspector": {
353 | "cols": {
354 | "lenName": 16,
355 | "lenType": 16,
356 | "lenVar": 40
357 | },
358 | "kernels_config": {
359 | "python": {
360 | "delete_cmd_postfix": "",
361 | "delete_cmd_prefix": "del ",
362 | "library": "var_list.py",
363 | "varRefreshCmd": "print(var_dic_list())"
364 | },
365 | "r": {
366 | "delete_cmd_postfix": ") ",
367 | "delete_cmd_prefix": "rm(",
368 | "library": "var_list.r",
369 | "varRefreshCmd": "cat(var_dic_list()) "
370 | }
371 | },
372 | "types_to_exclude": [
373 | "module",
374 | "function",
375 | "builtin_function_or_method",
376 | "instance",
377 | "_Feature"
378 | ],
379 | "window_display": false
380 | }
381 | },
382 | "nbformat": 4,
383 | "nbformat_minor": 5
384 | }
385 |
--------------------------------------------------------------------------------
/sem08_write/README.md:
--------------------------------------------------------------------------------
1 | # Cudly sniffle
--------------------------------------------------------------------------------
/sem08_write/data/ filtered-apartments.csv:
--------------------------------------------------------------------------------
1 | 95313,1,Бабушкинская,48313
2 | 63905,2,Бабушкинская,40060
3 | 15129,3,Бабушкинская,39585
4 | 49627,3,Бабушкинская,33404
5 | 21383,3,Бабушкинская,30854
6 | 61033,3,Бабушкинская,29796
7 | 93023,4,Бабушкинская,39861
8 | 28469,4,Бабушкинская,31315
9 |
--------------------------------------------------------------------------------
/sem08_write/data/apartments.csv:
--------------------------------------------------------------------------------
1 | 67200,2,Войковская,52611
2 | 69948,2,Войковская,40738
3 | 95313,1,Бабушкинская,48313
4 | 77793,3,Академическая,43650
5 | 23846,3,Профсоюзная,45192
6 | 38750,4,Войковская,48921
7 | 66145,2,Октябрьское Поле,36477
8 | 29028,3,Войковская,32382
9 | 15129,3,Бабушкинская,39585
10 | 88761,4,Профсоюзная,34029
11 | 16212,3,Свиблово,36241
12 | 32034,4,Свиблово,45514
13 | 50029,1,Войковская,35799
14 | 42201,1,Октябрьское Поле,54261
15 | 49627,3,Бабушкинская,33404
16 | 29759,3,Свиблово,59366
17 | 16826,2,Октябрьское Поле,52460
18 | 73123,4,Войковская,40730
19 | 15497,1,Октябрьское Поле,45117
20 | 97979,1,Свиблово,36418
21 | 42723,4,Свиблово,52948
22 | 36781,3,Сокол,41062
23 | 93023,4,Бабушкинская,39861
24 | 46173,1,Войковская,51202
25 | 68462,3,Октябрьское Поле,45792
26 | 31295,3,Академическая,58546
27 | 43863,4,Академическая,52354
28 | 21383,3,Бабушкинская,30854
29 | 45908,4,Академическая,33475
30 | 46828,4,Сокол,34421
31 | 67212,2,Сокол,40893
32 | 21700,4,Октябрьское Поле,37774
33 | 54687,3,Сокол,49489
34 | 46062,2,Свиблово,26303
35 | 46902,3,Сокол,25178
36 | 46552,1,Сокол,33149
37 | 81544,2,Октябрьское Поле,56647
38 | 25345,1,Свиблово,50594
39 | 94268,1,Войковская,34312
40 | 51894,4,Свиблово,45361
41 | 30979,4,Свиблово,26368
42 | 94824,1,Профсоюзная,26371
43 | 80394,3,Сокол,29543
44 | 63905,2,Бабушкинская,40060
45 | 51295,3,Свиблово,30696
46 | 22676,1,Сокол,45917
47 | 61033,3,Бабушкинская,29796
48 | 42783,3,Свиблово,26113
49 | 77057,4,Октябрьское Поле,56464
50 | 13225,1,Свиблово,47990
51 | 57386,3,Сокол,38675
52 | 25962,2,Войковская,33314
53 | 69769,4,Свиблово,28045
54 | 88669,1,Войковская,33793
55 | 13478,1,Войковская,28697
56 | 28469,4,Бабушкинская,31315
57 | 79188,1,Академическая,45087
58 |
--------------------------------------------------------------------------------
/sem08_write/data/data.txt:
--------------------------------------------------------------------------------
1 | @Simone_Biles That's nice of him to hold on and help you keep your balance :) Face with tears of joy
2 | Thank you to UK gymnastics director of operations @amyycoylee for hosting the team with a Thanksgiving potluck! Poultry legCroissantEar of maize
3 | Some current and future All-Americans taking in the @UCLAFootball game. Smiling face with sunglasses
4 | A skating bucket list item for me this morning! Edge class with Tracy Wilson and
5 | @jasonbskates ! It was as amazing as you can imagine!
6 | Lets flippin go… @Simone_Biles collection starts next Tuesday 11/16
7 | The @Simone_Biles High Score Collection drops next week! Five iconic moments from her career, hand chosen by Simone herself.
8 | i can’t believe it’s already over! major shout out to @Simone_Biles and a huge shout out to all of you for coming out and supporting!
9 | Huge thank you to Olympic figure skating medalist @jasonbskates
10 | We Eyes you, @jasonbskates ! Fire
11 | How was your weekend @amyycoylee ? Cat face with wry smile
--------------------------------------------------------------------------------
/sem08_write/data/msr_summary.tsv:
--------------------------------------------------------------------------------
1 | БЭК2110 18
2 | БЭК219 10
3 |
--------------------------------------------------------------------------------
/sem08_write/data/skating.txt:
--------------------------------------------------------------------------------
1 | 8 место - Ксения Монько / Кирилл Халявин, Россия
2 | 18 место - Каролина Москени / Адам Лукач, Венгрия
3 | 15 место - Федерика Теста / Лукаш Цолли, Словакия
4 | 20 место - Элисон Рид / Василий Рогов, Израиль
5 | 10 место - Мэдисон Хаббелл / Закари Донохью, США
6 | 19 место - Ван Шиюэ / Лю Синьюй, КНР
7 | 17 место - Александра Назарова / Максим Никитин, Украина
8 | 11 место - Лоуренс Фурнье-Бодри / Николай Сёренсен, Дания
9 | 7 место - Елена Ильиных / Руслан Жиганшин, Россия
10 | 5 место - Майя Шибутани / Алекс Шибутани, США
11 | 6 место - Пайпер Гиллес / Поль Пуарье, Канада
12 | 12 место - Шарлен Гиньяр / Марко Фаббри, Италия
13 | 3 место - Кэйтлин Уивер / Эндрю Поже, Канада
14 | 2 место - Мэдисон Чок / Эван Бейтс, США
15 | 14 место - Сара Уртадо / Адрия Диас, Испания
16 | 16 место - Алиса Агафонова / Альпер Учар, Турция
17 | 4 место - Анна Каппеллини / Лука Ланотте, Италия
18 | 13 место - Александра Пол / Митчелл Ислам, Канада
19 | 1 место - Габриэла Пападакис / Гийом Сизерон, Франция
20 | 10 место - Александра Степанова / Иван Букин, Россия
21 |
--------------------------------------------------------------------------------
/sem08_write/data/users.txt:
--------------------------------------------------------------------------------
1 | пользователь: @Simone_Biles, упоминаний: 4
2 | пользователь: @jasonbskates, упоминаний: 3
3 | пользователь: @amyycoylee, упоминаний: 2
4 | пользователь: @UCLAFootball, упоминаний: 1
5 |
--------------------------------------------------------------------------------
/sem08_write/data/users_.txt:
--------------------------------------------------------------------------------
1 | пользователь: @Simone_Biles, упоминаний: 4
2 | пользователь: @jasonbskates, упоминаний: 3
3 | пользователь: @amyycoylee, упоминаний: 2
4 | пользователь: @UCLAFootball, упоминаний: 1
5 |
--------------------------------------------------------------------------------
/sem08_write/txt_files/bill.txt:
--------------------------------------------------------------------------------
1 | sber twitter pupa&partners
2 |
--------------------------------------------------------------------------------
/sem08_write/txt_files/ilon.txt:
--------------------------------------------------------------------------------
1 | sber twitter lalkicorporation
2 |
--------------------------------------------------------------------------------
/sem08_write/txt_files/sasha.txt:
--------------------------------------------------------------------------------
1 | sber vk lalkicorporation
2 |
--------------------------------------------------------------------------------
/sem09_parsers/README.md:
--------------------------------------------------------------------------------
1 | # Cudly sniffle
--------------------------------------------------------------------------------
/sem10_API/README.md:
--------------------------------------------------------------------------------
1 | # Cudly sniffle
--------------------------------------------------------------------------------
/sem10_API/Untitled.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "id": "hollywood-foundation",
6 | "metadata": {},
7 | "source": [
8 | "# REST API"
9 | ]
10 | },
11 | {
12 | "cell_type": "markdown",
13 | "id": "electoral-grammar",
14 | "metadata": {},
15 | "source": [
16 | "Весь мир наполнен компьютерами. Интернет по сути является лишь набором протоколов, по которому компьютеры общаются между собой. Схематично почти весь интернет представлен на схеме. Компьютеры пользователей посылают запросы на другие компьютеры (они же серверы, высокопроизводительные компьютеры для обработки запросов). На сервере крутится обработчик запросов, который умеет общаться с базой данных, а также отсылать ответ пользователю.\n",
17 | "\n",
18 | ""
19 | ]
20 | },
21 | {
22 | "cell_type": "markdown",
23 | "id": "saving-gibson",
24 | "metadata": {},
25 | "source": [
26 | "Подавляющее большинство сайтов и приложений в интернете устроены по архитектуре клиент-сервер. Клиен -- это любой сайт или приложение, которое разворачивается в браузере, т.е. на машине пользователя. Клиент посылает запросы и обменивается данными с сервером. \n",
27 | "\n",
28 | "\n",
29 | "\n"
30 | ]
31 | },
32 | {
33 | "cell_type": "markdown",
34 | "id": "emerging-findings",
35 | "metadata": {},
36 | "source": [
37 | "По сути, сервера предоставляют так называемый API (Application Programming Interface). Это специальный набор команд, которые предоставляет сервер, и которые будут валидно обработаны при запросе от клиента на сервер.\n",
38 | "\n",
39 | "Приведём простой пример. Пусть вы хотите зарегистрироваться на каком-то сайте. Вы вводите логин, пароль, дату рождения и т.д. Далее происходят следующие действия.\n",
40 | "\n",
41 | "1. Клиент (копия сайта, развёрнутая на вашем компьютере) обрабатывает данные. Например, проверяет пароль на сложность\n",
42 | "\n",
43 | "2. Клиент запихивает данные в json-формат (редко -- что-то другое) и посылает на сервер запрос (request) с помощью HTTP. Запрос типизирован и имеет определённое содержание\n",
44 | "\n",
45 | "3. Сервер проверяет валидность запроса. Потом вытаскивает данные из json, записывает пользователя в базу данных\n",
46 | "\n",
47 | "4. Сервер формирует ответ (response)\n",
48 | "\n",
49 | "5. Клиент получает ответ, пользователю высвечивается что-то в духе \"Вы успешно зарегистрированы!\"\n",
50 | "\n",
51 | "\n",
52 | "В текущем семинаре мы сами руками напишем некоторые запросы, которые сайты пишут к серверам, а также напишем свой первый сервер!\n",
53 | "\n",
54 | "Зачем это нужно? Многие базы данных и приложения внутреннего пользования могут не иметь клиентской части. Следовательно, получить данные из них можно только с помощью запроса. Ну и, конечно, умение написать самому сервер может пригодиться для разработки почти любого приложения/проекта. (С клиентской частью всё несколько сложнее, там своя кухня)\n"
55 | ]
56 | },
57 | {
58 | "cell_type": "code",
59 | "execution_count": 4,
60 | "id": "ongoing-colleague",
61 | "metadata": {},
62 | "outputs": [],
63 | "source": [
64 | "# Библиотека requests позволяет писать HTTP-запросы\n",
65 | "import requests"
66 | ]
67 | },
68 | {
69 | "cell_type": "markdown",
70 | "id": "overall-practitioner",
71 | "metadata": {},
72 | "source": [
73 | "Основные типы запросов:\n",
74 | "\n",
75 | "1. GET -- Запрос данных (Например, когда пользователь логинится)\n",
76 | "2. POST -- Отправка новых данных на сервер (Регистрация пользователя)\n",
77 | "3. DELETE -- Удаление данных с сервера (Удаление пользователя)\n",
78 | "4. PUT -- Модификация данных (Смена пароля)\n",
79 | "\n",
80 | "Вообще есть ещё пяток других, но они используются достаточно редко. К тому же, разделение весьма условное и скорее используется для лучшей читабельности. Все задачи можно решать только POST-запросом, но имейте в виду, что любой бэкенд-разработчик (а именно они пишут серверы), попробует вас избить."
81 | ]
82 | },
83 | {
84 | "cell_type": "markdown",
85 | "id": "unlikely-flood",
86 | "metadata": {},
87 | "source": [
88 | "На этой точке семинарист должен героически открыть консоль разработчика своего браузера и показать, какие запросы шлёт гугл при поиске"
89 | ]
90 | },
91 | {
92 | "cell_type": "markdown",
93 | "id": "impressed-arrangement",
94 | "metadata": {},
95 | "source": [
96 | "Теперь напишем свой запрос к какому-нибудь серверу. Однако всё было бы слишком просто, если бы это можно было делать просто так. Конечно, нужна авторизация. Обычно API просят присылать с каждым запросом специальный ключ, который бы идентифицировал пользователя. Есть прекрасный сервис, который собрал в себя кучу бесплатных (и не только) API: https://rapidapi.com. Пусть ваш семинарист по своей гуглопочте подпишется на бесплатный трайал API гугл-транслейта. Более того, этот сайт позволяет генерировать HTTP-запросы для популярных языков."
97 | ]
98 | },
99 | {
100 | "cell_type": "code",
101 | "execution_count": 9,
102 | "id": "wooden-yeast",
103 | "metadata": {},
104 | "outputs": [
105 | {
106 | "name": "stdout",
107 | "output_type": "stream",
108 | "text": [
109 | "{\"data\":{\"detections\":[[{\"language\":\"en\",\"isReliable\":false,\"confidence\":1}]]}}\n"
110 | ]
111 | }
112 | ],
113 | "source": [
114 | "import requests\n",
115 | "\n",
116 | "url = \"https://google-translate1.p.rapidapi.com/language/translate/v2/detect\"\n",
117 | "\n",
118 | "# https://google-translate1.p.rapidapi.com -- адрес сервера.\n",
119 | "# language/translate/v2/detect - маршрут на сервере. Можно представлять это как папочки на компьютере.\n",
120 | "# Такой подход позволяет структурировать систему запросов на сервере.\n",
121 | "# Например, всё, что касается логина пользователя можно внести в /auth/\n",
122 | "\n",
123 | "payload = \"q=English%20is%20hard%2C%20but%20detectably%20so\"\n",
124 | "# Два вида передачи данных:\n",
125 | "# query -- со строкой запроса\n",
126 | "# payload -- \n",
127 | "\n",
128 | "# https://google-translate1.p.rapidapi.com/language/translate/v2/detect?\n",
129 | "\n",
130 | "headers = {\n",
131 | "\t\"content-type\": \"application/x-www-form-urlencoded\",\n",
132 | "\t\"Accept-Encoding\": \"application/gzip\",\n",
133 | "\t\"X-RapidAPI-Host\": \"google-translate1.p.rapidapi.com\",\n",
134 | "\t\"X-RapidAPI-Key\": Тут ваш семинарист должен вставить свой ключ авторизации\n",
135 | "}\n",
136 | "\n",
137 | "response = requests.request(\"POST\", url, data=payload, headers=headers)\n",
138 | "\n",
139 | "print(response.text)"
140 | ]
141 | },
142 | {
143 | "cell_type": "code",
144 | "execution_count": null,
145 | "id": "guilty-reverse",
146 | "metadata": {},
147 | "outputs": [],
148 | "source": []
149 | },
150 | {
151 | "cell_type": "markdown",
152 | "id": "coupled-textbook",
153 | "metadata": {},
154 | "source": [
155 | "# Flask"
156 | ]
157 | },
158 | {
159 | "cell_type": "markdown",
160 | "id": "random-subject",
161 | "metadata": {},
162 | "source": [
163 | "Теперь напишем собственный сервер. Маленький, но гордый. Да, он не будет доступен людям вовне, но мы сможем с ним поиграть. "
164 | ]
165 | },
166 | {
167 | "cell_type": "code",
168 | "execution_count": 12,
169 | "id": "respective-pressure",
170 | "metadata": {},
171 | "outputs": [
172 | {
173 | "name": "stdout",
174 | "output_type": "stream",
175 | "text": [
176 | " * Serving Flask app '__main__' (lazy loading)\n",
177 | " * Environment: production\n",
178 | "\u001b[31m WARNING: This is a development server. Do not use it in a production deployment.\u001b[0m\n",
179 | "\u001b[2m Use a production WSGI server instead.\u001b[0m\n",
180 | " * Debug mode: off\n"
181 | ]
182 | },
183 | {
184 | "name": "stderr",
185 | "output_type": "stream",
186 | "text": [
187 | " * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)\n"
188 | ]
189 | }
190 | ],
191 | "source": [
192 | "from flask import Flask\n",
193 | "\n",
194 | "app = Flask(__name__)\n",
195 | "\n",
196 | "\n",
197 | "@app.route(\"/\")\n",
198 | "def hello():\n",
199 | " return \"Hello World!\"\n",
200 | "\n",
201 | "\n",
202 | "if __name__ == \"__main__\":\n",
203 | " app.run()"
204 | ]
205 | },
206 | {
207 | "cell_type": "markdown",
208 | "id": "private-cause",
209 | "metadata": {},
210 | "source": [
211 | "Запустив код выше, ваш семинарист должен запустить другой ноутбук (или штуку типа Postman), чтобы послать запрос на свежесозданный сервер"
212 | ]
213 | }
214 | ],
215 | "metadata": {
216 | "kernelspec": {
217 | "display_name": "Python 3",
218 | "language": "python",
219 | "name": "python3"
220 | },
221 | "language_info": {
222 | "codemirror_mode": {
223 | "name": "ipython",
224 | "version": 3
225 | },
226 | "file_extension": ".py",
227 | "mimetype": "text/x-python",
228 | "name": "python",
229 | "nbconvert_exporter": "python",
230 | "pygments_lexer": "ipython3",
231 | "version": "3.9.2"
232 | }
233 | },
234 | "nbformat": 4,
235 | "nbformat_minor": 5
236 | }
237 |
--------------------------------------------------------------------------------
/sem10_API/bot_utils/Procfile:
--------------------------------------------------------------------------------
1 | worker: python main.py
--------------------------------------------------------------------------------
/sem10_API/bot_utils/main.py:
--------------------------------------------------------------------------------
1 | import telebot
2 | from telebot import types
3 | import sqlite3
4 |
5 | # подключаем базу данных
6 | conn = sqlite3.connect('planner_hse.db')
7 |
8 | # курсор для работы с таблицами
9 | cursor = conn.cursor()
10 |
11 | try:
12 | # sql запрос для создания таблицы
13 | query = "CREATE TABLE \"planner\" (\"ID\" INTEGER UNIQUE, \"user_id\" INTEGER, \"plan\" TEXT, PRIMARY KEY (\"ID\"))"
14 | # исполняем его –> ура, теперь у нас есть таблица, куда будем все сохранять!
15 | cursor.execute(query)
16 | except:
17 | pass
18 |
19 | # подключим токен нашего бота
20 | bot = telebot.TeleBot("your_token")
21 |
22 | # напишем, что делать нашему боту при команде старт
23 | @bot.message_handler(commands=['start'])
24 | def send_keyboard(message, text="Привет, чем я могу тебе помочь?"):
25 | keyboard = types.ReplyKeyboardMarkup(row_width=2) # наша клавиатура
26 | itembtn1 = types.KeyboardButton('Добавить дело в список') # создадим кнопку
27 | itembtn2 = types.KeyboardButton('Показать список дел')
28 | itembtn3 = types.KeyboardButton('Удалить дело из списка')
29 | itembtn4 = types.KeyboardButton("Удалить все дела из списка")
30 | itembtn5 = types.KeyboardButton('Другое')
31 | itembtn6 = types.KeyboardButton('Пока все!')
32 | keyboard.add(itembtn1, itembtn2) # добавим кнопки 1 и 2 на первый ряд
33 | keyboard.add(itembtn3, itembtn4, itembtn5, itembtn6) # добавим кнопки 3, 4, 5 на второй ряд
34 | # но если кнопок слишком много, они пойдут на след ряд автоматически
35 |
36 | # пришлем это все сообщением и запишем выбранный вариант
37 | msg = bot.send_message(message.from_user.id,
38 | text=text, reply_markup=keyboard)
39 |
40 | # отправим этот вариант в функцию, которая его обработает
41 | bot.register_next_step_handler(msg, callback_worker)
42 |
43 | @bot.message_handler(content_types=['text'])
44 | def handle_docs_audio(message):
45 | send_keyboard(message, text="Я не понимаю :-( Выберите один из пунктов меню:")
46 |
47 | # напишем функции для каждого случая
48 | # эта добавляет строчку с планом в хранилище
49 | def add_plan(msg):
50 | with sqlite3.connect('planner_hse.db') as con:
51 | cursor = con.cursor()
52 | cursor.execute('INSERT INTO planner (user_id, plan) VALUES (?, ?)',
53 | (msg.from_user.id, msg.text))
54 | con.commit()
55 | bot.send_message(msg.chat.id, 'Запомню :-)')
56 | send_keyboard(msg, "Чем еще могу помочь?")
57 |
58 | # просто функция, которая делает нам красивые строки для отправки пользователю
59 | def get_plans_string(tasks):
60 | tasks_str = []
61 | for val in list(enumerate(tasks)):
62 | tasks_str.append(str(val[0] + 1) + ') ' + val[1][0] + '\n')
63 | return ''.join(tasks_str)
64 |
65 | # отправляем пользователю его планы
66 | def show_plans(msg):
67 | with sqlite3.connect('planner_hse.db') as con:
68 | cursor = con.cursor()
69 | cursor.execute('SELECT plan FROM planner WHERE user_id=={}'.format(msg.from_user.id))
70 | tasks = get_plans_string(cursor.fetchall())
71 | bot.send_message(msg.chat.id, tasks)
72 | send_keyboard(msg, "Чем еще могу помочь?")
73 |
74 | # удаляет все планы для конкретного пользователя
75 | def delete_all_plans(msg):
76 | with sqlite3.connect('planner_hse.db') as con:
77 | cursor = con.cursor()
78 | cursor.execute('DELETE FROM planner WHERE user_id=={}'.format(msg.from_user.id))
79 | con.commit()
80 | bot.send_message(msg.chat.id, 'Удалены все дела. Хорошего отдыха!')
81 | send_keyboard(msg, "Чем еще могу помочь?")
82 |
83 | # выыделяет одно дело, которое пользователь хочет удалить
84 | def delete_one_plan(msg):
85 | markup = types.ReplyKeyboardMarkup(row_width=2)
86 | with sqlite3.connect('planner_hse.db') as con:
87 | cursor = con.cursor()
88 | # достаем все задачи пользователя
89 | cursor.execute('SELECT plan FROM planner WHERE user_id=={}'.format(msg.from_user.id))
90 | # достанем результат запроса
91 | tasks = cursor.fetchall()
92 | for value in tasks:
93 | markup.add(types.KeyboardButton(value[0]))
94 | msg = bot.send_message(msg.from_user.id,
95 | text = "Выбери одно дело из списка",
96 | reply_markup=markup)
97 | bot.register_next_step_handler(msg, delete_one_plan_)
98 |
99 | # удаляет это дело
100 | def delete_one_plan_(msg):
101 | with sqlite3.connect('planner_hse.db') as con:
102 | cursor = con.cursor()
103 | cursor.execute('DELETE FROM planner WHERE user_id==? AND plan==?', (msg.from_user.id, msg.text))
104 | bot.send_message(msg.chat.id, 'Ура, минус одна задача!')
105 | send_keyboard(msg, "Чем еще могу помочь?")
106 |
107 | # привязываем функции к кнопкам на клавиатуре
108 | def callback_worker(call):
109 | if call.text == "Добавить дело в список":
110 | msg = bot.send_message(call.chat.id, 'Давайте добавим дело! Напишите его в чат')
111 | bot.register_next_step_handler(msg, add_plan)
112 |
113 | elif call.text == "Показать список дел":
114 | try:
115 | show_plans(call)
116 | except:
117 | bot.send_message(call.chat.id, 'Здесь пусто. Можно отдыхать :-)')
118 | send_keyboard(call, "Чем еще могу помочь?")
119 |
120 | elif call.text == "Удалить дело из списка":
121 | try:
122 | delete_one_plan(call)
123 | except:
124 | bot.send_message(call.chat.id, 'Здесь пусто. Можно отдыхать :-)')
125 | send_keyboard(call, "Чем еще могу помочь?")
126 |
127 | elif call.text == "Удалить все дела из списка":
128 | try:
129 | delete_all_plans(call)
130 | except:
131 | bot.send_message(call.chat.id, 'Здесь пусто. Можно отдыхать :-)')
132 | send_keyboard(call, "Чем еще могу помочь?")
133 |
134 | elif call.text == "Другое":
135 | bot.send_message(call.chat.id, 'Больше я пока ничего не умею :-(')
136 | send_keyboard(call, "Чем еще могу помочь?")
137 |
138 | elif call.text == "Пока все!":
139 | bot.send_message(call.chat.id, 'Хорошего дня! Когда захотите продолжнить нажмите на команду /start')
140 |
141 |
142 |
143 | bot.polling(none_stop=True)
144 |
--------------------------------------------------------------------------------
/sem10_API/bot_utils/requirements.txt:
--------------------------------------------------------------------------------
1 | certifi==2021.5.30
2 | chardet==4.0.0
3 | idna==2.10
4 | pyTelegramBotAPI==3.7.9
5 | requests==2.25.1
6 | urllib3==1.26.5
7 |
--------------------------------------------------------------------------------
/sem10_API/images/client-server.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hse-econ-data-science/dap_2022-23/1e23952959de15a2f17b63dd48523a62245c74fc/sem10_API/images/client-server.png
--------------------------------------------------------------------------------
/sem10_API/images/scheme.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hse-econ-data-science/dap_2022-23/1e23952959de15a2f17b63dd48523a62245c74fc/sem10_API/images/scheme.png
--------------------------------------------------------------------------------
/utils/eds_test_contest.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hse-econ-data-science/dap_2022-23/1e23952959de15a2f17b63dd48523a62245c74fc/utils/eds_test_contest.pdf
--------------------------------------------------------------------------------
/utils/install_conda_mac.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hse-econ-data-science/dap_2022-23/1e23952959de15a2f17b63dd48523a62245c74fc/utils/install_conda_mac.pdf
--------------------------------------------------------------------------------
/utils/install_conda_windows.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hse-econ-data-science/dap_2022-23/1e23952959de15a2f17b63dd48523a62245c74fc/utils/install_conda_windows.pdf
--------------------------------------------------------------------------------