Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 13 additions & 28 deletions src/part1/constants.py
Original file line number Diff line number Diff line change
@@ -1,38 +1,23 @@
"""Bit layout and default epoch for the Twitter Snowflake ID generator.

A Snowflake identifier is a 63-bit positive integer packed as follows, from
the most significant bit downwards:

1 bit unused sign bit, always zero
41 bits milliseconds elapsed since a custom epoch
10 bits node identifier
12 bits per-millisecond sequence counter

The shift and mask constants should be derived from the bit widths so that
changing a width keeps everything else consistent.
"""

from typing import Final


# TODO: замените заглушки (0) на корректные значения, см. TASK.md.
# Все константы, зависящие от ёмкостей *_BITS, должны вычисляться из них.
def bits_value_max(n: int) -> int:
return 2**n - 1


# Twitter's original Snowflake epoch: 2010-11-04 01:42:54.657 UTC.
EPOCH_MS_DEFAULT: Final[int] = 0
EPOCH_MS_DEFAULT: Final[int] = 1219190400

# 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] = bits_value_max(TIMESTAMP_BITS)
NODE_ID_MAX: Final[int] = bits_value_max(NODE_ID_BITS)
SEQUENCE_ID_MAX: Final[int] = bits_value_max(SEQUENCE_ID_BITS)

# Здесь можно добавить собственные вспомогательные константы
# (например, сдвиги полей при сборке идентификатора).
TIMESTAMP_MOVE: Final[int] = NODE_ID_BITS + SEQUENCE_ID_BITS
121 changes: 44 additions & 77 deletions src/part1/snowflake.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,102 +13,69 @@
:func:`decode_node_id` and :func:`decode_sequence_id`.
"""

import time # noqa: F401
import time

from .constants import ( # noqa: F401
EPOCH_MS_DEFAULT,
NODE_ID_DEFAULT,
NODE_ID_MAX,
SEQUENCE_ID_MAX,
TIMESTAMP_MS_MAX,
)
from .constants import *


def read_current_millis(epoch_ms: int) -> int:
"""Read the number of milliseconds elapsed since the custom epoch.
call_time = (
time.time_ns() // 1_000_000 # наносекунды в милисекунды(time.time() - float)
)
return call_time - epoch_ms
# """Read the number of milliseconds elapsed since the custom epoch.

Args:
epoch_ms: The custom epoch expressed as Unix milliseconds.
# 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
# Returns:
# The count of whole milliseconds between ``epoch_ms`` and now. May be
# negative if ``epoch_ms`` lies in the future.
# """


def decode_timestamp_ms(snowflake_id: int, epoch_ms: int = EPOCH_MS_DEFAULT) -> int:
"""Read the timestamp field out of a Snowflake identifier.
return (snowflake_id >> TIMESTAMP_MOVE) + epoch_ms

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).
# """Read the timestamp field out of a Snowflake identifier.

Returns:
The absolute Unix time in milliseconds at which the identifier was
generated.
"""
# TODO: реализуйте функцию
return 0
# 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.
# """


def decode_node_id(snowflake_id: int) -> int:
"""Read the node identifier field out of a Snowflake identifier.
return (snowflake_id >> SEQUENCE_ID_BITS) & NODE_ID_BITS

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
def decode_sequence_id(snowflake_id: int) -> int:
return snowflake_id & SEQUENCE_ID_MAX


def decode_sequence_id(snowflake_id: int) -> int:
"""Read the sequence counter field out of a Snowflake identifier.
def generate_snowflake_id(
sequence_id: int, node_id: int = NODE_ID_DEFAULT, epoch_ms: int = EPOCH_MS_DEFAULT
) -> int | None:
time_call_gen = read_current_millis(epoch_ms)

Args:
snowflake_id: An identifier produced by :func:`generate_snowflake_id`.
if node_id < 0 or node_id > NODE_ID_MAX:
print("node_id must be in [0,", NODE_ID_MAX, "]")
return None

Returns:
The per-millisecond sequence counter packed into ``snowflake_id``, in
the range ``[0, SEQUENCE_ID_MAX]``.
"""
# TODO: реализуйте функцию
return 0
if sequence_id < 0 or sequence_id > SEQUENCE_ID_MAX:
print("sequence_id must be in [0,", SEQUENCE_ID_MAX, "]")
return None

if time_call_gen > TIMESTAMP_MS_MAX:
print("overflows time stamp")
return None

def generate_snowflake_id(
sequence_id: int,
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
snowflake_id = (
(time_call_gen << TIMESTAMP_MOVE) | (node_id << sequence_id) | sequence_id
)
return snowflake_id
68 changes: 60 additions & 8 deletions src/part2/cart.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -24,7 +24,7 @@

# TODO: задайте позиции полей внутри кортежа CartLine
LINE_PRODUCT_ID_INDEX: Final = 0
LINE_QUANTITY_INDEX: Final = 0
LINE_QUANTITY_INDEX: Final = 1


def add_to_cart(
Expand Down Expand Up @@ -53,9 +53,30 @@ def add_to_cart(
The cart line for ``product_id`` after the addition, or ``None``
when the product is unknown or the store cannot cover the request.
"""
# TODO: реализуйте функцию
return (0, 0)

prod = read_product(storage, product_id)
if prod is None:
return None

if prod[QUANTITY_INDEX] < quantity:
print(f"not enough stock for product {product_id}")
return None

new_stock_qty = prod[QUANTITY_INDEX] - quantity
update_product(
storage,
product_id,
(prod[NAME_INDEX], prod[PRICE_INDEX], new_stock_qty),
)

for i, line in enumerate(cart):
if line[LINE_PRODUCT_ID_INDEX] == product_id:
new_cart_qty = line[LINE_QUANTITY_INDEX] + quantity
cart[i] = (product_id, new_cart_qty)
return (product_id, new_cart_qty)

new_line = (product_id, quantity)
cart.append(new_line)
return new_line

def remove_from_cart(
storage: list[Product],
Expand Down Expand Up @@ -85,5 +106,36 @@ 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)
found_index = -1
for i, line in enumerate(cart):
if line[LINE_PRODUCT_ID_INDEX] == product_id:
found_index = i
break

if found_index == -1:
print(f"product {product_id} is not in the cart")
return None

line = cart[found_index]
if line[LINE_QUANTITY_INDEX] < quantity:
print(f"not enough quantity in cart for product {product_id}")
return None

new_cart_qty = line[LINE_QUANTITY_INDEX] - quantity
if new_cart_qty == 0:
cart.pop(found_index)
res_line = (product_id, 0)
else:
cart[found_index] = (product_id, new_cart_qty)
res_line = (product_id, new_cart_qty)

product = read_product(storage, product_id)
if product is not None:
new_stock_qty = product[QUANTITY_INDEX] + quantity
update_product(
storage,
product_id,
(product[NAME_INDEX], product[PRICE_INDEX], new_stock_qty),
)

return res_line
55 changes: 41 additions & 14 deletions src/part2/crud.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -34,9 +34,11 @@ def generate_product_id(storage: list[Product]) -> int:
:data:`~src.part2.storage.PRODUCT_ID_MIN` when ``storage`` is
empty.
"""
# TODO: реализуйте функцию
return 0

if len(storage) == 0:
return PRODUCT_ID_MIN

max_id = max(product[PRODUCT_ID_INDEX] for product in storage)
return max_id + 1

def create_product(
storage: list[Product], fields: tuple[str, Decimal, int]
Expand All @@ -56,9 +58,17 @@ def create_product(
``storage`` is left unchanged and a message naming the clashing
name is printed.
"""
# TODO: реализуйте функцию
return 0

name, price, quantity = fields[0], fields[1], fields[2]
for product in storage:
if product[NAME_INDEX] == name:
print(f"product name '{name}' is already taken")
return None

new_id = generate_product_id(storage)
normalized_price = normalize_price(price)

new_product: Product = (new_id, name, normalized_price, quantity)
storage.append(new_product)

def read_product(storage: list[Product], product_id: int) -> Product | None:
"""Return the product stored under ``product_id``.
Expand All @@ -72,9 +82,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"product with id {product_id} not found")
return None

def update_product(
storage: list[Product],
Expand All @@ -99,9 +112,18 @@ 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[0], fields[1], fields[2]

for i, product in enumerate(storage):
if product[PRODUCT_ID_INDEX] == product_id:
norm_price = normalize_price(price)
upd_product: Product = (product_id, name, norm_price, quantity)
storage[i] = upd_product
return upd_product

print(f"product with id {product_id} not found")
return None

def delete_product(storage: list[Product], product_id: int) -> int | None:
"""Remove the product stored under ``product_id`` from ``storage``.
Expand All @@ -116,5 +138,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.pop(i)
return product_id

print(f"product with id {product_id} not found")
return None
Loading
Loading