diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a917665 --- /dev/null +++ b/.gitignore @@ -0,0 +1,161 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +#poetry.lock + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +#pdm.lock +# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it +# in version control. +# https://pdm.fming.dev/#use-with-ide +.pdm.toml + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +.idea/ +.idea \ No newline at end of file diff --git a/README.md b/README.md index ee9d69b..48e7bde 100644 --- a/README.md +++ b/README.md @@ -31,6 +31,19 @@ ## Автор решения +Лаптев Максим Сергеевич + ## Описание реализации +Написан модуль `report.py`, содержащий класс `Report`. Помимо конструктора, принимающего как аргумент путь к файлу, он имеет 3 метода: +* `_find_out_month` - статический метод для определения месяца из даты в формате строки +* `__parse` - приватный метод для парсинга и обработки данных. На выходе имеем подсчитанные для каждого месяца пользовательские траты +* `find_max_month` - метод формирования отчета, получения месяца с максимальной суммой пользователских трат + +Также написан файл `main.py` для запуска решения на тестовом файле `input.json` + ## Инструкция по сборке и запуску решения + +```shell +python main.py +``` \ No newline at end of file diff --git a/main.py b/main.py new file mode 100644 index 0000000..36673b2 --- /dev/null +++ b/main.py @@ -0,0 +1,6 @@ +from src.report import Report + +if __name__ == "__main__": + input_file_name = 'input.json' + report = Report(input_file_name) + print(report.find_max_month()) diff --git a/src/__init__.py b/src/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/report.py b/src/report.py new file mode 100644 index 0000000..540faaf --- /dev/null +++ b/src/report.py @@ -0,0 +1,57 @@ +import json +from datetime import datetime + + +class Report: + month_names = ["january", "february", "march", "april", "may", "june", "july", "august", "september", + "october", "november", "december"] + + def __init__(self, input_file: str): + """ + Args: + input_file: str - path to input file + """ + self.input_file = input_file + + @staticmethod + def _find_out_month(timestamp: str) -> int: + """Find out month of timestamp + + Args: + timestamp: str - datetime in string format + + Returns: + month: int - month in timestamp + """ + format_string = "%Y-%m-%dT%H:%M:%S.%f" + date = datetime.strptime(timestamp, format_string) + return date.month + + def __parse(self) -> dict: + """Parse JSON file, count expenses and store it in a dictionary divided by months""" + months = {} + with open(self.input_file, "r") as f: + data = json.load(f) + for element in data: + # count only if order status is COMPLETED + if element['status'] == 'COMPLETED': + cur_month = self._find_out_month(element['ordered_at']) + # save user expense in dictionary by its month + months[cur_month] = months.get(cur_month, 0) + float(element['total']) + return months + + def find_max_month(self) -> dict: + """Find months with max user expenses + + Returns: + Dictionary in format below + {'months': ['march', 'december']} + """ + months = self.__parse() + # get max value of user expenses + max_value = max(months.values()) + # find month numbers where value equals max_value + max_months_numbers = sorted([month for month, value in months.items() if value == max_value]) + # convert numbers into month names + max_months_str = [self.month_names[index - 1] for index in max_months_numbers] + return {"months": max_months_str}