From fc51f364bc14fffedfae56c787d36c69f8cf6591 Mon Sep 17 00:00:00 2001 From: lev100908 Date: Mon, 21 Sep 2026 18:58:10 +0300 Subject: [PATCH 01/43] 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/43] 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/43] 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/43] 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/43] 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/43] 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/43] 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/43] 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/43] 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/43] 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/43] 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/43] 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/43] 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/43] 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/43] 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/43] 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/43] 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/43] 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/43] 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/43] 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/43] 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/43] 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/43] 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/43] 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/43] 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/43] 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/43] 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/43] 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/43] 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/43] 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/43] 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/43] 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/43] 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") From a0d9113b8a992ec5628e6324675344c1bc280bee Mon Sep 17 00:00:00 2001 From: lev100908 Date: Tue, 27 Oct 2026 15:53:43 +0300 Subject: [PATCH 34/43] feat: add constants to storage.py --- src/part4/storage.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/part4/storage.py b/src/part4/storage.py index 9acedf07..f0034782 100644 --- a/src/part4/storage.py +++ b/src/part4/storage.py @@ -39,7 +39,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" From e708d84113ec6dfb8dfd28249e85b70937a6e3bc Mon Sep 17 00:00:00 2001 From: lev100908 Date: Tue, 27 Oct 2026 18:46:37 +0300 Subject: [PATCH 35/43] feat: add functionality to utils.py --- src/part4/utils.py | 52 +++++++++++++++++++++++++++++++++------------- 1 file changed, 37 insertions(+), 15 deletions(-) diff --git a/src/part4/utils.py b/src/part4/utils.py index d2a940ea..9ba4099b 100644 --- a/src/part4/utils.py +++ b/src/part4/utils.py @@ -19,9 +19,10 @@ """ from decimal import ROUND_HALF_UP, Decimal # noqa: F401 +import re from typing import Final -from .storage import ( # noqa: F401 +from storage import ( # noqa: F401 NAME_KEY, PRICE_KEY, QUANTITY_KEY, @@ -31,16 +32,13 @@ # 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 +51,7 @@ 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, ROUND_HALF_UP) def normalize_product_name(name: str) -> str: @@ -71,11 +68,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 re.sub(r"\s+", " ", name.strip().lower()) def get_storage_str_representation(storage: dict[str, Product]) -> str: @@ -96,5 +90,33 @@ 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 "" + columns_values: list[list[str]] = [ + [column_header] for column_header in TABLE_HEADERS + ] + + for product_id, product in storage.items(): + column_fields = (product_id, *product.values()) + for col_ind in range(len(column_fields)): + columns_values[col_ind].append(str(column_fields[col_ind])) + + width_columns: list[int] = [ + len(max(column_values, key=len)) for column_values in columns_values + ] + + output_str: str = "|" + + for col_ind in range(len(columns_values)): + output_str += f" {f'{columns_values[col_ind][0]}':<{width_columns[col_ind]}} |" + output_str += "\n|" + + for col_ind in range(len(columns_values)): + output_str += f"{'-' * (width_columns[col_ind] + 2)}|" + output_str += "\n" + + for row_ind in range(1, len(storage) + 1): + output_str += "|" + for col_ind in range(len(columns_values)): + output_str += f" {f'{columns_values[col_ind][row_ind]}':<{width_columns[col_ind]}} |" + output_str += "\n" + + return output_str.removesuffix("\n") From 157edcfe6c70649914ac77cb2c5705af2b945e5e Mon Sep 17 00:00:00 2001 From: lev100908 Date: Tue, 27 Oct 2026 18:57:59 +0300 Subject: [PATCH 36/43] feat: add generate_product_id and create_product --- src/part4/crud.py | 28 ++++++++++++++++++++++++---- src/part4/tempCodeRunnerFile.py | 1 + src/part4/utils.py | 2 +- 3 files changed, 26 insertions(+), 5 deletions(-) create mode 100644 src/part4/tempCodeRunnerFile.py diff --git a/src/part4/crud.py b/src/part4/crud.py index 471eff00..9b6cbb6e 100644 --- a/src/part4/crud.py +++ b/src/part4/crud.py @@ -41,8 +41,7 @@ def generate_product_id() -> str: Returns: A freshly generated UUID, stringified. """ - # TODO: реализуйте функцию - return "" + return str(uuid.uuid4()) def create_product( @@ -73,8 +72,29 @@ def create_product( and ``product_names`` are left unchanged and an explanatory message is printed. """ - # TODO: реализуйте функцию - return "" + name, price, quantity = fields + + name = normalize_product_name(name) + + 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[product_id] = { + NAME_KEY : name, + PRICE_KEY : normalize_price(price), + QUANTITY_KEY : quantity + } + + product_names.add(name) + + return product_id def read_product(storage: dict[str, Product], product_id: str) -> Product | None: diff --git a/src/part4/tempCodeRunnerFile.py b/src/part4/tempCodeRunnerFile.py new file mode 100644 index 00000000..1b31771b --- /dev/null +++ b/src/part4/tempCodeRunnerFile.py @@ -0,0 +1 @@ +from utils import normalize_price, normalize_product_name # noqa: F401 diff --git a/src/part4/utils.py b/src/part4/utils.py index 9ba4099b..861bdc0e 100644 --- a/src/part4/utils.py +++ b/src/part4/utils.py @@ -22,7 +22,7 @@ import re from typing import Final -from storage import ( # noqa: F401 +from .storage import ( # noqa: F401 NAME_KEY, PRICE_KEY, QUANTITY_KEY, From f8e685aac6d012d34fbd0727b2a6824cf860533b Mon Sep 17 00:00:00 2001 From: lev100908 Date: Tue, 27 Oct 2026 19:29:51 +0300 Subject: [PATCH 37/43] feat: add read_product and update_product --- src/part4/crud.py | 40 ++++++++++++++++++++++++++++----- src/part4/tempCodeRunnerFile.py | 2 +- 2 files changed, 36 insertions(+), 6 deletions(-) diff --git a/src/part4/crud.py b/src/part4/crud.py index 9b6cbb6e..b4e1e6bb 100644 --- a/src/part4/crud.py +++ b/src/part4/crud.py @@ -72,7 +72,7 @@ def create_product( and ``product_names`` are left unchanged and an explanatory message is printed. """ - name, price, quantity = fields + name, price, quantity = fields.values() name = normalize_product_name(name) @@ -108,8 +108,10 @@ 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( @@ -149,8 +151,36 @@ def update_product( and an explanatory message is printed. Renaming a product to its own current name is allowed. """ - # TODO: реализуйте функцию - return {} + if product_id not in storage: + print(f"no product with id {product_id}") + return None + + product = storage[product_id] + + if NAME_KEY in fields: + name = normalize_product_name(fields[NAME_KEY]) + if not name: + print("product name must not be blank") + return None + + old_name = product[NAME_KEY] + + if name != old_name and name in product_names: + print(f"product name {name} is already taken") + return None + + fields[NAME_KEY] = name + + if old_name != name: + product_names.remove(old_name) + product_names.add(name) + + if PRICE_KEY in fields: + fields[PRICE_KEY] = normalize_price(fields[PRICE_KEY]) + + product.update(fields) + + return product def delete_product( diff --git a/src/part4/tempCodeRunnerFile.py b/src/part4/tempCodeRunnerFile.py index 1b31771b..64776781 100644 --- a/src/part4/tempCodeRunnerFile.py +++ b/src/part4/tempCodeRunnerFile.py @@ -1 +1 @@ -from utils import normalize_price, normalize_product_name # noqa: F401 +from .utils import normalize_price, normalize_product_name # noqa: F401 From df2e19ef2b7f01473bb691566ca3b320150afeb2 Mon Sep 17 00:00:00 2001 From: lev100908 Date: Tue, 27 Oct 2026 19:35:11 +0300 Subject: [PATCH 38/43] feat: add delete_product --- src/part4/crud.py | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/part4/crud.py b/src/part4/crud.py index b4e1e6bb..26723cb2 100644 --- a/src/part4/crud.py +++ b/src/part4/crud.py @@ -203,5 +203,11 @@ 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 + + del storage[product_id] + product_names.remove(storage[product_id][NAME_KEY]) + + return product_id From bc918438dd7d6c82c444187865193c0ef5142521 Mon Sep 17 00:00:00 2001 From: lev100908 Date: Tue, 27 Oct 2026 20:02:07 +0300 Subject: [PATCH 39/43] feat: add functions add_to_cart and remove_from_cart --- src/part4/cart.py | 54 ++++++++++++++++++++++++++++++--- src/part4/tempCodeRunnerFile.py | 1 - 2 files changed, 49 insertions(+), 6 deletions(-) delete mode 100644 src/part4/tempCodeRunnerFile.py diff --git a/src/part4/cart.py b/src/part4/cart.py index aed9bb72..0827a94f 100644 --- a/src/part4/cart.py +++ b/src/part4/cart.py @@ -9,7 +9,9 @@ an explanatory message to stdout and returns ``None``. """ -from .storage import Product +from .storage import Product, QUANTITY_KEY + +from .crud import read_product, update_product # TODO: при необходимости добавьте свои вспомогательные функции @@ -46,8 +48,26 @@ def add_to_cart( ``None`` when the product is unknown or the store cannot cover the request. """ - # TODO: реализуйте функцию - return 0 + searched_product = read_product(storage, product_id) + + storage_quantity = searched_product[QUANTITY_KEY] + + if storage_quantity < quantity: + print(f"not enough stock for product {product_id}: {storage_quantity} available, {quantity} requested") + return None + + storage_quantity -= quantity + + update_product( + storage, + product_names, + product_id, + {QUANTITY_KEY : storage_quantity} + ) + + cart[product_id] = cart.get(cart[product_id], 0) + quantity + + return cart[product_id] def remove_from_cart( @@ -83,5 +103,29 @@ 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") + + cart_quantity = cart[product_id] + + if cart_quantity < quantity: + print(f"cart holds only {cart_quantity} unit(s) of product {product_id}, cannot remove {quantity}") + return None + + searched_product = read_product(storage, product_id) + + update_product( + storage, + product_names, + product_id, + {QUANTITY_KEY : searched_product[QUANTITY_KEY] + quantity} + ) + + cart_quantity -= quantity + cart[product_id] = cart_quantity + + if not cart_quantity: + del cart[product_id] + + return cart_quantity diff --git a/src/part4/tempCodeRunnerFile.py b/src/part4/tempCodeRunnerFile.py deleted file mode 100644 index 64776781..00000000 --- a/src/part4/tempCodeRunnerFile.py +++ /dev/null @@ -1 +0,0 @@ -from .utils import normalize_price, normalize_product_name # noqa: F401 From 95d091708e598913709857c4a385b1130c1fb56f Mon Sep 17 00:00:00 2001 From: lev100908 Date: Wed, 28 Oct 2026 19:53:34 +0300 Subject: [PATCH 40/43] feat: rewrite run_admin.py and add several versions of update in console --- src/part4/run_admin.py | 83 +++++++++++++++++++++++++++++++++++++----- 1 file changed, 74 insertions(+), 9 deletions(-) diff --git a/src/part4/run_admin.py b/src/part4/run_admin.py index 2247b29b..cd539bcd 100644 --- a/src/part4/run_admin.py +++ b/src/part4/run_admin.py @@ -29,21 +29,33 @@ """ from decimal import Decimal, InvalidOperation # noqa: F401 +import re from typing import Final -from .crud import ( # noqa: F401 +from crud import ( # noqa: F401 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 # noqa: F401 +from utils import get_storage_str_representation # noqa: F401 # 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,8 @@ def print_result(result: object) -> None: operation already reported its own failure, so nothing is printed in that case. """ - # TODO: реализуйте функцию (используйте своё решение части 3) + if result: + print(result) def run_command( @@ -91,8 +104,60 @@ 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() + 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, product_names, + {NAME_KEY : " ".join(name), + PRICE_KEY : Decimal(price), + QUANTITY_KEY : int(quantity) + }) + ) + return True + + case ["read", id]: + print_result(read_product(storage, id)) + return True + case ["update", id, *name, price, quantity] if \ + bool(re.match(r"(([1-9][0-9]*|0)[.][0-9]*)|([1-9][0-9]*)", price)): + print_result( + update_product(storage, product_names, id, + {NAME_KEY : " ".join(name), + PRICE_KEY : Decimal(price), + QUANTITY_KEY : int(quantity) + }) + ) + return True + case ["update", id, *name, price] if \ + bool(re.match(r"(([1-9][0-9]*|0)[.][0-9]*)|([1-9][0-9]*)", price)): + print_result( + update_product(storage, product_names, id, + {NAME_KEY : " ".join(name), + PRICE_KEY : Decimal(price), + }) + ) + return True + case ["update", id, *name]: + print_result( + update_product(storage, product_names, id, + {NAME_KEY : " ".join(name), + }) + ) + return True + case ["delete", id]: + print_result(delete_product(storage, product_names, id)) + return True + case _: + print(f"'{line}' is not a command") + return True def main() -> None: From 45b76d3a734f9e95b80508aca50b2c7ef61f1614 Mon Sep 17 00:00:00 2001 From: lev100908 Date: Wed, 28 Oct 2026 20:03:02 +0300 Subject: [PATCH 41/43] fix: solve some problems --- src/part4/cart.py | 10 +++++----- src/part4/crud.py | 8 ++++---- src/part4/utils.py | 7 ++----- 3 files changed, 11 insertions(+), 14 deletions(-) diff --git a/src/part4/cart.py b/src/part4/cart.py index 0827a94f..bcf9a6b1 100644 --- a/src/part4/cart.py +++ b/src/part4/cart.py @@ -13,10 +13,6 @@ from .crud import read_product, update_product - -# TODO: при необходимости добавьте свои вспомогательные функции - - def add_to_cart( storage: dict[str, Product], product_names: set[str], @@ -50,6 +46,9 @@ def add_to_cart( """ searched_product = read_product(storage, product_id) + if not searched_product: + return None + storage_quantity = searched_product[QUANTITY_KEY] if storage_quantity < quantity: @@ -65,7 +64,7 @@ def add_to_cart( {QUANTITY_KEY : storage_quantity} ) - cart[product_id] = cart.get(cart[product_id], 0) + quantity + cart[product_id] = cart.get(product_id, 0) + quantity return cart[product_id] @@ -106,6 +105,7 @@ def remove_from_cart( if product_id not in cart: print(f"product {product_id} is not in the cart") + return None cart_quantity = cart[product_id] diff --git a/src/part4/crud.py b/src/part4/crud.py index 26723cb2..1b677d6d 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: @@ -207,7 +207,7 @@ def delete_product( print(f"no product with id {product_id}") return None - del storage[product_id] product_names.remove(storage[product_id][NAME_KEY]) + del storage[product_id] return product_id diff --git a/src/part4/utils.py b/src/part4/utils.py index 861bdc0e..c5e5c4ee 100644 --- a/src/part4/utils.py +++ b/src/part4/utils.py @@ -18,14 +18,11 @@ 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 import re from typing import Final -from .storage import ( # noqa: F401 - NAME_KEY, - PRICE_KEY, - QUANTITY_KEY, +from .storage import ( Product, ) From 19a2fb1be146020d347f3535509cf25a9872201c Mon Sep 17 00:00:00 2001 From: lev100908 Date: Wed, 28 Oct 2026 20:20:42 +0300 Subject: [PATCH 42/43] fix: solve some problems refactor: improve code style --- src/part4/cart.py | 28 ++++++++------- src/part4/crud.py | 6 ++-- src/part4/run_admin.py | 79 ++++++++++++++++++++++++++---------------- src/part4/utils.py | 8 +++-- 4 files changed, 73 insertions(+), 48 deletions(-) diff --git a/src/part4/cart.py b/src/part4/cart.py index bcf9a6b1..1a265a4e 100644 --- a/src/part4/cart.py +++ b/src/part4/cart.py @@ -9,9 +9,9 @@ an explanatory message to stdout and returns ``None``. """ -from .storage import Product, QUANTITY_KEY - from .crud import read_product, update_product +from .storage import QUANTITY_KEY, Product + def add_to_cart( storage: dict[str, Product], @@ -52,17 +52,14 @@ def add_to_cart( storage_quantity = searched_product[QUANTITY_KEY] if storage_quantity < quantity: - print(f"not enough stock for product {product_id}: {storage_quantity} available, {quantity} requested") + print( + f"not enough stock for product {product_id}: {storage_quantity} available, {quantity} requested" + ) return None storage_quantity -= quantity - update_product( - storage, - product_names, - product_id, - {QUANTITY_KEY : storage_quantity} - ) + update_product(storage, product_names, product_id, {QUANTITY_KEY: storage_quantity}) cart[product_id] = cart.get(product_id, 0) + quantity @@ -108,21 +105,26 @@ def remove_from_cart( return None cart_quantity = cart[product_id] - + if cart_quantity < quantity: - print(f"cart holds only {cart_quantity} unit(s) of product {product_id}, cannot remove {quantity}") + print( + f"cart holds only {cart_quantity} unit(s) of product {product_id}, cannot remove {quantity}" + ) return None searched_product = read_product(storage, product_id) + if not searched_product: + return None + update_product( storage, product_names, product_id, - {QUANTITY_KEY : searched_product[QUANTITY_KEY] + quantity} + {QUANTITY_KEY: searched_product[QUANTITY_KEY] + quantity}, ) - cart_quantity -= quantity + cart_quantity -= quantity cart[product_id] = cart_quantity if not cart_quantity: diff --git a/src/part4/crud.py b/src/part4/crud.py index 1b677d6d..fdfc75c0 100644 --- a/src/part4/crud.py +++ b/src/part4/crud.py @@ -87,9 +87,9 @@ def create_product( product_id = generate_product_id() storage[product_id] = { - NAME_KEY : name, - PRICE_KEY : normalize_price(price), - QUANTITY_KEY : quantity + NAME_KEY: name, + PRICE_KEY: normalize_price(price), + QUANTITY_KEY: quantity, } product_names.add(name) diff --git a/src/part4/run_admin.py b/src/part4/run_admin.py index cd539bcd..3da35390 100644 --- a/src/part4/run_admin.py +++ b/src/part4/run_admin.py @@ -28,18 +28,18 @@ is left untouched and the loop keeps running; only ``exit`` stops it. """ -from decimal import Decimal, InvalidOperation # noqa: F401 import re +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) @@ -115,43 +115,64 @@ def run_command( return True case ["create", *name, price, quantity]: print_result( - create_product(storage, product_names, - {NAME_KEY : " ".join(name), - PRICE_KEY : Decimal(price), - QUANTITY_KEY : int(quantity) - }) + create_product( + storage, + product_names, + { + NAME_KEY: " ".join(name), + PRICE_KEY: Decimal(price), + QUANTITY_KEY: int(quantity), + }, + ) ) return True - + case ["read", id]: print_result(read_product(storage, id)) return True - case ["update", id, *name, price, quantity] if \ - bool(re.match(r"(([1-9][0-9]*|0)[.][0-9]*)|([1-9][0-9]*)", price)): + case ["update", id, *name, price, quantity] if bool( + re.match(r"(([1-9][0-9]*|0)[.][0-9]*)|([1-9][0-9]*)", price) + ): print_result( - update_product(storage, product_names, id, - {NAME_KEY : " ".join(name), - PRICE_KEY : Decimal(price), - QUANTITY_KEY : int(quantity) - }) + update_product( + storage, + product_names, + id, + { + NAME_KEY: " ".join(name), + PRICE_KEY: Decimal(price), + QUANTITY_KEY: int(quantity), + }, + ) ) return True - case ["update", id, *name, price] if \ - bool(re.match(r"(([1-9][0-9]*|0)[.][0-9]*)|([1-9][0-9]*)", price)): + case ["update", id, *name, price] if bool( + re.match(r"(([1-9][0-9]*|0)[.][0-9]*)|([1-9][0-9]*)", price) + ): print_result( - update_product(storage, product_names, id, - {NAME_KEY : " ".join(name), - PRICE_KEY : Decimal(price), - }) + update_product( + storage, + product_names, + id, + { + NAME_KEY: " ".join(name), + PRICE_KEY: Decimal(price), + }, + ) ) return True case ["update", id, *name]: - print_result( - update_product(storage, product_names, id, - {NAME_KEY : " ".join(name), - }) - ) - return True + print_result( + update_product( + storage, + product_names, + id, + { + NAME_KEY: " ".join(name), + }, + ) + ) + return True case ["delete", id]: print_result(delete_product(storage, product_names, id)) return True diff --git a/src/part4/utils.py b/src/part4/utils.py index c5e5c4ee..118fe442 100644 --- a/src/part4/utils.py +++ b/src/part4/utils.py @@ -18,8 +18,8 @@ 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 ( @@ -90,7 +90,7 @@ def get_storage_str_representation(storage: dict[str, Product]) -> str: columns_values: list[list[str]] = [ [column_header] for column_header in TABLE_HEADERS ] - + for product_id, product in storage.items(): column_fields = (product_id, *product.values()) for col_ind in range(len(column_fields)): @@ -113,7 +113,9 @@ def get_storage_str_representation(storage: dict[str, Product]) -> str: for row_ind in range(1, len(storage) + 1): output_str += "|" for col_ind in range(len(columns_values)): - output_str += f" {f'{columns_values[col_ind][row_ind]}':<{width_columns[col_ind]}} |" + output_str += ( + f" {f'{columns_values[col_ind][row_ind]}':<{width_columns[col_ind]}} |" + ) output_str += "\n" return output_str.removesuffix("\n") From 2df07007f561be9af010bb51e24a3e6e9b075fc8 Mon Sep 17 00:00:00 2001 From: lev100908 Date: Wed, 28 Oct 2026 20:30:05 +0300 Subject: [PATCH 43/43] style: fix style --- src/part4/run_admin.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/part4/run_admin.py b/src/part4/run_admin.py index 3da35390..78246e83 100644 --- a/src/part4/run_admin.py +++ b/src/part4/run_admin.py @@ -42,7 +42,6 @@ from .utils import get_storage_str_representation -# TODO: задайте приглашение и текст справки (используйте своё решение части 3) PROMPT: Final[str] = "admin> " HELP_TEXT: Final[str] = """Available commands: help show this message @@ -51,6 +50,8 @@ create add a product, print its new id read print the product with that id update overwrite that product's fields + update overwrite that product's fields + 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 @@ -130,8 +131,8 @@ def run_command( case ["read", id]: print_result(read_product(storage, id)) return True - case ["update", id, *name, price, quantity] if bool( - re.match(r"(([1-9][0-9]*|0)[.][0-9]*)|([1-9][0-9]*)", price) + case ["update", id, *name, price, quantity] if re.match( + r"(([1-9][0-9]*|0)[.][0-9]*)|([1-9][0-9]*)", price ): print_result( update_product( @@ -146,8 +147,8 @@ def run_command( ) ) return True - case ["update", id, *name, price] if bool( - re.match(r"(([1-9][0-9]*|0)[.][0-9]*)|([1-9][0-9]*)", price) + case ["update", id, *name, price] if re.match( + r"(([1-9][0-9]*|0)[.][0-9]*)|([1-9][0-9]*)", price ): print_result( update_product(