From 9df3598e52e25a30484695aaae3ca7785fbe815b Mon Sep 17 00:00:00 2001 From: somet1me123 Date: Wed, 23 Sep 2026 00:19:33 +0300 Subject: [PATCH 01/12] modificed all functions --- src/part1/snowflake.py | 102 +++++++++++++---------------------------- 1 file changed, 33 insertions(+), 69 deletions(-) diff --git a/src/part1/snowflake.py b/src/part1/snowflake.py index d3abf050..cbd7f283 100644 --- a/src/part1/snowflake.py +++ b/src/part1/snowflake.py @@ -21,65 +21,33 @@ NODE_ID_MAX, SEQUENCE_ID_MAX, TIMESTAMP_MS_MAX, + NODE_ID_BITS, + SEQUENCE_ID_BITS, ) def read_current_millis(epoch_ms: int) -> int: - """Read the number of milliseconds elapsed since the custom epoch. + current_time = int(time.time()*1000) - Args: - epoch_ms: The custom epoch expressed as Unix milliseconds. - - Returns: - The count of whole milliseconds between ``epoch_ms`` and now. May be - negative if ``epoch_ms`` lies in the future. - """ - # TODO: реализуйте функцию - return 0 + return current_time - epoch_ms def decode_timestamp_ms(snowflake_id: int, epoch_ms: int = EPOCH_MS_DEFAULT) -> int: - """Read the timestamp field out of a Snowflake identifier. - - Args: - snowflake_id: An identifier produced against the same epoch. - epoch_ms: The epoch the identifier was generated against. Defaults to - the original Twitter epoch (2010-11-04 01:42:54.657 UTC). - - Returns: - The absolute Unix time in milliseconds at which the identifier was - generated. - """ - # TODO: реализуйте функцию - return 0 - + time_mark = (snowflake_id >> (NODE_ID_BITS + SEQUENCE_ID_BITS)) + + return time_mark + epoch_ms def decode_node_id(snowflake_id: int) -> int: - """Read the node identifier field out of a Snowflake identifier. - - Args: - snowflake_id: An identifier produced by :func:`generate_snowflake_id`. + without_seq = snowflake_id >> SEQUENCE_ID_BITS + node_id = without_seq & NODE_ID_MAX - Returns: - The node identifier packed into ``snowflake_id``, in the range - ``[0, NODE_ID_MAX]``. - """ - # TODO: реализуйте функцию - return 0 + return node_id def decode_sequence_id(snowflake_id: int) -> int: - """Read the sequence counter field out of a Snowflake identifier. - - Args: - snowflake_id: An identifier produced by :func:`generate_snowflake_id`. + sequence_id = snowflake_id & SEQUENCE_ID_MAX - Returns: - The per-millisecond sequence counter packed into ``snowflake_id``, in - the range ``[0, SEQUENCE_ID_MAX]``. - """ - # TODO: реализуйте функцию - return 0 + return sequence_id def generate_snowflake_id( @@ -87,28 +55,24 @@ def generate_snowflake_id( node_id: int = NODE_ID_DEFAULT, epoch_ms: int = EPOCH_MS_DEFAULT, ) -> int | None: - """Build and return a Snowflake identifier for the current millisecond. - - The function is stateless: the caller passes the per-millisecond sequence - counter explicitly. It is the caller's responsibility to increment - ``sequence_id`` for identifiers minted within the same millisecond and to - reset it once the clock advances. - - Args: - sequence_id: The per-millisecond sequence counter, in the range - ``[0, SEQUENCE_ID_MAX]``. - node_id: The identifier of this node, in the range ``[0, NODE_ID_MAX]``. - Optional; defaults to ``NODE_ID_DEFAULT``. - epoch_ms: The start of the epoch as Unix milliseconds. Optional; - defaults to the original Twitter epoch (2010-11-04 01:42:54.657 - UTC). - - Returns: - The Snowflake identifier as a positive 63-bit integer, or ``None`` if - ``node_id`` is outside ``[0, NODE_ID_MAX]``, ``sequence_id`` is outside - ``[0, SEQUENCE_ID_MAX]``, or the elapsed time no longer fits in the - timestamp field (roughly 69 years after ``epoch_ms``). In each of those - cases an explanatory message is printed to stdout first. - """ - # TODO: реализуйте функцию - return 0 + if not (0 <= node_id <= NODE_ID_MAX): + print('node_id must be in [0, 2**10-1]') + + return None + elif not (0 <= sequence_id <= SEQUENCE_ID_MAX): + print('sequence_id must be in [0, 2**12-1]') + + return None + elif read_current_millis(epoch_ms) > TIMESTAMP_MS_MAX: + + return "overflows" + else: + snowflake_id = ( + (read_current_millis(epoch_ms) << (NODE_ID_BITS + SEQUENCE_ID_BITS)) + | (node_id << SEQUENCE_ID_BITS) + | sequence_id + ) + + + + From 096d0483d475590140b58e8698397560e381a3c2 Mon Sep 17 00:00:00 2001 From: somet1me123 Date: Wed, 23 Sep 2026 00:32:27 +0300 Subject: [PATCH 02/12] Solve task 1 --- src/part1/snowflake.py | 40 ++++++++++++++++++---------------------- 1 file changed, 18 insertions(+), 22 deletions(-) diff --git a/src/part1/snowflake.py b/src/part1/snowflake.py index cbd7f283..6a602477 100644 --- a/src/part1/snowflake.py +++ b/src/part1/snowflake.py @@ -13,30 +13,31 @@ :func:`decode_node_id` and :func:`decode_sequence_id`. """ -import time # noqa: F401 +import time -from .constants import ( # noqa: F401 +from .constants import ( EPOCH_MS_DEFAULT, + NODE_ID_BITS, NODE_ID_DEFAULT, NODE_ID_MAX, + SEQUENCE_ID_BITS, SEQUENCE_ID_MAX, TIMESTAMP_MS_MAX, - NODE_ID_BITS, - SEQUENCE_ID_BITS, ) def read_current_millis(epoch_ms: int) -> int: - current_time = int(time.time()*1000) + current_time = int(time.time() * 1000) return current_time - epoch_ms def decode_timestamp_ms(snowflake_id: int, epoch_ms: int = EPOCH_MS_DEFAULT) -> int: - time_mark = (snowflake_id >> (NODE_ID_BITS + SEQUENCE_ID_BITS)) - + time_mark = snowflake_id >> (NODE_ID_BITS + SEQUENCE_ID_BITS) + return time_mark + epoch_ms + def decode_node_id(snowflake_id: int) -> int: without_seq = snowflake_id >> SEQUENCE_ID_BITS node_id = without_seq & NODE_ID_MAX @@ -56,23 +57,18 @@ def generate_snowflake_id( epoch_ms: int = EPOCH_MS_DEFAULT, ) -> int | None: if not (0 <= node_id <= NODE_ID_MAX): - print('node_id must be in [0, 2**10-1]') - + print("node_id must be in [0, 2**10-1]") return None elif not (0 <= sequence_id <= SEQUENCE_ID_MAX): - print('sequence_id must be in [0, 2**12-1]') - + print("sequence_id must be in [0, 2**12-1]") return None elif read_current_millis(epoch_ms) > TIMESTAMP_MS_MAX: + print("overflows") + return None + snowflake_id = ( + (read_current_millis(epoch_ms) << (NODE_ID_BITS + SEQUENCE_ID_BITS)) + | (node_id << SEQUENCE_ID_BITS) + | sequence_id + ) - return "overflows" - else: - snowflake_id = ( - (read_current_millis(epoch_ms) << (NODE_ID_BITS + SEQUENCE_ID_BITS)) - | (node_id << SEQUENCE_ID_BITS) - | sequence_id - ) - - - - + return snowflake_id From ff04e6c8617e56734a6e566e588f95d1930d2767 Mon Sep 17 00:00:00 2001 From: somet1me123 Date: Wed, 23 Sep 2026 00:34:49 +0300 Subject: [PATCH 03/12] Solve task 1 --- src/part1/constants.py | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/part1/constants.py b/src/part1/constants.py index 9abfbba2..caa537fa 100644 --- a/src/part1/constants.py +++ b/src/part1/constants.py @@ -19,20 +19,20 @@ # Все константы, зависящие от ёмкостей *_BITS, должны вычисляться из них. # Twitter's original Snowflake epoch: 2010-11-04 01:42:54.657 UTC. -EPOCH_MS_DEFAULT: Final[int] = 0 +EPOCH_MS_DEFAULT: Final[int] = 1288834974657 # Node identifier used when the caller does not supply one. -NODE_ID_DEFAULT: Final[int] = 0 +NODE_ID_DEFAULT: Final[int] = 1 # Width of each field, in bits. -TIMESTAMP_BITS: Final[int] = 0 -NODE_ID_BITS: Final[int] = 0 -SEQUENCE_ID_BITS: Final[int] = 0 +TIMESTAMP_BITS: Final[int] = 41 +NODE_ID_BITS: Final[int] = 10 +SEQUENCE_ID_BITS: Final[int] = 12 # Largest value each field can hold. -TIMESTAMP_MS_MAX: Final[int] = 0 -NODE_ID_MAX: Final[int] = 0 -SEQUENCE_ID_MAX: Final[int] = 0 +TIMESTAMP_MS_MAX: Final[int] = 2**TIMESTAMP_BITS-1 +NODE_ID_MAX: Final[int] = 2**NODE_ID_BITS-1 +SEQUENCE_ID_MAX: Final[int] = 2**SEQUENCE_ID_BITS-1 # Здесь можно добавить собственные вспомогательные константы # (например, сдвиги полей при сборке идентификатора). From 1e1ef11dcd1a2f7ab043e14a0e3e36dc4ade02d0 Mon Sep 17 00:00:00 2001 From: somet1me123 Date: Wed, 23 Sep 2026 00:35:39 +0300 Subject: [PATCH 04/12] Solve task 1 --- src/part1/constants.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/part1/constants.py b/src/part1/constants.py index caa537fa..7a112a77 100644 --- a/src/part1/constants.py +++ b/src/part1/constants.py @@ -30,9 +30,9 @@ SEQUENCE_ID_BITS: Final[int] = 12 # Largest value each field can hold. -TIMESTAMP_MS_MAX: Final[int] = 2**TIMESTAMP_BITS-1 -NODE_ID_MAX: Final[int] = 2**NODE_ID_BITS-1 -SEQUENCE_ID_MAX: Final[int] = 2**SEQUENCE_ID_BITS-1 +TIMESTAMP_MS_MAX: Final[int] = 2**TIMESTAMP_BITS - 1 +NODE_ID_MAX: Final[int] = 2**NODE_ID_BITS - 1 +SEQUENCE_ID_MAX: Final[int] = 2**SEQUENCE_ID_BITS - 1 # Здесь можно добавить собственные вспомогательные константы # (например, сдвиги полей при сборке идентификатора). From 3e39cb789b903fe3242a7713cc947808fbbc3917 Mon Sep 17 00:00:00 2001 From: somet1me123 Date: Wed, 23 Sep 2026 00:44:26 +0300 Subject: [PATCH 05/12] Solve task 1 --- src/part1/snowflake.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/part1/snowflake.py b/src/part1/snowflake.py index 6a602477..5b67e6f9 100644 --- a/src/part1/snowflake.py +++ b/src/part1/snowflake.py @@ -56,17 +56,18 @@ def generate_snowflake_id( node_id: int = NODE_ID_DEFAULT, epoch_ms: int = EPOCH_MS_DEFAULT, ) -> int | None: + time_stamp = read_current_millis(epoch_ms) if not (0 <= node_id <= NODE_ID_MAX): print("node_id must be in [0, 2**10-1]") return None elif not (0 <= sequence_id <= SEQUENCE_ID_MAX): print("sequence_id must be in [0, 2**12-1]") return None - elif read_current_millis(epoch_ms) > TIMESTAMP_MS_MAX: + elif time_stamp > TIMESTAMP_MS_MAX: print("overflows") return None snowflake_id = ( - (read_current_millis(epoch_ms) << (NODE_ID_BITS + SEQUENCE_ID_BITS)) + (time_stamp << (NODE_ID_BITS + SEQUENCE_ID_BITS)) | (node_id << SEQUENCE_ID_BITS) | sequence_id ) From a540f3bedd640901e9901bdca1aaf72e1c4512aa Mon Sep 17 00:00:00 2001 From: somet1me123 Date: Wed, 30 Sep 2026 11:04:31 +0300 Subject: [PATCH 06/12] add constants to storage.py --- src/part2/storage.py | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/src/part2/storage.py b/src/part2/storage.py index b63d5fc7..e4bceff1 100644 --- a/src/part2/storage.py +++ b/src/part2/storage.py @@ -24,11 +24,9 @@ type Product = tuple[int, str, Decimal, int] -# TODO: задайте позиции полей внутри кортежа Product PRODUCT_ID_INDEX: Final = 0 -NAME_INDEX: Final = 0 -PRICE_INDEX: Final = 0 -QUANTITY_INDEX: Final = 0 +NAME_INDEX: Final = 1 +PRICE_INDEX: Final = 2 +QUANTITY_INDEX: Final = 3 -# TODO: задайте идентификатор первого товара в пустом хранилище -PRODUCT_ID_MIN: Final[int] = 0 +PRODUCT_ID_MIN: Final[int] = 1 From c2137461f9a3ca94a00d1d9d4833f1d483948d1b Mon Sep 17 00:00:00 2001 From: somet1me123 Date: Wed, 30 Sep 2026 11:19:25 +0300 Subject: [PATCH 07/12] modificated function in utils.py --- src/part2/TASK.md | 213 --------------------------------------------- src/part2/utils.py | 21 ++--- 2 files changed, 6 insertions(+), 228 deletions(-) delete mode 100644 src/part2/TASK.md diff --git a/src/part2/TASK.md b/src/part2/TASK.md deleted file mode 100644 index 25736d9c..00000000 --- a/src/part2/TASK.md +++ /dev/null @@ -1,213 +0,0 @@ -# Задача: CRUD и корзина для интернет-магазина - -## Легенда - -Наше хранилище данных уже умеет выдавать уникальные идентификаторы, но пока это -лишь «голая» база: записи лежат в памяти, и работать с ними приходится вручную. -Чтобы проверить, что хранилище годится для настоящей прикладной задачи, мы -построим на нём серверную часть простого интернет-магазина: каталог товаров и -корзину покупателя. - -Если писать такой код «в лоб», быстро возникают проблемы: - -- записи о товарах разбросаны по программе, и каждый кусок кода сам решает, как - их создавать, менять и удалять, — в итоге в каталоге появляются дубликаты и - «осиротевшие» идентификаторы; -- деньги хранят во `float`, и суммы вроде `0.1 + 0.2` начинают расходиться с - копейками, а в бухгалтерии такое недопустимо; -- товар «переезжает» между складом и корзиной в два отдельных действия, и если - одно из них не выполнилось, товар пропадает или появляется из воздуха. - -Именно эти вопросы решают классические CRUD-операции (create, read, update, -delete) над единым хранилищем, аккуратная работа с ценой через `Decimal` и -операции корзины, которые сохраняют общее количество товара. Их нам и предстоит -написать. Позже на этих функциях мы построим интерфейс работы с нашей базой. - -## Контекст - -Нужно реализовать серверную часть простого интернет-магазина: хранилище товаров, -операции CRUD над ним и работу с корзиной покупателя. Настоящая база данных не -используется — хранилище это список кортежей в оперативной памяти. - -Решение состоит из четырёх модулей: - -- `storage.py` — форма записи о товаре и связанные с ней константы; -- `utils.py` — округление денежных сумм; -- `crud.py` — создание, чтение, изменение и удаление записей о товарах; -- `cart.py` — перенос товаров между хранилищем и корзиной. - -Все функции, кроме `find_cart_line` и `change_cart_quantity`, на неуспешном пути -ничего не бросают: печатают сообщение об ошибке в stdout и возвращают `None`. - -## Формат записи о товаре - -Запись о товаре (`Product`) — кортеж из четырёх полей, перечисленных по порядку: - -| Поле | Тип | Что хранит | -| ------------- | --------- | ------------------------------------------------------------------ | -| идентификатор | `int` | уникальный положительный ключ, назначается при создании записи | -| наименование | `str` | человекочитаемое имя, уникальное в пределах хранилища | -| цена | `Decimal` | цена за единицу, округлённая до фиксированного числа знаков дроби | -| количество | `int` | число единиц товара на складе | - -Позиции полей задаются константами `*_INDEX`, чтобы обращение к кортежу не -использовало числовые литералы. - -Строка корзины (`CartLine`) — кортеж `(идентификатор товара, количество)`. В -корзине не более одной строки на каждый товар. - -## Модуль `storage.py` - -Определите: - -- `Product` — псевдоним типа `tuple[int, str, Decimal, int]`. -- `PRODUCT_ID_INDEX`, `NAME_INDEX`, `PRICE_INDEX`, `QUANTITY_INDEX` — позиции - полей в кортеже `Product`: `0`, `1`, `2`, `3`. Каждая аннотирована - `typing.Final`. -- `PRODUCT_ID_MIN: Final[int] = 1` — идентификатор, который получает первый - товар, добавленный в пустое хранилище. - -## Модуль `utils.py` - -- `PRICE_PRECISION: Final[int] = 2` — число знаков после запятой, до которого - округляется каждая сохраняемая цена. -- `PRICE_STEP: Final` — шаг квантования. Вычисляется из `PRICE_PRECISION` - (`Decimal(1).scaleb(-PRICE_PRECISION)`, то есть `Decimal("0.01")` при значении - по умолчанию), а не задаётся числом напрямую; при изменении `PRICE_PRECISION` - шаг меняется согласованно. - -### `normalize_price(price: Decimal) -> Decimal` - -- **Вход:** `price` — произвольная денежная сумма типа `Decimal`. -- **Выход:** та же сумма, приведённая к `PRICE_PRECISION` знакам после запятой; - ровно половина шага округляется вверх (режим `ROUND_HALF_UP`). - -Примеры: `Decimal("12.999") → Decimal("13.00")`, -`Decimal("2.3451") → Decimal("2.35")`, `Decimal("2.3449") → Decimal("2.34")`, -`Decimal("5") → Decimal("5.00")` (число знаков дроби в результате всегда равно -`PRICE_PRECISION`). - -## Модуль `crud.py` - -Каждая функция получает хранилище `storage: list[Product]` первым параметром и -меняет его на месте. - -### `generate_product_id(storage: list[Product]) -> int` - -- **Вход:** хранилище. -- **Выход:** если хранилище пустое — `PRODUCT_ID_MIN`; иначе — наибольший - идентификатор среди записей плюс `1`. Пропуски в нумерации (например, - оставшиеся после удаления) не переиспользуются — берётся именно максимум. - -### `create_product(storage: list[Product], fields: tuple[str, Decimal, int]) -> int | None` - -- **Вход:** `fields` — кортеж `(наименование, цена, количество)`; `цена` типа - `Decimal`. -- **Выход:** сгенерированный идентификатор новой записи, либо `None`. - -**Поведение.** - -1. Если в хранилище уже есть запись с таким же наименованием — новая запись не - создаётся, хранилище не меняется, печатается сообщение об ошибке, содержащее - это наименование, возвращается `None`. (Например: - `product name '<имя>' is already taken`.) -2. Иначе идентификатор вычисляется через `generate_product_id`, цена приводится - через `normalize_price`, кортеж - `(идентификатор, наименование, нормализованная цена, количество)` добавляется - в хранилище, возвращается идентификатор. - -### `read_product(storage: list[Product], product_id: int) -> Product | None` - -- **Вход:** целочисленный идентификатор. -- **Выход:** запись с этим идентификатором, либо `None`. Если записи нет — - печатается сообщение об ошибке, содержащее переданный идентификатор (например, - `no product with id `). - -### `update_product(storage: list[Product], product_id: int, fields: tuple[str, Decimal, int]) -> Product | None` - -- **Вход:** идентификатор и кортеж `(наименование, цена, количество)` с новыми - значениями полей. -- **Выход:** изменённая запись - `(идентификатор, наименование, нормализованная цена, количество)` — сам - идентификатор сохраняется прежним, остальные три поля заменяются, цена - приводится через `normalize_price`. Если записи с таким идентификатором нет — - хранилище не меняется, печатается сообщение об ошибке с идентификатором - (`no product with id `), возвращается `None`. Уникальность нового - наименования не проверяется. - -### `delete_product(storage: list[Product], product_id: int) -> int | None` - -- **Вход:** идентификатор. -- **Выход:** тот же идентификатор, если запись была найдена и удалена из - хранилища. Если записи нет — хранилище не меняется, печатается сообщение об - ошибке с идентификатором (`no product with id `), возвращается `None`. - -## Модуль `cart.py` - -- `CartLine` — псевдоним типа `tuple[int, int]` - (`(идентификатор товара, количество)`). -- `LINE_PRODUCT_ID_INDEX`, `LINE_QUANTITY_INDEX` — позиции полей строки корзины - (`0`, `1`), аннотированы `typing.Final`. - -### `add_to_cart(storage: list[Product], cart: list[CartLine], product_id: int, quantity: int) -> CartLine | None` - -Переносит `quantity` единиц товара `product_id` со склада в корзину. - -- **Вход:** хранилище, корзина, идентификатор товара, количество для добавления. -- **Выход:** строка корзины для `product_id` после добавления, либо `None`. - -**Поведение.** Проверки выполняются в этом порядке; при первой же неудаче -остальные действия не выполняются: - -1. Товар ищется в хранилище (через `read_product`). Если его нет — `read_product` - печатает сообщение с идентификатором, `add_to_cart` возвращает `None`, больше - ничего не меняется. -2. Иначе количество на складе сравнивается с запрошенным. Если на складе строго - меньше, чем `quantity` — печатается сообщение об ошибке, содержащее - идентификатор товара (например: - `not enough stock for product : <склад> available, requested`), - возвращается `None`, ничего не меняется. Запрос ровно на всё имеющееся - количество (`quantity == склад`) допустим. -3. Иначе количество товара в хранилище уменьшается на `quantity` (наименование и - цена не меняются), а в корзину добавляется `quantity` единиц: если строка для - товара уже была — увеличивается её количество, иначе создаётся новая строка. - Возвращается получившаяся строка корзины. - -### `remove_from_cart(storage: list[Product], cart: list[CartLine], product_id: int, quantity: int) -> CartLine | None` - -Переносит `quantity` единиц товара `product_id` из корзины обратно на склад. -Принимает тот же набор аргументов, что и `add_to_cart`. - -- **Выход:** строка корзины для `product_id` после удаления (количество `0` - означает, что строка удалена), либо `None`. - -**Поведение.** Проверки в этом порядке: - -1. Строка корзины для `product_id` ищется через `find_cart_line`. Если её нет — - печатается сообщение об ошибке, содержащее идентификатор (например: - `product is not in the cart`), возвращается `None`, ничего не меняется. -2. Иначе количество в строке корзины сравнивается с запрошенным. Если в корзине - строго меньше, чем `quantity` — печатается сообщение об ошибке с - идентификатором (например: - `cart holds only <в корзине> unit(s) of product , cannot remove `), - возвращается `None`, ничего не меняется. -3. Товар ищется в хранилище через `read_product`; если его там нет — - возвращается `None` (сообщение печатает `read_product`). -4. Иначе количество товара в хранилище увеличивается на `quantity`, а из строки - корзины вычитается `quantity` (наименование и цена не меняются); если - количество в строке стало `0`, строка удаляется. Возвращается получившаяся - строка корзины. - -## Инварианты - -- Для любой успешно созданной записи - `read_product(storage, create_product(storage, (name, price, qty)))` возвращает - `(id, name, normalize_price(price), qty)`. -- После `delete_product(storage, id)` вызов `read_product(storage, id)` - возвращает `None`. -- Цена в хранилище всегда нормализована: `normalize_price` применяется при - каждом создании и изменении записи. -- Сохранение количества: при успешном `add_to_cart` или `remove_from_cart` сумма - «количество товара на складе + количество этого товара в корзине» не меняется. -- `add_to_cart(...)` и следующий за ним `remove_from_cart(...)` с тем же - `quantity` возвращают склад и корзину к исходному состоянию. diff --git a/src/part2/utils.py b/src/part2/utils.py index ec0348d3..50ce048e 100644 --- a/src/part2/utils.py +++ b/src/part2/utils.py @@ -6,24 +6,15 @@ currency values free of binary floating-point error. """ -from decimal import ROUND_HALF_UP, Decimal # noqa: F401 +from decimal import ROUND_HALF_UP, Decimal from typing import Final -# TODO: задайте число знаков после запятой и шаг квантования -PRICE_PRECISION: Final[int] = 0 -PRICE_STEP: Final = Decimal(0) +PRICE_PRECISION: Final[int] = 2 +PRICE_STEP: Final = Decimal(1).scaleb(-PRICE_PRECISION) def normalize_price(price: Decimal) -> Decimal: - """Round a price to the precision every stored record uses. - - Args: - price: The raw price amount. - - Returns: - ``price`` quantised to :data:`PRICE_PRECISION` fractional digits, - with halves rounded up. - """ - # TODO: реализуйте функцию - return Decimal(0) + true_price = price.quantize(PRICE_STEP, rounding=ROUND_HALF_UP) + + return true_price From c30612d3e55ab7180ece0eba0bf4e1924aae3b0a Mon Sep 17 00:00:00 2001 From: somet1me123 Date: Thu, 1 Oct 2026 17:40:08 +0300 Subject: [PATCH 08/12] modificed all functions and solved task 2 --- src/part2/cart.py | 111 +++++++++++++++++++++++-------------------- src/part2/crud.py | 118 ++++++++++++++++------------------------------ 2 files changed, 102 insertions(+), 127 deletions(-) diff --git a/src/part2/cart.py b/src/part2/cart.py index 063f9aea..53f6679e 100644 --- a/src/part2/cart.py +++ b/src/part2/cart.py @@ -11,8 +11,8 @@ from typing import Final -from .crud import read_product, update_product # noqa: F401 -from .storage import ( # noqa: F401 +from .crud import read_product, update_product +from .storage import ( NAME_INDEX, PRICE_INDEX, QUANTITY_INDEX, @@ -22,9 +22,8 @@ type CartLine = tuple[int, int] -# TODO: задайте позиции полей внутри кортежа CartLine LINE_PRODUCT_ID_INDEX: Final = 0 -LINE_QUANTITY_INDEX: Final = 0 +LINE_QUANTITY_INDEX: Final = 1 def add_to_cart( @@ -33,28 +32,41 @@ def add_to_cart( product_id: int, quantity: int, ) -> CartLine | None: - """Move ``quantity`` units of ``product_id`` from the store into ``cart``. - - The product is looked up in ``storage``. If it is missing, a message is - printed (by :func:`~src.part2.crud.read_product`) and nothing - changes. If the store holds fewer units than requested, an explanatory - message is printed and nothing changes. Otherwise the store record is - decremented by ``quantity`` and the cart line for ``product_id`` gains - ``quantity`` units -- a new line is created when the cart had none. - - Args: - storage: The product store to draw stock from; modified in place on - success. - cart: The cart to add the units to; modified in place on success. - product_id: The identifier of the product to add. - quantity: Number of units to move into the cart. - - Returns: - The cart line for ``product_id`` after the addition, or ``None`` - when the product is unknown or the store cannot cover the request. - """ - # TODO: реализуйте функцию - return (0, 0) + item = read_product(storage, product_id) + if item is None: + return None + + available = item[QUANTITY_INDEX] + if available < quantity: + print(f"not enough stock for product {product_id}: {available} available, {quantity} requested") + return None + + new_quantity = (available - quantity) + new_fields = (item[NAME_INDEX], item[PRICE_INDEX], new_quantity) + update_product(storage, product_id, new_fields) + + for i in range(len(cart)): + if cart[i][LINE_PRODUCT_ID_INDEX] == product_id: + prev_cart_quant = cart[i][LINE_QUANTITY_INDEX] + new_cart_item = (product_id, prev_cart_quant + quantity) + cart[i] = new_cart_item + return cart[i] + + new_cart_item = (product_id, quantity) + cart.append(new_cart_item) + return new_cart_item + + + +def find_cart_line( + cart: list[CartLine], + product_id: int, +) -> CartLine | None: + for i in range(len(cart)): + if cart[i][LINE_PRODUCT_ID_INDEX] == product_id: + return cart[i] + + return None def remove_from_cart( @@ -63,27 +75,26 @@ def remove_from_cart( product_id: int, quantity: int, ) -> CartLine | None: - """Move ``quantity`` units of ``product_id`` from ``cart`` back to the store. - - The cart line for ``product_id`` is looked up. If there is none, a - message is printed and nothing changes. If the line holds fewer units - than requested, an explanatory message is printed and nothing changes. - Otherwise the cart line loses ``quantity`` units -- the line is dropped - when it reaches zero -- and the store record gains ``quantity`` units - back. - - Args: - storage: The product store to return stock to; modified in place on - success. - cart: The cart to take the units from; modified in place on - success. - product_id: The identifier of the product to remove. - quantity: Number of units to move back into the store. - - Returns: - The cart line for ``product_id`` after the removal (a quantity of - zero means the line was dropped), or ``None`` when the cart has no - line for the product or holds too few units. - """ - # TODO: реализуйте функцию - return (0, 0) + line = find_cart_line(cart, product_id) + if not line: + print(f"product {product_id} is not in the cart") + return None + + if quantity > line[LINE_QUANTITY_INDEX]: + print(f"cart holds only {line[LINE_QUANTITY_INDEX]} unit(s) of product {product_id}, cannot remove {quantity}") + return None + + product = read_product(storage, product_id) + if not product: + return None + + new_quantity = (product[QUANTITY_INDEX] + quantity) + new_fields = (product[NAME_INDEX], product[PRICE_INDEX], new_quantity) + update_product(storage, product_id, new_fields) + for i in range(len(cart)): + if cart[i][LINE_PRODUCT_ID_INDEX] == product_id: + cart[i] = (product_id, line[LINE_QUANTITY_INDEX] - quantity) + if cart[i][LINE_QUANTITY_INDEX] == 0: + cart.pop(i) + return (product_id, 0) + return cart[i] diff --git a/src/part2/crud.py b/src/part2/crud.py index d026cbcb..25ce2ee3 100644 --- a/src/part2/crud.py +++ b/src/part2/crud.py @@ -24,56 +24,36 @@ def generate_product_id(storage: list[Product]) -> int: - """Choose the identifier for the next product added to ``storage``. - - Args: - storage: The product store to inspect. - - Returns: - One past the greatest identifier currently held in ``storage``, or - :data:`~src.part2.storage.PRODUCT_ID_MIN` when ``storage`` is - empty. - """ - # TODO: реализуйте функцию - return 0 + if not storage: + return PRODUCT_ID_MIN + + max_storage = max(product[PRODUCT_ID_INDEX] for product in storage) + 1 + return max_storage def create_product( storage: list[Product], fields: tuple[str, Decimal, int] ) -> int | None: - """Append a new product to ``storage`` and return its new identifier. - - Args: - storage: The product store to append to; modified in place on - success. - fields: A ``(name, price, quantity)`` tuple describing the product. - ``price`` is a :class:`~decimal.Decimal` amount and is rounded - to the stored money precision before it is saved. - - Returns: - The identifier generated for the new product, or ``None`` when a - product with the same name already exists. In the ``None`` case - ``storage`` is left unchanged and a message naming the clashing - name is printed. - """ - # TODO: реализуйте функцию - return 0 + name, price, quantity = fields + for item in storage: + if name == item[NAME_INDEX]: + print(f"product name '{name}' is already taken") + return None + + new_id = generate_product_id(storage) + new_price = normalize_price(price) + new_product = (new_id, name, new_price, quantity) + storage.append(new_product) + return new_id def read_product(storage: list[Product], product_id: int) -> Product | None: - """Return the product stored under ``product_id``. - - Args: - storage: The product store to search. - product_id: The identifier to look up. + for i in range(len(storage)): + if storage[i][PRODUCT_ID_INDEX] == product_id: + return storage[i] - Returns: - The matching ``(product_id, name, price, quantity)`` record, or - ``None`` when no product carries that identifier (a message is - printed in that case). - """ - # TODO: реализуйте функцию - return (0, "", Decimal(0), 0) + print(f"no product with id {product_id}") + return None def update_product( @@ -81,40 +61,24 @@ def update_product( product_id: int, fields: tuple[str, Decimal, int], ) -> Product | None: - """Overwrite the fields of the product stored under ``product_id``. - - The identifier itself is preserved; only ``name``, ``price`` and - ``quantity`` are replaced. - - Args: - storage: The product store to modify; the matching record is - replaced in place on success. - product_id: The identifier of the product to change. - fields: A ``(name, price, quantity)`` tuple with the new values. - ``price`` is a :class:`~decimal.Decimal` amount and is rounded - to the stored money precision before it is saved. - - Returns: - The updated ``(product_id, name, price, quantity)`` record, or - ``None`` when no product carries that identifier (``storage`` is - left unchanged and a message is printed). - """ - # TODO: реализуйте функцию - return (0, "", Decimal(0), 0) - - + name, price, quantity = fields + for i in range(len(storage)): + if product_id == storage[i][PRODUCT_ID_INDEX]: + new_price = normalize_price(price) + new_item = (product_id, name, new_price, quantity) + storage[i] = new_item + return new_item + + print(f"no product with id '{product_id}'") + return None + + def delete_product(storage: list[Product], product_id: int) -> int | None: - """Remove the product stored under ``product_id`` from ``storage``. - - Args: - storage: The product store to remove from; modified in place on - success. - product_id: The identifier of the product to remove. - - Returns: - ``product_id`` when a product was removed, or ``None`` when no - product carried that identifier (``storage`` is left unchanged and - a message is printed). - """ - # TODO: реализуйте функцию - return 0 + for item in storage: + if item[PRODUCT_ID_INDEX] == product_id: + storage.remove(item) + return product_id + + print(f"no product with id '{product_id}'") + return None + From 2bbf0cf48cbc72a0a69403511c19a9bb788cbadd Mon Sep 17 00:00:00 2001 From: somet1me123 Date: Thu, 1 Oct 2026 17:41:47 +0300 Subject: [PATCH 09/12] slightly modificed the solution --- src/part2/cart.py | 16 ++++++++++------ src/part2/crud.py | 17 ++++++++--------- src/part2/utils.py | 4 ++-- 3 files changed, 20 insertions(+), 17 deletions(-) diff --git a/src/part2/cart.py b/src/part2/cart.py index 53f6679e..2f8e11f9 100644 --- a/src/part2/cart.py +++ b/src/part2/cart.py @@ -38,10 +38,12 @@ def add_to_cart( available = item[QUANTITY_INDEX] if available < quantity: - print(f"not enough stock for product {product_id}: {available} available, {quantity} requested") + print( + f"not enough stock for product {product_id}: {available} available, {quantity} requested" + ) return None - - new_quantity = (available - quantity) + + new_quantity = available - quantity new_fields = (item[NAME_INDEX], item[PRICE_INDEX], new_quantity) update_product(storage, product_id, new_fields) @@ -57,7 +59,6 @@ def add_to_cart( return new_cart_item - def find_cart_line( cart: list[CartLine], product_id: int, @@ -81,14 +82,16 @@ def remove_from_cart( return None if quantity > line[LINE_QUANTITY_INDEX]: - print(f"cart holds only {line[LINE_QUANTITY_INDEX]} unit(s) of product {product_id}, cannot remove {quantity}") + print( + f"cart holds only {line[LINE_QUANTITY_INDEX]} unit(s) of product {product_id}, cannot remove {quantity}" + ) return None product = read_product(storage, product_id) if not product: return None - new_quantity = (product[QUANTITY_INDEX] + quantity) + new_quantity = product[QUANTITY_INDEX] + quantity new_fields = (product[NAME_INDEX], product[PRICE_INDEX], new_quantity) update_product(storage, product_id, new_fields) for i in range(len(cart)): @@ -98,3 +101,4 @@ def remove_from_cart( cart.pop(i) return (product_id, 0) return cart[i] + return None diff --git a/src/part2/crud.py b/src/part2/crud.py index 25ce2ee3..4e3a9b3e 100644 --- a/src/part2/crud.py +++ b/src/part2/crud.py @@ -14,19 +14,19 @@ from decimal import Decimal -from .storage import ( # noqa: F401 +from .storage import ( NAME_INDEX, PRODUCT_ID_INDEX, PRODUCT_ID_MIN, Product, ) -from .utils import normalize_price # noqa: F401 +from .utils import normalize_price def generate_product_id(storage: list[Product]) -> int: if not storage: return PRODUCT_ID_MIN - + max_storage = max(product[PRODUCT_ID_INDEX] for product in storage) + 1 return max_storage @@ -39,7 +39,7 @@ def create_product( if name == item[NAME_INDEX]: print(f"product name '{name}' is already taken") return None - + new_id = generate_product_id(storage) new_price = normalize_price(price) new_product = (new_id, name, new_price, quantity) @@ -52,7 +52,7 @@ def read_product(storage: list[Product], product_id: int) -> Product | None: if storage[i][PRODUCT_ID_INDEX] == product_id: return storage[i] - print(f"no product with id {product_id}") + print(f"no product with id '{product_id}'") return None @@ -69,16 +69,15 @@ def update_product( storage[i] = new_item return new_item - print(f"no product with id '{product_id}'") + print(f"no product with id {product_id}") return None - + def delete_product(storage: list[Product], product_id: int) -> int | None: for item in storage: if item[PRODUCT_ID_INDEX] == product_id: storage.remove(item) return product_id - + print(f"no product with id '{product_id}'") return None - diff --git a/src/part2/utils.py b/src/part2/utils.py index 50ce048e..b0e3cdb3 100644 --- a/src/part2/utils.py +++ b/src/part2/utils.py @@ -6,7 +6,7 @@ currency values free of binary floating-point error. """ -from decimal import ROUND_HALF_UP, Decimal +from decimal import ROUND_HALF_UP, Decimal from typing import Final @@ -16,5 +16,5 @@ def normalize_price(price: Decimal) -> Decimal: true_price = price.quantize(PRICE_STEP, rounding=ROUND_HALF_UP) - + return true_price From 1a3503c7ecf868583d0915958d3b27619b507975 Mon Sep 17 00:00:00 2001 From: somet1me123 Date: Wed, 7 Oct 2026 03:46:39 +0300 Subject: [PATCH 10/12] started to modify func. in crud.py --- src/part3/crud.py | 62 +++++++++++++++-------------------------------- 1 file changed, 20 insertions(+), 42 deletions(-) diff --git a/src/part3/crud.py b/src/part3/crud.py index 68811d7e..d9b54e9d 100644 --- a/src/part3/crud.py +++ b/src/part3/crud.py @@ -30,58 +30,36 @@ def generate_product_id(storage: list[Product]) -> int: - """Choose the identifier for the next product added to ``storage``. - - Args: - storage: The product store to inspect. - - Returns: - One past the greatest identifier currently held in ``storage``, or - :data:`~src.part3.storage.PRODUCT_ID_MIN` when ``storage`` is - empty. - """ - # TODO: реализуйте функцию (используйте своё решение части 2) - return 0 + if not storage: + return PRODUCT_ID_MIN + + max_storage = max(product[PRODUCT_ID_INDEX] for product in storage) + 1 + return max_storage def create_product( storage: list[Product], fields: tuple[str, Decimal, int] ) -> int | None: - """Append a new product to ``storage`` and return its new identifier. - - Args: - storage: The product store to append to; modified in place on - success. - fields: A ``(name, price, quantity)`` tuple describing the product. - ``name`` is normalised (surrounding whitespace stripped, - lower-cased) before it is stored or compared. ``price`` is a - :class:`~decimal.Decimal` amount and is rounded to the stored - money precision before it is saved. + name, price, quantity = fields + for item in storage: + if name == item[NAME_INDEX]: + print(f"product name '{name}' is already taken") + return None - Returns: - The identifier generated for the new product, or ``None`` when - ``name`` is blank once normalised or a product with the same - normalised name already exists. In the ``None`` case ``storage`` - is left unchanged and an explanatory message is printed. - """ - # TODO: реализуйте функцию - return 0 + new_id = generate_product_id(storage) + new_price = normalize_price(price) + new_product = (new_id, name, new_price, quantity) + storage.append(new_product) + return new_id def read_product(storage: list[Product], product_id: int) -> Product | None: - """Return the product stored under ``product_id``. - - Args: - storage: The product store to search. - product_id: The identifier to look up. + for i in range(len(storage)): + if storage[i][PRODUCT_ID_INDEX] == product_id: + return storage[i] - Returns: - The matching ``(product_id, name, price, quantity)`` record, or - ``None`` when no product carries that identifier (a message is - printed in that case). - """ - # TODO: реализуйте функцию (используйте своё решение части 2) - return (0, "", Decimal(0), 0) + print(f"no product with id '{product_id}'") + return None def update_product( From af32ad30270f76e617f73cc0368224acad954431 Mon Sep 17 00:00:00 2001 From: somet1me123 Date: Fri, 9 Oct 2026 15:47:58 +0300 Subject: [PATCH 11/12] Changed some functions, preparing for ending assignment --- src/part3/crud.py | 4 +- src/part3/run_admin.py | 98 ++++++++++++++++++++++++------------------ src/part3/storage.py | 8 ++-- src/part3/utils.py | 96 ++++++++++++++++------------------------- 4 files changed, 100 insertions(+), 106 deletions(-) diff --git a/src/part3/crud.py b/src/part3/crud.py index d9b54e9d..226ae457 100644 --- a/src/part3/crud.py +++ b/src/part3/crud.py @@ -31,8 +31,8 @@ def generate_product_id(storage: list[Product]) -> int: if not storage: - return PRODUCT_ID_MIN - + return PRODUCT_ID_MIN + max_storage = max(product[PRODUCT_ID_INDEX] for product in storage) + 1 return max_storage diff --git a/src/part3/run_admin.py b/src/part3/run_admin.py index c5feeb0b..260406fb 100644 --- a/src/part3/run_admin.py +++ b/src/part3/run_admin.py @@ -29,67 +29,81 @@ it. """ -from decimal import Decimal, InvalidOperation # noqa: F401 +from decimal import Decimal, InvalidOperation from typing import Final -from .crud import ( # noqa: F401 +from .crud import ( create_product, delete_product, read_product, update_product, ) from .storage import Product -from .utils import get_storage_str_representation # noqa: F401 +from .utils import get_storage_str_representation -# TODO: задайте приглашение и текст справки -PROMPT: Final[str] = "" -HELP_TEXT: Final[str] = "" +PROMPT: Final[str] = "admin> " +HELP_TEXT: Final[str] = """\ +Available commands: + help show this message + exit leave the console + show print the whole store as a table + create add a product, print its new id + read print the product with that id + update overwrite that product's fields + delete remove the product with that id +For create and update the price and quantity are the last two words of the +line; everything before them is the product name, so it may contain spaces +(for example "Gibson SG Junior") and needs no quoting.""" -def show_help() -> None: - """Print the command reference to stdout. - The text is the module-level :data:`HELP_TEXT` constant, printed as - is: a heading, one line per command with a short description, and a - note on how multi-word names are parsed. - """ - # TODO: реализуйте функцию +def show_help() -> None: + print(HELP_TEXT) def print_result(result: object) -> None: - """Print a CRUD result to stdout unless it is ``None``. - - Args: - result: The value returned by a CRUD operation. ``None`` means the - operation already reported its own failure, so nothing is - printed in that case. - """ - # TODO: реализуйте функцию + if result is not None: + print(result) + return None def run_command(storage: list[Product], line: str) -> bool: - """Parse one console line and carry out the command it names. - - Args: - storage: The product store shared across the session; mutated in - place by the ``create``, ``update`` and ``delete`` commands. - line: One line of console input, already stripped of surrounding - whitespace. - - Returns: - ``True`` to keep the read-eval-print loop running, or ``False`` - once the ``exit`` command has been seen. A line that is not a - known command prints a notice and still returns ``True``. - - Raises: - ValueError: If an id or quantity argument of a CRUD command does - not parse as a base-10 integer. - decimal.InvalidOperation: If the price argument of ``create`` or - ``update`` does not parse as a decimal number. - """ - # TODO: реализуйте функцию - return False + match line.split(): + case ["read", prod_id]: + print_result(read_product(storage, int(prod_id))) + return True + + case ["create", *name, price, quantity] if name: + name = " ".join(name) + fields_case = (name, Decimal(price), int(quantity)) + print_result(create_product(storage, fields_case)) + return True + + case ["update", prod_id, *name, price, quantity] if name: + name = " ".join(name) + fields_case = (name, Decimal(price), int(quantity)) + print_result(update_product(storage, int(prod_id), fields_case)) + return True + + case ["delete", prod_id]: + print_result(delete_product(storage, int(prod_id))) + return True + + case ["exit"]: + return False + + case ["help"]: + show_help() + return True + + case ["show"]: + print(get_storage_str_representation(storage)) + return True + + case _: + print(f"'{line}' is not a command") + return True def main() -> None: diff --git a/src/part3/storage.py b/src/part3/storage.py index c5e34be5..36e9af7f 100644 --- a/src/part3/storage.py +++ b/src/part3/storage.py @@ -27,9 +27,9 @@ # TODO: задайте позиции полей внутри кортежа Product (используйте своё решение # части 2) PRODUCT_ID_INDEX: Final = 0 -NAME_INDEX: Final = 0 -PRICE_INDEX: Final = 0 -QUANTITY_INDEX: Final = 0 +NAME_INDEX: Final = 1 +PRICE_INDEX: Final = 2 +QUANTITY_INDEX: Final = 3 # TODO: задайте идентификатор первого товара в пустом хранилище -PRODUCT_ID_MIN: Final[int] = 0 +PRODUCT_ID_MIN: Final[int] = 1 diff --git a/src/part3/utils.py b/src/part3/utils.py index 318ded0b..27600002 100644 --- a/src/part3/utils.py +++ b/src/part3/utils.py @@ -20,76 +20,56 @@ from decimal import ROUND_HALF_UP, Decimal # noqa: F401 from typing import Final +from .storage import ( + PRODUCT_ID_INDEX, + NAME_INDEX, + PRICE_INDEX, + QUANTITY_INDEX, + Product, +) -from .storage import Product +PRICE_PRECISION: Final[int] = 2 +PRICE_STEP: Final = Decimal(1).scaleb(-PRICE_PRECISION) -# Number of fractional digits every stored price is rounded to. -# Quantisation step derived from PRICE_PRECISION, e.g. Decimal("0.01"). -# TODO: задайте число знаков после запятой и шаг квантования (используйте своё -# решение части 2) -PRICE_PRECISION: Final[int] = 0 -PRICE_STEP: Final = Decimal(0) -# Column headers of the table produced by get_storage_str_representation, -# left to right. The width of each column is not fixed here -- it is -# measured per call from the data (see the function). -# TODO: задайте заголовки столбцов таблицы -TABLE_HEADERS: Final[tuple[str, ...]] = () +TABLE_HEADERS: Final[tuple[str, ...]] = ("ID", "name", "price", "quantity") def normalize_price(price: Decimal) -> Decimal: - """Round a price to the precision every stored record uses. + true_price = price.quantize(PRICE_STEP, rounding=ROUND_HALF_UP) - Args: - price: The raw price amount. - - Returns: - ``price`` quantised to :data:`PRICE_PRECISION` fractional digits, - with halves rounded up. - """ - # TODO: реализуйте функцию (используйте своё решение части 2) - return Decimal(0) + return true_price def normalize_product_name(name: str) -> str: - """Reduce a product name to the canonical form the store keeps. - - Args: - name: The raw product name. - - Returns: - ``name`` with every leading and trailing whitespace character - removed, every internal run of whitespace (spaces, tabs and the - like) collapsed to a single space, and the rest lower-cased. For - example ``"abc def\tghi\tjkl"`` becomes ``"abc def ghi jkl"``. - The result is an empty string when ``name`` holds nothing but - whitespace. - """ - # TODO: реализуйте функцию - return "" - + new_name = " ".join(name.split()).lower -# TODO: при необходимости добавьте свои вспомогательные функции + return new_name def get_storage_str_representation(storage: list[Product]) -> str: - """Render the product store as a text table with data-sized columns. - - The table has the columns named by :data:`TABLE_HEADERS` -- id, name, - price and quantity. Each column is made exactly as wide as the longest - value it carries in this call (its header counted), so the columns - line up when the string is printed to a terminal and no value is ever - truncated. - - Args: - storage: The product store to render. - - Returns: - A multi-line string: a header row, a dashed separator row, then - one row per product in ``storage`` in list order. When ``storage`` - is empty only the header and separator rows are returned, sized to - the header labels. - """ - # TODO: реализуйте функцию - return "" + mx_len_id = len(TABLE_HEADERS[0]) + 2 + mx_len_name = len(TABLE_HEADERS[1]) + 2 + mx_len_price = len(TABLE_HEADERS[2]) + 2 + mx_len_quantity = len(TABLE_HEADERS[3]) + 2 + for item in storage: + mx_len_id = max(mx_len_id, len(str(item[PRODUCT_ID_INDEX])) + 2) + mx_len_name = max(mx_len_name, len(item[NAME_INDEX]) + 2) + mx_len_price = max(mx_len_price, len(str(item[PRICE_INDEX])) + 2) + mx_len_quantity = max(mx_len_quantity, len(str(item[QUANTITY_INDEX])) + 2) + + s = ( + f"| {TABLE_HEADERS[0]}{' ' * (mx_len_id - 3)}| {TABLE_HEADERS[1]}{' ' * (mx_len_name - 5)}| {TABLE_HEADERS[2]}{' ' * (mx_len_price - 6)}| {TABLE_HEADERS[3]}{' ' * (mx_len_quantity - 9)}|\n" + f"|{'-' * mx_len_id}|{'-' * mx_len_name}|{'-' * mx_len_price}|{'-' * mx_len_quantity}|" + ) + + for item in storage: + s_new = ( + f"\n| {item[PRODUCT_ID_INDEX]}{' ' * (mx_len_id - len(str(item[PRODUCT_ID_INDEX])) - 1)}" + f"| {item[NAME_INDEX]}{' ' * (mx_len_name - len(str(item[NAME_INDEX])) - 1)}" + f"| {item[PRICE_INDEX]}{' ' * (mx_len_price - len(str(item[PRICE_INDEX])) - 1)}" + f"| {item[QUANTITY_INDEX]}{' ' * (mx_len_quantity - len(str(item[QUANTITY_INDEX])) - 1)}|" + ) + s += s_new + return s From 4554e9f7e3401bcb80ab95085cca5100dbc521b8 Mon Sep 17 00:00:00 2001 From: somet1me123 Date: Fri, 9 Oct 2026 16:11:04 +0300 Subject: [PATCH 12/12] Solved task 3 --- src/part3/crud.py | 90 ++++++++++++++++++++++-------------------- src/part3/run_admin.py | 10 ++--- src/part3/utils.py | 7 ++-- 3 files changed, 57 insertions(+), 50 deletions(-) diff --git a/src/part3/crud.py b/src/part3/crud.py index 226ae457..d3a42410 100644 --- a/src/part3/crud.py +++ b/src/part3/crud.py @@ -20,13 +20,13 @@ from decimal import Decimal -from .storage import ( # noqa: F401 +from .storage import ( NAME_INDEX, PRODUCT_ID_INDEX, PRODUCT_ID_MIN, Product, ) -from .utils import normalize_price, normalize_product_name # noqa: F401 +from .utils import normalize_price, normalize_product_name def generate_product_id(storage: list[Product]) -> int: @@ -41,14 +41,19 @@ def create_product( storage: list[Product], fields: tuple[str, Decimal, int] ) -> int | None: name, price, quantity = fields + new_name = normalize_product_name(name) + if not new_name: + print("product name must not be blank") + return None + for item in storage: - if name == item[NAME_INDEX]: - print(f"product name '{name}' is already taken") + if new_name == item[NAME_INDEX]: + print(f"product name '{new_name}' is already taken") return None new_id = generate_product_id(storage) new_price = normalize_price(price) - new_product = (new_id, name, new_price, quantity) + new_product = (new_id, new_name, new_price, quantity) storage.append(new_product) return new_id @@ -67,43 +72,44 @@ def update_product( product_id: int, fields: tuple[str, Decimal, int], ) -> Product | None: - """Overwrite the fields of the product stored under ``product_id``. - - The identifier itself is preserved; only ``name``, ``price`` and - ``quantity`` are replaced. - - Args: - storage: The product store to modify; the matching record is - replaced in place on success. - product_id: The identifier of the product to change. - fields: A ``(name, price, quantity)`` tuple with the new values. - ``price`` is a :class:`~decimal.Decimal` amount and is rounded - to the stored money precision before it is saved. - - Returns: - The updated ``(product_id, name, price, quantity)`` record, or - ``None`` when ``name`` is blank once normalised, no product - carries that identifier, or the normalised name is already taken - by another product. In every ``None`` case ``storage`` is left - unchanged and an explanatory message is printed. Renaming a - product to its own current name is allowed. - """ - # TODO: реализуйте функцию - return (0, "", Decimal(0), 0) + name, price, quantity = fields + new_name = normalize_product_name(name) + if not new_name: + print("product name must not be blank") + return None + + f = False + for i in range(len(storage)): + if product_id == storage[i][PRODUCT_ID_INDEX]: + f = True + break + if f == False: + print(f"no product with id {product_id}") + return None + + for i in range(len(storage)): + if ( + new_name == storage[i][NAME_INDEX] + and product_id != storage[i][PRODUCT_ID_INDEX] + ): + print(f"product name '{new_name}' is already taken") + return None + + for i in range(len(storage)): + if product_id == storage[i][PRODUCT_ID_INDEX]: + new_price = normalize_price(price) + new_item = (product_id, new_name, new_price, quantity) + storage[i] = new_item + return new_item + + return None def delete_product(storage: list[Product], product_id: int) -> int | None: - """Remove the product stored under ``product_id`` from ``storage``. - - Args: - storage: The product store to remove from; modified in place on - success. - product_id: The identifier of the product to remove. - - Returns: - ``product_id`` when a product was removed, or ``None`` when no - product carried that identifier (``storage`` is left unchanged and - a message is printed). - """ - # TODO: реализуйте функцию (используйте своё решение части 2) - return 0 + for item in storage: + if item[PRODUCT_ID_INDEX] == product_id: + storage.remove(item) + return product_id + + print(f"no product with id '{product_id}'") + return None diff --git a/src/part3/run_admin.py b/src/part3/run_admin.py index 260406fb..556e2d36 100644 --- a/src/part3/run_admin.py +++ b/src/part3/run_admin.py @@ -65,7 +65,7 @@ def show_help() -> None: def print_result(result: object) -> None: if result is not None: print(result) - return None + return def run_command(storage: list[Product], line: str) -> bool: @@ -75,14 +75,14 @@ def run_command(storage: list[Product], line: str) -> bool: return True case ["create", *name, price, quantity] if name: - name = " ".join(name) - fields_case = (name, Decimal(price), int(quantity)) + name_str = " ".join(name) + fields_case = (name_str, Decimal(price), int(quantity)) print_result(create_product(storage, fields_case)) return True case ["update", prod_id, *name, price, quantity] if name: - name = " ".join(name) - fields_case = (name, Decimal(price), int(quantity)) + name_str = " ".join(name) + fields_case = (name_str, Decimal(price), int(quantity)) print_result(update_product(storage, int(prod_id), fields_case)) return True diff --git a/src/part3/utils.py b/src/part3/utils.py index 27600002..e397a034 100644 --- a/src/part3/utils.py +++ b/src/part3/utils.py @@ -18,12 +18,13 @@ the longest value it holds in that particular call. """ -from decimal import ROUND_HALF_UP, Decimal # noqa: F401 +from decimal import ROUND_HALF_UP, Decimal from typing import Final + from .storage import ( - PRODUCT_ID_INDEX, NAME_INDEX, PRICE_INDEX, + PRODUCT_ID_INDEX, QUANTITY_INDEX, Product, ) @@ -43,7 +44,7 @@ def normalize_price(price: Decimal) -> Decimal: def normalize_product_name(name: str) -> str: - new_name = " ".join(name.split()).lower + new_name = " ".join(name.split()).lower() return new_name