From e120dc260f4c338360944fb7b54fb108c4487366 Mon Sep 17 00:00:00 2001 From: Roman Shkryl Date: Sun, 20 Sep 2026 23:34:24 +0300 Subject: [PATCH 01/14] Added and changed constants. --- src/part1/constants.py | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/src/part1/constants.py b/src/part1/constants.py index 9abfbba2..a01b7b98 100644 --- a/src/part1/constants.py +++ b/src/part1/constants.py @@ -15,24 +15,23 @@ from typing import Final -# TODO: замените заглушки (0) на корректные значения, см. TASK.md. -# Все константы, зависящие от ёмкостей *_BITS, должны вычисляться из них. + # Twitter's original Snowflake epoch: 2010-11-04 01:42:54.657 UTC. -EPOCH_MS_DEFAULT: Final[int] = 0 +EPOCH_MS_DEFAULT: Final[int] = 1288834974657 # Node identifier used when the caller does not supply one. -NODE_ID_DEFAULT: Final[int] = 0 +NODE_ID_DEFAULT: Final[int] = 1 # Width of each field, in bits. -TIMESTAMP_BITS: Final[int] = 0 -NODE_ID_BITS: Final[int] = 0 -SEQUENCE_ID_BITS: Final[int] = 0 +TIMESTAMP_BITS: Final[int] = 41 +NODE_ID_BITS: Final[int] = 10 +SEQUENCE_ID_BITS: Final[int] = 12 # Largest value each field can hold. -TIMESTAMP_MS_MAX: Final[int] = 0 -NODE_ID_MAX: Final[int] = 0 -SEQUENCE_ID_MAX: Final[int] = 0 +TIMESTAMP_MS_MAX: Final[int] = 2 ** TIMESTAMP_BITS - 1 +NODE_ID_MAX: Final[int] = 2 ** NODE_ID_BITS - 1 +SEQUENCE_ID_MAX: Final[int] = 2 ** SEQUENCE_ID_BITS - 1 # Здесь можно добавить собственные вспомогательные константы # (например, сдвиги полей при сборке идентификатора). From 0aebe01c8b4a70035f7f2f09135a84fb68718728 Mon Sep 17 00:00:00 2001 From: Roman Shkryl Date: Sun, 20 Sep 2026 23:44:07 +0300 Subject: [PATCH 02/14] Added function 'read_current_millis' --- src/part1/snowflake.py | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/src/part1/snowflake.py b/src/part1/snowflake.py index d3abf050..81bed18d 100644 --- a/src/part1/snowflake.py +++ b/src/part1/snowflake.py @@ -25,17 +25,10 @@ def read_current_millis(epoch_ms: int) -> int: - """Read the number of milliseconds elapsed since the custom epoch. + current_time = int(time.time() * 1000) - Args: - epoch_ms: The custom epoch expressed as Unix milliseconds. - Returns: - The count of whole milliseconds between ``epoch_ms`` and now. May be - negative if ``epoch_ms`` lies in the future. - """ - # TODO: реализуйте функцию - return 0 + return current_time - epoch_ms def decode_timestamp_ms(snowflake_id: int, epoch_ms: int = EPOCH_MS_DEFAULT) -> int: From 5ce5d0d5f6c288b905c4afd6f45efffd0c70ceef Mon Sep 17 00:00:00 2001 From: Roman Shkryl Date: Mon, 21 Sep 2026 15:05:42 +0300 Subject: [PATCH 03/14] modifided 'decode_timestamp_ms' --- src/part1/snowflake.py | 23 ++--------------------- 1 file changed, 2 insertions(+), 21 deletions(-) diff --git a/src/part1/snowflake.py b/src/part1/snowflake.py index 81bed18d..2b2e3f18 100644 --- a/src/part1/snowflake.py +++ b/src/part1/snowflake.py @@ -32,32 +32,13 @@ def read_current_millis(epoch_ms: int) -> int: def decode_timestamp_ms(snowflake_id: int, epoch_ms: int = EPOCH_MS_DEFAULT) -> int: - """Read the timestamp field out of a Snowflake identifier. + default_time = snowflake_id >> 22 - Args: - snowflake_id: An identifier produced against the same epoch. - epoch_ms: The epoch the identifier was generated against. Defaults to - the original Twitter epoch (2010-11-04 01:42:54.657 UTC). - Returns: - The absolute Unix time in milliseconds at which the identifier was - generated. - """ - # TODO: реализуйте функцию - return 0 + return default_time + epoch_ms def decode_node_id(snowflake_id: int) -> int: - """Read the node identifier field out of a Snowflake identifier. - - Args: - snowflake_id: An identifier produced by :func:`generate_snowflake_id`. - - Returns: - The node identifier packed into ``snowflake_id``, in the range - ``[0, NODE_ID_MAX]``. - """ - # TODO: реализуйте функцию return 0 From 2de06967bd4a7fa29568b2d34475569100661f2e Mon Sep 17 00:00:00 2001 From: Roman Shkryl Date: Mon, 21 Sep 2026 15:10:30 +0300 Subject: [PATCH 04/14] modificed 'decode_node_id' --- src/part1/snowflake.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/part1/snowflake.py b/src/part1/snowflake.py index 2b2e3f18..9798a340 100644 --- a/src/part1/snowflake.py +++ b/src/part1/snowflake.py @@ -39,7 +39,9 @@ def decode_timestamp_ms(snowflake_id: int, epoch_ms: int = EPOCH_MS_DEFAULT) -> def decode_node_id(snowflake_id: int) -> int: - return 0 + node_id = (snowflake_id >> 12) & 0b1111111111 + + return node_id def decode_sequence_id(snowflake_id: int) -> int: From b1f51c48c003d628162ba24a1ad2af6706686849 Mon Sep 17 00:00:00 2001 From: Roman Shkryl Date: Mon, 21 Sep 2026 15:12:49 +0300 Subject: [PATCH 05/14] modificed 'decode_sequence_id' --- src/part1/snowflake.py | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) diff --git a/src/part1/snowflake.py b/src/part1/snowflake.py index 9798a340..4d6217af 100644 --- a/src/part1/snowflake.py +++ b/src/part1/snowflake.py @@ -45,17 +45,9 @@ def decode_node_id(snowflake_id: int) -> int: def decode_sequence_id(snowflake_id: int) -> int: - """Read the sequence counter field out of a Snowflake identifier. + sequence_id = snowflake_id & 0b111111111111 - Args: - snowflake_id: An identifier produced by :func:`generate_snowflake_id`. - - Returns: - The per-millisecond sequence counter packed into ``snowflake_id``, in - the range ``[0, SEQUENCE_ID_MAX]``. - """ - # TODO: реализуйте функцию - return 0 + return sequence_id def generate_snowflake_id( From 2af0c8083b601df14b0e6db9e064baab9a93d7f9 Mon Sep 17 00:00:00 2001 From: Roman Shkryl Date: Mon, 21 Sep 2026 15:33:24 +0300 Subject: [PATCH 06/14] modificed 'generate_snowflake_id' --- src/part1/snowflake.py | 42 +++++++++++++++++------------------------- 1 file changed, 17 insertions(+), 25 deletions(-) diff --git a/src/part1/snowflake.py b/src/part1/snowflake.py index 4d6217af..2abce632 100644 --- a/src/part1/snowflake.py +++ b/src/part1/snowflake.py @@ -55,28 +55,20 @@ def generate_snowflake_id( node_id: int = NODE_ID_DEFAULT, epoch_ms: int = EPOCH_MS_DEFAULT, ) -> int | None: - """Build and return a Snowflake identifier for the current millisecond. - - The function is stateless: the caller passes the per-millisecond sequence - counter explicitly. It is the caller's responsibility to increment - ``sequence_id`` for identifiers minted within the same millisecond and to - reset it once the clock advances. - - Args: - sequence_id: The per-millisecond sequence counter, in the range - ``[0, SEQUENCE_ID_MAX]``. - node_id: The identifier of this node, in the range ``[0, NODE_ID_MAX]``. - Optional; defaults to ``NODE_ID_DEFAULT``. - epoch_ms: The start of the epoch as Unix milliseconds. Optional; - defaults to the original Twitter epoch (2010-11-04 01:42:54.657 - UTC). - - Returns: - The Snowflake identifier as a positive 63-bit integer, or ``None`` if - ``node_id`` is outside ``[0, NODE_ID_MAX]``, ``sequence_id`` is outside - ``[0, SEQUENCE_ID_MAX]``, or the elapsed time no longer fits in the - timestamp field (roughly 69 years after ``epoch_ms``). In each of those - cases an explanatory message is printed to stdout first. - """ - # TODO: реализуйте функцию - return 0 + + if (node_id < 0 or node_id > NODE_ID_MAX): + print('node_id must be in range[0; 1023]') + return None + + + elif (sequence_id < 0 or sequence_id > SEQUENCE_ID_MAX): + print('sequence_id must be in [0; 4095]') + return None + + + elif (decode_timestamp_ms(epoch_ms) > TIMESTAMP_MS_MAX): + print('overflows') + return None + + + return read_current_millis(epoch_ms) << 22 | node_id << 12 | sequence_id From ca03d8378031869a5d0bb99b9bec304251ed760f Mon Sep 17 00:00:00 2001 From: Roman Shkryl Date: Mon, 21 Sep 2026 15:46:10 +0300 Subject: [PATCH 07/14] fixed shorcoming --- src/part1/constants.py | 28 +++------------------------- src/part1/snowflake.py | 39 ++++++++------------------------------- 2 files changed, 11 insertions(+), 56 deletions(-) diff --git a/src/part1/constants.py b/src/part1/constants.py index a01b7b98..afc19ecf 100644 --- a/src/part1/constants.py +++ b/src/part1/constants.py @@ -1,37 +1,15 @@ -"""Bit layout and default epoch for the Twitter Snowflake ID generator. - -A Snowflake identifier is a 63-bit positive integer packed as follows, from -the most significant bit downwards: - - 1 bit unused sign bit, always zero - 41 bits milliseconds elapsed since a custom epoch - 10 bits node identifier - 12 bits per-millisecond sequence counter - -The shift and mask constants should be derived from the bit widths so that -changing a width keeps everything else consistent. -""" - from typing import Final - - -# Twitter's original Snowflake epoch: 2010-11-04 01:42:54.657 UTC. EPOCH_MS_DEFAULT: Final[int] = 1288834974657 -# Node identifier used when the caller does not supply one. NODE_ID_DEFAULT: Final[int] = 1 -# Width of each field, in bits. 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] = 2 ** TIMESTAMP_BITS - 1 -NODE_ID_MAX: Final[int] = 2 ** NODE_ID_BITS - 1 -SEQUENCE_ID_MAX: Final[int] = 2 ** SEQUENCE_ID_BITS - 1 -# Здесь можно добавить собственные вспомогательные константы -# (например, сдвиги полей при сборке идентификатора). +TIMESTAMP_MS_MAX: Final[int] = 2**TIMESTAMP_BITS - 1 +NODE_ID_MAX: Final[int] = 2**NODE_ID_BITS - 1 +SEQUENCE_ID_MAX: Final[int] = 2**SEQUENCE_ID_BITS - 1 diff --git a/src/part1/snowflake.py b/src/part1/snowflake.py index 2abce632..7c441711 100644 --- a/src/part1/snowflake.py +++ b/src/part1/snowflake.py @@ -1,21 +1,6 @@ -"""Twitter Snowflake identifier generator. +import time -Snowflake produces roughly time-ordered 64-bit integer identifiers without -coordination between nodes. Each identifier packs the milliseconds elapsed -since a custom epoch, a node identifier and a per-millisecond sequence counter -into a single 63-bit positive integer (see ``constants`` for the layout). - -The public entry point is :func:`generate_snowflake_id`. It is stateless: the -caller passes the sequence counter on every call and is responsible for -advancing it within a millisecond and resetting it when the clock ticks over. - -Each packed field can be read back on its own with :func:`decode_timestamp_ms`, -:func:`decode_node_id` and :func:`decode_sequence_id`. -""" - -import time # noqa: F401 - -from .constants import ( # noqa: F401 +from .constants import ( EPOCH_MS_DEFAULT, NODE_ID_DEFAULT, NODE_ID_MAX, @@ -27,14 +12,12 @@ def read_current_millis(epoch_ms: int) -> int: current_time = int(time.time() * 1000) - return current_time - epoch_ms def decode_timestamp_ms(snowflake_id: int, epoch_ms: int = EPOCH_MS_DEFAULT) -> int: default_time = snowflake_id >> 22 - return default_time + epoch_ms @@ -55,20 +38,14 @@ def generate_snowflake_id( node_id: int = NODE_ID_DEFAULT, epoch_ms: int = EPOCH_MS_DEFAULT, ) -> int | None: - - if (node_id < 0 or node_id > NODE_ID_MAX): - print('node_id must be in range[0; 1023]') + if node_id < 0 or node_id > NODE_ID_MAX: + print("node_id must be in range[0; 1023]") return None - - - elif (sequence_id < 0 or sequence_id > SEQUENCE_ID_MAX): - print('sequence_id must be in [0; 4095]') + elif sequence_id < 0 or sequence_id > SEQUENCE_ID_MAX: + print("sequence_id must be in [0; 4095]") return None - - - elif (decode_timestamp_ms(epoch_ms) > TIMESTAMP_MS_MAX): - print('overflows') + elif decode_timestamp_ms(epoch_ms) > TIMESTAMP_MS_MAX: + print("overflows") return None - return read_current_millis(epoch_ms) << 22 | node_id << 12 | sequence_id From a1ea3f21e30e414ce0642e4a0f4cf7543de0d061 Mon Sep 17 00:00:00 2001 From: Roman Shkryl Date: Tue, 29 Sep 2026 21:08:49 +0300 Subject: [PATCH 08/14] Modificed storage.py --- src/part1/snowflake.py | 2 +- src/part2/storage.py | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/part1/snowflake.py b/src/part1/snowflake.py index 7c441711..8f332ff1 100644 --- a/src/part1/snowflake.py +++ b/src/part1/snowflake.py @@ -48,4 +48,4 @@ def generate_snowflake_id( print("overflows") return None - return read_current_millis(epoch_ms) << 22 | node_id << 12 | sequence_id + return read_current_millis(epoch_ms) << 22 | node_id << 12 | sequence_id \ No newline at end of file diff --git a/src/part2/storage.py b/src/part2/storage.py index b63d5fc7..35821c5f 100644 --- a/src/part2/storage.py +++ b/src/part2/storage.py @@ -26,9 +26,9 @@ # 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 79a15174617d03c4de9893bdd3f83f404d07b039 Mon Sep 17 00:00:00 2001 From: Roman Shkryl Date: Tue, 29 Sep 2026 21:23:52 +0300 Subject: [PATCH 09/14] Modificed utils.py --- src/part2/utils.py | 16 ++++------------ 1 file changed, 4 insertions(+), 12 deletions(-) diff --git a/src/part2/utils.py b/src/part2/utils.py index ec0348d3..7f6e5322 100644 --- a/src/part2/utils.py +++ b/src/part2/utils.py @@ -11,19 +11,11 @@ # TODO: задайте число знаков после запятой и шаг квантования -PRICE_PRECISION: Final[int] = 0 -PRICE_STEP: Final = Decimal(0) +PRICE_PRECISION: Final[int] = 2 +PRICE_STEP: Final = Decimal(1).scaleb(-PRICE_PRECISION) def normalize_price(price: Decimal) -> Decimal: - """Round a price to the precision every stored record uses. + correct_price = price.quantize(PRICE_STEP, rounding=ROUND_HALF_UP) - Args: - price: The raw price amount. - - Returns: - ``price`` quantised to :data:`PRICE_PRECISION` fractional digits, - with halves rounded up. - """ - # TODO: реализуйте функцию - return Decimal(0) + return correct_price From 512f4c329f302b85b6c235c7501d6f11e861b4a1 Mon Sep 17 00:00:00 2001 From: Roman Shkryl Date: Tue, 29 Sep 2026 21:58:58 +0300 Subject: [PATCH 10/14] modificed crud.py --- src/part2/crud.py | 106 +++++++++++++++------------------------------- 1 file changed, 34 insertions(+), 72 deletions(-) diff --git a/src/part2/crud.py b/src/part2/crud.py index d026cbcb..5cafa888 100644 --- a/src/part2/crud.py +++ b/src/part2/crud.py @@ -24,97 +24,59 @@ def generate_product_id(storage: list[Product]) -> int: - """Choose the identifier for the next product added to ``storage``. + if len(storage) == 0: + return PRODUCT_ID_MIN + mx = max(product[PRODUCT_ID_INDEX] for product in storage) + 1 - Args: - storage: The product store to inspect. - - Returns: - One past the greatest identifier currently held in ``storage``, or - :data:`~src.part2.storage.PRODUCT_ID_MIN` when ``storage`` is - empty. - """ - # TODO: реализуйте функцию - return 0 + return mx def create_product( storage: list[Product], fields: tuple[str, Decimal, int] ) -> int | None: - """Append a new product to ``storage`` and return its new identifier. + for product in storage: + if product[NAME_INDEX] == fields[0]: + print(f"product name {product[NAME_INDEX]} is already taken.") + return None - Args: - storage: The product store to append to; modified in place on - success. - fields: A ``(name, price, quantity)`` tuple describing the product. - ``price`` is a :class:`~decimal.Decimal` amount and is rounded - to the stored money precision before it is saved. + product_id = generate_product_id(storage) + name, price, quantity = fields + new_product = (product_id, name, normalize_price(price), quantity) + + storage.append(new_product) - Returns: - The identifier generated for the new product, or ``None`` when a - product with the same name already exists. In the ``None`` case - ``storage`` is left unchanged and a message naming the clashing - name is printed. - """ - # TODO: реализуйте функцию - return 0 + return product_id def read_product(storage: list[Product], product_id: int) -> Product | None: - """Return the product stored under ``product_id``. - - Args: - storage: The product store to search. - product_id: The identifier to look up. - - Returns: - The matching ``(product_id, name, price, quantity)`` record, or - ``None`` when no product carries that identifier (a message is - printed in that case). - """ - # 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( storage: list[Product], product_id: int, fields: tuple[str, Decimal, int], ) -> Product | None: - """Overwrite the fields of the product stored under ``product_id``. + for i in range(len(storage)): + if storage[i][PRODUCT_ID_INDEX] == product_id: + name, price, quality = fields + new_product = (product_id, name, normalize_price(price), quality) + storage[i] = new_product + return new_product - The identifier itself is preserved; only ``name``, ``price`` and - ``quantity`` are replaced. - - Args: - storage: The product store to modify; the matching record is - replaced in place on success. - product_id: The identifier of the product to change. - fields: A ``(name, price, quantity)`` tuple with the new values. - ``price`` is a :class:`~decimal.Decimal` amount and is rounded - to the stored money precision before it is saved. - - Returns: - The updated ``(product_id, name, price, quantity)`` record, or - ``None`` when no product carries that identifier (``storage`` is - left unchanged and a message is printed). - """ - # TODO: реализуйте функцию - return (0, "", Decimal(0), 0) + print(f"no product with id <{product_id}>") + return None def delete_product(storage: list[Product], product_id: int) -> int | None: - """Remove the product stored under ``product_id`` from ``storage``. - - Args: - storage: The product store to remove from; modified in place on - success. - product_id: The identifier of the product to remove. - - Returns: - ``product_id`` when a product was removed, or ``None`` when no - product carried that identifier (``storage`` is left unchanged and - a message is printed). - """ - # TODO: реализуйте функцию - return 0 + for product in storage: + if product[PRODUCT_ID_INDEX] == product_id: + storage.remove(product) + return product_id + + print(f"no product with id <{product_id}>") + return None From d8e8330da607ac7213ae0f10278f32f971c5e302 Mon Sep 17 00:00:00 2001 From: Roman Shkryl Date: Wed, 30 Sep 2026 16:11:24 +0300 Subject: [PATCH 11/14] modificed cart.py --- src/part2/cart.py | 104 +++++++++++++++++++++++++--------------------- 1 file changed, 57 insertions(+), 47 deletions(-) diff --git a/src/part2/cart.py b/src/part2/cart.py index 063f9aea..609890e8 100644 --- a/src/part2/cart.py +++ b/src/part2/cart.py @@ -16,6 +16,7 @@ NAME_INDEX, PRICE_INDEX, QUANTITY_INDEX, + PRODUCT_ID_INDEX, Product, ) @@ -24,7 +25,7 @@ # TODO: задайте позиции полей внутри кортежа CartLine LINE_PRODUCT_ID_INDEX: Final = 0 -LINE_QUANTITY_INDEX: Final = 0 +LINE_QUANTITY_INDEX: Final = 1 def add_to_cart( @@ -33,28 +34,33 @@ def add_to_cart( product_id: int, quantity: int, ) -> CartLine | None: - """Move ``quantity`` units of ``product_id`` from the store into ``cart``. - - The product is looked up in ``storage``. If it is missing, a message is - printed (by :func:`~src.part2.crud.read_product`) and nothing - changes. If the store holds fewer units than requested, an explanatory - message is printed and nothing changes. Otherwise the store record is - decremented by ``quantity`` and the cart line for ``product_id`` gains - ``quantity`` units -- a new line is created when the cart had none. - - Args: - storage: The product store to draw stock from; modified in place on - success. - cart: The cart to add the units to; modified in place on success. - product_id: The identifier of the product to add. - quantity: Number of units to move into the cart. - - Returns: - The cart line for ``product_id`` after the addition, or ``None`` - when the product is unknown or the store cannot cover the request. - """ - # TODO: реализуйте функцию - return (0, 0) + product = read_product(storage, product_id) + if product is None: + return None + + + for i in range(len(storage)): + product = storage[i] + if product_id == product[PRODUCT_ID_INDEX]: + quantity_storage = product[QUANTITY_INDEX] + if quantity > quantity_storage: + print(f"not enough stock for product <{product_id}>: {quantity_storage} available, {quantity} requested") + return None + + name, price = product[NAME_INDEX], product[PRICE_INDEX] + new_product = (product_id, name, price, quantity_storage - quantity) + storage[i] = new_product + + for j in range(len(cart)): + cur_cart = cart[j] + if cur_cart[LINE_PRODUCT_ID_INDEX] == product_id: + new_cart = (cur_cart[LINE_PRODUCT_ID_INDEX], cur_cart[LINE_QUANTITY_INDEX] + quantity) + cart[j] = new_cart + return new_cart + + new_cart = (product_id, quantity) + cart.append(new_cart) + return new_cart def remove_from_cart( @@ -63,27 +69,31 @@ def remove_from_cart( product_id: int, quantity: int, ) -> CartLine | None: - """Move ``quantity`` units of ``product_id`` from ``cart`` back to the store. - - The cart line for ``product_id`` is looked up. If there is none, a - message is printed and nothing changes. If the line holds fewer units - than requested, an explanatory message is printed and nothing changes. - Otherwise the cart line loses ``quantity`` units -- the line is dropped - when it reaches zero -- and the store record gains ``quantity`` units - back. - - Args: - storage: The product store to return stock to; modified in place on - success. - cart: The cart to take the units from; modified in place on - success. - product_id: The identifier of the product to remove. - quantity: Number of units to move back into the store. - - Returns: - The cart line for ``product_id`` after the removal (a quantity of - zero means the line was dropped), or ``None`` when the cart has no - line for the product or holds too few units. - """ - # TODO: реализуйте функцию - return (0, 0) + for i in range(len(cart)): + id, quantity_cart = cart[i] + if id == product_id: + if quantity > quantity_cart: + print(f'cart holds only {quantity_cart} unit(s) of product <{product_id}>, cannot remove {quantity}') + return None + + product = read_product(storage, product_id) + if product is None: + return None + + new_product = (product[NAME_INDEX], product[PRICE_INDEX], product[QUANTITY_INDEX] + quantity) + update_product(storage, product_id, new_product) + + if quantity == quantity_cart: + cart.pop(i) + return (product_id, 0) + + cart[i] = (product_id, quantity_cart - quantity) + + return cart[i] + + print(f'product <{product_id}> is not in the cart') + return None + + + + \ No newline at end of file From 7690602a4bfe4801fbe9bb4c9cf0b8f0b4c1b18f Mon Sep 17 00:00:00 2001 From: Roman Shkryl Date: Wed, 30 Sep 2026 16:15:08 +0300 Subject: [PATCH 12/14] delete small mistakes --- src/part1/snowflake.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/part1/snowflake.py b/src/part1/snowflake.py index 8f332ff1..5e1d0ecc 100644 --- a/src/part1/snowflake.py +++ b/src/part1/snowflake.py @@ -6,6 +6,8 @@ NODE_ID_MAX, SEQUENCE_ID_MAX, TIMESTAMP_MS_MAX, + NODE_ID_BITS, + SEQUENCE_ID_BITS, ) @@ -16,19 +18,19 @@ def read_current_millis(epoch_ms: int) -> int: def decode_timestamp_ms(snowflake_id: int, epoch_ms: int = EPOCH_MS_DEFAULT) -> int: - default_time = snowflake_id >> 22 + default_time = snowflake_id >> (NODE_ID_DEFAULT + SEQUENCE_ID_BITS) return default_time + epoch_ms def decode_node_id(snowflake_id: int) -> int: - node_id = (snowflake_id >> 12) & 0b1111111111 + node_id = (snowflake_id >> 12) & NODE_ID_BITS return node_id def decode_sequence_id(snowflake_id: int) -> int: - sequence_id = snowflake_id & 0b111111111111 + sequence_id = snowflake_id & SEQUENCE_ID_BITS return sequence_id @@ -48,4 +50,4 @@ def generate_snowflake_id( print("overflows") return None - return read_current_millis(epoch_ms) << 22 | node_id << 12 | sequence_id \ No newline at end of file + return read_current_millis(epoch_ms) << (NODE_ID_BITS + SEQUENCE_ID_BITS) | node_id << SEQUENCE_ID_BITS | sequence_id \ No newline at end of file From 34e14673de9669e3cb68a4e1c61070d3ef805020 Mon Sep 17 00:00:00 2001 From: Roman Shkryl Date: Wed, 30 Sep 2026 16:24:38 +0300 Subject: [PATCH 13/14] correct mistakes --- src/part1/snowflake.py | 10 +++++++--- src/part2/cart.py | 45 ++++++++++++++++++++---------------------- src/part2/crud.py | 21 ++++---------------- src/part2/utils.py | 11 +---------- 4 files changed, 33 insertions(+), 54 deletions(-) diff --git a/src/part1/snowflake.py b/src/part1/snowflake.py index 5e1d0ecc..13997f48 100644 --- a/src/part1/snowflake.py +++ b/src/part1/snowflake.py @@ -2,12 +2,12 @@ from .constants import ( EPOCH_MS_DEFAULT, + NODE_ID_BITS, NODE_ID_DEFAULT, NODE_ID_MAX, + SEQUENCE_ID_BITS, SEQUENCE_ID_MAX, TIMESTAMP_MS_MAX, - NODE_ID_BITS, - SEQUENCE_ID_BITS, ) @@ -50,4 +50,8 @@ def generate_snowflake_id( print("overflows") return None - return read_current_millis(epoch_ms) << (NODE_ID_BITS + SEQUENCE_ID_BITS) | node_id << SEQUENCE_ID_BITS | sequence_id \ No newline at end of file + return ( + read_current_millis(epoch_ms) << (NODE_ID_BITS + SEQUENCE_ID_BITS) + | node_id << SEQUENCE_ID_BITS + | sequence_id + ) diff --git a/src/part2/cart.py b/src/part2/cart.py index 609890e8..1671a72b 100644 --- a/src/part2/cart.py +++ b/src/part2/cart.py @@ -1,22 +1,11 @@ -"""Shopping-cart operations layered on top of the product store. - -The cart is a plain list of tuples, one :data:`CartLine` -- -``(product_id, quantity)`` -- per distinct product. Moving units between the -store and the cart keeps the two sides in balance: :func:`add_to_cart` takes -units out of stock, :func:`remove_from_cart` puts them back. - -Like the CRUD layer, the failure path never raises -- the operation prints -an explanatory message to stdout and returns ``None``. -""" - 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, PRODUCT_ID_INDEX, + QUANTITY_INDEX, Product, ) @@ -38,13 +27,14 @@ def add_to_cart( if product is None: return None - for i in range(len(storage)): product = storage[i] if product_id == product[PRODUCT_ID_INDEX]: quantity_storage = product[QUANTITY_INDEX] if quantity > quantity_storage: - print(f"not enough stock for product <{product_id}>: {quantity_storage} available, {quantity} requested") + print( + f"not enough stock for product <{product_id}>: {quantity_storage} available, {quantity} requested" + ) return None name, price = product[NAME_INDEX], product[PRICE_INDEX] @@ -54,7 +44,10 @@ def add_to_cart( for j in range(len(cart)): cur_cart = cart[j] if cur_cart[LINE_PRODUCT_ID_INDEX] == product_id: - new_cart = (cur_cart[LINE_PRODUCT_ID_INDEX], cur_cart[LINE_QUANTITY_INDEX] + quantity) + new_cart = ( + cur_cart[LINE_PRODUCT_ID_INDEX], + cur_cart[LINE_QUANTITY_INDEX] + quantity, + ) cart[j] = new_cart return new_cart @@ -62,6 +55,8 @@ def add_to_cart( cart.append(new_cart) return new_cart + return None + def remove_from_cart( storage: list[Product], @@ -73,14 +68,20 @@ def remove_from_cart( id, quantity_cart = cart[i] if id == product_id: if quantity > quantity_cart: - print(f'cart holds only {quantity_cart} unit(s) of product <{product_id}>, cannot remove {quantity}') + print( + f"cart holds only {quantity_cart} unit(s) of product <{product_id}>, cannot remove {quantity}" + ) return None product = read_product(storage, product_id) if product is None: return None - new_product = (product[NAME_INDEX], product[PRICE_INDEX], product[QUANTITY_INDEX] + quantity) + new_product = ( + product[NAME_INDEX], + product[PRICE_INDEX], + product[QUANTITY_INDEX] + quantity, + ) update_product(storage, product_id, new_product) if quantity == quantity_cart: @@ -91,9 +92,5 @@ def remove_from_cart( return cart[i] - print(f'product <{product_id}> is not in the cart') + print(f"product <{product_id}> is not in the cart") return None - - - - \ No newline at end of file diff --git a/src/part2/crud.py b/src/part2/crud.py index 5cafa888..3fc9ab49 100644 --- a/src/part2/crud.py +++ b/src/part2/crud.py @@ -1,26 +1,12 @@ -"""Create/read/update/delete operations over the in-memory product store. - -Every operation takes the store -- a list of -:data:`~src.part2.storage.Product` tuples -- as its first argument and -works on it in place. The failure path never raises: the operation prints -an explanatory message to stdout and returns ``None``. - -The identifier of a new product is derived from the store itself -(:func:`generate_product_id`): one past the greatest identifier in use, or -:data:`~src.part2.storage.PRODUCT_ID_MIN` when the store is empty. -Product names are kept unique -- :func:`create_product` refuses a name that -is already taken. -""" - 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: @@ -42,7 +28,7 @@ def create_product( product_id = generate_product_id(storage) name, price, quantity = fields new_product = (product_id, name, normalize_price(price), quantity) - + storage.append(new_product) return product_id @@ -56,6 +42,7 @@ def read_product(storage: list[Product], product_id: int) -> Product | None: print(f"no product with id <{product_id}>") return None + def update_product( storage: list[Product], product_id: int, diff --git a/src/part2/utils.py b/src/part2/utils.py index 7f6e5322..659d1d07 100644 --- a/src/part2/utils.py +++ b/src/part2/utils.py @@ -1,16 +1,7 @@ -"""Standalone helpers shared by the hw4 storage and CRUD modules. - -For now this is limited to money handling: :func:`normalize_price` rounds a -raw :class:`~decimal.Decimal` amount to the fixed number of fractional -digits (:data:`PRICE_PRECISION`) that every stored price uses, keeping -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] = 2 PRICE_STEP: Final = Decimal(1).scaleb(-PRICE_PRECISION) From bcea0d50751814376ca9685085c5e3b83cced8fd Mon Sep 17 00:00:00 2001 From: Roman Shkryl Date: Wed, 30 Sep 2026 16:41:22 +0300 Subject: [PATCH 14/14] add new function 'find_cart_line' --- src/part2/cart.py | 18 +++++++++++++++++- src/part2/storage.py | 24 ++---------------------- 2 files changed, 19 insertions(+), 23 deletions(-) diff --git a/src/part2/cart.py b/src/part2/cart.py index 1671a72b..a53f3570 100644 --- a/src/part2/cart.py +++ b/src/part2/cart.py @@ -58,12 +58,29 @@ def add_to_cart( return None +def find_cart_line( + cart: list[CartLine], + product_id: int, +) -> CartLine | None: + for product in cart: + if product_id == product[LINE_PRODUCT_ID_INDEX]: + return product + + return None + + def remove_from_cart( storage: list[Product], cart: list[CartLine], product_id: int, quantity: int, ) -> CartLine | None: + cart_line = find_cart_line(cart, product_id) + + if cart_line is None: + print(f"product <{product_id}> is not in the cart") + return None + for i in range(len(cart)): id, quantity_cart = cart[i] if id == product_id: @@ -92,5 +109,4 @@ def remove_from_cart( return cart[i] - print(f"product <{product_id}> is not in the cart") return None diff --git a/src/part2/storage.py b/src/part2/storage.py index 35821c5f..03128124 100644 --- a/src/part2/storage.py +++ b/src/part2/storage.py @@ -1,34 +1,14 @@ -"""In-memory product store for the shop CRUD exercise. - -The store is deliberately primitive: a plain list of tuples, with no -persistence, no indexing and no schema enforcement. Each element is a -:data:`Product` record -- a ``(product_id, name, price, quantity)`` tuple -where: - -* ``product_id`` -- unique positive integer key, assigned by the create - operation in :mod:`src.part2.crud`; -* ``name`` -- human-readable product name, unique across the store; -* ``price`` -- price of a single unit, held as a :class:`~decimal.Decimal` - amount rounded to a fixed number of decimal places (see - :func:`src.part2.utils.normalize_price`) so that money is never - subject to binary floating-point error; -* ``quantity`` -- number of units currently in stock. - -Field positions are exposed as ``*_INDEX`` constants so callers never -hard-code tuple offsets. -""" - from decimal import Decimal from typing import Final type Product = tuple[int, str, Decimal, int] -# TODO: задайте позиции полей внутри кортежа Product + PRODUCT_ID_INDEX: Final = 0 NAME_INDEX: Final = 1 PRICE_INDEX: Final = 2 QUANTITY_INDEX: Final = 3 -# TODO: задайте идентификатор первого товара в пустом хранилище + PRODUCT_ID_MIN: Final[int] = 1