From 96d83fafb90263b1484508427ff6cbd9acf63c85 Mon Sep 17 00:00:00 2001 From: GitDefeatedMe Date: Tue, 27 Sep 2022 18:07:37 +0300 Subject: [PATCH 1/4] Vasilevsky Alexander --- homeworks/GitDefeatedMe/1.py | 17 ++++++++++ homeworks/GitDefeatedMe/2.py | 66 ++++++++++++++++++++++++++++++++++++ 2 files changed, 83 insertions(+) create mode 100644 homeworks/GitDefeatedMe/1.py create mode 100644 homeworks/GitDefeatedMe/2.py diff --git a/homeworks/GitDefeatedMe/1.py b/homeworks/GitDefeatedMe/1.py new file mode 100644 index 0000000..8ea1fdc --- /dev/null +++ b/homeworks/GitDefeatedMe/1.py @@ -0,0 +1,17 @@ +question = { + "Какая версия языка сейчас актуальна?" : "Python3", + "Какая кодировка используется в строках?" : "UTF8", + "Какой оператор сравнения нужно использовать для работы с None и bool?" : "is", + "Сколько значений есть у bool?" : "2" +} + +RightAnswer = 0 + +for i in question: + answer = input(i+" ") + if (answer.lower() == question[i].lower()): + print("Ответ {0} верен".format(answer)) + RightAnswer+=1 + continue + print("Неверный ответ") +print("You have {0} correct answers out of {1}" .format(RightAnswer ,len(question))) \ No newline at end of file diff --git a/homeworks/GitDefeatedMe/2.py b/homeworks/GitDefeatedMe/2.py new file mode 100644 index 0000000..2b42466 --- /dev/null +++ b/homeworks/GitDefeatedMe/2.py @@ -0,0 +1,66 @@ + +class Array(object): + + def __init__(self, *args): + self._data = args + + def append(self, item): + self._data = self._data + (item,); + + def __len__(self): + return len(self._data) + + def index(self, elem): + if (elem in self._data): + return self._data.index(elem) + return -1 + + def __getitem__(self, index_of_elem): + return self._data[index_of_elem] + + def __add__(self, other): + result = Array() + result._data = self._data + other._data + return result + + def __iadd__(self, other): + self._data += other._data + return self + + def __str__(self): + return str(self._data) + + + +print('Create: \n\ta = Array()\n\tb = Array("qwe")\n\tc = Array("asd","zxc")') + +a = Array() +b = Array("qwe") +c = Array("asd","zxc") + +print("We have:\n\ta = {0}\n\tb = {1}\n\tc = {2}\n".format(str(a),str(b),str(c))) +print('Trying to find index "qwe" in a, get : ' + str(a.index("qwe"))) +print('Trying to find index "qwe" in b, get : ' + str(b.index("qwe"))) + +print("\nLen of c == " + str(len(c))) + +print('\nc[1] = ' + c[1]) + +print('\nc = a + b') +c = a + b +print("c = " + str(c)) + + +print('\nc += b') +c += b +print("b = " + str(b)) +print("c = " + str(c)) + + +print('\nc.append("SomeText")') +c.append("SomeText") +print("c = " + str(c)) +print('\ntryign to use "for elem in c" and get :') + +for elem in c: + print(elem) \ No newline at end of file From 03a5349a9d8e7d3504d78417f2b0b70ad1dfaacc Mon Sep 17 00:00:00 2001 From: GitDefeatedMe Date: Wed, 28 Sep 2022 19:33:12 +0300 Subject: [PATCH 2/4] practice --- practice/1/1.py | 119 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 119 insertions(+) create mode 100644 practice/1/1.py diff --git a/practice/1/1.py b/practice/1/1.py new file mode 100644 index 0000000..e91b9e1 --- /dev/null +++ b/practice/1/1.py @@ -0,0 +1,119 @@ +# `random` module is used to shuffle field, see: +# https://docs.python.org/3/library/random.html#random.shuffle +from operator import is_ +import random + +# Empty tile, there's only one empty cell on a field: +EMPTY_MARK = 'x' + +# Dictionary of possible moves if a form of: +# key -> delta to move the empty tile on a field. +MOVES = { + 'w': -4, + 's': 4, + 'a': -1, + 'd': 1, +} + + +def shuffle_field(): + """ + This function is used to create a field at the very start of the game. + + :return: list with 16 randomly shuffled tiles, + one of which is a empty space. + """ + data = [i+1 for i in range (16)] + data[15] = EMPTY_MARK + for move in range(100): + data = perform_move(data, random.choice("wasd")) + return data + + +def print_field(field): + """ + This function prints field to user. + + :param field: current field state to be printed. + :return: None + """ + + print(field[0:4]) + print(field[4:8]) + print(field[8:12]) + print(field[12:17]) + pass + + +def is_game_finished(field): + """ + This function checks if the game is finished. + + :param field: current field state. + :return: True if the game is finished, False otherwise. + """ + data = [i+1 for i in range (16)] + data[15] = EMPTY_MARK + if field == data: + return True + return False + + +def perform_move(field, key): + """ + Moves empty-tile inside the field. + + :param field: current field state. + :param key: move direction. + :return: new field state (after the move) + or `None` if the move can't me done. + """ + index = field.index(EMPTY_MARK) + if index + MOVES[key] <= 15 and index + MOVES[key] >= 0: + if(key == 'a' or key == 'd'): + if (index)//4 == (index + MOVES[key])//4: + field[index], field[index + MOVES[key]] = field[index + MOVES[key]], field[index] + else: + field[index], field[index + MOVES[key]] = field[index + MOVES[key]], field[index] + return field + + + +def handle_user_input(): + """ + Handles user input. + + List of accepted moves: + 'w' - up, + 's' - down, + 'a' - left, + 'd' - right + + :return: current move. + """ + key = str(input()) + return key + + +def main(): + """ + The main function. It starts when the program is called. + + It also calls other functions. + :return: None + """ + + map = shuffle_field() + print_field(map) + + + while(not is_game_finished(map)): + map = perform_move(map, handle_user_input()) + print_field(map) + pass + + +if __name__ == '__main__': + # See what this means: + # http://stackoverflow.com/questions/419163/what-does-if-name-main-do + main() From 44ed5bd671bfcb6b5482624bfbf55780b9311a3c Mon Sep 17 00:00:00 2001 From: GitDefeatedMe Date: Wed, 5 Oct 2022 17:23:02 +0300 Subject: [PATCH 3/4] hw4 and practice --- homeworks/GitDefeatedMe/4.md | 85 ++++++++++++++++++++++++++++++++++++ practice/1/1.py | 3 +- 2 files changed, 86 insertions(+), 2 deletions(-) create mode 100644 homeworks/GitDefeatedMe/4.md diff --git a/homeworks/GitDefeatedMe/4.md b/homeworks/GitDefeatedMe/4.md new file mode 100644 index 0000000..b0a3fc2 --- /dev/null +++ b/homeworks/GitDefeatedMe/4.md @@ -0,0 +1,85 @@ +## Теория + +### Exceptions + +- `try/except/else/finally`: https://pythonz.net/references/named/try-except-finally/ +- `raise`: https://pythonz.net/references/named/raise/ +- Иерархия Exception: https://docs.python.org/3/library/exceptions.html#exception-hierarchy +- Когда не нужно использовать Exception? https://sobolevn.me/2019/02/python-exceptions-considered-an-antipattern + +### Decorators + +- Декораторы шаг за шагом: https://pythonworld.ru/osnovy/dekoratory.html + +### Generators + +- Iterable vs Iterator vs Generator: https://nvie.com/posts/iterators-vs-generators/ + +### Comprehensions + +- Comprehensions: https://python-3-patterns-idioms-test.readthedocs.io/en/latest/Comprehensions.html + +### Context managers + +- Менеджеры контекста: https://pythonz.net/references/named/contextmanager/ +- `with`: https://pythonz.net/references/named/with/ + + +## Практика + +Задача: реализовать декоратор `@contract`. Смотри файл `contract.py` + +Требования: + +1. Необходимо проверять типы аргументов и тип выходного значения функции. Указываем кортеж типов для `arg_types`. Каждый тип в кортеже - соответсвует типу аргумента. Для типа выходного значения - указываем `return_type` + +```python +@contract(arg_types=(int, int), return_type=int) +def add_two_numbers(first, second): + return first + second + +add_two_numbers(1, 2) # ok +``` + +2. Если передан неправильный тип, вызываем ошибку `ContractError`: + +```python +add_two_numbers('a', 'b') # raises ContractError +``` + +3. Параметр `raises` отвечает за типы исключений, которые функция может кидать. Если выкинутое исключение отсутсвует в списке разрешенных, то мы добавляем `ContractError` (смотри `raise from`). Пример: + +```python +@contract(arg_types=(int, int), return_type=float, raises=(ZeroDivisionError,)) +def div(first, second): + return first / second + +div(1, 2) # ok +div(1, 0) # raises ZeroDisionError +div(1, None) # raises ContractError from TypeError +``` + +4. Можно не передавать какое-то значение из `arg_types` или `return_type`. Или передать значение `None`: тогда ничего не будет происходить. Пример: + +```python +# validates only return type, args and raises are ignored: +@contract(return_type=int) + +# validation is completely disabled: +@contract(return_type=None, arg_types=None, raises=None) + +# return type and raises checks are disabled: +@contract(arg_types=(str, str)) +``` + +5. Можно передать специальное значение `Any` для того, чтобы игнорировать какой-то один тип внутри `arg_types` или `raises`. Например: + +```python +@contract(arg_types=(int, Any)) +def add_two_numbers(first, second): + return first + second + +add_two_numbers(1, 2) # ok +add_two_numbers(1, 3.4) # ok +add_two_numbers(2.1, 1) # raises ContractError +``` diff --git a/practice/1/1.py b/practice/1/1.py index e91b9e1..ff3c2c1 100644 --- a/practice/1/1.py +++ b/practice/1/1.py @@ -112,8 +112,7 @@ def main(): print_field(map) pass - if __name__ == '__main__': # See what this means: # http://stackoverflow.com/questions/419163/what-does-if-name-main-do - main() + main() \ No newline at end of file From c6dd91a4c8df4a7d8f0161e644f58cc2658bf527 Mon Sep 17 00:00:00 2001 From: GitDefeatedMe Date: Wed, 19 Oct 2022 17:30:54 +0300 Subject: [PATCH 4/4] add HW5 --- .../5/my-awesome-script/README.md | 0 .../my_awesome_script/__init__.py | 0 .../my_awesome_script/__main__.py | 6 +++ .../my_awesome_script/modul.py | 34 ++++++++++++++ .../5/my-awesome-script/poetry.lock | 45 +++++++++++++++++++ .../5/my-awesome-script/pyproject.toml | 23 ++++++++++ .../5/my-awesome-script/tests/__init__.py | 0 7 files changed, 108 insertions(+) create mode 100644 homeworks/GitDefeatedMe/5/my-awesome-script/README.md create mode 100644 homeworks/GitDefeatedMe/5/my-awesome-script/my_awesome_script/__init__.py create mode 100644 homeworks/GitDefeatedMe/5/my-awesome-script/my_awesome_script/__main__.py create mode 100644 homeworks/GitDefeatedMe/5/my-awesome-script/my_awesome_script/modul.py create mode 100644 homeworks/GitDefeatedMe/5/my-awesome-script/poetry.lock create mode 100644 homeworks/GitDefeatedMe/5/my-awesome-script/pyproject.toml create mode 100644 homeworks/GitDefeatedMe/5/my-awesome-script/tests/__init__.py diff --git a/homeworks/GitDefeatedMe/5/my-awesome-script/README.md b/homeworks/GitDefeatedMe/5/my-awesome-script/README.md new file mode 100644 index 0000000..e69de29 diff --git a/homeworks/GitDefeatedMe/5/my-awesome-script/my_awesome_script/__init__.py b/homeworks/GitDefeatedMe/5/my-awesome-script/my_awesome_script/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/homeworks/GitDefeatedMe/5/my-awesome-script/my_awesome_script/__main__.py b/homeworks/GitDefeatedMe/5/my-awesome-script/my_awesome_script/__main__.py new file mode 100644 index 0000000..17e3fea --- /dev/null +++ b/homeworks/GitDefeatedMe/5/my-awesome-script/my_awesome_script/__main__.py @@ -0,0 +1,6 @@ +from .modul import input_from_cmd +def main(): + input_from_cmd() + +if __name__ == "__main__": + main() diff --git a/homeworks/GitDefeatedMe/5/my-awesome-script/my_awesome_script/modul.py b/homeworks/GitDefeatedMe/5/my-awesome-script/my_awesome_script/modul.py new file mode 100644 index 0000000..c7c7446 --- /dev/null +++ b/homeworks/GitDefeatedMe/5/my-awesome-script/my_awesome_script/modul.py @@ -0,0 +1,34 @@ +import argparse + +from pygments import highlight +from pygments.style import Style +from pygments.token import Token +from pygments.lexers import Python3Lexer +from pygments.formatters import Terminal256Formatter + +from cowpy import cow + +from datetime import datetime +from pytz import timezone + + + +def input_from_cmd(): + parser = argparse.ArgumentParser(description = "my_awesome_script highlights the syntax and outputs the time") + parser.add_argument("command", type = str, help = "input command", choices=["highlight", "cowsay", "time"]) + parser.add_argument("text", type = str, help = "input text") + args = parser.parse_args() + + commands[args.command](args.text) + +def _highlight(text :str): + print(highlight(text, Python3Lexer(), Terminal256Formatter(style='colorful'))) + +def _cowsay(text :str): + print(cow.milk_random_cow(text)) + +def _time(region :str): + fmt = '%Y-%m-%d %H:%M:%S' + print(datetime.now(timezone(region)).strftime(fmt)) + +commands = {"highlight": _highlight, "cowsay":_cowsay, "time": _time} diff --git a/homeworks/GitDefeatedMe/5/my-awesome-script/poetry.lock b/homeworks/GitDefeatedMe/5/my-awesome-script/poetry.lock new file mode 100644 index 0000000..3ba0020 --- /dev/null +++ b/homeworks/GitDefeatedMe/5/my-awesome-script/poetry.lock @@ -0,0 +1,45 @@ +[[package]] +name = "cowpy" +version = "1.1.5" +description = "" +category = "main" +optional = false +python-versions = ">=3.6" + +[[package]] +name = "pygments" +version = "2.13.0" +description = "Pygments is a syntax highlighting package written in Python." +category = "main" +optional = false +python-versions = ">=3.6" + +[package.extras] +plugins = ["importlib-metadata"] + +[[package]] +name = "pytz" +version = "2022.5" +description = "World timezone definitions, modern and historical" +category = "main" +optional = false +python-versions = "*" + +[metadata] +lock-version = "1.1" +python-versions = "^3.10" +content-hash = "1c3fc7f6e686f6b2207e512fb4ebcd988685ff043918073aa53bebd057bedc21" + +[metadata.files] +cowpy = [ + {file = "cowpy-1.1.5-py3-none-any.whl", hash = "sha256:de5ae7646dd30b4936013666c6bd019af9cf411cc3b377c8538cfd8414262921"}, + {file = "cowpy-1.1.5.tar.gz", hash = "sha256:089172db1d88c30a2e1b741b18945ee84170bd943a3ca71948e4ae3a3255e554"}, +] +pygments = [ + {file = "Pygments-2.13.0-py3-none-any.whl", hash = "sha256:f643f331ab57ba3c9d89212ee4a2dabc6e94f117cf4eefde99a0574720d14c42"}, + {file = "Pygments-2.13.0.tar.gz", hash = "sha256:56a8508ae95f98e2b9bdf93a6be5ae3f7d8af858b43e02c5a2ff083726be40c1"}, +] +pytz = [ + {file = "pytz-2022.5-py2.py3-none-any.whl", hash = "sha256:335ab46900b1465e714b4fda4963d87363264eb662aab5e65da039c25f1f5b22"}, + {file = "pytz-2022.5.tar.gz", hash = "sha256:c4d88f472f54d615e9cd582a5004d1e5f624854a6a27a6211591c251f22a6914"}, +] diff --git a/homeworks/GitDefeatedMe/5/my-awesome-script/pyproject.toml b/homeworks/GitDefeatedMe/5/my-awesome-script/pyproject.toml new file mode 100644 index 0000000..4aae549 --- /dev/null +++ b/homeworks/GitDefeatedMe/5/my-awesome-script/pyproject.toml @@ -0,0 +1,23 @@ +[tool.poetry] +name = "my-awesome-script" +version = "0.1.0" +description = "" +authors = ["GitDefeatedMe "] +readme = "README.md" +packages = [{include = "my_awesome_script"}] + +[tool.poetry.dependencies] +python = "^3.10" +pygments = "^2.13.0" +cowpy = "^1.1.5" +pytz = "^2022.5" + +[tool.poetry.scripts] +my_awesome_script = "my_awesome_script.__main__:main" + +[tool.poetry.group.dev.dependencies] +pygments = "^2.13.0" + +[build-system] +requires = ["poetry-core"] +build-backend = "poetry.core.masonry.api" diff --git a/homeworks/GitDefeatedMe/5/my-awesome-script/tests/__init__.py b/homeworks/GitDefeatedMe/5/my-awesome-script/tests/__init__.py new file mode 100644 index 0000000..e69de29