From fc51f364bc14fffedfae56c787d36c69f8cf6591 Mon Sep 17 00:00:00 2001 From: lev100908 Date: Mon, 21 Sep 2026 18:58:10 +0300 Subject: [PATCH 01/33] feat: add constants.py --- src/part1/constants.py | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/part1/constants.py b/src/part1/constants.py index 9abfbba2..f23e6f45 100644 --- a/src/part1/constants.py +++ b/src/part1/constants.py @@ -19,20 +19,20 @@ # Все константы, зависящие от ёмкостей *_BITS, должны вычисляться из них. # Twitter's original Snowflake epoch: 2010-11-04 01:42:54.657 UTC. -EPOCH_MS_DEFAULT: Final[int] = 0 +EPOCH_MS_DEFAULT: Final[int] = 1288834974657 # Node identifier used when the caller does not supply one. -NODE_ID_DEFAULT: Final[int] = 0 +NODE_ID_DEFAULT: Final[int] = 1 # Width of each field, in bits. -TIMESTAMP_BITS: Final[int] = 0 -NODE_ID_BITS: Final[int] = 0 -SEQUENCE_ID_BITS: Final[int] = 0 +TIMESTAMP_BITS: Final[int] = 41 +NODE_ID_BITS: Final[int] = 10 +SEQUENCE_ID_BITS: Final[int] = 12 # Largest value each field can hold. -TIMESTAMP_MS_MAX: Final[int] = 0 -NODE_ID_MAX: Final[int] = 0 -SEQUENCE_ID_MAX: Final[int] = 0 +TIMESTAMP_MS_MAX: Final[int] = 1 << TIMESTAMP_BITS - 1 +NODE_ID_MAX: Final[int] = 1 << NODE_ID_BITS - 1 +SEQUENCE_ID_MAX: Final[int] = 1 << SEQUENCE_ID_BITS - 1 # Здесь можно добавить собственные вспомогательные константы # (например, сдвиги полей при сборке идентификатора). From 21eb845f93883d6834ed90a923b786a066411a7f Mon Sep 17 00:00:00 2001 From: lev100908 Date: Mon, 21 Sep 2026 19:05:00 +0300 Subject: [PATCH 02/33] feat: function read_current_millis --- src/part1/snowflake.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/part1/snowflake.py b/src/part1/snowflake.py index d3abf050..6b235bd4 100644 --- a/src/part1/snowflake.py +++ b/src/part1/snowflake.py @@ -34,8 +34,8 @@ 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 + now_ms = time.time() * 1_000 + return now_ms - epoch_ms def decode_timestamp_ms(snowflake_id: int, epoch_ms: int = EPOCH_MS_DEFAULT) -> int: From bfba356e9004053c7653e0922ee2471fab67c007 Mon Sep 17 00:00:00 2001 From: lev100908 Date: Mon, 21 Sep 2026 19:08:12 +0300 Subject: [PATCH 03/33] fix: change time() to time_ns() --- 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 6b235bd4..85f215b9 100644 --- a/src/part1/snowflake.py +++ b/src/part1/snowflake.py @@ -34,7 +34,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. """ - now_ms = time.time() * 1_000 + now_ms = time.time_ns() // 1_000_000 return now_ms - epoch_ms From 48fa5be558906167f38716365b6e84d83fcff83f Mon Sep 17 00:00:00 2001 From: lev100908 Date: Mon, 21 Sep 2026 19:28:05 +0300 Subject: [PATCH 04/33] feat: add constants for shift abd function decode_timestamp_ms --- src/part1/constants.py | 4 ++++ src/part1/snowflake.py | 7 +++++-- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/src/part1/constants.py b/src/part1/constants.py index f23e6f45..efb5e1b8 100644 --- a/src/part1/constants.py +++ b/src/part1/constants.py @@ -36,3 +36,7 @@ # Здесь можно добавить собственные вспомогательные константы # (например, сдвиги полей при сборке идентификатора). + +SEQUENCE_SHIFT = 0 +NODE_SHIFT = SEQUENCE_ID_BITS +TIMESTAMP_SHIFT = SEQUENCE_ID_BITS + NODE_ID_BITS \ No newline at end of file diff --git a/src/part1/snowflake.py b/src/part1/snowflake.py index 85f215b9..f304b7f8 100644 --- a/src/part1/snowflake.py +++ b/src/part1/snowflake.py @@ -21,6 +21,9 @@ NODE_ID_MAX, SEQUENCE_ID_MAX, TIMESTAMP_MS_MAX, + SEQUENCE_ID_BITS, + NODE_SHIFT, + TIMESTAMP_SHIFT ) @@ -50,8 +53,8 @@ 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 + current_millis = snowflake_id >> TIMESTAMP_SHIFT + return epoch_ms + current_millis def decode_node_id(snowflake_id: int) -> int: From b72c5db04e4ccbb823e4f106b492519567710732 Mon Sep 17 00:00:00 2001 From: lev100908 Date: Mon, 21 Sep 2026 19:33:27 +0300 Subject: [PATCH 05/33] feat: add decode_node_id and decode_sequence_id --- src/part1/snowflake.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/part1/snowflake.py b/src/part1/snowflake.py index f304b7f8..4260b784 100644 --- a/src/part1/snowflake.py +++ b/src/part1/snowflake.py @@ -23,6 +23,7 @@ TIMESTAMP_MS_MAX, SEQUENCE_ID_BITS, NODE_SHIFT, + SEQUENCE_SHIFT, TIMESTAMP_SHIFT ) @@ -67,8 +68,7 @@ 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 >> NODE_SHIFT & NODE_ID_MAX def decode_sequence_id(snowflake_id: int) -> int: @@ -81,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_SHIFT & SEQUENCE_ID_MAX def generate_snowflake_id( From 373adc2bfd5c3733c5afe982478ddf26f3487d8e Mon Sep 17 00:00:00 2001 From: lev100908 Date: Mon, 21 Sep 2026 20:17:19 +0300 Subject: [PATCH 06/33] feat: add function generate_snowflake_id --- src/part1/snowflake.py | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/src/part1/snowflake.py b/src/part1/snowflake.py index 4260b784..84dfde20 100644 --- a/src/part1/snowflake.py +++ b/src/part1/snowflake.py @@ -112,5 +112,20 @@ def generate_snowflake_id( 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 node_id > NODE_ID_MAX or node_id < 0: + print(f"node_id must be in [0, {NODE_ID_MAX}], got {node_id}") + return None + + if sequence_id > SEQUENCE_ID_MAX or sequence_id < 0: + print(f"sequence_id must be in [0, {SEQUENCE_ID_MAX}], got {sequence_id}") + return None + + current_millis = read_current_millis(epoch_ms) + + if current_millis > TIMESTAMP_MS_MAX: + print("overflows") + return None + + snowflake_id = current_millis << TIMESTAMP_SHIFT | node_id << NODE_SHIFT | sequence_id << SEQUENCE_SHIFT + + return snowflake_id From a253f2ce31043d157204d710f073ceb5b69b8bb3 Mon Sep 17 00:00:00 2001 From: lev100908 Date: Mon, 21 Sep 2026 20:22:20 +0300 Subject: [PATCH 07/33] refactor: improve code style --- src/part1/constants.py | 2 +- src/part1/snowflake.py | 17 ++++++++++------- 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/src/part1/constants.py b/src/part1/constants.py index efb5e1b8..259fba72 100644 --- a/src/part1/constants.py +++ b/src/part1/constants.py @@ -39,4 +39,4 @@ SEQUENCE_SHIFT = 0 NODE_SHIFT = SEQUENCE_ID_BITS -TIMESTAMP_SHIFT = SEQUENCE_ID_BITS + NODE_ID_BITS \ No newline at end of file +TIMESTAMP_SHIFT = SEQUENCE_ID_BITS + NODE_ID_BITS diff --git a/src/part1/snowflake.py b/src/part1/snowflake.py index 84dfde20..2fc4add4 100644 --- a/src/part1/snowflake.py +++ b/src/part1/snowflake.py @@ -13,18 +13,17 @@ :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_DEFAULT, NODE_ID_MAX, - SEQUENCE_ID_MAX, - TIMESTAMP_MS_MAX, - SEQUENCE_ID_BITS, NODE_SHIFT, + SEQUENCE_ID_MAX, SEQUENCE_SHIFT, - TIMESTAMP_SHIFT + TIMESTAMP_MS_MAX, + TIMESTAMP_SHIFT, ) @@ -126,6 +125,10 @@ def generate_snowflake_id( print("overflows") return None - snowflake_id = current_millis << TIMESTAMP_SHIFT | node_id << NODE_SHIFT | sequence_id << SEQUENCE_SHIFT + snowflake_id = ( + current_millis << TIMESTAMP_SHIFT + | node_id << NODE_SHIFT + | sequence_id << SEQUENCE_SHIFT + ) return snowflake_id From cae10c0633a0d2def93b971d1431301750983926 Mon Sep 17 00:00:00 2001 From: lev100908 Date: Sun, 27 Sep 2026 17:19:06 +0300 Subject: [PATCH 08/33] feat: add constants in storage.py --- src/part2/storage.py | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/src/part2/storage.py b/src/part2/storage.py index b63d5fc7..e4bceff1 100644 --- a/src/part2/storage.py +++ b/src/part2/storage.py @@ -24,11 +24,9 @@ type Product = tuple[int, str, Decimal, int] -# TODO: задайте позиции полей внутри кортежа Product PRODUCT_ID_INDEX: Final = 0 -NAME_INDEX: Final = 0 -PRICE_INDEX: Final = 0 -QUANTITY_INDEX: Final = 0 +NAME_INDEX: Final = 1 +PRICE_INDEX: Final = 2 +QUANTITY_INDEX: Final = 3 -# TODO: задайте идентификатор первого товара в пустом хранилище -PRODUCT_ID_MIN: Final[int] = 0 +PRODUCT_ID_MIN: Final[int] = 1 From 740c25c963f80233cd33b1a5319a57f3bdbb146e Mon Sep 17 00:00:00 2001 From: lev100908 Date: Sun, 27 Sep 2026 17:48:38 +0300 Subject: [PATCH 09/33] feat: add function normalize_price and constants in utils.py --- src/part2/utils.py | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/src/part2/utils.py b/src/part2/utils.py index ec0348d3..da990d18 100644 --- a/src/part2/utils.py +++ b/src/part2/utils.py @@ -6,13 +6,13 @@ 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 +25,4 @@ 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, ROUND_HALF_UP) From 825f77d741a32977ea5e41d30514c2de7138a255 Mon Sep 17 00:00:00 2001 From: lev100908 Date: Sun, 27 Sep 2026 17:57:52 +0300 Subject: [PATCH 10/33] feat: add function generate_product_id in crud.py --- src/part2/crud.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/part2/crud.py b/src/part2/crud.py index d026cbcb..71feff7c 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,10 @@ def generate_product_id(storage: list[Product]) -> int: :data:`~src.part2.storage.PRODUCT_ID_MIN` when ``storage`` is empty. """ - # TODO: реализуйте функцию - return 0 + if not storage: + return PRODUCT_ID_MIN + + return max(product[PRODUCT_ID_INDEX] for product in storage) + 1 def create_product( From 115190b17054f5ae55e5ed79508f757b23739a8b Mon Sep 17 00:00:00 2001 From: lev100908 Date: Sun, 27 Sep 2026 18:17:24 +0300 Subject: [PATCH 11/33] feat: add function create_product to crud.py --- src/part2/crud.py | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/src/part2/crud.py b/src/part2/crud.py index 71feff7c..8e373252 100644 --- a/src/part2/crud.py +++ b/src/part2/crud.py @@ -58,8 +58,23 @@ def create_product( ``storage`` is left unchanged and a message naming the clashing name is printed. """ - # TODO: реализуйте функцию - return 0 + name, price, quantity = fields + product_names = [product[NAME_INDEX] for product in storage] + + if name in product_names: + print(f"product name {name} is already taken.") + return None + + product_id = generate_product_id(storage) + + storage.append(( + product_id, + name, + normalize_price(price), + quantity + )) + + return product_id def read_product(storage: list[Product], product_id: int) -> Product | None: From a4bc22ad5bf027da39c107fa8a7ad5a918b3f5fb Mon Sep 17 00:00:00 2001 From: lev100908 Date: Sun, 27 Sep 2026 18:29:09 +0300 Subject: [PATCH 12/33] feat: add function read_product to crud.py --- src/part2/crud.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/part2/crud.py b/src/part2/crud.py index 8e373252..e31e634a 100644 --- a/src/part2/crud.py +++ b/src/part2/crud.py @@ -89,8 +89,12 @@ 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) + for product in storage: + if product[PRODUCT_ID_INDEX] == product_id: + return product + + print(f"no product with id {product_id}") + return None def update_product( From c7c2d7b3d47d4af9938be6df9225a6f4641703e2 Mon Sep 17 00:00:00 2001 From: lev100908 Date: Sun, 27 Sep 2026 19:01:46 +0300 Subject: [PATCH 13/33] feat: add function update_product to crud.py --- src/part2/crud.py | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/src/part2/crud.py b/src/part2/crud.py index e31e634a..4d912d4f 100644 --- a/src/part2/crud.py +++ b/src/part2/crud.py @@ -120,8 +120,21 @@ 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) + name, price, quantity = fields + + for i, product in enumerate(storage): + if product[PRODUCT_ID_INDEX] == product_id: + updated_product = ( + product_id, + name, + normalize_price(price), + quantity + ) + storage[i] = updated_product + return updated_product + + print(f"no product with id {product_id}") + return None def delete_product(storage: list[Product], product_id: int) -> int | None: From 0b55970b4d409d79ece9ab9ce9fee933b9679a8a Mon Sep 17 00:00:00 2001 From: lev100908 Date: Sun, 27 Sep 2026 19:09:13 +0300 Subject: [PATCH 14/33] feat: add function delete_product to crud.py --- src/part2/crud.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/part2/crud.py b/src/part2/crud.py index 4d912d4f..8a504f2a 100644 --- a/src/part2/crud.py +++ b/src/part2/crud.py @@ -150,5 +150,10 @@ 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 + for i, product in enumerate(storage): + if product[PRODUCT_ID_INDEX] == product_id: + storage = storage[:i] + storage[i+1:] + return product_id + + print(f"no product with id {product_id}") + return None From c87a973ab3bbe69fd72ee23aa7cd571bb120e9d1 Mon Sep 17 00:00:00 2001 From: lev100908 Date: Sun, 27 Sep 2026 20:02:06 +0300 Subject: [PATCH 15/33] feat: add constants and function add_to_cart to cart.py --- src/part2/cart.py | 45 +++++++++++++++++++++++++++++++++++++++------ 1 file changed, 39 insertions(+), 6 deletions(-) diff --git a/src/part2/cart.py b/src/part2/cart.py index 063f9aea..fc626e3c 100644 --- a/src/part2/cart.py +++ b/src/part2/cart.py @@ -11,8 +11,8 @@ from typing import Final -from .crud import read_product, update_product # noqa: F401 -from .storage import ( # noqa: F401 +from .crud import read_product, update_product +from .storage import ( NAME_INDEX, PRICE_INDEX, QUANTITY_INDEX, @@ -22,9 +22,8 @@ type CartLine = tuple[int, int] -# TODO: задайте позиции полей внутри кортежа CartLine LINE_PRODUCT_ID_INDEX: Final = 0 -LINE_QUANTITY_INDEX: Final = 0 +LINE_QUANTITY_INDEX: Final = 1 def add_to_cart( @@ -53,8 +52,42 @@ 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_product = read_product(storage, product_id) + + if not search_product: + return None + + if quantity > search_product[QUANTITY_INDEX]: + print( + f"not enough stock for product {product_id}: {search_product[QUANTITY_INDEX]} available, {quantity} requested" + ) + return None + + update_product( + storage, + product_id, + ( + search_product[NAME_INDEX], + search_product[PRICE_INDEX], + search_product[QUANTITY_INDEX] - quantity + ) + ) + + updated_cartline = ( + product_id, + ) + + for i, cartline in enumerate(cart): + if cartline[LINE_PRODUCT_ID_INDEX] == product_id: + updated_cartline += (cartline[LINE_QUANTITY_INDEX] + quantity, ) + cart[i] = updated_cartline + return updated_cartline + + updated_cartline += (quantity, ) + + cart.append(updated_cartline) + + return updated_cartline def remove_from_cart( From 4a81729f6aea9a6cad9ab7cea7a26f36fc0ed2bd Mon Sep 17 00:00:00 2001 From: lev100908 Date: Sun, 27 Sep 2026 20:16:57 +0300 Subject: [PATCH 16/33] feat: add find_cart_line to cart.py refactor: cartline to cart_line --- src/part2/cart.py | 30 +++++++++++++++++++++++++++--- 1 file changed, 27 insertions(+), 3 deletions(-) diff --git a/src/part2/cart.py b/src/part2/cart.py index fc626e3c..383481d5 100644 --- a/src/part2/cart.py +++ b/src/part2/cart.py @@ -77,9 +77,9 @@ def add_to_cart( product_id, ) - for i, cartline in enumerate(cart): - if cartline[LINE_PRODUCT_ID_INDEX] == product_id: - updated_cartline += (cartline[LINE_QUANTITY_INDEX] + quantity, ) + for i, cart_line in enumerate(cart): + if cart_line[LINE_PRODUCT_ID_INDEX] == product_id: + updated_cartline += (cart_line[LINE_QUANTITY_INDEX] + quantity, ) cart[i] = updated_cartline return updated_cartline @@ -120,3 +120,27 @@ def remove_from_cart( """ # TODO: реализуйте функцию return (0, 0) + +def find_cart_line( + cart: list[CartLine], + product_id: int, +) -> bool: + """Check cart for cart line. + + The cart line for ``product_id`` is looked up. If there is none, return False + else return True. + + Args: + + cart: The cart to take the units from; modified in place on + success. + product_id: The identifier of the product to remove. + + Returns: + True if cart line was found in cart, or False + """ + + for cart_line in cart: + if cart_line[LINE_PRODUCT_ID_INDEX] == product_id: + return True + return False From 23f6759d15d2ac97224e1328b05505e9f568b0bd Mon Sep 17 00:00:00 2001 From: lev100908 Date: Sun, 27 Sep 2026 20:18:46 +0300 Subject: [PATCH 17/33] refactor: updated_cartline to updated_cart_line --- src/part2/cart.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/part2/cart.py b/src/part2/cart.py index 383481d5..ff4cd9e0 100644 --- a/src/part2/cart.py +++ b/src/part2/cart.py @@ -73,21 +73,21 @@ def add_to_cart( ) ) - updated_cartline = ( + updated_cart_line = ( product_id, ) for i, cart_line in enumerate(cart): if cart_line[LINE_PRODUCT_ID_INDEX] == product_id: - updated_cartline += (cart_line[LINE_QUANTITY_INDEX] + quantity, ) - cart[i] = updated_cartline - return updated_cartline + updated_cart_line += (cart_line[LINE_QUANTITY_INDEX] + quantity, ) + cart[i] = updated_cart_line + return updated_cart_line - updated_cartline += (quantity, ) + updated_cart_line += (quantity, ) - cart.append(updated_cartline) + cart.append(updated_cart_line) - return updated_cartline + return updated_cart_line def remove_from_cart( From fdfd991ffc1d30c988e692a10375a2f240e0ddc9 Mon Sep 17 00:00:00 2001 From: lev100908 Date: Sun, 27 Sep 2026 20:46:40 +0300 Subject: [PATCH 18/33] feat: change return value in find_cart_line feat: add change_cart_quantity to cart.py --- src/part2/cart.py | 35 +++++++++++++++++++++++++++-------- 1 file changed, 27 insertions(+), 8 deletions(-) diff --git a/src/part2/cart.py b/src/part2/cart.py index ff4cd9e0..4a0d6a29 100644 --- a/src/part2/cart.py +++ b/src/part2/cart.py @@ -124,14 +124,13 @@ def remove_from_cart( def find_cart_line( cart: list[CartLine], product_id: int, -) -> bool: +) -> int | None: """Check cart for cart line. - The cart line for ``product_id`` is looked up. If there is none, return False - else return True. + The cart line for ``product_id`` is looked up. If there is none, return None + else return index of required cart line in cart. Args: - cart: The cart to take the units from; modified in place on success. product_id: The identifier of the product to remove. @@ -139,8 +138,28 @@ def find_cart_line( Returns: True if cart line was found in cart, or False """ + for i, cart_line in enumerate(cart): + if cart_line[LINE_PRODUCT_ID_INDEX] == product_id: + return i + return None - for cart_line in cart: - if cart_line[LINE_PRODUCT_ID_INDEX] == product_id: - return True - return False +def change_cart_quantity( + cart: list[CartLine], + index: int, + quantity: int, +) -> CartLine: + """Change cart quantity in cart line at ``index`` to ``quantity``. + + Args: + cart: The cart to take the units from; modified in place on + success. + index: The index of cart line in cart (as index of list). + quantity: Number of units. + + Returns: + The cart line for ``product_id`` after the changing quantity. + """ + + updated_cart_line = (cart[index][LINE_PRODUCT_ID_INDEX], quantity) + cart[index] = updated_cart_line + return updated_cart_line From 23ed7632109c12f2e31130cc6fb24cf846bbe9f9 Mon Sep 17 00:00:00 2001 From: lev100908 Date: Sun, 27 Sep 2026 20:48:07 +0300 Subject: [PATCH 19/33] refactor move find_cart_line and change_cart_line --- src/part2/cart.py | 85 +++++++++++++++++++++++------------------------ 1 file changed, 42 insertions(+), 43 deletions(-) diff --git a/src/part2/cart.py b/src/part2/cart.py index 4a0d6a29..0ff9f13e 100644 --- a/src/part2/cart.py +++ b/src/part2/cart.py @@ -25,6 +25,48 @@ LINE_PRODUCT_ID_INDEX: Final = 0 LINE_QUANTITY_INDEX: Final = 1 +def find_cart_line( + cart: list[CartLine], + product_id: int, +) -> int | None: + """Check cart for cart line. + + The cart line for ``product_id`` is looked up. If there is none, return None + else return index of required cart line in cart. + + Args: + cart: The cart to take the units from; modified in place on + success. + product_id: The identifier of the product to remove. + + Returns: + True if cart line was found in cart, or False + """ + for i, cart_line in enumerate(cart): + if cart_line[LINE_PRODUCT_ID_INDEX] == product_id: + return i + return None + +def change_cart_quantity( + cart: list[CartLine], + index: int, + quantity: int, +) -> CartLine: + """Change cart quantity in cart line at ``index`` to ``quantity``. + + Args: + cart: The cart to take the units from; modified in place on + success. + index: The index of cart line in cart (as index of list). + quantity: Number of units. + + Returns: + The cart line for ``product_id`` after the changing quantity. + """ + + updated_cart_line = (cart[index][LINE_PRODUCT_ID_INDEX], quantity) + cart[index] = updated_cart_line + return updated_cart_line def add_to_cart( storage: list[Product], @@ -120,46 +162,3 @@ def remove_from_cart( """ # TODO: реализуйте функцию return (0, 0) - -def find_cart_line( - cart: list[CartLine], - product_id: int, -) -> int | None: - """Check cart for cart line. - - The cart line for ``product_id`` is looked up. If there is none, return None - else return index of required cart line in cart. - - Args: - cart: The cart to take the units from; modified in place on - success. - product_id: The identifier of the product to remove. - - Returns: - True if cart line was found in cart, or False - """ - for i, cart_line in enumerate(cart): - if cart_line[LINE_PRODUCT_ID_INDEX] == product_id: - return i - return None - -def change_cart_quantity( - cart: list[CartLine], - index: int, - quantity: int, -) -> CartLine: - """Change cart quantity in cart line at ``index`` to ``quantity``. - - Args: - cart: The cart to take the units from; modified in place on - success. - index: The index of cart line in cart (as index of list). - quantity: Number of units. - - Returns: - The cart line for ``product_id`` after the changing quantity. - """ - - updated_cart_line = (cart[index][LINE_PRODUCT_ID_INDEX], quantity) - cart[index] = updated_cart_line - return updated_cart_line From 188b3478a7e93db68d9d64cdb5d14a7202438932 Mon Sep 17 00:00:00 2001 From: lev100908 Date: Sun, 27 Sep 2026 20:55:06 +0300 Subject: [PATCH 20/33] feat: add functionality of find_cart_line and change_cart_quantity to add_to_cart --- src/part2/cart.py | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/src/part2/cart.py b/src/part2/cart.py index 0ff9f13e..53d525cf 100644 --- a/src/part2/cart.py +++ b/src/part2/cart.py @@ -115,18 +115,16 @@ def add_to_cart( ) ) + index_cart_line = find_cart_line(cart, product_id) + + if index_cart_line: + return change_cart_quantity(cart, index_cart_line, quantity) + updated_cart_line = ( product_id, + quantity ) - for i, cart_line in enumerate(cart): - if cart_line[LINE_PRODUCT_ID_INDEX] == product_id: - updated_cart_line += (cart_line[LINE_QUANTITY_INDEX] + quantity, ) - cart[i] = updated_cart_line - return updated_cart_line - - updated_cart_line += (quantity, ) - cart.append(updated_cart_line) return updated_cart_line From c64bb7743971af27c09bd69d1b213bfcbf331d7c Mon Sep 17 00:00:00 2001 From: lev100908 Date: Sun, 27 Sep 2026 21:24:40 +0300 Subject: [PATCH 21/33] fix: rewrite condition of checking cart line in line (include index_cart_line = 0) fix: quantity that passed to change_cart_quantity feat: add function remove_from_cart to cart.py --- src/part2/cart.py | 55 ++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 47 insertions(+), 8 deletions(-) diff --git a/src/part2/cart.py b/src/part2/cart.py index 53d525cf..bf555294 100644 --- a/src/part2/cart.py +++ b/src/part2/cart.py @@ -51,7 +51,7 @@ def change_cart_quantity( cart: list[CartLine], index: int, quantity: int, -) -> CartLine: +) -> CartLine | None: """Change cart quantity in cart line at ``index`` to ``quantity``. Args: @@ -62,11 +62,18 @@ def change_cart_quantity( Returns: The cart line for ``product_id`` after the changing quantity. + None if quantity = 0. """ - updated_cart_line = (cart[index][LINE_PRODUCT_ID_INDEX], quantity) - cart[index] = updated_cart_line - return updated_cart_line + + if quantity: + updated_cart_line = (cart[index][LINE_PRODUCT_ID_INDEX], quantity) + cart[index] = updated_cart_line + return updated_cart_line + + cart[index] = cart[:index] + cart[index+1:] + return None + def add_to_cart( storage: list[Product], @@ -117,8 +124,11 @@ def add_to_cart( index_cart_line = find_cart_line(cart, product_id) - if index_cart_line: - return change_cart_quantity(cart, index_cart_line, quantity) + if not index_cart_line is None: + return change_cart_quantity( + cart, + index_cart_line, + cart[index_cart_line][QUANTITY_INDEX] + quantity) updated_cart_line = ( product_id, @@ -158,5 +168,34 @@ 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) + index_cart_line = find_cart_line(cart, product_id) + + if index_cart_line is None: + print( + f"product {product_id} is not in the cart" + ) + return None + + cart_line_quantity = cart[index_cart_line][LINE_QUANTITY_INDEX] + if cart_line_quantity < quantity: + print( + f"cart holds only {cart_line_quantity} unit(s) of product {product_id}, cannot remove {quantity}" + ) + return None + + search_product = read_product(storage, product_id) + + if not search_product: + return None + + update_product( + storage, + product_id, + ( + search_product[NAME_INDEX], + search_product[PRICE_INDEX], + search_product[QUANTITY_INDEX] + quantity + ) + ) + + return change_cart_quantity(cart, index_cart_line, cart_line_quantity - quantity) From 0f47b4886c54a00189eb2c45173e3d127aac31c4 Mon Sep 17 00:00:00 2001 From: lev100908 Date: Sun, 27 Sep 2026 21:40:33 +0300 Subject: [PATCH 22/33] fix: fix deleting an empty cart line fix: switch QUANTITY_INDEX to LINE_QUANTITY_INDEX in 131 line refactor: delete TODO in utils.py --- src/part2/cart.py | 4 ++-- src/part2/utils.py | 1 - 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/src/part2/cart.py b/src/part2/cart.py index bf555294..caab2c51 100644 --- a/src/part2/cart.py +++ b/src/part2/cart.py @@ -71,7 +71,7 @@ def change_cart_quantity( cart[index] = updated_cart_line return updated_cart_line - cart[index] = cart[:index] + cart[index+1:] + cart = cart[:index] + cart[index+1:] return None @@ -128,7 +128,7 @@ def add_to_cart( return change_cart_quantity( cart, index_cart_line, - cart[index_cart_line][QUANTITY_INDEX] + quantity) + cart[index_cart_line][LINE_QUANTITY_INDEX] + quantity) updated_cart_line = ( product_id, diff --git a/src/part2/utils.py b/src/part2/utils.py index da990d18..22f837a0 100644 --- a/src/part2/utils.py +++ b/src/part2/utils.py @@ -10,7 +10,6 @@ from typing import Final -# TODO: задайте число знаков после запятой и шаг квантования PRICE_PRECISION: Final[int] = 2 PRICE_STEP: Final = Decimal(1).scaleb(-PRICE_PRECISION) From 86e851d92850c71fa5be2b740986caadb8f5b612 Mon Sep 17 00:00:00 2001 From: lev100908 Date: Mon, 28 Sep 2026 19:12:51 +0300 Subject: [PATCH 23/33] refactor: improve code style --- src/part2/cart.py | 51 +++++++++++++++++++++-------------------------- src/part2/crud.py | 16 +++------------ 2 files changed, 26 insertions(+), 41 deletions(-) diff --git a/src/part2/cart.py b/src/part2/cart.py index caab2c51..439e9921 100644 --- a/src/part2/cart.py +++ b/src/part2/cart.py @@ -25,13 +25,14 @@ LINE_PRODUCT_ID_INDEX: Final = 0 LINE_QUANTITY_INDEX: Final = 1 + def find_cart_line( cart: list[CartLine], product_id: int, ) -> int | None: """Check cart for cart line. - - The cart line for ``product_id`` is looked up. If there is none, return None + + The cart line for ``product_id`` is looked up. If there is none, return None else return index of required cart line in cart. Args: @@ -43,17 +44,18 @@ def find_cart_line( True if cart line was found in cart, or False """ for i, cart_line in enumerate(cart): - if cart_line[LINE_PRODUCT_ID_INDEX] == product_id: - return i + if cart_line[LINE_PRODUCT_ID_INDEX] == product_id: + return i return None + def change_cart_quantity( cart: list[CartLine], index: int, quantity: int, ) -> CartLine | None: """Change cart quantity in cart line at ``index`` to ``quantity``. - + Args: cart: The cart to take the units from; modified in place on success. @@ -65,13 +67,12 @@ def change_cart_quantity( None if quantity = 0. """ - if quantity: updated_cart_line = (cart[index][LINE_PRODUCT_ID_INDEX], quantity) cart[index] = updated_cart_line return updated_cart_line - - cart = cart[:index] + cart[index+1:] + + cart = cart[:index] + cart[index + 1 :] return None @@ -113,27 +114,23 @@ def add_to_cart( return None update_product( - storage, - product_id, + storage, + product_id, ( search_product[NAME_INDEX], search_product[PRICE_INDEX], - search_product[QUANTITY_INDEX] - quantity - ) + search_product[QUANTITY_INDEX] - quantity, + ), ) index_cart_line = find_cart_line(cart, product_id) if not index_cart_line is None: return change_cart_quantity( - cart, - index_cart_line, - cart[index_cart_line][LINE_QUANTITY_INDEX] + quantity) + cart, index_cart_line, cart[index_cart_line][LINE_QUANTITY_INDEX] + quantity + ) - updated_cart_line = ( - product_id, - quantity - ) + updated_cart_line = (product_id, quantity) cart.append(updated_cart_line) @@ -170,12 +167,10 @@ def remove_from_cart( """ index_cart_line = find_cart_line(cart, product_id) - if index_cart_line is None: - print( - f"product {product_id} is not in the cart" - ) + if index_cart_line is None: + print(f"product {product_id} is not in the cart") return None - + cart_line_quantity = cart[index_cart_line][LINE_QUANTITY_INDEX] if cart_line_quantity < quantity: print( @@ -189,13 +184,13 @@ def remove_from_cart( return None update_product( - storage, - product_id, + storage, + product_id, ( search_product[NAME_INDEX], search_product[PRICE_INDEX], - search_product[QUANTITY_INDEX] + quantity - ) + search_product[QUANTITY_INDEX] + quantity, + ), ) return change_cart_quantity(cart, index_cart_line, cart_line_quantity - quantity) diff --git a/src/part2/crud.py b/src/part2/crud.py index 8a504f2a..4b057d39 100644 --- a/src/part2/crud.py +++ b/src/part2/crud.py @@ -67,12 +67,7 @@ def create_product( product_id = generate_product_id(storage) - storage.append(( - product_id, - name, - normalize_price(price), - quantity - )) + storage.append((product_id, name, normalize_price(price), quantity)) return product_id @@ -124,12 +119,7 @@ def update_product( for i, product in enumerate(storage): if product[PRODUCT_ID_INDEX] == product_id: - updated_product = ( - product_id, - name, - normalize_price(price), - quantity - ) + updated_product = (product_id, name, normalize_price(price), quantity) storage[i] = updated_product return updated_product @@ -152,7 +142,7 @@ def delete_product(storage: list[Product], product_id: int) -> int | None: """ for i, product in enumerate(storage): if product[PRODUCT_ID_INDEX] == product_id: - storage = storage[:i] + storage[i+1:] + storage = storage[:i] + storage[i + 1 :] return product_id print(f"no product with id {product_id}") From 90d73754d5f37ac4e8d69dc700699a0bd481e1e4 Mon Sep 17 00:00:00 2001 From: lev100908 Date: Thu, 8 Oct 2026 14:25:03 +0300 Subject: [PATCH 24/33] feat: add several functions from task2 to crud.py storage.py and utils.py --- src/part3/crud.py | 58 +++++++++++++++++++++++++++++++++++--------- src/part3/storage.py | 11 +++------ src/part3/utils.py | 11 +++------ 3 files changed, 54 insertions(+), 26 deletions(-) diff --git a/src/part3/crud.py b/src/part3/crud.py index 68811d7e..bd22af0c 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 ( # noqa: F401 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 # noqa: F401 def generate_product_id(storage: list[Product]) -> int: @@ -40,8 +40,10 @@ def generate_product_id(storage: list[Product]) -> int: :data:`~src.part3.storage.PRODUCT_ID_MIN` when ``storage`` is empty. """ - # TODO: реализуйте функцию (используйте своё решение части 2) - return 0 + if not storage: + return PRODUCT_ID_MIN + + return max(product[PRODUCT_ID_INDEX] for product in storage) + 1 def create_product( @@ -64,8 +66,22 @@ def create_product( normalised name already exists. In the ``None`` case ``storage`` is left unchanged and an explanatory message is printed. """ - # TODO: реализуйте функцию - return 0 + name, price, quantity = fields + product_names = [product[NAME_INDEX] for product in storage] + + if not name: + print("product name must not be blank") + return None + + if name in product_names: + print(f"product name {name} is already taken.") + return None + + product_id = generate_product_id(storage) + + storage.append((product_id, normalize_product_name(name), normalize_price(price), quantity)) + + return product_id def read_product(storage: list[Product], product_id: int) -> Product | None: @@ -80,8 +96,12 @@ 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: реализуйте функцию (используйте своё решение части 2) - return (0, "", Decimal(0), 0) + for product in storage: + if product[PRODUCT_ID_INDEX] == product_id: + return product + + print(f"no product with id {product_id}") + return None def update_product( @@ -110,8 +130,17 @@ def update_product( unchanged and an explanatory message is printed. Renaming a product to its own current name is allowed. """ - # TODO: реализуйте функцию - return (0, "", Decimal(0), 0) + name, price, quantity = fields + + for i, product in enumerate(storage): + if product[PRODUCT_ID_INDEX] == product_id: + updated_product = (product_id, normalize_product_name(name), normalize_price(price), quantity) + storage[i] = updated_product + return updated_product + + print(f"no product with id {product_id}") + return None + def delete_product(storage: list[Product], product_id: int) -> int | None: @@ -127,5 +156,10 @@ 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 + for i, product in enumerate(storage): + if product[PRODUCT_ID_INDEX] == product_id: + storage = storage[:i] + storage[i + 1 :] + return product_id + + print(f"no product with id {product_id}") + return None diff --git a/src/part3/storage.py b/src/part3/storage.py index c5e34be5..c516645b 100644 --- a/src/part3/storage.py +++ b/src/part3/storage.py @@ -24,12 +24,9 @@ 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..8f18d61c 100644 --- a/src/part3/utils.py +++ b/src/part3/utils.py @@ -21,15 +21,13 @@ from decimal import ROUND_HALF_UP, Decimal # noqa: F401 from typing import Final -from .storage import Product +from storage import 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 @@ -48,8 +46,7 @@ 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, ROUND_HALF_UP) def normalize_product_name(name: str) -> str: From 8d1af88081c8439b7ddafb16bc9817b694039605 Mon Sep 17 00:00:00 2001 From: lev100908 Date: Thu, 8 Oct 2026 14:27:34 +0300 Subject: [PATCH 25/33] style: delete useless comments --- src/part3/crud.py | 4 ++-- src/part3/run_admin.py | 4 ++-- src/part3/utils.py | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/part3/crud.py b/src/part3/crud.py index bd22af0c..f68d254c 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: diff --git a/src/part3/run_admin.py b/src/part3/run_admin.py index c5feeb0b..7ed8a2b4 100644 --- a/src/part3/run_admin.py +++ b/src/part3/run_admin.py @@ -29,10 +29,10 @@ 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, diff --git a/src/part3/utils.py b/src/part3/utils.py index 8f18d61c..78f40c24 100644 --- a/src/part3/utils.py +++ b/src/part3/utils.py @@ -18,7 +18,7 @@ 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 e1ae299c864e101e8106173abdd1d66e17e11e1e Mon Sep 17 00:00:00 2001 From: lev100908 Date: Thu, 8 Oct 2026 15:18:52 +0300 Subject: [PATCH 26/33] feat: add function normalize_product_name to utils.py --- src/part3/utils.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/part3/utils.py b/src/part3/utils.py index 78f40c24..04a58c9f 100644 --- a/src/part3/utils.py +++ b/src/part3/utils.py @@ -19,6 +19,7 @@ """ from decimal import ROUND_HALF_UP, Decimal +import re from typing import Final from storage import Product @@ -33,7 +34,7 @@ # 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: @@ -63,8 +64,8 @@ def normalize_product_name(name: str) -> str: The result is an empty string when ``name`` holds nothing but whitespace. """ - # TODO: реализуйте функцию - return "" + + return re.sub(r"\s+", " ", name.strip().lower()) # TODO: при необходимости добавьте свои вспомогательные функции From 258cb47c4c2ca89c56c8702cfdd5878c293583e1 Mon Sep 17 00:00:00 2001 From: lev100908 Date: Thu, 8 Oct 2026 15:22:10 +0300 Subject: [PATCH 27/33] fix: moved normalizing name before checking it --- src/part3/crud.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/part3/crud.py b/src/part3/crud.py index f68d254c..fbd96e16 100644 --- a/src/part3/crud.py +++ b/src/part3/crud.py @@ -68,18 +68,20 @@ def create_product( """ name, price, quantity = fields product_names = [product[NAME_INDEX] for product in storage] - + if not name: print("product name must not be blank") return None + name = normalize_product_name(name) + if name in product_names: print(f"product name {name} is already taken.") return None product_id = generate_product_id(storage) - storage.append((product_id, normalize_product_name(name), normalize_price(price), quantity)) + storage.append((product_id, name, normalize_price(price), quantity)) return product_id @@ -131,10 +133,11 @@ def update_product( product to its own current name is allowed. """ name, price, quantity = fields + name = normalize_product_name(name) for i, product in enumerate(storage): if product[PRODUCT_ID_INDEX] == product_id: - updated_product = (product_id, normalize_product_name(name), normalize_price(price), quantity) + updated_product = (product_id, name, normalize_price(price), quantity) storage[i] = updated_product return updated_product From 66030fcb8632bf3fbe70451d0fb635d40bae34b3 Mon Sep 17 00:00:00 2001 From: lev100908 Date: Thu, 8 Oct 2026 16:48:09 +0300 Subject: [PATCH 28/33] feat: redone function update_product in crud.py --- src/part3/crud.py | 33 +++++++++++++++++++++++++-------- 1 file changed, 25 insertions(+), 8 deletions(-) diff --git a/src/part3/crud.py b/src/part3/crud.py index fbd96e16..00e330dc 100644 --- a/src/part3/crud.py +++ b/src/part3/crud.py @@ -68,15 +68,15 @@ def create_product( """ name, price, quantity = fields product_names = [product[NAME_INDEX] for product in storage] + + name = normalize_product_name(name) if not name: print("product name must not be blank") return None - name = normalize_product_name(name) - if name in product_names: - print(f"product name {name} is already taken.") + print(f"product name '{name}' is already taken.") return None product_id = generate_product_id(storage) @@ -133,17 +133,34 @@ def update_product( product to its own current name is allowed. """ name, price, quantity = fields + name = normalize_product_name(name) + if not name: + print("product name must not be blank") + return None + + index_for_updating: int | None = None + fl_name_taken: bool = False + for i, product in enumerate(storage): if product[PRODUCT_ID_INDEX] == product_id: - updated_product = (product_id, name, normalize_price(price), quantity) - storage[i] = updated_product - return updated_product + index_for_updating = i + elif product[NAME_INDEX] == name and product[PRODUCT_ID_INDEX] != product_id: + fl_name_taken = True - print(f"no product with id {product_id}") - return None + if index_for_updating is None: + print(f"no product with id {product_id}") + return None + + if fl_name_taken: + print(f"product name '{name}' is already taken") + return None + + updated_product = (product_id, name, normalize_price(price), quantity) + storage[index_for_updating] = updated_product + return updated_product def delete_product(storage: list[Product], product_id: int) -> int | None: From 2ef476cac5e74fd7778cb3b23e8099e468b52aa3 Mon Sep 17 00:00:00 2001 From: lev100908 Date: Thu, 8 Oct 2026 17:55:09 +0300 Subject: [PATCH 29/33] feat: add function get_storage_str_representation and helper functions --- src/part3/utils.py | 63 ++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 58 insertions(+), 5 deletions(-) diff --git a/src/part3/utils.py b/src/part3/utils.py index 04a58c9f..d03f468d 100644 --- a/src/part3/utils.py +++ b/src/part3/utils.py @@ -22,7 +22,7 @@ import re 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. @@ -33,7 +33,6 @@ # 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, ...]] = ("ID", "name", "price", "quantity") @@ -68,8 +67,40 @@ def normalize_product_name(name: str) -> str: return re.sub(r"\s+", " ", name.strip().lower()) -# TODO: при необходимости добавьте свои вспомогательные функции +def get_row_str_representation(values: list[list[Product]], row_index: int, lengths_columns: list[int]) -> str: + """Render the row of table by index. + Args: + values (list[list[Product]]): values + row_index (int): index of row + lengths_columns (list[int]): list of lengths of columns + + Returns: + str: string of the row of table by index + """ + return ( + f"| {f'{values[PRODUCT_ID_INDEX][row_index]}':<{lengths_columns[PRODUCT_ID_INDEX]}} |" + + f" {f'{values[NAME_INDEX][row_index]}':<{lengths_columns[NAME_INDEX]}} |" + + f" {f'{values[PRICE_INDEX][row_index]}':<{lengths_columns[PRICE_INDEX]}} |" + + f" {f'{values[QUANTITY_INDEX][row_index]}':<{lengths_columns[QUANTITY_INDEX]}} |" + "\n" + ) + +def get_horizonal_line_str(lengths_columns: list[int]) -> str: + """Render the dashed separator row. + + Args: + lengths_columns (list[int]): list of lengths of columns + + Returns: + str: string of the dashed separator row + """ + + return ( + f"|{'-' * (lengths_columns[PRODUCT_ID_INDEX] + 2)}|" + + f"{'-' * (lengths_columns[NAME_INDEX] + 2)}|" + + f"{'-' * (lengths_columns[PRICE_INDEX] + 2)}|" + + f"{'-' * (lengths_columns[QUANTITY_INDEX] + 2)}|" + "\n" + ) def get_storage_str_representation(storage: list[Product]) -> str: """Render the product store as a text table with data-sized columns. @@ -89,5 +120,27 @@ 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 "" + values_columns: list[list[str]] = [ + [TABLE_HEADERS[PRODUCT_ID_INDEX]], + [TABLE_HEADERS[NAME_INDEX]], + [TABLE_HEADERS[PRICE_INDEX]], + [TABLE_HEADERS[QUANTITY_INDEX]], + ] + for product in storage: + values_columns[PRODUCT_ID_INDEX].append(str(product[PRODUCT_ID_INDEX])) + values_columns[NAME_INDEX].append(product[NAME_INDEX]) + values_columns[PRICE_INDEX].append(str(product[PRICE_INDEX])) + values_columns[QUANTITY_INDEX].append(str(product[QUANTITY_INDEX])) + + lengths_colums: list[int] = [len(max(values_columns[PRODUCT_ID_INDEX], key=len)), + len(max(values_columns[NAME_INDEX], key=len)), + len(max(values_columns[PRICE_INDEX], key=len)), + len(max(values_columns[QUANTITY_INDEX], key=len)), + ] + + output_string: str = get_row_str_representation(values_columns, 0, lengths_colums) + get_horizonal_line_str(lengths_colums) + for i in range(1, len(values_columns[0])): + output_string += get_row_str_representation(values_columns, i, lengths_colums) + + return output_string + From d0acfaa72dee76dfdc12d7de2dd93c4c9dcde0db Mon Sep 17 00:00:00 2001 From: lev100908 Date: Thu, 8 Oct 2026 17:58:10 +0300 Subject: [PATCH 30/33] feat: add constants and function show_help to run_admin.py --- src/part3/run_admin.py | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/src/part3/run_admin.py b/src/part3/run_admin.py index 7ed8a2b4..0a362b2d 100644 --- a/src/part3/run_admin.py +++ b/src/part3/run_admin.py @@ -42,9 +42,19 @@ from .utils import get_storage_str_representation # noqa: F401 -# 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 +64,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: From 52db6e4c05794f985dc44ceeedceb8a8825b44d5 Mon Sep 17 00:00:00 2001 From: lev100908 Date: Thu, 8 Oct 2026 18:46:44 +0300 Subject: [PATCH 31/33] feat: add function print_result and run_command to run_admin.py --- src/part3/crud.py | 4 ++-- src/part3/run_admin.py | 30 ++++++++++++++++++++++++++---- src/part3/utils.py | 2 +- 3 files changed, 29 insertions(+), 7 deletions(-) diff --git a/src/part3/crud.py b/src/part3/crud.py index 00e330dc..48af5b7f 100644 --- a/src/part3/crud.py +++ b/src/part3/crud.py @@ -20,13 +20,13 @@ from decimal import Decimal -from storage import ( +from .storage import ( NAME_INDEX, PRODUCT_ID_INDEX, PRODUCT_ID_MIN, Product, ) -from utils import normalize_price, normalize_product_name +from .utils import normalize_price, normalize_product_name def generate_product_id(storage: list[Product]) -> int: diff --git a/src/part3/run_admin.py b/src/part3/run_admin.py index 0a362b2d..3d524e6d 100644 --- a/src/part3/run_admin.py +++ b/src/part3/run_admin.py @@ -75,7 +75,8 @@ def print_result(result: object) -> None: operation already reported its own failure, so nothing is printed in that case. """ - # TODO: реализуйте функцию + if result: + print(result) def run_command(storage: list[Product], line: str) -> bool: @@ -98,9 +99,30 @@ 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() + return True + case ["exit"]: + return False + case ["show"]: + print(get_storage_str_representation(storage)) + return True + case ["create", *name, price, quantity]: + print_result(create_product(storage, (" ".join(name), Decimal(price), int(quantity)))) + return True + case ["read", id]: + print_result(read_product(storage, int(id))) + return True + case ["update", id, *name, price, quantity]: + print_result(update_product(storage, int(id), (" ".join(name), Decimal(price), int(quantity)))) + return True + case ["delete", id]: + print_result(delete_product(storage, int(id))) + return True + case _: + print(f"'{line}' is not a command") + return True def main() -> None: """Run the admin console until the ``exit`` command is entered. diff --git a/src/part3/utils.py b/src/part3/utils.py index d03f468d..9638ce40 100644 --- a/src/part3/utils.py +++ b/src/part3/utils.py @@ -22,7 +22,7 @@ import re from typing import Final -from storage import NAME_INDEX, PRICE_INDEX, PRODUCT_ID_INDEX, QUANTITY_INDEX, Product +from .storage import NAME_INDEX, PRICE_INDEX, PRODUCT_ID_INDEX, QUANTITY_INDEX, Product # Number of fractional digits every stored price is rounded to. From 0eb452452064ad3a33b8e138465d26701a3318c2 Mon Sep 17 00:00:00 2001 From: lev100908 Date: Thu, 8 Oct 2026 19:14:18 +0300 Subject: [PATCH 32/33] refactor: improve code style --- src/part3/crud.py | 2 +- src/part3/run_admin.py | 13 +++++++--- src/part3/utils.py | 54 ++++++++++++++++++++++++++---------------- 3 files changed, 45 insertions(+), 24 deletions(-) diff --git a/src/part3/crud.py b/src/part3/crud.py index 48af5b7f..ea983925 100644 --- a/src/part3/crud.py +++ b/src/part3/crud.py @@ -70,7 +70,7 @@ def create_product( product_names = [product[NAME_INDEX] for product in storage] name = normalize_product_name(name) - + if not name: print("product name must not be blank") return None diff --git a/src/part3/run_admin.py b/src/part3/run_admin.py index 3d524e6d..c412305e 100644 --- a/src/part3/run_admin.py +++ b/src/part3/run_admin.py @@ -39,7 +39,7 @@ update_product, ) from .storage import Product -from .utils import get_storage_str_representation # noqa: F401 +from .utils import get_storage_str_representation PROMPT: Final[str] = "admin> " @@ -109,13 +109,19 @@ def run_command(storage: list[Product], line: str) -> bool: print(get_storage_str_representation(storage)) return True case ["create", *name, price, quantity]: - print_result(create_product(storage, (" ".join(name), Decimal(price), int(quantity)))) + print_result( + create_product(storage, (" ".join(name), Decimal(price), int(quantity))) + ) return True case ["read", id]: print_result(read_product(storage, int(id))) return True case ["update", id, *name, price, quantity]: - print_result(update_product(storage, int(id), (" ".join(name), Decimal(price), int(quantity)))) + print_result( + update_product( + storage, int(id), (" ".join(name), Decimal(price), int(quantity)) + ) + ) return True case ["delete", id]: print_result(delete_product(storage, int(id))) @@ -124,6 +130,7 @@ def run_command(storage: list[Product], line: str) -> bool: print(f"'{line}' is not a command") return True + def main() -> None: """Run the admin console until the ``exit`` command is entered. diff --git a/src/part3/utils.py b/src/part3/utils.py index 9638ce40..a35f8b1c 100644 --- a/src/part3/utils.py +++ b/src/part3/utils.py @@ -18,11 +18,17 @@ the longest value it holds in that particular call. """ -from decimal import ROUND_HALF_UP, Decimal import re +from decimal import ROUND_HALF_UP, Decimal from typing import Final -from .storage import NAME_INDEX, PRICE_INDEX, PRODUCT_ID_INDEX, QUANTITY_INDEX, Product +from .storage import ( + NAME_INDEX, + PRICE_INDEX, + PRODUCT_ID_INDEX, + QUANTITY_INDEX, + Product, +) # Number of fractional digits every stored price is rounded to. @@ -63,15 +69,17 @@ def normalize_product_name(name: str) -> str: The result is an empty string when ``name`` holds nothing but whitespace. """ - + return re.sub(r"\s+", " ", name.strip().lower()) -def get_row_str_representation(values: list[list[Product]], row_index: int, lengths_columns: list[int]) -> str: +def get_row_str_representation( + values: list[list[str]], row_index: int, lengths_columns: list[int] +) -> str: """Render the row of table by index. Args: - values (list[list[Product]]): values + values (list[list[Product]]): values row_index (int): index of row lengths_columns (list[int]): list of lengths of columns @@ -79,12 +87,14 @@ def get_row_str_representation(values: list[list[Product]], row_index: int, leng str: string of the row of table by index """ return ( - f"| {f'{values[PRODUCT_ID_INDEX][row_index]}':<{lengths_columns[PRODUCT_ID_INDEX]}} |" + - f" {f'{values[NAME_INDEX][row_index]}':<{lengths_columns[NAME_INDEX]}} |" + - f" {f'{values[PRICE_INDEX][row_index]}':<{lengths_columns[PRICE_INDEX]}} |" + - f" {f'{values[QUANTITY_INDEX][row_index]}':<{lengths_columns[QUANTITY_INDEX]}} |" + "\n" + f"| {f'{values[PRODUCT_ID_INDEX][row_index]}':<{lengths_columns[PRODUCT_ID_INDEX]}} |" + + f" {f'{values[NAME_INDEX][row_index]}':<{lengths_columns[NAME_INDEX]}} |" + + f" {f'{values[PRICE_INDEX][row_index]}':<{lengths_columns[PRICE_INDEX]}} |" + + f" {f'{values[QUANTITY_INDEX][row_index]}':<{lengths_columns[QUANTITY_INDEX]}} |" + + "\n" ) + def get_horizonal_line_str(lengths_columns: list[int]) -> str: """Render the dashed separator row. @@ -96,12 +106,14 @@ def get_horizonal_line_str(lengths_columns: list[int]) -> str: """ return ( - f"|{'-' * (lengths_columns[PRODUCT_ID_INDEX] + 2)}|" + - f"{'-' * (lengths_columns[NAME_INDEX] + 2)}|" + - f"{'-' * (lengths_columns[PRICE_INDEX] + 2)}|" + - f"{'-' * (lengths_columns[QUANTITY_INDEX] + 2)}|" + "\n" + f"|{'-' * (lengths_columns[PRODUCT_ID_INDEX] + 2)}|" + + f"{'-' * (lengths_columns[NAME_INDEX] + 2)}|" + + f"{'-' * (lengths_columns[PRICE_INDEX] + 2)}|" + + f"{'-' * (lengths_columns[QUANTITY_INDEX] + 2)}|" + + "\n" ) + def get_storage_str_representation(storage: list[Product]) -> str: """Render the product store as a text table with data-sized columns. @@ -121,7 +133,7 @@ def get_storage_str_representation(storage: list[Product]) -> str: the header labels. """ values_columns: list[list[str]] = [ - [TABLE_HEADERS[PRODUCT_ID_INDEX]], + [TABLE_HEADERS[PRODUCT_ID_INDEX]], [TABLE_HEADERS[NAME_INDEX]], [TABLE_HEADERS[PRICE_INDEX]], [TABLE_HEADERS[QUANTITY_INDEX]], @@ -132,15 +144,17 @@ def get_storage_str_representation(storage: list[Product]) -> str: values_columns[PRICE_INDEX].append(str(product[PRICE_INDEX])) values_columns[QUANTITY_INDEX].append(str(product[QUANTITY_INDEX])) - lengths_colums: list[int] = [len(max(values_columns[PRODUCT_ID_INDEX], key=len)), - len(max(values_columns[NAME_INDEX], key=len)), - len(max(values_columns[PRICE_INDEX], key=len)), - len(max(values_columns[QUANTITY_INDEX], key=len)), + lengths_colums: list[int] = [ + len(max(values_columns[PRODUCT_ID_INDEX], key=len)), + len(max(values_columns[NAME_INDEX], key=len)), + len(max(values_columns[PRICE_INDEX], key=len)), + len(max(values_columns[QUANTITY_INDEX], key=len)), ] - output_string: str = get_row_str_representation(values_columns, 0, lengths_colums) + get_horizonal_line_str(lengths_colums) + output_string: str = get_row_str_representation( + values_columns, 0, lengths_colums + ) + get_horizonal_line_str(lengths_colums) for i in range(1, len(values_columns[0])): output_string += get_row_str_representation(values_columns, i, lengths_colums) return output_string - From 1fefaff9942ab686e8b8e9fa485ac94ee2e10a1d Mon Sep 17 00:00:00 2001 From: lev100908 Date: Sun, 11 Oct 2026 09:55:51 +0300 Subject: [PATCH 33/33] fix: drop trailing newline from show table --- src/part3/utils.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/part3/utils.py b/src/part3/utils.py index a35f8b1c..e62c1989 100644 --- a/src/part3/utils.py +++ b/src/part3/utils.py @@ -157,4 +157,4 @@ def get_storage_str_representation(storage: list[Product]) -> str: for i in range(1, len(values_columns[0])): output_string += get_row_str_representation(values_columns, i, lengths_colums) - return output_string + return output_string.removesuffix("\n")