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
4 changes: 4 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"python-envs.defaultEnvManager": "ms-python.python:conda",
"python-envs.defaultPackageManager": "ms-python.python:conda"
}
22 changes: 22 additions & 0 deletions fix_and_test.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
#!/usr/bin/env bash
# Auto-fix imports/format, then run tests.
set -euo pipefail

cd "$(dirname "$0")"

if ! command -v uv >/dev/null 2>&1; then
echo "Error: uv is not installed. Install it: https://docs.astral.sh/uv/getting-started/installation/" >&2
exit 1
fi

echo "==> Install dependencies"
uv sync --locked

echo "==> Ruff fix (imports, lint)"
uv run ruff check --fix src
uv run ruff format src

# echo "==> Pytest"
# uv run pytest src/part3/tests

echo "All done."
11 changes: 11 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ dependencies = []
dev = [
"mypy==2.3.1",
"ruff==0.16.8",
"pytest>=9.1.1",
]

[tool.ruff]
Expand All @@ -33,3 +34,13 @@ avoid-escape = true
[tool.ruff.lint.isort]
lines-after-imports = 2
split-on-trailing-comma = true

[tool.mypy]
strict = true
files = ["src"]
mypy_path = "src"
explicit_package_bases = true

[tool.pytest.ini_options]
pythonpath = ["src"]
testpaths = ["src/tests"]
33 changes: 8 additions & 25 deletions src/part1/constants.py
Original file line number Diff line number Diff line change
@@ -1,38 +1,21 @@
"""Bit layout and default epoch for the Twitter Snowflake ID generator.

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

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

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

from typing import Final


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

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

# Node identifier used when the caller does not supply one.
NODE_ID_DEFAULT: Final[int] = 0
NODE_ID_DEFAULT: Final[int] = 1

# Width of each field, in bits.
TIMESTAMP_BITS: Final[int] = 0
NODE_ID_BITS: Final[int] = 0
SEQUENCE_ID_BITS: Final[int] = 0
TIMESTAMP_BITS: Final[int] = 41
NODE_ID_BITS: Final[int] = 10
SEQUENCE_ID_BITS: Final[int] = 12

# Largest value each field can hold.
TIMESTAMP_MS_MAX: Final[int] = 0
NODE_ID_MAX: Final[int] = 0
SEQUENCE_ID_MAX: Final[int] = 0
TIMESTAMP_MS_MAX: Final[int] = 2**TIMESTAMP_BITS - 1
NODE_ID_MAX: Final[int] = 2**NODE_ID_BITS - 1
SEQUENCE_ID_MAX: Final[int] = 2**SEQUENCE_ID_BITS - 1

# Здесь можно добавить собственные вспомогательные константы
# (например, сдвиги полей при сборке идентификатора).
64 changes: 29 additions & 35 deletions src/part1/snowflake.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,16 @@
:func:`decode_node_id` and :func:`decode_sequence_id`.
"""

import time # noqa: F401
import time

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

Expand All @@ -34,8 +37,7 @@ def read_current_millis(epoch_ms: int) -> int:
The count of whole milliseconds between ``epoch_ms`` and now. May be
negative if ``epoch_ms`` lies in the future.
"""
# TODO: реализуйте функцию
return 0
return time.time_ns() // 10**6 - epoch_ms


def decode_timestamp_ms(snowflake_id: int, epoch_ms: int = EPOCH_MS_DEFAULT) -> int:
Expand All @@ -50,8 +52,9 @@ def decode_timestamp_ms(snowflake_id: int, epoch_ms: int = EPOCH_MS_DEFAULT) ->
The absolute Unix time in milliseconds at which the identifier was
generated.
"""
# TODO: реализуйте функцию
return 0
del_time = (snowflake_id >> (NODE_ID_BITS + TIMESTAMP_BITS)) & TIMESTAMP_MS_MAX

return epoch_ms + del_time


def decode_node_id(snowflake_id: int) -> int:
Expand All @@ -64,8 +67,8 @@ def decode_node_id(snowflake_id: int) -> int:
The node identifier packed into ``snowflake_id``, in the range
``[0, NODE_ID_MAX]``.
"""
# TODO: реализуйте функцию
return 0

return (snowflake_id >> SEQUENCE_ID_BITS) & NODE_ID_MAX


def decode_sequence_id(snowflake_id: int) -> int:
Expand All @@ -78,37 +81,28 @@ def decode_sequence_id(snowflake_id: int) -> int:
The per-millisecond sequence counter packed into ``snowflake_id``, in
the range ``[0, SEQUENCE_ID_MAX]``.
"""
# TODO: реализуйте функцию
return 0
return snowflake_id & SEQUENCE_ID_MAX


def generate_snowflake_id(
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
if not (0 <= node_id <= NODE_ID_MAX):
print(f"node_id must be in [0, {NODE_ID_MAX}]. Your id {node_id}")
return None
elif not (0 <= sequence_id <= SEQUENCE_ID_MAX):
print(f"sequence_id must be in [0, {SEQUENCE_ID_MAX}] Your id {sequence_id}")
return None

else:
if 0 <= epoch_ms <= TIMESTAMP_MS_MAX:
return (
epoch_ms
<< (SEQUENCE_ID_BITS + NODE_ID_BITS) + node_id
<< SEQUENCE_ID_BITS + sequence_id
)
else:
print("overflows")
return None
69 changes: 61 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 @@ -22,9 +22,9 @@

type CartLine = tuple[int, int]

# TODO: задайте позиции полей внутри кортежа CartLine

LINE_PRODUCT_ID_INDEX: Final = 0
LINE_QUANTITY_INDEX: Final = 0
LINE_QUANTITY_INDEX: Final = 1


def add_to_cart(
Expand Down Expand Up @@ -53,8 +53,31 @@ def add_to_cart(
The cart line for ``product_id`` after the addition, or ``None``
when the product is unknown or the store cannot cover the request.
"""
# TODO: реализуйте функцию
return (0, 0)
search = read_product(storage, product_id)
if search == None:
return None
elif search[QUANTITY_INDEX] < quantity:
print(
f"not enough stock for product {product_id}: {search[NAME_INDEX]} available, {search[QUANTITY_INDEX]} requested"
)
return None

update_product(
storage,
product_id,
(search[NAME_INDEX], search[PRICE_INDEX], search[QUANTITY_INDEX] - quantity),
)

cart_search_l = [el for el in cart if el[LINE_PRODUCT_ID_INDEX] == product_id]
cart_search = cart_search_l[0]
if cart_search:
new_cart_line = (product_id, cart_search[LINE_QUANTITY_INDEX] + quantity)
cart.remove(cart_search)
cart.append(new_cart_line)
return new_cart_line
else:
cart.append((product_id, quantity))
return (product_id, quantity)


def remove_from_cart(
Expand Down Expand Up @@ -85,5 +108,35 @@ def remove_from_cart(
zero means the line was dropped), or ``None`` when the cart has no
line for the product or holds too few units.
"""
# TODO: реализуйте функцию
return (0, 0)
search_l = [el for el in cart if el[LINE_PRODUCT_ID_INDEX] == product_id]
search = search_l[0]
if not search:
print(f"product {product_id} is not in the cart")
return None
elif search[LINE_QUANTITY_INDEX] < quantity:
print(
f"cart holds only {search[LINE_QUANTITY_INDEX]} unit(s) of product {product_id}, cannot remove {quantity}"
)
return None

search_storage = read_product(storage, product_id)
if search_storage == None:
return None

update_product(
storage,
product_id,
(
search_storage[NAME_INDEX],
search_storage[PRICE_INDEX],
(search_storage[QUANTITY_INDEX] + quantity),
),
)

if quantity == search[LINE_QUANTITY_INDEX]:
cart.remove(search)
return (product_id, 0)

new_line = (product_id, search[LINE_QUANTITY_INDEX] - quantity)
cart[cart.index(search)] = new_line
return new_line
45 changes: 33 additions & 12 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,8 +34,12 @@ def generate_product_id(storage: list[Product]) -> int:
:data:`~src.part2.storage.PRODUCT_ID_MIN` when ``storage`` is
empty.
"""
# TODO: реализуйте функцию
return 0
if storage:
id: int = max(tuple(el[PRODUCT_ID_INDEX] for el in storage)) + 1
else:
id = PRODUCT_ID_MIN

return id


def create_product(
Expand All @@ -56,8 +60,12 @@ def create_product(
``storage`` is left unchanged and a message naming the clashing
name is printed.
"""
# TODO: реализуйте функцию
return 0
if fields[NAME_INDEX - 1] in tuple(el[NAME_INDEX] for el in storage):
print(f"product name {fields[0]} is already taken")
return None
id = generate_product_id(storage)
storage.append((id, fields[0], normalize_price(fields[1]), fields[2]))
return id


def read_product(storage: list[Product], product_id: int) -> Product | None:
Expand All @@ -72,8 +80,11 @@ def read_product(storage: list[Product], product_id: int) -> Product | None:
``None`` when no product carries that identifier (a message is
printed in that case).
"""
# TODO: реализуйте функцию
return (0, "", Decimal(0), 0)
if product_id not in tuple(el[PRODUCT_ID_INDEX] for el in storage):
print(f"no product with id {product_id}")
return None

return next(filter(lambda x: x[PRODUCT_ID_INDEX], storage))


def update_product(
Expand All @@ -99,8 +110,14 @@ def update_product(
``None`` when no product carries that identifier (``storage`` is
left unchanged and a message is printed).
"""
# TODO: реализуйте функцию
return (0, "", Decimal(0), 0)
search = read_product(storage, product_id)
if search == None:
print(f"no product with id {product_id}")
return None

storage[storage.index(search)] = (product_id,) + fields

return next(filter(lambda x: x[PRODUCT_ID_INDEX] == product_id, storage))


def delete_product(storage: list[Product], product_id: int) -> int | None:
Expand All @@ -116,5 +133,9 @@ def delete_product(storage: list[Product], product_id: int) -> int | None:
product carried that identifier (``storage`` is left unchanged and
a message is printed).
"""
# TODO: реализуйте функцию
return 0
if not filter(lambda x: x[PRODUCT_ID_INDEX] == product_id, storage):
print(f"no product with id {product_id}")
return None

storage.remove(next(filter(lambda x: x[PRODUCT_ID_INDEX] == product_id, storage)))
return product_id
Loading
Loading