From 3dab7478ccfe2561a9a1c07cc1dae39e3727dcb2 Mon Sep 17 00:00:00 2001 From: Alex Date: Fri, 25 Sep 2026 23:02:48 +0300 Subject: [PATCH 1/9] Solve task 1 --- src/part1/constants.py | 33 ++++++---------------- src/part1/snowflake.py | 64 +++++++++++++++++++----------------------- 2 files changed, 37 insertions(+), 60 deletions(-) diff --git a/src/part1/constants.py b/src/part1/constants.py index 9abfbba2..12e23773 100644 --- a/src/part1/constants.py +++ b/src/part1/constants.py @@ -1,38 +1,21 @@ -"""Bit layout and default epoch for the Twitter Snowflake ID generator. - -A Snowflake identifier is a 63-bit positive integer packed as follows, from -the most significant bit downwards: - - 1 bit unused sign bit, always zero - 41 bits milliseconds elapsed since a custom epoch - 10 bits node identifier - 12 bits per-millisecond sequence counter - -The shift and mask constants should be derived from the bit widths so that -changing a width keeps everything else consistent. -""" - from typing import Final -# TODO: замените заглушки (0) на корректные значения, см. TASK.md. -# Все константы, зависящие от ёмкостей *_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 # Здесь можно добавить собственные вспомогательные константы # (например, сдвиги полей при сборке идентификатора). diff --git a/src/part1/snowflake.py b/src/part1/snowflake.py index d3abf050..146293e2 100644 --- a/src/part1/snowflake.py +++ b/src/part1/snowflake.py @@ -13,13 +13,16 @@ :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_BITS, TIMESTAMP_MS_MAX, ) @@ -34,8 +37,7 @@ def read_current_millis(epoch_ms: int) -> int: The count of whole milliseconds between ``epoch_ms`` and now. May be negative if ``epoch_ms`` lies in the future. """ - # TODO: реализуйте функцию - return 0 + return int(time.time()) - epoch_ms def decode_timestamp_ms(snowflake_id: int, epoch_ms: int = EPOCH_MS_DEFAULT) -> int: @@ -50,8 +52,9 @@ def decode_timestamp_ms(snowflake_id: int, epoch_ms: int = EPOCH_MS_DEFAULT) -> The absolute Unix time in milliseconds at which the identifier was generated. """ - # TODO: реализуйте функцию - return 0 + del_time = (snowflake_id >> (NODE_ID_BITS + TIMESTAMP_BITS)) & TIMESTAMP_MS_MAX + + return epoch_ms + del_time def decode_node_id(snowflake_id: int) -> int: @@ -64,8 +67,8 @@ def decode_node_id(snowflake_id: int) -> int: The node identifier packed into ``snowflake_id``, in the range ``[0, NODE_ID_MAX]``. """ - # TODO: реализуйте функцию - return 0 + + return (snowflake_id >> SEQUENCE_ID_BITS) & NODE_ID_MAX def decode_sequence_id(snowflake_id: int) -> int: @@ -78,8 +81,7 @@ def decode_sequence_id(snowflake_id: int) -> int: The per-millisecond sequence counter packed into ``snowflake_id``, in the range ``[0, SEQUENCE_ID_MAX]``. """ - # TODO: реализуйте функцию - return 0 + return snowflake_id & SEQUENCE_ID_MAX def generate_snowflake_id( @@ -87,28 +89,20 @@ 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(f"node_id must be in [0, {NODE_ID_MAX}]. Your id {node_id}") + return None + elif not (0 <= sequence_id <= SEQUENCE_ID_MAX): + print(f"sequence_id must be in [0, {SEQUENCE_ID_MAX}] Your id {sequence_id}") + return None + + else: + if 0 <= epoch_ms <= TIMESTAMP_MS_MAX: + return ( + epoch_ms + << (SEQUENCE_ID_BITS + NODE_ID_BITS) + node_id + << SEQUENCE_ID_BITS + sequence_id + ) + else: + print("overflows") + return None From fa70f2926f0ae76d35dac97a7607cc001eafd083 Mon Sep 17 00:00:00 2001 From: Alex Date: Fri, 25 Sep 2026 23:39:13 +0300 Subject: [PATCH 2/9] Solve task 1 --- src/part1/snowflake.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/part1/snowflake.py b/src/part1/snowflake.py index 146293e2..00fb93f2 100644 --- a/src/part1/snowflake.py +++ b/src/part1/snowflake.py @@ -37,7 +37,7 @@ def read_current_millis(epoch_ms: int) -> int: The count of whole milliseconds between ``epoch_ms`` and now. May be negative if ``epoch_ms`` lies in the future. """ - return int(time.time()) - epoch_ms + return time.time_ns() // 10**6 - epoch_ms def decode_timestamp_ms(snowflake_id: int, epoch_ms: int = EPOCH_MS_DEFAULT) -> int: From c6267e7af88908c2ffa02c194c91b05dc7528259 Mon Sep 17 00:00:00 2001 From: Alex Date: Fri, 2 Oct 2026 22:44:31 +0300 Subject: [PATCH 3/9] Solve task 2 --- src/part2/cart.py | 65 ++++++++++++++++++++++++++++++++++++++------ src/part2/crud.py | 45 ++++++++++++++++++++++-------- src/part2/storage.py | 12 ++++---- src/part2/utils.py | 11 ++++---- 4 files changed, 101 insertions(+), 32 deletions(-) diff --git a/src/part2/cart.py b/src/part2/cart.py index 063f9aea..8a0c9684 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,9 @@ 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( @@ -53,8 +53,30 @@ def add_to_cart( 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) + search = read_product(storage, product_id) + if search == None: + return None + elif search[QUANTITY_INDEX] < quantity: + print( + f"not enough stock for product {product_id}: {search[NAME_INDEX]} available, {search[QUANTITY_INDEX]} requested" + ) + return None + + update_product( + storage, + product_id, + search[NAME_INDEX : PRICE_INDEX + 1] + (search[QUANTITY_INDEX] - quantity,), + ) + + cart_search = [el for el in cart if el[LINE_PRODUCT_ID_INDEX] == product_id] + if cart_search: + new_cart_line = (product_id, cart_search[0][LINE_QUANTITY_INDEX] + quantity) + cart.remove(cart_search) + cart.append(new_cart_line) + return new_cart_line + else: + cart.append((product_id, quantity)) + return (product_id, quantity) def remove_from_cart( @@ -85,5 +107,32 @@ def remove_from_cart( 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) + search = [el for el in cart if el[LINE_PRODUCT_ID_INDEX] == product_id] + search = search[0] + if not search: + print(f"product {product_id} is not in the cart") + return None + elif search[QUANTITY_INDEX] < quantity: + print( + f"cart holds only {search[QUANTITY_INDEX]} unit(s) of product {product_id}, cannot remove {quantity}" + ) + return None + + search_storage = read_product(storage, product_id) + if search_storage == None: + return None + + update_product( + storage, + product_id, + search_storage[NAME_INDEX : PRICE_INDEX + 1] + + (search_storage[QUANTITY_INDEX] + quantity,), + ) + + if quantity == search[LINE_QUANTITY_INDEX]: + cart.remove(search) + return (product_id, 0) + + new_line = (product_id, search[LINE_QUANTITY_INDEX] - quantity) + cart[cart.index(search)] = new_line + return new_line diff --git a/src/part2/crud.py b/src/part2/crud.py index d026cbcb..417d8823 100644 --- a/src/part2/crud.py +++ b/src/part2/crud.py @@ -14,13 +14,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 # noqa: F401 +from .utils import normalize_price def generate_product_id(storage: list[Product]) -> int: @@ -34,8 +34,12 @@ def generate_product_id(storage: list[Product]) -> int: :data:`~src.part2.storage.PRODUCT_ID_MIN` when ``storage`` is empty. """ - # TODO: реализуйте функцию - return 0 + if storage: + id: int = max(tuple(el[PRODUCT_ID_INDEX] for el in storage)) + 1 + else: + id = PRODUCT_ID_MIN + + return id def create_product( @@ -56,8 +60,12 @@ def create_product( ``storage`` is left unchanged and a message naming the clashing name is printed. """ - # TODO: реализуйте функцию - return 0 + if fields[NAME_INDEX - 1] in tuple(el[NAME_INDEX] for el in storage): + print(f"product name {fields[0]} is already taken") + return None + id = generate_product_id(storage) + storage.append((id, fields[0], normalize_price(fields[1]), fields[2])) + return id def read_product(storage: list[Product], product_id: int) -> Product | None: @@ -72,8 +80,11 @@ def read_product(storage: list[Product], product_id: int) -> Product | None: ``None`` when no product carries that identifier (a message is printed in that case). """ - # TODO: реализуйте функцию - return (0, "", Decimal(0), 0) + if product_id not in tuple(el[PRODUCT_ID_INDEX] for el in storage): + print(f"no product with id {product_id}") + return None + + return next(filter(lambda x: x[PRODUCT_ID_INDEX], storage)) def update_product( @@ -99,8 +110,14 @@ def update_product( ``None`` when no product carries that identifier (``storage`` is left unchanged and a message is printed). """ - # TODO: реализуйте функцию - return (0, "", Decimal(0), 0) + search = read_product(storage, product_id) + if not filter(lambda x: x[PRODUCT_ID_INDEX] == product_id, storage): + print(f"no product with id {product_id}") + return None + + storage[storage.index(search)] = product_id, +fields + + return next(filter(lambda x: x[PRODUCT_ID_INDEX] == product_id, storage)) def delete_product(storage: list[Product], product_id: int) -> int | None: @@ -116,5 +133,9 @@ def delete_product(storage: list[Product], product_id: int) -> int | None: product carried that identifier (``storage`` is left unchanged and a message is printed). """ - # TODO: реализуйте функцию - return 0 + if not filter(lambda x: x[PRODUCT_ID_INDEX] == product_id, storage): + print(f"no product with id {product_id}") + return None + + storage.remove(next(filter(lambda x: x[PRODUCT_ID_INDEX] == product_id, storage))) + return product_id diff --git a/src/part2/storage.py b/src/part2/storage.py index b63d5fc7..74ca50e5 100644 --- a/src/part2/storage.py +++ b/src/part2/storage.py @@ -24,11 +24,11 @@ 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 diff --git a/src/part2/utils.py b/src/part2/utils.py index ec0348d3..fa159f32 100644 --- a/src/part2/utils.py +++ b/src/part2/utils.py @@ -6,13 +6,12 @@ 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: @@ -25,5 +24,5 @@ def normalize_price(price: Decimal) -> Decimal: ``price`` quantised to :data:`PRICE_PRECISION` fractional digits, with halves rounded up. """ - # TODO: реализуйте функцию - return Decimal(0) + + return price.quantize(PRICE_STEP, rounding=ROUND_HALF_UP) From 3ff22df0849d70cefb8b4e08f784b5fb0b73ca1d Mon Sep 17 00:00:00 2001 From: Alex Date: Fri, 2 Oct 2026 23:36:21 +0300 Subject: [PATCH 4/9] Solve task 2 --- src/part2/cart.py | 9 +++++---- src/part2/crud.py | 2 +- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/src/part2/cart.py b/src/part2/cart.py index 8a0c9684..1ff78746 100644 --- a/src/part2/cart.py +++ b/src/part2/cart.py @@ -65,10 +65,11 @@ def add_to_cart( update_product( storage, product_id, - search[NAME_INDEX : PRICE_INDEX + 1] + (search[QUANTITY_INDEX] - quantity,), + (search[NAME_INDEX], search[PRICE_INDEX], search[QUANTITY_INDEX] - quantity), ) - cart_search = [el for el in cart if el[LINE_PRODUCT_ID_INDEX] == product_id] + cart_search_l = [el for el in cart if el[LINE_PRODUCT_ID_INDEX] == product_id] + cart_search = cart_search_l[0] if cart_search: new_cart_line = (product_id, cart_search[0][LINE_QUANTITY_INDEX] + quantity) cart.remove(cart_search) @@ -107,8 +108,8 @@ def remove_from_cart( zero means the line was dropped), or ``None`` when the cart has no line for the product or holds too few units. """ - search = [el for el in cart if el[LINE_PRODUCT_ID_INDEX] == product_id] - search = search[0] + search_l = [el for el in cart if el[LINE_PRODUCT_ID_INDEX] == product_id] + search = search_l[0] if not search: print(f"product {product_id} is not in the cart") return None diff --git a/src/part2/crud.py b/src/part2/crud.py index 417d8823..27231843 100644 --- a/src/part2/crud.py +++ b/src/part2/crud.py @@ -115,7 +115,7 @@ def update_product( print(f"no product with id {product_id}") return None - storage[storage.index(search)] = product_id, +fields + storage[storage.index(search)] = (product_id,) + fields return next(filter(lambda x: x[PRODUCT_ID_INDEX] == product_id, storage)) From 52e4325ee359cdbb6df111630d23cc99a5c3cbf4 Mon Sep 17 00:00:00 2001 From: Alex Date: Fri, 2 Oct 2026 23:42:24 +0300 Subject: [PATCH 5/9] Solve task 2 --- src/part2/cart.py | 14 ++++++++------ src/part2/crud.py | 2 +- 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/src/part2/cart.py b/src/part2/cart.py index 1ff78746..9e05dc33 100644 --- a/src/part2/cart.py +++ b/src/part2/cart.py @@ -19,7 +19,6 @@ Product, ) - type CartLine = tuple[int, int] @@ -71,7 +70,7 @@ def add_to_cart( cart_search_l = [el for el in cart if el[LINE_PRODUCT_ID_INDEX] == product_id] cart_search = cart_search_l[0] if cart_search: - new_cart_line = (product_id, cart_search[0][LINE_QUANTITY_INDEX] + quantity) + new_cart_line = (product_id, cart_search[LINE_QUANTITY_INDEX] + quantity) cart.remove(cart_search) cart.append(new_cart_line) return new_cart_line @@ -113,9 +112,9 @@ def remove_from_cart( if not search: print(f"product {product_id} is not in the cart") return None - elif search[QUANTITY_INDEX] < quantity: + elif search[LINE_QUANTITY_INDEX] < quantity: print( - f"cart holds only {search[QUANTITY_INDEX]} unit(s) of product {product_id}, cannot remove {quantity}" + f"cart holds only {search[LINE_QUANTITY_INDEX]} unit(s) of product {product_id}, cannot remove {quantity}" ) return None @@ -126,8 +125,11 @@ def remove_from_cart( update_product( storage, product_id, - search_storage[NAME_INDEX : PRICE_INDEX + 1] - + (search_storage[QUANTITY_INDEX] + quantity,), + ( + search_storage[NAME_INDEX], + search_storage[PRICE_INDEX], + (search_storage[QUANTITY_INDEX] + quantity), + ), ) if quantity == search[LINE_QUANTITY_INDEX]: diff --git a/src/part2/crud.py b/src/part2/crud.py index 27231843..3bc815d1 100644 --- a/src/part2/crud.py +++ b/src/part2/crud.py @@ -111,7 +111,7 @@ def update_product( left unchanged and a message is printed). """ search = read_product(storage, product_id) - if not filter(lambda x: x[PRODUCT_ID_INDEX] == product_id, storage): + if search == None: print(f"no product with id {product_id}") return None From 4d08fda344b3f9b0ce34767c721d32041238c561 Mon Sep 17 00:00:00 2001 From: Alex Date: Fri, 2 Oct 2026 23:43:36 +0300 Subject: [PATCH 6/9] Solve task 2 --- src/part2/cart.py | 1 + 1 file changed, 1 insertion(+) diff --git a/src/part2/cart.py b/src/part2/cart.py index 9e05dc33..a0e50b62 100644 --- a/src/part2/cart.py +++ b/src/part2/cart.py @@ -19,6 +19,7 @@ Product, ) + type CartLine = tuple[int, int] From f9af63c62e12cf9735f5884330b287d57e2c136d Mon Sep 17 00:00:00 2001 From: Alex Date: Mon, 12 Oct 2026 20:23:55 +0300 Subject: [PATCH 7/9] Solve task 3 --- .vscode/settings.json | 4 ++ src/part3/crud.py | 97 +++++++++++++++++++++++++++--------------- src/part3/run_admin.py | 74 +++++++++++++++++++++++++++----- src/part3/storage.py | 17 ++++---- src/part3/utils.py | 80 ++++++++++++++++++++++++---------- 5 files changed, 195 insertions(+), 77 deletions(-) create mode 100644 .vscode/settings.json diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 00000000..4b5a2944 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,4 @@ +{ + "python-envs.defaultEnvManager": "ms-python.python:conda", + "python-envs.defaultPackageManager": "ms-python.python:conda" +} \ No newline at end of file diff --git a/src/part3/crud.py b/src/part3/crud.py index 68811d7e..b7a04fe5 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: @@ -37,11 +37,15 @@ def generate_product_id(storage: list[Product]) -> int: Returns: One past the greatest identifier currently held in ``storage``, or - :data:`~src.part3.storage.PRODUCT_ID_MIN` when ``storage`` is + :data:`~src.part2.storage.PRODUCT_ID_MIN` when ``storage`` is empty. """ - # TODO: реализуйте функцию (используйте своё решение части 2) - return 0 + if storage: + id: int = max(tuple(el[PRODUCT_ID_INDEX] for el in storage)) + 1 + else: + id = PRODUCT_ID_MIN + + return id def create_product( @@ -53,35 +57,43 @@ def create_product( 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. + ``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 - ``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. + 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 + if not (name := normalize_product_name(fields[0])): + print("product name must not be blank") + return None + elif name in tuple(el[NAME_INDEX] for el in storage): + print(f"product name {name} is already taken") + return None + id = generate_product_id(storage) + storage.append((id, name, normalize_price(fields[1]), fields[2])) + return 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. - - Returns: - The matching ``(product_id, name, price, quantity)`` record, or - ``None`` when no product carries that identifier (a message is - printed in that case). + exit + Args: + storage: The product store to search. + product_id: The identifier to look up. + + 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) + if product_id not in tuple(el[PRODUCT_ID_INDEX] for el in storage): + print(f"no product with id {product_id}") + return None + + return next(filter(lambda x: x[PRODUCT_ID_INDEX] == product_id, storage)) def update_product( @@ -104,14 +116,25 @@ def update_product( 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. + ``None`` when no product carries that identifier (``storage`` is + left unchanged and a message is printed). """ - # TODO: реализуйте функцию - return (0, "", Decimal(0), 0) + if not (name := normalize_product_name(fields[0])): + print("product name must not be blank") + + search = read_product(storage, product_id) + if search == None: + print(f"no product with id {product_id}") + return None + + name_search = next(filter(lambda x: x[NAME_INDEX], storage)) + if name in name_search and product_id not in name_search: + print(f"product name {name} is already taken") + return None + + storage[storage.index(search)] = (product_id,) + (name,) + fields[1:] + + return read_product(storage, product_id) def delete_product(storage: list[Product], product_id: int) -> int | None: @@ -127,5 +150,9 @@ def delete_product(storage: list[Product], product_id: int) -> int | None: product carried that identifier (``storage`` is left unchanged and a message is printed). """ - # TODO: реализуйте функцию (используйте своё решение части 2) - return 0 + if not filter(lambda x: x[PRODUCT_ID_INDEX] == product_id, storage): + print(f"no product with id {product_id}") + return None + + storage.remove(next(filter(lambda x: x[PRODUCT_ID_INDEX] == product_id, storage))) + return product_id diff --git a/src/part3/run_admin.py b/src/part3/run_admin.py index c5feeb0b..41261a7c 100644 --- a/src/part3/run_admin.py +++ b/src/part3/run_admin.py @@ -29,22 +29,34 @@ 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: @@ -54,7 +66,7 @@ def show_help() -> None: is: a heading, one line per command with a short description, and a note on how multi-word names are parsed. """ - # TODO: реализуйте функцию + print(HELP_TEXT) def print_result(result: object) -> None: @@ -65,7 +77,7 @@ def print_result(result: object) -> None: operation already reported its own failure, so nothing is printed in that case. """ - # TODO: реализуйте функцию + print(result) if result else "" def run_command(storage: list[Product], line: str) -> bool: @@ -88,8 +100,44 @@ def run_command(storage: list[Product], line: str) -> bool: decimal.InvalidOperation: If the price argument of ``create`` or ``update`` does not parse as a decimal number. """ - # TODO: реализуйте функцию - return False + match line.split(): + case ["help"]: + show_help() + + case ["exit"]: + return False + + case ["show"]: + print_result(get_storage_str_representation(storage)) + + case ["create", *name, price, quantity]: + if not name: + print_result(f"{line} is not a command") + return True + print_result( + create_product(storage, (" ".join(name), Decimal(price), int(quantity))) + ) + + case ["read", id]: + print_result(read_product(storage, int(id))) + + case ["update", id, *name, price, quantity]: + if not name: + print_result(f"{line} is not a command") + return True + print_result( + update_product( + storage, int(id), (" ".join(name), Decimal(price), int(quantity)) + ) + ) + + case ["delete", id]: + print_result(delete_product(storage, int(id))) + + case _: + print_result(f"{line} is not a command") + + return True def main() -> None: @@ -102,7 +150,11 @@ def main() -> None: not parse is caught here and reported without stopping the loop; only ``exit`` ends it. """ - storage: list[Product] = [] + # storage: list[Product] = [] + storage: list[Product] = [ + (1, "cordless drill", Decimal("90.00"), 12), + (2, "claw hammer", Decimal("9.90"), 40), + ] running = True while running: diff --git a/src/part3/storage.py b/src/part3/storage.py index c5e34be5..74ca50e5 100644 --- a/src/part3/storage.py +++ b/src/part3/storage.py @@ -6,11 +6,11 @@ where: * ``product_id`` -- unique positive integer key, assigned by the create - operation in :mod:`src.part3.crud`; + operation in :mod:`src.part2.crud`; * ``name`` -- human-readable product name, unique across the store; * ``price`` -- price of a single unit, held as a :class:`~decimal.Decimal` amount rounded to a fixed number of decimal places (see - :func:`src.part3.utils.normalize_price`) so that money is never + :func:`src.part2.utils.normalize_price`) so that money is never subject to binary floating-point error; * ``quantity`` -- number of units currently in stock. @@ -24,12 +24,11 @@ type Product = tuple[int, str, Decimal, int] -# 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..880356fc 100644 --- a/src/part3/utils.py +++ b/src/part3/utils.py @@ -18,24 +18,22 @@ 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 +from .storage import ( + NAME_INDEX, + PRICE_INDEX, + PRODUCT_ID_INDEX, + QUANTITY_INDEX, + Product, +) -# 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) +PRICE_PRECISION: Final[int] = 2 +PRICE_STEP: Final = Decimal(1).scaleb(-PRICE_PRECISION) -# 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: @@ -48,8 +46,8 @@ def normalize_price(price: Decimal) -> Decimal: ``price`` quantised to :data:`PRICE_PRECISION` fractional digits, with halves rounded up. """ - # TODO: реализуйте функцию (используйте своё решение части 2) - return Decimal(0) + + return price.quantize(PRICE_STEP, rounding=ROUND_HALF_UP) def normalize_product_name(name: str) -> str: @@ -66,11 +64,7 @@ def normalize_product_name(name: str) -> str: The result is an empty string when ``name`` holds nothing but whitespace. """ - # TODO: реализуйте функцию - return "" - - -# TODO: при необходимости добавьте свои вспомогательные функции + return "".join([elem.lower() for elem in name.split()]) def get_storage_str_representation(storage: list[Product]) -> str: @@ -91,5 +85,47 @@ def get_storage_str_representation(storage: list[Product]) -> str: is empty only the header and separator rows are returned, sized to the header labels. """ - # TODO: реализуйте функцию - return "" + table_len_columns = ( + max( + max(len(str(elem[PRODUCT_ID_INDEX])) for elem in storage), + len(TABLE_HEADERS[PRODUCT_ID_INDEX]), + ), + max( + max(len(elem[NAME_INDEX]) for elem in storage), + len(TABLE_HEADERS[NAME_INDEX]), + ), + max( + max(len(str(elem[PRICE_INDEX])) for elem in storage), + len(TABLE_HEADERS[PRICE_INDEX]), + ), + max( + max(len(str(elem[QUANTITY_INDEX])) for elem in storage), + len(TABLE_HEADERS[QUANTITY_INDEX]), + ), + ) + + first_string = make_string(TABLE_HEADERS, table_len_columns) + + second_string = ( + "|" + "|".join("-" * (length + 2) for length in table_len_columns) + "|" + ) + + product_strings = "\n".join( + make_string(string, table_len_columns) for string in storage + ) + + return first_string + "\n" + second_string + "\n" + product_strings + + +def make_string( + string: tuple[str, ...] | Product, + table_len_columns: tuple[int, ...], +) -> str: + return ( + "|" + + "|".join( + str(el).ljust(length + 1).rjust(length + 2) + for el, length in zip(string, table_len_columns) + ) + + "|" + ) From 7c2e5dffc63c5ed6de57a256835be088d13453d7 Mon Sep 17 00:00:00 2001 From: Alex Date: Sun, 1 Nov 2026 16:05:29 +0300 Subject: [PATCH 8/9] Solve task 4 --- fix_and_test.sh | 22 ++ pyproject.toml | 11 + src/part3/tests/test_part3.py | 624 ++++++++++++++++++++++++++++++++++ src/part4/cart.py | 62 +++- src/part4/crud.py | 71 +++- src/part4/run_admin.py | 101 +++++- src/part4/storage.py | 8 +- src/part4/utils.py | 82 +++-- uv.lock | 65 +++- 9 files changed, 981 insertions(+), 65 deletions(-) create mode 100644 fix_and_test.sh create mode 100644 src/part3/tests/test_part3.py diff --git a/fix_and_test.sh b/fix_and_test.sh new file mode 100644 index 00000000..2cdc7b2b --- /dev/null +++ b/fix_and_test.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash +# Auto-fix imports/format, then run tests. +set -euo pipefail + +cd "$(dirname "$0")" + +if ! command -v uv >/dev/null 2>&1; then + echo "Error: uv is not installed. Install it: https://docs.astral.sh/uv/getting-started/installation/" >&2 + exit 1 +fi + +echo "==> Install dependencies" +uv sync --locked + +echo "==> Ruff fix (imports, lint)" +uv run ruff check --fix src +uv run ruff format src + +# echo "==> Pytest" +# uv run pytest src/part3/tests + +echo "All done." \ No newline at end of file diff --git a/pyproject.toml b/pyproject.toml index 06fbe913..f2a7c2d4 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -10,6 +10,7 @@ dependencies = [] dev = [ "mypy==2.3.1", "ruff==0.16.8", + "pytest>=9.1.1", ] [tool.ruff] @@ -33,3 +34,13 @@ avoid-escape = true [tool.ruff.lint.isort] lines-after-imports = 2 split-on-trailing-comma = true + +[tool.mypy] +strict = true +files = ["src"] +mypy_path = "src" +explicit_package_bases = true + +[tool.pytest.ini_options] +pythonpath = ["src"] +testpaths = ["src/tests"] \ No newline at end of file diff --git a/src/part3/tests/test_part3.py b/src/part3/tests/test_part3.py new file mode 100644 index 00000000..96956fec --- /dev/null +++ b/src/part3/tests/test_part3.py @@ -0,0 +1,624 @@ +from __future__ import annotations + +from decimal import Decimal, InvalidOperation +from typing import Any, cast + +import pytest + +from part3.crud import create_product, delete_product, read_product, update_product +from part3.run_admin import ( + HELP_TEXT, + PROMPT, + main, + print_result, + run_command, + show_help, +) +from part3.storage import ( + NAME_INDEX, + PRICE_INDEX, + PRODUCT_ID_INDEX, + PRODUCT_ID_MIN, + QUANTITY_INDEX, + Product, +) +from part3.utils import ( + TABLE_HEADERS, + get_storage_str_representation, + normalize_price, + normalize_product_name, +) + + +# ============================================================ +# Helpers +# ============================================================ + + +def product( + product_id: int, + name: str, + price: str = "10.00", + quantity: int = 10, +) -> Product: + """Build a Product using the public index constants, not fixed positions.""" + fields: list[Any] = [None] * 4 + fields[PRODUCT_ID_INDEX] = product_id + fields[NAME_INDEX] = name + fields[PRICE_INDEX] = normalize_price(Decimal(price)) + fields[QUANTITY_INDEX] = quantity + return cast(Product, tuple(fields)) + + +def product_id(record: Product) -> int: + return record[PRODUCT_ID_INDEX] + + +def product_name(record: Product) -> str: + return record[NAME_INDEX] + + +def product_price(record: Product) -> Decimal: + return record[PRICE_INDEX] + + +def product_quantity(record: Product) -> int: + return record[QUANTITY_INDEX] + + +EXPECTED_HELP_TEXT = """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.""" + + +# ============================================================ +# utils — TABLE_HEADERS and normalize_product_name +# ============================================================ + + +class TestTableHeaders: + def test_table_headers_have_the_required_order(self) -> None: + assert TABLE_HEADERS == ("ID", "name", "price", "quantity") + + +class TestNormalizeProductName: + @pytest.mark.parametrize( + ("raw", "expected"), + [ + (" Cordless Drill ", "cordless drill"), + ("abc def\tghi\tjkl", "abc def ghi jkl"), + (" \t\n ", ""), + ("claw hammer", "claw hammer"), + (" RUBBER\t\tMALLET ", "rubber mallet"), + ("one\ntwo\r\nthree", "one two three"), + ("\v A\fB ", "a b"), + ("123 ABC", "123 abc"), + ("", ""), + ], + ) + def test_normalizes_name(self, raw: str, expected: str) -> None: + assert normalize_product_name(raw) == expected + + def test_normalization_is_idempotent(self) -> None: + normalized = normalize_product_name(" Cordless\t DRILL \n") + assert normalize_product_name(normalized) == normalized + + +# ============================================================ +# utils — get_storage_str_representation +# ============================================================ + + +class TestGetStorageStringRepresentation: + def test_empty_storage_has_only_header_and_separator(self) -> None: + assert get_storage_str_representation([]) == ( + "| ID | name | price | quantity |\n|----|------|-------|----------|" + ) + + def test_simple_storage_matches_exact_table(self) -> None: + storage = [ + product(1, "saw", "9.90", 5), + product(2, "axe", "12.00", 8), + ] + + assert get_storage_str_representation(storage) == ( + "| ID | name | price | quantity |\n" + "|----|------|-------|----------|\n" + "| 1 | saw | 9.90 | 5 |\n" + "| 2 | axe | 12.00 | 8 |" + ) + + def test_column_widths_expand_to_fit_values(self) -> None: + storage = [ + product(10, "compressor", "1299.99", 3), + product(2, "nail", "2.50", 500), + ] + + assert get_storage_str_representation(storage) == ( + "| ID | name | price | quantity |\n" + "|----|------------|---------|----------|\n" + "| 10 | compressor | 1299.99 | 3 |\n" + "| 2 | nail | 2.50 | 500 |" + ) + + def test_table_preserves_storage_order(self) -> None: + storage = [ + product(8, "last alphabetically", "1.00", 1), + product(2, "first alphabetically", "2.00", 2), + ] + + table = get_storage_str_representation(storage) + assert table.index("last alphabetically") < table.index("first alphabetically") + + def test_all_rows_have_the_same_width_and_aligned_separators(self) -> None: + storage = [ + product(100, "a much longer product name", "123456.78", 1000), + product(2, "x", "0.01", 1), + product(30, "medium name", "10.00", 99999), + ] + lines = get_storage_str_representation(storage).split("\n") + + assert len({len(line) for line in lines}) == 1 + bar_positions = [ + [i for i, char in enumerate(line) if char == "|"] for line in lines + ] + assert all(positions == bar_positions[0] for positions in bar_positions) + + def test_table_has_no_trailing_newline(self) -> None: + table = get_storage_str_representation([product(1, "saw")]) + assert not table.endswith("\n") + + def test_data_values_are_not_reordered_or_truncated(self) -> None: + storage = [product(17, "A very long name", "12345.67", 123456)] + table = get_storage_str_representation(storage) + + assert "A very long name" in table + assert "12345.67" in table + assert "123456" in table + assert table.index("17") < table.index("A very long name") + + +# ============================================================ +# crud — create_product with normalized names +# ============================================================ + + +class TestCreateProductPart3: + def test_success_normalizes_name_and_price(self) -> None: + storage: list[Product] = [] + + created_id = create_product( + storage, + (" Cordless Drill ", Decimal("89.999"), 12), + ) + + assert created_id == PRODUCT_ID_MIN + assert len(storage) == 1 + saved = storage[0] + assert product_id(saved) == created_id + assert product_name(saved) == "cordless drill" + assert product_price(saved) == Decimal("90.00") + assert product_quantity(saved) == 12 + + def test_successive_products_receive_successive_ids(self) -> None: + storage: list[Product] = [] + first_id = create_product(storage, ("Cordless Drill", Decimal(10), 1)) + second_id = create_product(storage, ("Claw Hammer", Decimal(20), 2)) + + assert first_id == PRODUCT_ID_MIN + assert second_id == PRODUCT_ID_MIN + 1 + assert [product_id(item) for item in storage] == [first_id, second_id] + + def test_duplicate_after_normalization_is_rejected_without_mutation( + self, capsys: pytest.CaptureFixture[str] + ) -> None: + storage = [product(1, "cordless drill", "50.00", 3)] + before = list(storage) + + result = create_product( + storage, + (" CORDLESS DRILL ", Decimal(75), 1), + ) + + assert result is None + assert storage == before + assert ( + capsys.readouterr().out + == "product name 'cordless drill' is already taken\n" + ) + + @pytest.mark.parametrize("blank_name", ["", " ", "\t \n"]) + def test_blank_name_is_rejected_without_mutation( + self, blank_name: str, capsys: pytest.CaptureFixture[str] + ) -> None: + storage = [product(1, "hammer")] + before = list(storage) + + result = create_product(storage, (blank_name, Decimal(10), 3)) + + assert result is None + assert storage == before + assert capsys.readouterr().out == "product name must not be blank\n" + + def test_successfully_created_product_can_be_read(self) -> None: + storage: list[Product] = [] + created_id = create_product( + storage, (" RUBBER MALLET ", Decimal("7.505"), 25) + ) + + assert created_id is not None + saved = read_product(storage, created_id) + assert saved is not None + assert product_name(saved) == "rubber mallet" + assert product_price(saved) == Decimal("7.51") + assert product_quantity(saved) == 25 + + +# ============================================================ +# crud — update_product with normalized names +# ============================================================ + + +class TestUpdateProductPart3: + def test_success_normalizes_name_and_price_and_keeps_id(self) -> None: + storage = [ + product(1, "cordless drill", "90.00", 12), + product(2, "claw hammer", "9.90", 40), + ] + + updated = update_product( + storage, + 2, + (" Rubber Mallet ", Decimal("7.505"), 25), + ) + + assert updated is not None + assert product_id(updated) == 2 + assert product_name(updated) == "rubber mallet" + assert product_price(updated) == Decimal("7.51") + assert product_quantity(updated) == 25 + assert storage == [product(1, "cordless drill", "90.00", 12), updated] + + def test_update_to_same_name_in_different_form_is_allowed(self) -> None: + storage = [product(1, "cordless drill", "90.00", 12)] + + updated = update_product( + storage, + 1, + (" CORDLESS Drill ", Decimal(85), 10), + ) + + assert updated is not None + assert product_id(updated) == 1 + assert product_name(updated) == "cordless drill" + assert product_price(updated) == Decimal("85.00") + assert product_quantity(updated) == 10 + assert storage == [updated] + + def test_duplicate_name_owned_by_another_product_is_rejected( + self, capsys: pytest.CaptureFixture[str] + ) -> None: + storage = [ + product(1, "cordless drill", "90.00", 12), + product(2, "claw hammer", "9.90", 40), + ] + before = list(storage) + + result = update_product( + storage, + 1, + (" CLAW HAMMER ", Decimal(85), 10), + ) + + assert result is None + assert storage == before + assert ( + capsys.readouterr().out == "product name 'claw hammer' is already taken\n" + ) + + @pytest.mark.parametrize("blank_name", ["", " ", "\t\n"]) + def test_blank_name_is_rejected_without_mutation( + self, blank_name: str, capsys: pytest.CaptureFixture[str] + ) -> None: + storage = [product(1, "cordless drill", "90.00", 12)] + before = list(storage) + + result = update_product(storage, 1, (blank_name, Decimal(85), 10)) + + assert result is None + assert storage == before + assert capsys.readouterr().out == "product name must not be blank\n" + + def test_blank_name_is_checked_before_missing_product_id( + self, capsys: pytest.CaptureFixture[str] + ) -> None: + storage = [product(1, "cordless drill")] + + result = update_product(storage, 99, (" ", Decimal(20), 5)) + + assert result is None + assert capsys.readouterr().out == "product name must not be blank\n" + assert storage == [product(1, "cordless drill")] + + def test_missing_product_id_does_not_change_storage( + self, capsys: pytest.CaptureFixture[str] + ) -> None: + storage = [product(1, "cordless drill", "90.00", 12)] + before = list(storage) + + result = update_product(storage, 99, ("saw", Decimal(20), 5)) + + assert result is None + assert storage == before + assert capsys.readouterr().out == "no product with id 99\n" + + def test_normalized_name_can_be_reused_after_old_product_is_deleted( + self, capsys: pytest.CaptureFixture[str] + ) -> None: + storage = [ + product(PRODUCT_ID_MIN, "cordless drill"), + product(PRODUCT_ID_MIN + 1, "claw hammer"), + product(PRODUCT_ID_MIN + 2, "saw"), + ] + assert delete_product(storage, PRODUCT_ID_MIN + 1) == PRODUCT_ID_MIN + 1 + capsys.readouterr() + + created_id = create_product(storage, (" CLAW HAMMER ", Decimal(11), 3)) + + assert created_id == PRODUCT_ID_MIN + 3 + assert product_name(storage[-1]) == "claw hammer" + + +# ============================================================ +# run_admin — show_help and print_result +# ============================================================ + + +class TestAdminOutputHelpers: + def test_help_text_matches_the_task(self) -> None: + assert HELP_TEXT == EXPECTED_HELP_TEXT + + def test_show_help_prints_the_help_text( + self, capsys: pytest.CaptureFixture[str] + ) -> None: + show_help() + assert capsys.readouterr().out == EXPECTED_HELP_TEXT + "\n" + + @pytest.mark.parametrize("result", [1, "created", (1, "hammer")]) + def test_print_result_prints_non_none_values( + self, result: object, capsys: pytest.CaptureFixture[str] + ) -> None: + print_result(result) + assert capsys.readouterr().out == f"{result}\n" + + def test_print_result_does_not_print_none( + self, capsys: pytest.CaptureFixture[str] + ) -> None: + print_result(None) + assert capsys.readouterr().out == "" + + +# ============================================================ +# run_admin — run_command +# ============================================================ + + +class TestRunCommand: + def test_help_prints_exact_help_text_and_continues( + self, capsys: pytest.CaptureFixture[str] + ) -> None: + assert run_command([], "help") is True + assert capsys.readouterr().out == EXPECTED_HELP_TEXT + "\n" + + def test_exit_returns_false_without_output( + self, capsys: pytest.CaptureFixture[str] + ) -> None: + assert run_command([], "exit") is False + assert capsys.readouterr().out == "" + + def test_show_prints_empty_storage_table( + self, capsys: pytest.CaptureFixture[str] + ) -> None: + assert run_command([], "show") is True + assert capsys.readouterr().out == ( + "| ID | name | price | quantity |\n|----|------|-------|----------|\n" + ) + + def test_create_parses_multiword_name_and_prints_id( + self, capsys: pytest.CaptureFixture[str] + ) -> None: + storage: list[Product] = [] + + assert run_command(storage, "create Cordless Drill 89.999 12") is True + + assert capsys.readouterr().out == f"{PRODUCT_ID_MIN}\n" + assert len(storage) == 1 + assert product_id(storage[0]) == PRODUCT_ID_MIN + assert product_name(storage[0]) == "cordless drill" + assert product_price(storage[0]) == Decimal("90.00") + assert product_quantity(storage[0]) == 12 + + def test_create_duplicate_does_not_print_none( + self, capsys: pytest.CaptureFixture[str] + ) -> None: + storage = [product(1, "cordless drill")] + + assert run_command(storage, "create CORDLESS DRILL 20 4") is True + + assert ( + capsys.readouterr().out + == "product name 'cordless drill' is already taken\n" + ) + assert storage == [product(1, "cordless drill")] + + def test_read_prints_the_product(self, capsys: pytest.CaptureFixture[str]) -> None: + storage = [product(7, "hammer", "9.90", 3)] + + assert run_command(storage, "read 7") is True + + assert capsys.readouterr().out == "(7, 'hammer', Decimal('9.90'), 3)\n" + + def test_read_missing_product_prints_only_error( + self, capsys: pytest.CaptureFixture[str] + ) -> None: + storage = [product(7, "hammer")] + + assert run_command(storage, "read 99") is True + + assert capsys.readouterr().out == "no product with id 99\n" + + def test_update_parses_multiword_name_and_prints_updated_product( + self, capsys: pytest.CaptureFixture[str] + ) -> None: + storage = [product(1, "cordless drill", "90.00", 12)] + + assert run_command(storage, "update 1 Rubber Mallet 7.505 25") is True + + assert capsys.readouterr().out == "(1, 'rubber mallet', Decimal('7.51'), 25)\n" + assert storage == [product(1, "rubber mallet", "7.51", 25)] + + def test_update_duplicate_name_does_not_change_storage( + self, capsys: pytest.CaptureFixture[str] + ) -> None: + storage = [product(1, "cordless drill"), product(2, "claw hammer")] + before = list(storage) + + assert run_command(storage, "update 1 Claw Hammer 20 5") is True + + assert ( + capsys.readouterr().out == "product name 'claw hammer' is already taken\n" + ) + assert storage == before + + def test_delete_removes_product_and_prints_id( + self, capsys: pytest.CaptureFixture[str] + ) -> None: + storage = [product(1, "hammer"), product(2, "saw")] + + assert run_command(storage, "delete 1") is True + + assert capsys.readouterr().out == "1\n" + assert storage == [product(2, "saw")] + + @pytest.mark.parametrize( + "line", + [ + "frobnicate", + "read 1 2 3", + "delete", + "show extra", + "help now", + "exit now", + "create 89.90 12", + "update 1 89.90 12", + "", + ], + ) + def test_unknown_command_or_wrong_argument_count_is_rejected( + self, + line: str, + capsys: pytest.CaptureFixture[str], + ) -> None: + storage = [product(1, "hammer")] + before = list(storage) + + assert run_command(storage, line) is True + + assert capsys.readouterr().out == f"'{line}' is not a command\n" + assert storage == before + + def test_invalid_integer_argument_propagates_value_error(self) -> None: + with pytest.raises(ValueError): + run_command([], "read not-an-id") + + def test_invalid_decimal_argument_propagates_invalid_operation(self) -> None: + with pytest.raises(InvalidOperation): + run_command([], "create hammer not-a-price 4") + + def test_invalid_update_id_propagates_value_error(self) -> None: + with pytest.raises(ValueError): + run_command([], "update not-an-id hammer 10 4") + + +# ============================================================ +# run_admin — main loop and invalid arguments +# ============================================================ + + +class TestAdminMain: + def test_main_keeps_one_storage_for_the_whole_session( + self, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], + ) -> None: + commands = iter( + [ + "create Cordless Drill 89.99 12", + "create Claw Hammer 9.9 40", + "show", + "exit", + ] + ) + prompts: list[str] = [] + + def fake_input(prompt: str = "") -> str: + prompts.append(prompt) + return next(commands) + + monkeypatch.setattr("builtins.input", fake_input) + main() + + output = capsys.readouterr().out + expected_storage = [ + product(PRODUCT_ID_MIN, "cordless drill", "89.99", 12), + product(PRODUCT_ID_MIN + 1, "claw hammer", "9.90", 40), + ] + expected_table = get_storage_str_representation(expected_storage) + assert output == (f"{PRODUCT_ID_MIN}\n{PRODUCT_ID_MIN + 1}\n{expected_table}\n") + assert prompts == [PROMPT, PROMPT, PROMPT, PROMPT] + + @pytest.mark.parametrize( + ("bad_command", "expected_error"), + [ + ( + "read not-an-id", + "'read not-an-id' names a command but its arguments are invalid\n", + ), + ( + "create hammer not-a-price 4", + "'create hammer not-a-price 4' names a command but its arguments are invalid\n", + ), + ( + "update bad-id hammer 10 4", + "'update bad-id hammer 10 4' names a command but its arguments are invalid\n", + ), + ], + ) + def test_main_handles_invalid_arguments_and_continues( + self, + bad_command: str, + expected_error: str, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], + ) -> None: + commands = iter([bad_command, "exit"]) + prompts: list[str] = [] + + def fake_input(prompt: str = "") -> str: + prompts.append(prompt) + return next(commands) + + monkeypatch.setattr("builtins.input", fake_input) + main() + + assert capsys.readouterr().out == expected_error + assert prompts == [PROMPT, PROMPT] diff --git a/src/part4/cart.py b/src/part4/cart.py index aed9bb72..f2126b55 100644 --- a/src/part4/cart.py +++ b/src/part4/cart.py @@ -9,10 +9,14 @@ an explanatory message to stdout and returns ``None``. """ -from .storage import Product - - -# TODO: при необходимости добавьте свои вспомогательные функции +from .crud import ( + read_product, + update_product, +) +from .storage import ( + QUANTITY_KEY, + Product, +) def add_to_cart( @@ -46,8 +50,29 @@ def add_to_cart( ``None`` when the product is unknown or the store cannot cover the request. """ - # TODO: реализуйте функцию - return 0 + + item = read_product(storage, product_id) + if not item: + return None + if item[QUANTITY_KEY] < quantity: + print( + f"not enough stock for product {product_id}: {storage[product_id][QUANTITY_KEY]} available, {quantity} requested" + ) + return None + + update_product( + storage, + product_names, + product_id, + {QUANTITY_KEY: item[QUANTITY_KEY] - quantity}, + ) + + if product_id not in cart: + cart[product_id] = item[QUANTITY_KEY] + else: + cart[product_id] += quantity + + return cart[product_id] def remove_from_cart( @@ -83,5 +108,26 @@ def remove_from_cart( (zero means the product was dropped from the cart), or ``None`` when the cart does not hold the product or holds too few units. """ - # TODO: реализуйте функцию - return 0 + if product_id not in cart: + print(f"product {product_id} is not in the cart") + return None + + if cart[product_id] < quantity: + print( + f"cart holds only {cart[product_id]} unit(s) of product {product_id}, cannot remove {quantity}" + ) + return None + + update_product( + storage, + product_names, + product_id, + {QUANTITY_KEY: storage[product_id][QUANTITY_KEY] + quantity}, + ) + cart[product_id] -= quantity + + if cart[product_id] == 0: + del cart[product_id] + return 0 + + return cart[product_id] diff --git a/src/part4/crud.py b/src/part4/crud.py index 471eff00..fe779f25 100644 --- a/src/part4/crud.py +++ b/src/part4/crud.py @@ -23,16 +23,16 @@ than a scan over ``storage.values()``. """ -import uuid # noqa: F401 +import uuid from typing import Any -from .storage import ( # noqa: F401 +from .storage import ( NAME_KEY, PRICE_KEY, QUANTITY_KEY, Product, ) -from .utils import normalize_price, normalize_product_name # noqa: F401 +from .utils import normalize_price, normalize_product_name def generate_product_id() -> str: @@ -41,8 +41,8 @@ def generate_product_id() -> str: Returns: A freshly generated UUID, stringified. """ - # TODO: реализуйте функцию - return "" + + return str(uuid.uuid4()) def create_product( @@ -73,8 +73,22 @@ def create_product( and ``product_names`` are left unchanged and an explanatory message is printed. """ - # TODO: реализуйте функцию - return "" + + if not (name := normalize_product_name(fields[NAME_KEY])): + print("product name must not be blank") + return None + + if name in product_names: + print(f"{name} is already taken") + return None + + id = generate_product_id() + fields[PRICE_KEY] = normalize_price(fields[PRICE_KEY]) + fields[NAME_KEY] = name + storage[id] = fields + product_names.add(fields[NAME_KEY]) + + return id def read_product(storage: dict[str, Product], product_id: str) -> Product | None: @@ -88,8 +102,12 @@ def read_product(storage: dict[str, Product], product_id: str) -> Product | None The matching product record, or ``None`` when no product carries that identifier (a message is printed in that case). """ - # TODO: реализуйте функцию - return {} + + if product_id not in storage: + print(f"no product with id {product_id}") + return None + + return storage[product_id] def update_product( @@ -129,8 +147,28 @@ def update_product( and an explanatory message is printed. Renaming a product to its own current name is allowed. """ - # TODO: реализуйте функцию - return {} + read_product(storage, product_id) + + if NAME_KEY in fields: + if not (name := normalize_product_name(fields[NAME_KEY])): + print("product name must not be blank") + return None + + if name in product_names: + print(f"{name} is already taken") + return None + + product_names.remove(storage[product_id][NAME_KEY]) + product_names.add(name) + storage[product_id][NAME_KEY] = name + + if PRICE_KEY in fields: + storage[product_id][PRICE_KEY] = normalize_price(fields[PRICE_KEY]) + + if QUANTITY_KEY in fields: + storage[product_id][QUANTITY_KEY] = fields[QUANTITY_KEY] + + return read_product(storage, product_id) def delete_product( @@ -153,5 +191,12 @@ def delete_product( product carried that identifier (``storage`` and ``product_names`` are left unchanged and a message is printed). """ - # TODO: реализуйте функцию - return "" + + if product_id not in storage: + print(f"no product with id {product_id}") + return None + + product_names.remove(storage[product_id][NAME_KEY]) + del storage[product_id] + + return product_id diff --git a/src/part4/run_admin.py b/src/part4/run_admin.py index 2247b29b..73c059c7 100644 --- a/src/part4/run_admin.py +++ b/src/part4/run_admin.py @@ -28,22 +28,34 @@ is left untouched and the loop keeps running; only ``exit`` stops 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 NAME_KEY, PRICE_KEY, QUANTITY_KEY, Product # noqa: F401 -from .utils import get_storage_str_representation # noqa: F401 +from .storage import NAME_KEY, PRICE_KEY, QUANTITY_KEY, Product +from .utils import get_storage_str_representation -# TODO: задайте приглашение и текст справки (используйте своё решение части 3) -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: @@ -53,7 +65,7 @@ def show_help() -> None: is: a heading, one line per command with a short description, and a note on how multi-word names are parsed. """ - # TODO: реализуйте функцию (используйте своё решение части 3) + print(HELP_TEXT) def print_result(result: object) -> None: @@ -64,7 +76,7 @@ def print_result(result: object) -> None: operation already reported its own failure, so nothing is printed in that case. """ - # TODO: реализуйте функцию (используйте своё решение части 3) + print(result) if result else "" def run_command( @@ -91,19 +103,74 @@ def run_command( decimal.InvalidOperation: If the price argument of ``create`` or ``update`` does not parse as a decimal number. """ - # TODO: реализуйте функцию - return False + + match line.split(): + case ["help"]: + show_help() + + case ["exit"]: + return False + + case ["show"]: + print_result(get_storage_str_representation(storage)) + + case ["create", *name, price, quantity]: + if not name: + print_result(f"{line} is not a command") + return True + print_result( + create_product( + storage, + product_names, + { + NAME_KEY: " ".join(name), + PRICE_KEY: Decimal(price), + QUANTITY_KEY: int(quantity), + }, + ) + ) + + case ["read", id]: + print_result(read_product(storage, id)) + + case ["update", id, *name, price, quantity]: + if not name: + print_result(f"{line} is not a command") + return True + print_result( + update_product( + storage, + product_names, + id, + { + NAME_KEY: " ".join(name), + PRICE_KEY: Decimal(price), + QUANTITY_KEY: int(quantity), + }, + ) + ) + + case ["delete", id]: + print_result(delete_product(storage, product_names, id)) + + case _: + print_result(f"{line} is not a command") + + return True def main() -> None: """Run the admin console until the ``exit`` command is entered. - A single product store, and the set of normalised names it holds, are - created empty and kept in memory for the whole session. Each iteration - reads one line from stdin, strips its surrounding whitespace and hands - it to :func:`run_command`. A line that names a command but whose price - or quantity argument does not parse is caught here and reported - without stopping the loop; only ``exit`` ends it. + A single product store, and the set of normalised names it holds, are + created empty and kept in memory for the whole session. Each iteration + reads one line from stdin, strips its surrounding whitespace and hands + it to :func:`run_command`. A line that names a command but whose price + or quantity argument does not pars + + + de is caught here and reported + without stopping the loop; only ``exit`` ends it. """ storage: dict[str, Product] = {} product_names: set[str] = set() diff --git a/src/part4/storage.py b/src/part4/storage.py index 9acedf07..01afb14f 100644 --- a/src/part4/storage.py +++ b/src/part4/storage.py @@ -38,8 +38,6 @@ type Product = dict[str, Any] -# Name of each field inside a Product record. -# TODO: задайте имена полей записи -NAME_KEY: Final = "" -PRICE_KEY: Final = "" -QUANTITY_KEY: Final = "" +NAME_KEY: Final = "name" +PRICE_KEY: Final = "price" +QUANTITY_KEY: Final = "quantity" diff --git a/src/part4/utils.py b/src/part4/utils.py index d2a940ea..f622936b 100644 --- a/src/part4/utils.py +++ b/src/part4/utils.py @@ -18,10 +18,10 @@ 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 ( # noqa: F401 +from .storage import ( NAME_KEY, PRICE_KEY, QUANTITY_KEY, @@ -29,18 +29,10 @@ ) -# Number of fractional digits every stored price is rounded to. -# Quantisation step derived from PRICE_PRECISION, e.g. Decimal("0.01"). -# TODO: задайте число знаков после запятой и шаг квантования (используйте своё -# решение части 3) -PRICE_PRECISION: Final[int] = 0 -PRICE_STEP: Final = Decimal(0) +PRICE_PRECISION: Final[int] = 2 +PRICE_STEP: Final = Decimal(1).scaleb(-PRICE_PRECISION) -# 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: задайте заголовки столбцов таблицы (используйте своё решение части 3) -TABLE_HEADERS: Final[tuple[str, ...]] = () +TABLE_HEADERS: Final[tuple[str, ...]] = ("ID", "name", "price", "quantity") def normalize_price(price: Decimal) -> Decimal: @@ -53,8 +45,8 @@ def normalize_price(price: Decimal) -> Decimal: ``price`` quantised to :data:`PRICE_PRECISION` fractional digits, with halves rounded up. """ - # TODO: реализуйте функцию (используйте своё решение части 3) - return Decimal(0) + + return price.quantize(PRICE_STEP, rounding=ROUND_HALF_UP) def normalize_product_name(name: str) -> str: @@ -71,11 +63,8 @@ def normalize_product_name(name: str) -> str: The result is an empty string when ``name`` holds nothing but whitespace. """ - # TODO: реализуйте функцию (используйте своё решение части 3) - return "" - -# TODO: при необходимости добавьте свои вспомогательные функции + return "".join([elem.lower() for elem in name.split()]) def get_storage_str_representation(storage: dict[str, Product]) -> str: @@ -96,5 +85,56 @@ def get_storage_str_representation(storage: dict[str, Product]) -> str: ``storage`` is empty only the header and separator rows are returned, sized to the header labels. """ - # TODO: реализуйте функцию (используйте своё решение части 3) - return "" + if storage: + table_len_columns = ( + max( + max(len(elem) for elem in storage), + len(TABLE_HEADERS[0]), + ), + max( + max(len(elem[NAME_KEY]) for elem in storage.values()), + len(TABLE_HEADERS[1]), + ), + max( + max(len(str(elem[PRICE_KEY])) for elem in storage.values()), + len(TABLE_HEADERS[2]), + ), + max( + max(len(str(elem[QUANTITY_KEY])) for elem in storage.values()), + len(TABLE_HEADERS[3]), + ), + ) + else: + table_len_columns = ( + len(TABLE_HEADERS[0]), + len(TABLE_HEADERS[1]), + len(TABLE_HEADERS[2]), + len(TABLE_HEADERS[3]), + ) + + first_string = make_string(TABLE_HEADERS, table_len_columns) + + second_string = ( + "|" + "|".join("-" * (length + 2) for length in table_len_columns) + "|" + ) + + product_strings = "\n".join( + make_string((id,) + tuple(storage[id].values()), table_len_columns) + for id in storage + ) + + return first_string + "\n" + second_string + "\n" + product_strings + + +def make_string( + string: tuple[str, ...], + table_len_columns: tuple[int, ...], +) -> str: + return ( + "|" + + "|".join( + str(el).ljust(length + 1).rjust(length + 2) + for el, length in zip(string, table_len_columns) + ) + + "|" + ) diff --git a/uv.lock b/uv.lock index 2a56c481..07e72fc9 100644 --- a/uv.lock +++ b/uv.lock @@ -1,5 +1,5 @@ version = 1 -revision = 2 +revision = 3 requires-python = ">=3.12" resolution-markers = [ "python_full_version >= '3.15'", @@ -70,6 +70,24 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/91/a7/c8bbb2173f7a7131b3b2412035b2d814ab5ef2ce9799bd06f07c451640e4/ast_serialize-0.11.2-cp39-abi3-win_arm64.whl", hash = "sha256:dab599cbdcb7b45b18c41fad746645580b3a24357082b7f0e8921cd373804f27", size = 1136031, upload-time = "2026-09-13T18:48:54.04Z" }, ] +[[package]] +name = "colorama" +version = "0.4.6" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d8/53/6f443c9a4a8358a93a6792e2acffb9d9d5cb0a5cfd8802644b7b1c9a02e4/colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44", size = 27697, upload-time = "2022-10-25T02:36:22.414Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" }, +] + +[[package]] +name = "iniconfig" +version = "2.3.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/01/e1/2069291243c926a2ff1cd706c7f3eeb9b62144bf60f77c9fb9ff2fb26bd3/iniconfig-2.3.1.tar.gz", hash = "sha256:67f4b9c50da0dedf52af349e7749a80a9057a5031199791b906c3bb3ae878960", size = 21209, upload-time = "2026-10-06T22:48:38.076Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/56/43/4ca9e49d27a1fcf6bece6f6aec0ea46bb9112489b93d4b688fb415457bdb/iniconfig-2.3.1-py3-none-any.whl", hash = "sha256:9121e2c1fdb355232495be3194c8dfe87ccc2d5dee45947b78e68f499790d7a7", size = 7552, upload-time = "2026-10-06T22:48:36.959Z" }, +] + [[package]] name = "librt" version = "0.15.0" @@ -234,6 +252,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/79/7b/2c79738432f5c924bef5071f933bcc9efd0473bac3b4aa584a6f7c1c8df8/mypy_extensions-1.1.0-py3-none-any.whl", hash = "sha256:1be4cccdb0f2482337c4743e60421de3a356cd97508abadd57d47403e94f5505", size = 4963, upload-time = "2025-04-22T14:54:22.983Z" }, ] +[[package]] +name = "packaging" +version = "26.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/7d/fa/3944b40b07da9ce895c0e6303a5ab7d53da063554f534556b134a54d6093/packaging-26.3.tar.gz", hash = "sha256:94edc256424af38762eb31306eed28beb9f0efc50a8837492c9d6fd6004aed79", size = 313412, upload-time = "2026-08-04T18:15:28.737Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/63/34/ba1c580383c9eada3711951fef0795c80b829a078d72188184bcab9dd527/packaging-26.3-py3-none-any.whl", hash = "sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c", size = 129956, upload-time = "2026-08-04T18:15:27.159Z" }, +] + [[package]] name = "pathspec" version = "1.1.1" @@ -251,6 +278,7 @@ source = { virtual = "." } [package.dev-dependencies] dev = [ { name = "mypy" }, + { name = "pytest" }, { name = "ruff" }, ] @@ -259,9 +287,44 @@ dev = [ [package.metadata.requires-dev] dev = [ { name = "mypy", specifier = "==2.3.1" }, + { name = "pytest", specifier = ">=9.1.1" }, { name = "ruff", specifier = "==0.16.8" }, ] +[[package]] +name = "pluggy" +version = "1.7.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/bf/db/7fc19e6f2dc92a966727031389fc2e08b558f0f25eb7403c1119ad4713cd/pluggy-1.7.0.tar.gz", hash = "sha256:d1eaa46ebb595891b860ab086b4d09c8588af65ebd4361b8e8f4bb8920b90ba8", size = 123304, upload-time = "2026-10-15T09:50:58.343Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/40/9e/2b38731e0fc536806f16490e1a12d7f0dc2a1235aa8cc07bcc75416a7daa/pluggy-1.7.0-py3-none-any.whl", hash = "sha256:7dd7b0d8832ba3cb632c306926ded123429211b83641b35dc5c41ad2d34f9bec", size = 27082, upload-time = "2026-10-15T09:50:56.808Z" }, +] + +[[package]] +name = "pygments" +version = "2.21.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/49/2e/ced460408999b33da6b31b0021b0f37d329e202d4169aeb164493778f25b/pygments-2.21.0.tar.gz", hash = "sha256:610ca751c9bc2492b38eb9a38a7fbc93edbbb2d7182edaf34e66ae493dee5c8c", size = 5005329, upload-time = "2026-08-17T08:02:48.824Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/71/46/17f022dd3e953bf20a04a028a21ec746d942f8d2af30fa0f124fa0e6a684/pygments-2.21.0-py3-none-any.whl", hash = "sha256:2363c69b61c4a97c838da3b130dcd6468f4848992b21a82f2a63ec34377137d9", size = 1250147, upload-time = "2026-08-17T08:02:44.912Z" }, +] + +[[package]] +name = "pytest" +version = "9.1.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "colorama", marker = "sys_platform == 'win32'" }, + { name = "iniconfig" }, + { name = "packaging" }, + { name = "pluggy" }, + { name = "pygments" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/e4/47/b9efed96c114afcfa3c9d3fe98a76a1d14c74a9e266d397cf6eb64be5e01/pytest-9.1.1.tar.gz", hash = "sha256:1088fbde8f2b49d95a549a195707afa7a76a3ce9bcadc26b6d71f0ffda5fe313", size = 1636369, upload-time = "2026-06-19T10:58:32.857Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/24/25/1de2678b631f5a49215c6c96fff41ba892b0a34df68d6d80292b1b48aa7f/pytest-9.1.1-py3-none-any.whl", hash = "sha256:37a86b45efb9a47a61a36449063e8e18d0cab3161329fc099eb21783169c4f0c", size = 386536, upload-time = "2026-06-19T10:58:31.347Z" }, +] + [[package]] name = "ruff" version = "0.16.8" From d62965ca4a3378d8972eff1e00dd5aa1e1016254 Mon Sep 17 00:00:00 2001 From: Alex Date: Wed, 11 Nov 2026 18:30:26 +0300 Subject: [PATCH 9/9] Solve task 5 --- src/part5/cart.py | 63 ++++++++++++++--- src/part5/constants.py | 21 +++--- src/part5/crud.py | 97 +++++++++++++++++++------- src/part5/decorators.py | 28 ++++++-- src/part5/run_admin.py | 102 +++++++++++++++++++++++---- src/part5/snowflake.py | 77 ++++++++++++++++----- src/part5/storage.py | 27 ++++---- src/part5/utils.py | 149 ++++++++++++++++++++++++++++++++++------ 8 files changed, 449 insertions(+), 115 deletions(-) diff --git a/src/part5/cart.py b/src/part5/cart.py index a2363b3a..740ab91e 100644 --- a/src/part5/cart.py +++ b/src/part5/cart.py @@ -9,10 +9,14 @@ an explanatory message to stdout and returns ``None``. """ -from .storage import Product - - -# TODO: при необходимости добавьте свои вспомогательные функции +from .crud import ( + read_product, + update_product, +) +from .storage import ( + QUANTITY_KEY, + Product, +) def add_to_cart( @@ -47,8 +51,29 @@ def add_to_cart( ``None`` when the product is unknown or the store cannot cover the request. """ - # TODO: реализуйте функцию (используйте своё решение части 4) - return 0 + + item = read_product(storage, product_id) + if not item: + return None + if item[QUANTITY_KEY] < quantity: + print( + f"not enough stock for product {product_id}: {storage[product_id][QUANTITY_KEY]} available, {quantity} requested" + ) + return None + + update_product( + storage, + product_names, + product_id, + {QUANTITY_KEY: item[QUANTITY_KEY] - quantity}, + ) + + if product_id not in cart: + cart[product_id] = item[QUANTITY_KEY] + else: + cart[product_id] += quantity + + return cart[product_id] def remove_from_cart( @@ -84,5 +109,27 @@ def remove_from_cart( (zero means the product was dropped from the cart), or ``None`` when the cart does not hold the product or holds too few units. """ - # TODO: реализуйте функцию (используйте своё решение части 4) - return 0 + + if product_id not in cart: + print(f"product {product_id} is not in the cart") + return None + + if cart[product_id] < quantity: + print( + f"cart holds only {cart[product_id]} unit(s) of product {product_id}, cannot remove {quantity}" + ) + return None + + update_product( + storage, + product_names, + product_id, + {QUANTITY_KEY: storage[product_id][QUANTITY_KEY] + quantity}, + ) + cart[product_id] -= quantity + + if cart[product_id] == 0: + del cart[product_id] + return 0 + + return cart[product_id] diff --git a/src/part5/constants.py b/src/part5/constants.py index 984671bb..96d0898f 100644 --- a/src/part5/constants.py +++ b/src/part5/constants.py @@ -15,23 +15,18 @@ from typing import Final -# TODO: замените заглушки (0) на корректные значения (используйте своё решение -# части 1). - # 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 diff --git a/src/part5/crud.py b/src/part5/crud.py index 243b0528..9d7574b9 100644 --- a/src/part5/crud.py +++ b/src/part5/crud.py @@ -38,20 +38,25 @@ from collections.abc import Callable from typing import Any, Final -from .decorators import Registry -from .storage import Product +from .decorators import Registry, collect_stats +from .snowflake import get_snowflake_id_generator +from .storage import ( + NAME_KEY, + PRICE_KEY, + QUANTITY_KEY, + Product, +) +from .utils import normalize_price, normalize_product_name STATS_REGISTRY: Final[Registry] = {} -# TODO: задайте ключи операций в реестре, см. TASK.md -CREATE_KEY: Final[str] = "" -READ_KEY: Final[str] = "" -UPDATE_KEY: Final[str] = "" -DELETE_KEY: Final[str] = "" +CREATE_KEY: Final[str] = "create" +READ_KEY: Final[str] = "read" +UPDATE_KEY: Final[str] = "update" +DELETE_KEY: Final[str] = "delete" -# TODO: при необходимости заведите здесь общий генератор Snowflake-идентификаторов -# для generate_snowflake_id (см. TASK.md) +main_generator_snowflake = get_snowflake_id_generator() def generate_snowflake_id() -> int | None: @@ -65,11 +70,11 @@ def generate_snowflake_id() -> int | None: :func:`~src.part5.snowflake.get_snowflake_id_generator` for the cases. """ - # TODO: реализуйте функцию - return 0 + return main_generator_snowflake() if main_generator_snowflake else None -# TODO: оберните операцию декоратором collect_stats + +@collect_stats(CREATE_KEY, STATS_REGISTRY) def create_product( storage: dict[int, Product], product_names: set[str], @@ -104,11 +109,25 @@ def create_product( ``product_names`` are left unchanged and an explanatory message is printed (for the last case, by ``generate_id`` itself). """ - # TODO: реализуйте функцию - return 0 + if not (name := normalize_product_name(fields[NAME_KEY])): + print("product name must not be blank") + return None + + if name in product_names: + print(f"{name} is already taken") + return None + + if (id := generate_id()) == None: + return None + fields[PRICE_KEY] = normalize_price(fields[PRICE_KEY]) + fields[NAME_KEY] = name + storage[id] = fields + product_names.add(fields[NAME_KEY]) + + return id -# TODO: оберните операцию декоратором collect_stats +@collect_stats(READ_KEY, STATS_REGISTRY) def read_product(storage: dict[int, Product], product_id: int) -> Product | None: """Return the product stored under ``product_id``. @@ -120,11 +139,15 @@ def read_product(storage: dict[int, Product], product_id: int) -> Product | None The matching product record, or ``None`` when no product carries that identifier (a message is printed in that case). """ - # TODO: реализуйте функцию (используйте своё решение части 4) - return {} + if product_id not in storage: + print(f"no product with id {product_id}") + return None -# TODO: оберните операцию декоратором collect_stats + return storage[product_id] + + +@collect_stats(UPDATE_KEY, STATS_REGISTRY) def update_product( storage: dict[int, Product], product_names: set[str], @@ -162,11 +185,32 @@ def update_product( and an explanatory message is printed. Renaming a product to its own current name is allowed. """ - # TODO: реализуйте функцию (используйте своё решение части 4) - return {} + read_product(storage, product_id) + + if NAME_KEY in fields: + if not (name := normalize_product_name(fields[NAME_KEY])): + print("product name must not be blank") + return None + + if name in product_names: + print(f"{name} is already taken") + return None -# TODO: оберните операцию декоратором collect_stats + product_names.remove(storage[product_id][NAME_KEY]) + product_names.add(name) + storage[product_id][NAME_KEY] = name + + if PRICE_KEY in fields: + storage[product_id][PRICE_KEY] = normalize_price(fields[PRICE_KEY]) + + if QUANTITY_KEY in fields: + storage[product_id][QUANTITY_KEY] = fields[QUANTITY_KEY] + + return read_product(storage, product_id) + + +@collect_stats(DELETE_KEY, STATS_REGISTRY) def delete_product( storage: dict[int, Product], product_names: set[str], @@ -187,5 +231,12 @@ def delete_product( product carried that identifier (``storage`` and ``product_names`` are left unchanged and a message is printed). """ - # TODO: реализуйте функцию (используйте своё решение части 4) - return 0 + + if product_id not in storage: + print(f"no product with id {product_id}") + return None + + product_names.remove(storage[product_id][NAME_KEY]) + del storage[product_id] + + return product_id diff --git a/src/part5/decorators.py b/src/part5/decorators.py index 21a9f237..df72d699 100644 --- a/src/part5/decorators.py +++ b/src/part5/decorators.py @@ -14,12 +14,12 @@ """ from collections.abc import Callable -from typing import Final +from functools import wraps +from typing import Any, Final -# TODO: задайте имена двух счётчиков, см. TASK.md -SUCCESS_KEY: Final[str] = "" -FAILS_KEY: Final[str] = "" +SUCCESS_KEY: Final[str] = "success" +FAILS_KEY: Final[str] = "fails" type Stats = dict[str, int] @@ -53,5 +53,21 @@ def collect_stats[**P, R]( ``None``. The decorated function has the same signature, name and docstring as the original (see :func:`functools.wraps`). """ - # TODO: реализуйте декоратор - return lambda function: function + + def decorator(function: Callable[..., Any]) -> Any: + if key in registry: + print(f"stats key '{key}' is already registered") + return function + + registry[key] = {SUCCESS_KEY: 0, FAILS_KEY: 0} + + @wraps(function) + def wrapper(*args: Any, **kwargs: Any) -> Any: + res = function(*args, **kwargs) + registry[key][SUCCESS_KEY] += 1 if res != None else 0 + registry[key][FAILS_KEY] += 1 if res == None else 0 + return res + + return wrapper + + return decorator diff --git a/src/part5/run_admin.py b/src/part5/run_admin.py index d2e83947..3ebbc422 100644 --- a/src/part5/run_admin.py +++ b/src/part5/run_admin.py @@ -36,16 +36,37 @@ is left untouched and the loop keeps running; only ``exit`` stops it. """ -from decimal import InvalidOperation +from decimal import Decimal, InvalidOperation from typing import Final -from .storage import Product - - -# TODO: задайте приглашение и текст справки (используйте своё решение части 4, -# не забудьте добавить команду stats, см. TASK.md) -PROMPT: Final[str] = "" -HELP_TEXT: Final[str] = "" +from .crud import ( + STATS_REGISTRY, + create_product, + delete_product, + generate_snowflake_id, + read_product, + update_product, +) +from .storage import NAME_KEY, PRICE_KEY, QUANTITY_KEY, Product +from .utils import get_stats_str_representation, get_storage_str_representation + + +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 + stats print call statistics of the CRUD commands + + 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: @@ -55,7 +76,8 @@ def show_help() -> None: is: a heading, one line per command with a short description, and a note on how multi-word names are parsed. """ - # TODO: реализуйте функцию (используйте своё решение части 4) + + print(HELP_TEXT) def print_result(result: object) -> None: @@ -66,7 +88,7 @@ def print_result(result: object) -> None: operation already reported its own failure, so nothing is printed in that case. """ - # TODO: реализуйте функцию (используйте своё решение части 4) + print(result) if result else "" def run_command( @@ -93,8 +115,64 @@ def run_command( decimal.InvalidOperation: If the price argument of ``create`` or ``update`` does not parse as a decimal number. """ - # TODO: реализуйте функцию - return False + + match line.split(): + case ["help"]: + show_help() + + case ["exit"]: + return False + + case ["show"]: + print_result(get_storage_str_representation(storage)) + + case ["stats"]: + print_result(get_stats_str_representation(STATS_REGISTRY)) + + case ["create", *name, price, quantity]: + if not name: + print_result(f"{line} is not a command") + return True + print_result( + create_product( + storage, + product_names, + { + NAME_KEY: " ".join(name), + PRICE_KEY: Decimal(price), + QUANTITY_KEY: int(quantity), + }, + generate_snowflake_id, + ) + ) + + case ["read", id]: + print_result(read_product(storage, int(id))) + + case ["update", id, *name, price, quantity]: + if not name: + print_result(f"{line} is not a command") + return True + print_result( + update_product( + storage, + product_names, + int(id), + { + NAME_KEY: " ".join(name), + PRICE_KEY: Decimal(price), + QUANTITY_KEY: int(quantity), + }, + ) + ) + + case ["delete", id]: + print_result(delete_product(storage, product_names, int(id))) + + case _: + print_result(f"{line} is not a command") + + return True def main() -> None: diff --git a/src/part5/snowflake.py b/src/part5/snowflake.py index 64e28468..dff781f7 100644 --- a/src/part5/snowflake.py +++ b/src/part5/snowflake.py @@ -14,9 +14,20 @@ :func:`decode_node_id` and :func:`decode_sequence_id`. """ +import time from collections.abc import Callable +from typing import Any -from .constants import EPOCH_MS_DEFAULT, NODE_ID_DEFAULT +from .constants import ( + EPOCH_MS_DEFAULT, + NODE_ID_BITS, + NODE_ID_DEFAULT, + NODE_ID_MAX, + SEQUENCE_ID_BITS, + SEQUENCE_ID_MAX, + TIMESTAMP_BITS, + TIMESTAMP_MS_MAX, +) def read_current_millis(epoch_ms: int) -> int: @@ -26,11 +37,10 @@ def read_current_millis(epoch_ms: int) -> int: epoch_ms: The custom epoch expressed as Unix milliseconds. Returns: - The count of whole milliseconds between ``epoch_ms`` and now. Negative - if ``epoch_ms`` lies in the future. + The count of whole milliseconds between ``epoch_ms`` and now. May be + negative if ``epoch_ms`` lies in the future. """ - # TODO: реализуйте функцию (используйте своё решение части 1) - return 0 + return time.time_ns() // 10**6 - epoch_ms def decode_timestamp_ms(snowflake_id: int, epoch_ms: int = EPOCH_MS_DEFAULT) -> int: @@ -45,38 +55,36 @@ def decode_timestamp_ms(snowflake_id: int, epoch_ms: int = EPOCH_MS_DEFAULT) -> The absolute Unix time in milliseconds at which the identifier was generated. """ - # TODO: реализуйте функцию (используйте своё решение части 1) - return 0 + del_time = (snowflake_id >> (NODE_ID_BITS + TIMESTAMP_BITS)) & TIMESTAMP_MS_MAX + + return epoch_ms + del_time 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 a generator from - :func:`get_snowflake_id_generator`. + snowflake_id: An identifier produced by :func:`generate_snowflake_id`. Returns: The node identifier packed into ``snowflake_id``, in the range ``[0, NODE_ID_MAX]``. """ - # TODO: реализуйте функцию (используйте своё решение части 1) - return 0 + + return (snowflake_id >> SEQUENCE_ID_BITS) & NODE_ID_MAX 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 a generator from - :func:`get_snowflake_id_generator`. + snowflake_id: An identifier produced by :func:`generate_snowflake_id`. Returns: The per-millisecond sequence counter packed into ``snowflake_id``, in the range ``[0, SEQUENCE_ID_MAX]``. """ - # TODO: реализуйте функцию (используйте своё решение части 1) - return 0 + return snowflake_id & SEQUENCE_ID_MAX def get_snowflake_id_generator( @@ -108,5 +116,40 @@ def get_snowflake_id_generator( to stdout, if ``node_id`` is outside ``[0, NODE_ID_MAX]`` or ``epoch_ms`` lies in the future. """ - # TODO: реализуйте функцию - return lambda: 0 + if not (0 <= node_id <= NODE_ID_MAX): + print(f"node_id must be in [0, {NODE_ID_MAX}]. got {node_id}") + return None + elif read_current_millis(epoch_ms) < 0: + print(f"epoch_ms must not be in the future, got {epoch_ms}") + return None + else: + sequence_id = -1 + time_old = read_current_millis(epoch_ms) + + def generator() -> int | Any: + nonlocal sequence_id + nonlocal time_old + + if (time := read_current_millis(epoch_ms)) != time_old: + time_old = time + sequence_id = -1 + + if (sequence_id := sequence_id + 1) > SEQUENCE_ID_MAX + 1: + print( + f"sequence_id must be in [0, {SEQUENCE_ID_MAX}], got {sequence_id}" + ) + return None + + elif time > TIMESTAMP_MS_MAX: + print( + f"timestamp {time} ms overflows {TIMESTAMP_MS_MAX} ms, где {time}" + ) + return None + + return ( + (time << (SEQUENCE_ID_BITS + NODE_ID_BITS)) + + (node_id << SEQUENCE_ID_BITS) + + sequence_id + ) + + return generator diff --git a/src/part5/storage.py b/src/part5/storage.py index fa8ef3bb..01afb14f 100644 --- a/src/part5/storage.py +++ b/src/part5/storage.py @@ -2,19 +2,19 @@ The store is deliberately primitive: a plain dictionary, with no persistence and no schema enforcement. It maps a product's ``id`` -- a -Snowflake integer issued by the identifier generator handed to the create -operation in :mod:`src.part5.crud` -- to its :data:`Product` record -- -a dictionary with the keys ``name``, ``price`` and ``quantity`` -- where: +UUID string assigned by the create operation in :mod:`src.part4.crud` +-- to its :data:`Product` record -- a dictionary with the keys ``name``, +``price`` and ``quantity`` -- where: -* the ``storage`` key itself -- unique integer identifier, issued by the - generator passed to the create operation in :mod:`src.part5.crud`; - it is not duplicated inside the record; +* the ``storage`` key itself -- unique string identifier, assigned by the + create operation in :mod:`src.part4.crud`; it is not duplicated + inside the record; * ``name`` -- human-readable product name, unique across the store, held in normalised form (see - :func:`src.part5.utils.normalize_product_name`); + :func:`src.part4.utils.normalize_product_name`); * ``price`` -- price of a single unit, held as a :class:`~decimal.Decimal` amount rounded to a fixed number of decimal places (see - :func:`src.part5.utils.normalize_price`) so that money is never + :func:`src.part4.utils.normalize_price`) so that money is never subject to binary floating-point error; * ``quantity`` -- number of units currently in stock. @@ -24,12 +24,12 @@ Every caller that mutates the store also threads along a second structure, a ``set[str]`` of the normalised names currently in use -- see, for example, the ``product_names`` parameter of -:func:`src.part5.crud.create_product`. Keeping that name index as a +:func:`src.part4.crud.create_product`. Keeping that name index as a plain set passed next to ``storage``, rather than bundling the two into an object, lets a name-uniqueness check become an O(1) membership test against the set instead of a linear scan over ``storage.values()``. The set must always mirror the normalised names present in ``storage``; the -functions in :mod:`src.part5.crud` keep the two in sync on every +functions in :mod:`src.part4.crud` keep the two in sync on every successful create, update and delete. """ @@ -38,7 +38,6 @@ type Product = dict[str, Any] -# TODO: задайте имена полей записи (используйте своё решение части 4) -NAME_KEY: Final = "" -PRICE_KEY: Final = "" -QUANTITY_KEY: Final = "" +NAME_KEY: Final = "name" +PRICE_KEY: Final = "price" +QUANTITY_KEY: Final = "quantity" diff --git a/src/part5/utils.py b/src/part5/utils.py index b2ad4dc4..c22022a4 100644 --- a/src/part5/utils.py +++ b/src/part5/utils.py @@ -21,23 +21,33 @@ look, with the success rate of every command as a percentage. """ -from decimal import Decimal -from typing import Final +from decimal import ROUND_HALF_UP, Decimal +from typing import Any, Final -from .decorators import Registry -from .storage import Product +from .decorators import ( + FAILS_KEY, + SUCCESS_KEY, + Registry, +) +from .storage import ( + NAME_KEY, + PRICE_KEY, + QUANTITY_KEY, + Product, +) -# TODO: задайте число знаков после запятой и шаг квантования (используйте своё -# решение части 4) -PRICE_PRECISION: Final[int] = 0 -PRICE_STEP: Final = Decimal(0) +PRICE_PRECISION: Final[int] = 2 +PRICE_STEP: Final = Decimal(1).scaleb(-PRICE_PRECISION) -# TODO: задайте заголовки столбцов таблицы (используйте своё решение части 4) -TABLE_HEADERS: Final[tuple[str, ...]] = () -# TODO: задайте заголовки столбцов таблицы статистики, см. TASK.md -STATS_TABLE_HEADERS: Final[tuple[str, ...]] = () +TABLE_HEADERS: Final[tuple[str, ...]] = ("ID", "name", "price", "quantity") +STATS_TABLE_HEADERS: Final[tuple[str, ...]] = ( + "command name", + "success", + "fails", + "success rate", +) def normalize_price(price: Decimal) -> Decimal: @@ -50,8 +60,8 @@ def normalize_price(price: Decimal) -> Decimal: ``price`` quantised to :data:`PRICE_PRECISION` fractional digits, with halves rounded up. """ - # TODO: реализуйте функцию (используйте своё решение части 4) - return Decimal(0) + + return price.quantize(PRICE_STEP, rounding=ROUND_HALF_UP) def normalize_product_name(name: str) -> str: @@ -68,11 +78,8 @@ def normalize_product_name(name: str) -> str: The result is an empty string when ``name`` holds nothing but whitespace. """ - # TODO: реализуйте функцию (используйте своё решение части 4) - return "" - -# TODO: при необходимости добавьте свои вспомогательные функции + return "".join([elem.lower() for elem in name.split()]) def get_storage_str_representation(storage: dict[int, Product]) -> str: @@ -93,8 +100,60 @@ def get_storage_str_representation(storage: dict[int, Product]) -> str: ``storage`` is empty only the header and separator rows are returned, sized to the header labels. """ - # TODO: реализуйте функцию (используйте своё решение части 4) - return "" + if storage: + table_len_columns = ( + max( + max(len(str(elem)) for elem in storage), + len(TABLE_HEADERS[0]), + ), + max( + max(len(elem[NAME_KEY]) for elem in storage.values()), + len(TABLE_HEADERS[1]), + ), + max( + max(len(str(elem[PRICE_KEY])) for elem in storage.values()), + len(TABLE_HEADERS[2]), + ), + max( + max(len(str(elem[QUANTITY_KEY])) for elem in storage.values()), + len(TABLE_HEADERS[3]), + ), + ) + else: + table_len_columns = ( + len(TABLE_HEADERS[0]), + len(TABLE_HEADERS[1]), + len(TABLE_HEADERS[2]), + len(TABLE_HEADERS[3]), + ) + + first_string = make_string(TABLE_HEADERS, table_len_columns) + + second_string = ( + "|" + "|".join("-" * (length + 2) for length in table_len_columns) + "|" + ) + + product_strings = "\n".join( + make_string((id,) + tuple(storage[id].values()), table_len_columns) + for id in storage + ) + + return first_string + "\n" + second_string + "\n" + product_strings + + +def make_string( + string: tuple[Any, ...], + table_len_columns: tuple[int, ...], +) -> str: + string = tuple(str(i) for i in string) + return ( + "|" + + "|".join( + str(el).ljust(length + 1).rjust(length + 2) + for el, length in zip(string, table_len_columns) + ) + + "|" + ) def get_stats_str_representation(registry: Registry) -> str: @@ -116,5 +175,51 @@ def get_stats_str_representation(registry: Registry) -> str: empty only the header and separator rows are returned, sized to the header labels. """ - # TODO: реализуйте функцию - return "" + if registry: + table_len_columns = ( + max( + max(len(str(elem)) for elem in registry), + len(STATS_TABLE_HEADERS[0]), + ), + max( + max(len(str(elem[SUCCESS_KEY])) for elem in registry.values()), + len(STATS_TABLE_HEADERS[1]), + ), + max( + max(len(str(elem[FAILS_KEY])) for elem in registry.values()), + len(STATS_TABLE_HEADERS[2]), + ), + max( + len("100.00%"), + len(STATS_TABLE_HEADERS[3]), + ), + ) + else: + table_len_columns = ( + len(STATS_TABLE_HEADERS[0]), + len(STATS_TABLE_HEADERS[1]), + len(STATS_TABLE_HEADERS[2]), + len(STATS_TABLE_HEADERS[3]), + ) + + first_string = make_string(STATS_TABLE_HEADERS, table_len_columns) + + second_string = ( + "|" + "|".join("-" * (length + 2) for length in table_len_columns) + "|" + ) + + statistic_strings = "\n".join( + ( + make_string( + (cmd,) + + tuple(registry[cmd].values()) + + ( + f"{(0 if not sum(registry[cmd].values()) else registry[cmd][SUCCESS_KEY] / sum(registry[cmd].values())):.2%}", + ), + table_len_columns, + ) + ) + for cmd in registry + ) + + return first_string + "\n" + second_string + "\n" + statistic_strings