Задачи про деньги
Шесть задач работают с деньгами: сколько программа авансов может выплатить продавцу (merchant), какой платёж оплатил какой счёт, как отправить выплату и не заплатить дважды, MRR, файл выплат от партнёра с плохими строками и тесты для функции, которая делит выплату. Они проверяют Decimal с правильным округлением, проверку входа до любых расчётов, правила сопоставления в фиксированном порядке, повторы, безопасные для денег, и тесты, которые заметят потерянный цент. Задачи опираются на страницы Деньги и Decimal, Ошибки и проверка ввода, Множества и дубли, Итерация и генераторы и Тесты и сложность.
P06. How much can we advance?
Заголовок раздела «P06. How much can we advance?»The platform pays merchants part of their future channel payout today — an advance. The question: how much can we pay out, and what is the fee?
The amount is the smallest of three numbers: 70% of the expected proceeds after a refund reserve (0.7 × proceeds × (1 − refund_rate)), the merchant's risk limit, and what is left of our total budget. Round the amount DOWN to cents — we never pay more than allowed. If it is below 1.00, we pay nothing: (0.00, 0.00).
The fee is 3% of the amount, rounded to cents (half up). Everything is Decimal. Negative inputs, or a refund_rate outside [0, 1], are a ValueError.
proceeds 1000, refund_rate 0.05, limit 5000, budget 100000 → 0.7 × 1000 × 0.95 = 665.00; fee 19.95 limit 500 → the limit wins: (500.00, 15.00) proceeds 1.20, refund_rate 0 → 0.84 < 1.00 → (0.00, 0.00)
Полное условие (как в файле задачи)
The platform pays merchants part of their future marketplace payout today. Write
compute_advance(expected_proceeds, refund_rate, merchant_limit, global_remaining) -> (amount, fee)
All inputs and outputs are Decimal (never float for money).
- amount = the SMALLEST of three numbers:
1) 70% of expected_proceeds after the refund reserve: 0.70 * expected_proceeds * (1 - refund_rate)
2) merchant_limit (the risk limit for this merchant)
3) global_remaining (what is left of our total budget)
- Round amount DOWN to cents (we never advance more than allowed).
- If amount < 1.00 -> return (Decimal("0.00"), Decimal("0.00")): not worth a bank transfer.
- fee = 3% of amount, rounded HALF UP to cents.
- Negative inputs, or refund_rate outside [0, 1] -> ValueError.
Example: compute_advance(Decimal("1000"), Decimal("0.05"), Decimal("5000"), Decimal("100000"))
-> (Decimal("665.00"), Decimal("19.95"))Перевод
Платформа уже сегодня выплачивает продавцам (merchant) часть их будущей выплаты от канала продаж — это аванс. Вопрос: сколько мы можем выплатить и какая будет комиссия?
Сумма — наименьшее из трёх чисел: 70 % ожидаемых поступлений (proceeds) за вычетом резерва на возвраты (0.7 × proceeds × (1 − refund_rate)), лимит риска продавца и остаток нашего общего бюджета. Округляйте сумму ВНИЗ до центов — мы никогда не платим больше, чем разрешено. Если она меньше 1.00, мы ничего не платим: (0.00, 0.00).
Комиссия — 3 % от суммы, с округлением до центов (половина — вверх, half up). Все числа — Decimal. Отрицательные входные значения или refund_rate вне [0, 1] — ValueError.
proceeds 1000, refund_rate 0.05, лимит 5000, бюджет 100000 → 0.7 × 1000 × 0.95 = 665.00; комиссия 19.95 лимит 500 → побеждает лимит: (500.00, 15.00) proceeds 1.20, refund_rate 0 → 0.84 < 1.00 → (0.00, 0.00)
Сначала спросите
Задайте каждый вопрос вслух до того, как писать код. Ответ интервьюера открывайте только после вопроса.
Запишите вопросы, которые задали бы интервьюеру, и произнесите каждый вслух. Вопросы задачи и ответы на них откроются, когда вы закончите мок.
How do I round the amount and the fee?Как округлять сумму и комиссию?
The amount down to cents, the fee half up to cents.
Перевод: Сумму — вниз до центов, комиссию — до центов с округлением половины вверх (half up).
What if the amount is very small?А если сумма совсем маленькая?
Below 1.00 we pay nothing: (0.00, 0.00).
Перевод: Меньше 1.00 — ничего не платим: (0.00, 0.00).
Invalid input?Некорректный вход?
Negative numbers, or refund_rate outside [0, 1] -> ValueError.
Перевод: Отрицательные числа или
refund_rateвне[0, 1]-> ValueError.
from decimal import Decimal
def compute_advance(expected_proceeds, refund_rate, merchant_limit, global_remaining):
raise NotImplementedError("your code")
«Запустить» выполняет файл сверху вниз, как python file.py. «Проверить» импортирует его как модуль и запускает тесты.
Подсказка: на что намекнул бы интервьюер
Запишите три ограничения тремя отдельными строками и возьмите наименьшее. Потом решите с округлением: в какую сторону для суммы и в какую для комиссии?
Скажите вслух: Money is Decimal; the amount rounds down so we never advance more than allowed, the fee rounds half up.
Эталонное решение
from decimal import Decimal, ROUND_DOWN, ROUND_HALF_UP
CENT = Decimal("0.01")ADVANCE_SHARE = Decimal("0.70")FEE_RATE = Decimal("0.03")MIN_ADVANCE = Decimal("1.00")
def compute_advance(expected_proceeds, refund_rate, merchant_limit, global_remaining): if min(expected_proceeds, merchant_limit, global_remaining) < 0: raise ValueError("amounts must not be negative") if not Decimal(0) <= refund_rate <= Decimal(1): raise ValueError("refund_rate must be between 0 and 1") by_proceeds = ADVANCE_SHARE * expected_proceeds * (1 - refund_rate) amount = min(by_proceeds, merchant_limit, global_remaining).quantize(CENT, rounding=ROUND_DOWN) if amount < MIN_ADVANCE: return Decimal("0.00"), Decimal("0.00") fee = (amount * FEE_RATE).quantize(CENT, rounding=ROUND_HALF_UP) return amount, feeРазборСначала решите задачу сами: разбор полезнее всего после своей попытки.
Зачем. Программа авансов платит продавцу сегодня часть будущей выплаты маркетплейса. Сумма — наименьшее из трёх ограничений: 70 % ожидаемой выручки за вычетом резерва на возвраты, лимит риска на продавца и остаток общего бюджета.
Шаги. Проверить вход; посчитать три числа; взять min; округлить вниз до центов; меньше 1,00 — вернуть (0.00, 0.00); иначе комиссия — 3 % от суммы с округлением half up.
Ловушки.
- Округлять вниз умеет только
quantize(Decimal("0.01"), rounding=ROUND_DOWN).round()дляDecimalокругляет к ближайшему. В одном тесте 0,70 × 33,33 × 0,9 = 20,99790:round()даёт21.00, аquantizeсROUND_DOWN—20.99. - Для комиссии
round()тоже не годится: дляDecimalон округляет ровно половину к чётному центу. В одном тесте комиссия 3 % × 1,50 = 0,045:round()даёт0.04, аquantizeсROUND_HALF_UP—0.05. - Проверка входа — до расчёта. Отрицательный бюджет должен быть ошибкой, а не отрицательным авансом.
- Деньги — только
Decimal, созданный из строк или целых. Float не хранит центы точно:0.1 + 0.2— это0.30000000000000004. - Комиссия считается от округлённой суммы — той, что реально выплачивается.
Проверка. Пример из задачи: 0,70 × 1000 × 0,95 = 665,00, комиссия 19,95.
Сложность. Константа. Интересны здесь правила округления — назовите их до того, как писать код.
P07. Match payments to invoices
Заголовок раздела «P07. Match payments to invoices»Accounting has the invoices we sent and the payments that came in. We need to find which payment paid which invoice.
Both steps take the payments in order of date, then id. First by reference: if a payment has a reference and it is the id of an invoice that is still open, they match — even if the amounts differ. So if two payments refer to the same invoice, the earlier payment gets it. Then guess for the payments that are left: same counterparty, same amount, and the payment date at most 3 days away from the invoice due date. Of those, take the closest date; on a tie, the smaller invoice id.
Each invoice and each payment is used at most once. Return the matches, the unmatched invoices and the unmatched payments, all sorted.
invoices: inv_1 acme 100 due Sep 10; inv_2 acme 100 due Sep 10; inv_3 beta 50 due Sep 1 payments: pay_a acme 100 Sep 11; pay_b acme 60 Sep 20 ref=inv_1; pay_c beta 50 Sep 9 → matches: (inv_1, pay_b) by reference, (inv_2, pay_a) by amount and date → unmatched: inv_3 and pay_c — they are 8 days apart
Полное условие (как в файле задачи)
reconcile(invoices, payments) -> {"matches": [(invoice_id, payment_id), ...],
"unmatched_invoices": [...], "unmatched_payments": [...]}
invoice: {"id": "inv_1", "counterparty": "acme", "amount": Decimal("100.00"), "due": date(2026, 9, 10)}
payment: {"id": "pay_1", "counterparty": "acme", "amount": Decimal("100.00"), "date": date(2026, 9, 11),
"reference": "inv_1" or None}
Rules, in this order. Both rules take the payments in payment order: by date, then by id.
1. Reference: if payment["reference"] equals an unmatched invoice id, match them (the amount may differ: partial payments are handled elsewhere). References are applied in payment order, so when two payments refer to the same invoice, the earlier payment gets it.
2. Heuristic: for each payment still unmatched, in payment order, find unmatched invoices with the same counterparty, the same amount, and |payment date - due date| <= 3 days. Pick the one with the smallest date difference; tie -> smallest invoice id.
- Every invoice and every payment is used at most once.
- All three lists are sorted (matches by invoice id).Перевод
У бухгалтерии есть выставленные нами счета (invoices) и поступившие платежи. Нужно найти, какой платёж оплатил какой счёт.
Оба шага берут платежи по порядку: по дате, затем по id. Сначала по ссылке (reference): если у платежа есть reference и это id ещё открытого счёта, они совпадают — даже если суммы разные. Поэтому если два платежа ссылаются на один счёт, его получает более ранний платёж. Затем подберите пары для оставшихся платежей: тот же контрагент, та же сумма, и дата платежа не дальше 3 дней от срока оплаты счёта. Из подходящих счетов берите тот, чья дата ближе; при равенстве — с меньшим id.
Каждый счёт и каждый платёж используются не больше одного раза. Верните совпадения, несопоставленные счета и несопоставленные платежи, всё в отсортированном виде.
счета: inv_1 acme 100 срок 10 сен; inv_2 acme 100 срок 10 сен; inv_3 beta 50 срок 1 сен платежи: pay_a acme 100 11 сен; pay_b acme 60 20 сен ref=inv_1; pay_c beta 50 9 сен → совпадения: (inv_1, pay_b) по ссылке, (inv_2, pay_a) по сумме и дате → без пары: inv_3 и pay_c — между ними 8 дней
Сначала спросите
Задайте каждый вопрос вслух до того, как писать код. Ответ интервьюера открывайте только после вопроса.
Запишите вопросы, которые задали бы интервьюеру, и произнесите каждый вслух. Вопросы задачи и ответы на них откроются, когда вы закончите мок.
Can a reference point to an invoice of another counterparty?Может ли reference указывать на счёт другого контрагента?
Yes, trust the reference.
Перевод: Да, доверяйте reference.
What if the reference points to an invoice that is already matched?А если reference указывает на счёт, у которого уже есть пара?
Treat the payment as having no reference. References are applied in payment order (date, then id).
Перевод: Считайте, что у платежа нет reference. Ссылки применяются в порядке платежей (по дате, затем по id).
What if a payment has no reference?А если у платежа нет reference?
Same counterparty, same amount, at most 3 days from the due date; the closest date wins, then the smallest invoice id.
Перевод: Тот же контрагент, та же сумма, не дальше 3 дней от срока оплаты; побеждает ближайшая дата, затем меньший id счёта.
def reconcile(invoices, payments):
raise NotImplementedError("your code")
«Запустить» выполняет файл сверху вниз, как python file.py. «Проверить» импортирует его как модуль и запускает тесты.
Подсказка: на что намекнул бы интервьюер
Что пойдёт не так, если догадка заберёт счёт, на который ссылается другой платёж? Решите, в каком порядке идут два правила, до того как их писать. Потом: какие счета вообще могут подойти одному платежу и как найти их, не перебирая все счета?
Скажите вслух: I index open invoices by (counterparty, amount), so each payment only looks at real candidates.
Эталонное решение
from collections import defaultdict
WINDOW_DAYS = 3
def reconcile(invoices, payments): open_invoices = {inv["id"]: inv for inv in invoices} matches, unmatched_payments = [], [] in_order = sorted(payments, key=lambda p: (p["date"], p["id"])) # both rules use payment order
# 1) exact references first, so heuristics cannot steal those invoices rest = [] for p in in_order: ref = p.get("reference") if ref in open_invoices: matches.append((ref, p["id"])) del open_invoices[ref] else: rest.append(p)
# 2) index open invoices by (counterparty, amount) to avoid scanning everything by_key = defaultdict(list) for inv in open_invoices.values(): by_key[(inv["counterparty"], inv["amount"])].append(inv)
for p in rest: # still in payment order candidates = [inv for inv in by_key[(p["counterparty"], p["amount"])] if inv["id"] in open_invoices and abs((p["date"] - inv["due"]).days) <= WINDOW_DAYS] if not candidates: unmatched_payments.append(p["id"]) continue best = min(candidates, key=lambda inv: (abs((p["date"] - inv["due"]).days), inv["id"])) matches.append((best["id"], p["id"])) del open_invoices[best["id"]]
return {"matches": sorted(matches), "unmatched_invoices": sorted(open_invoices), "unmatched_payments": sorted(unmatched_payments)}РазборСначала решите задачу сами: разбор полезнее всего после своей попытки.
Зачем. Бухгалтерия сопоставляет входящие платежи со счетами. Ссылка в платеже — надёжный сигнал. Для платежей без ссылки — эвристика по контрагенту, сумме и дате.
Шаги.
- Один раз отсортировать платежи по (дата, id). Оба прохода идут в этом порядке.
- Проход 1: платежи, чья ссылка указывает на открытый счёт. Сопоставить и убрать счёт из открытых. Если два платежа ссылаются на один счёт, его получает более ранний, а второй идёт во второй проход.
- Проиндексировать оставшиеся открытые счета по
(counterparty, amount). - Проход 2: остальные платежи, в том же порядке. Кандидаты — открытые счета с тем же ключом и разницей между датой платежа и сроком не больше 3 дней. Лучший —
minпо (разница в днях, id счёта). Убрать его из открытых.
Ловушки.
- Сначала все ссылки, потом эвристика. Иначе эвристика «украдёт» счёт, на который ссылается другой платёж.
- Ссылка на уже сопоставленный счёт считается отсутствующей: такой платёж идёт во второй проход.
- Сортировать нужно до первого прохода, а не только до второго. Иначе, когда два платежа ссылаются на один счёт, побеждает тот, что случайно стоит первым во входном списке.
- Ссылке на счёт другого контрагента всё равно доверяем. Проверку контрагента в первый проход не добавляйте.
- Для разницы дат нужен
abs(): платёж может прийти раньше срока. - Все три списка результата отсортировать.
Сложность. С индексом по (counterparty, amount) каждый платёж смотрит только на настоящих кандидатов, а не на все счета. Остальное — сортировки: O(n log n).
Продолжение. Частичные оплаты, допуск по сумме, несколько валют. Назовите их как расширения и скажите, где каждое изменило бы код.
P09. Pay out safely with retries
Заголовок раздела «P09. Pay out safely with retries»We send a payout to a merchant through a bank. The main rule: never pay twice.
The bank client has two methods: pay(key, amount) pays and returns a payment id, and get_payment(key) tells us whether a payment with this key already exists. pay can fail in two ways. TransientError means the bank did nothing for sure, so it is safe to retry. TimeoutError means we do not know whether the money left: first ask get_payment; if the payment exists, return it, otherwise retry.
Use one key for every attempt: f"payout:{payout_id}". Call pay at most max_attempts times, and before retry k wait base_delay × 2^(k−1) using the sleep function you get. If every attempt fails, raise PayoutFailed with the last error as the cause. Any other error goes straight up, with no retries.
bank: TransientError, TransientError, success → 'bank_1', waits [0.5, 1.0], pay called 3 times bank: timeout, but the money was sent → get_payment finds it → 'bank_1', pay called once
Полное условие (как в файле задачи)
Send a payout through a bank client and never pay twice.
payment_id = pay_with_retry(bank, payout_id="po_42", amount=Decimal("760.00"))
The bank client has two methods:
bank.pay(idempotency_key, amount) -> payment_id
bank.get_payment(idempotency_key) -> payment_id or None
bank.pay can fail in two ways:
TransientError — the bank says the request was NOT processed. Safe to retry.
TimeoutError — we do not know. The money may already be sent.
Rules:
- The idempotency key is f"payout:{payout_id}", the same on every attempt.
- After a TimeoutError, first call bank.get_payment(key). If it returns a payment id, return it. If it returns None, retry. (get_payment itself does not fail in this exercise.)
- At most `max_attempts` calls to bank.pay. Before retry number k (k = 1, 2, …) wait base_delay * 2 ** (k - 1) seconds, using the `sleep` function you get (tests pass a fake one).
- If all attempts fail -> raise PayoutFailed (defined below), with the last error as the cause.
- Any other exception from bank.pay -> do not retry, let it propagate.Перевод
Мы отправляем выплату продавцу (merchant) через банк. Главное правило: никогда не платить дважды.
У клиента банка два метода: pay(key, amount) платит и возвращает id платежа, а get_payment(key) сообщает, есть ли уже платёж с этим ключом. pay может упасть двумя способами. TransientError значит, что банк точно ничего не сделал, поэтому повторить безопасно. TimeoutError значит, что мы не знаем, ушли ли деньги: сначала спросите get_payment; если платёж есть, верните его, иначе повторите.
Используйте один ключ для всех попыток: f"payout:{payout_id}". Вызывайте pay не больше max_attempts раз, а перед повтором номер k ждите base_delay × 2^(k−1) с помощью переданной функции sleep. Если все попытки неудачны, бросьте PayoutFailed, указав последнюю ошибку как причину (cause). Любая другая ошибка сразу уходит наверх, без повторов.
банк: TransientError, TransientError, успех → 'bank_1', ожидания [0.5, 1.0], pay вызван 3 раза банк: таймаут, но деньги ушли → get_payment находит платёж → 'bank_1', pay вызван один раз
Сначала спросите
Задайте каждый вопрос вслух до того, как писать код. Ответ интервьюера открывайте только после вопроса.
Запишите вопросы, которые задали бы интервьюеру, и произнесите каждый вслух. Вопросы задачи и ответы на них откроются, когда вы закончите мок.
Does the bank itself honour the idempotency key?Соблюдает ли сам банк ключ идемпотентности?
Assume NOT — that is why we check get_payment.
Перевод: Считайте, что НЕТ, — поэтому мы и проверяем
get_payment.
import time
class TransientError(Exception):
pass
class PayoutFailed(Exception):
pass
def pay_with_retry(bank, payout_id, amount, max_attempts=5, base_delay=0.5, sleep=time.sleep):
raise NotImplementedError("your code")
«Запустить» выполняет файл сверху вниз, как python file.py. «Проверить» импортирует его как модуль и запускает тесты.
Подсказка: на что намекнул бы интервьюер
Обрабатывайте две ошибки по-разному: после TransientError повтор безопасен, а после TimeoutError сначала нужно узнать, ушли ли деньги. Один ключ на все попытки.
Скажите вслух: After a timeout I first ask the bank whether the payment exists — a blind retry could pay twice.
Эталонное решение
import time
class PayoutFailed(Exception): pass
class TransientError(Exception): pass
def pay_with_retry(bank, payout_id, amount, max_attempts=5, base_delay=0.5, sleep=time.sleep): key = f"payout:{payout_id}" last_error = None for attempt in range(1, max_attempts + 1): if attempt > 1: sleep(base_delay * 2 ** (attempt - 2)) try: return bank.pay(key, amount) except TransientError as e: # not processed: safe to retry last_error = e except TimeoutError as e: # unknown outcome: ask before paying again last_error = e existing = bank.get_payment(key) if existing is not None: return existing raise PayoutFailed(f"payout {payout_id} failed after {max_attempts} attempts") from last_errorРазборСначала решите задачу сами: разбор полезнее всего после своей попытки.
Зачем. Выплата через банк не должна уйти дважды, даже если запрос завис.
Шаги.
- Один ключ идемпотентности на все попытки:
f"payout:{payout_id}". - Цикл по попыткам 1 …
max_attempts. Перед повтором k — паузаbase_delay * 2 ** (k - 1). TransientError→ запомнить и повторить.TimeoutError→ сначала спроситьbank.get_payment(key). Есть id платежа — вернуть его;None— повторить.- После цикла —
raise PayoutFailed(...) from last_error.
Ловушки.
- Слепой повтор после таймаута может заплатить дважды. В этом весь смысл задачи.
- Новый ключ на каждой попытке убивает идемпотентность.
- Ловить только
TransientErrorиTimeoutError. Любая другая ошибка сразу уходит наверх. - Нет паузы перед первой попыткой и нет паузы после последней.
from last_errorсохраняет причину, и в логе видно, почему выплата не прошла.
Проверка. Два TransientError, потом успех: pay вызывается 3 раза, паузы — 0,5 и 1,0.
Продолжение. «Последняя попытка упала по таймауту, и get_payment по-прежнему ничего не находит. Выплата не прошла?» Наверняка сказать нельзя: исход неизвестен, и банк ещё может её провести. В упражнении поднимается PayoutFailed, чтобы правило было простым. В продакшене поднимают отдельную ошибку «исход неизвестен» или откладывают выплату для джобы сверки, чтобы вызывающий код не повторял вслепую.
В продакшене. Сохранить выплату и её статус до вызова банка. Тогда сбой посередине или неизвестный исход можно разобрать позже, спросив банк по тому же ключу.
P10. MRR by plan
Заголовок раздела «P10. MRR by plan»Finance wants to see MRR: how much money per month the subscriptions that are active right now bring in, per plan. A yearly subscription counts as price / 12 per month, a weekly one as price × 52 / 12, and so on — see the table in the task.
The input is a list of transactions (the same fields as the transactions table) and a moment as_of. Count only subscriptions active at that moment: not a trial, not a test purchase, not promo, and not refunded by that moment (a refund in the future does not count yet).
Return a dict: plan → MRR. Money is Decimal; add everything up without rounding and round to cents once at the end. Plans with nothing active are not in the result. A duration that is not in the table is a ValueError.
two active monthly subscriptions of prd_03.monthly at 9.99
→ {'prd_03.monthly': Decimal('19.98')}
yearly 59.99 → 5.00 per month; weekly 2.99 → 12.96 per monthПолное условие (как в файле задачи)
MRR (monthly recurring revenue) = the monthly value of all subscriptions that are active right now.
mrr_by_plan(transactions, as_of=datetime(2026, 9, 30)) -> {"prd_03.monthly": Decimal("69.86"), ...}
Each transaction is a dict with the same fields as the SQL table `transactions` (start_time, end_time, plan_id, plan_period, channel, is_trial, is_test, charged_usd as Decimal, refunded_at or None).
- Count a transaction if it is active at as_of (start_time <= as_of < end_time), is not a trial, not a test purchase, not 'promo', and not refunded at or before as_of.
- Monthly value = charged_usd * factor:
P1W: 52/12 P1M: 1 P3M: 1/3 P6M: 1/6 P1Y: 1/12
Unknown duration -> ValueError.
- Sum per plan in full precision, then round each plan total HALF UP to cents.
- Plans with nothing active are not in the result.Перевод
Финансовый отдел хочет видеть MRR: сколько денег в месяц приносят подписки, активные прямо сейчас, по каждому тарифу (plan). Годовая подписка считается как price / 12 в месяц, недельная — как price × 52 / 12 и так далее; таблица есть в условии задачи.
На входе — список транзакций (те же поля, что в таблице transactions) и момент as_of. Учитывайте только подписки, активные в этот момент: не триал, не тестовая покупка, не промо-доступ и без возврата к этому моменту (будущий возврат пока не учитывается).
Верните словарь: тариф → MRR. Деньги — Decimal; складывайте всё без округления и округлите до центов один раз в конце. Тарифов без активных подписок в результате нет. Длительность, которой нет в таблице, — ValueError.
две активные месячные подписки prd_03.monthly по 9.99
→ {'prd_03.monthly': Decimal('19.98')}
годовая 59.99 → 5.00 в месяц; недельная 2.99 → 12.96 в месяцСначала спросите
Задайте каждый вопрос вслух до того, как писать код. Ответ интервьюера открывайте только после вопроса.
Запишите вопросы, которые задали бы интервьюеру, и произнесите каждый вслух. Вопросы задачи и ответы на них откроются, когда вы закончите мок.
What does active at as_of mean?Что значит «активна на момент
as_of»?start_time <= as_of < end_time; not a trial, not a test purchase, not promo; not refunded at or before as_of.
Перевод:
start_time <= as_of < end_time; не триал, не тестовая покупка, не промо-доступ; нет возврата в моментas_ofили раньше.How do I turn a price into a monthly value?Как перевести цену в месячную стоимость?
Use the table: P1M x 1, P1Y x 1/12, P1W x 52/12, P3M x 1/3, P6M x 1/6. Unknown duration -> ValueError.
Перевод: По таблице: P1M x 1, P1Y x 1/12, P1W x 52/12, P3M x 1/3, P6M x 1/6. Неизвестная длительность -> ValueError.
When do I round?Когда округлять?
Once per plan, at the end, half up to cents.
Перевод: Один раз для каждого тарифа, в конце, до центов с округлением половины вверх (half up).
def mrr_by_plan(transactions, as_of):
raise NotImplementedError("your code")
«Запустить» выполняет файл сверху вниз, как python file.py. «Проверить» импортирует его как модуль и запускает тесты.
Подсказка: на что намекнул бы интервьюер
Напишите маленькую функцию, которая решает, считается ли одна транзакция на as_of, и проверьте её отдельно. Потом переведите каждую цену в месячную и округляйте только в конце.
Скажите вслух: I sum in full precision and round once per plan at the end, half up.
Эталонное решение
from collections import defaultdictfrom decimal import Decimal, ROUND_HALF_UP
FACTOR = {"P1W": Decimal(52) / Decimal(12), "P1M": Decimal(1), "P3M": Decimal(1) / Decimal(3), "P6M": Decimal(1) / Decimal(6), "P1Y": Decimal(1) / Decimal(12)}
def _is_counted(t, as_of): return (t["start_time"] <= as_of < t["end_time"] and not t["is_trial"] and not t["is_test"] and t["channel"] != "promo" and (t["refunded_at"] is None or t["refunded_at"] > as_of))
def mrr_by_plan(transactions, as_of): totals = defaultdict(Decimal) for t in transactions: if not _is_counted(t, as_of): continue if t["plan_period"] not in FACTOR: raise ValueError(f"unknown duration {t['plan_period']!r}") totals[t["plan_id"]] += t["charged_usd"] * FACTOR[t["plan_period"]] return {p: v.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) for p, v in totals.items()}РазборСначала решите задачу сами: разбор полезнее всего после своей попытки.
Зачем. MRR — сколько денег в месяц приносят подписки, активные прямо сейчас. Годовой тариф (plan) за 120 даёт 10 в месяц, недельный — цену × 52 / 12. Это одна из главных цифр любого бизнеса на подписках.
Шаги.
- Отдельная функция «активна и платная на
as_of» — те же фильтры, что в SQL-задаче Q03. - Множитель по
plan_period. - Сумма по
plan_idвDecimal, в полной точности. - Одно округление на тариф в конце, half up до центов.
Ловушки.
- Если округлять каждую транзакцию, центы расходятся.
- Возврат в будущем ещё не считается:
refunded_at is None or refunded_at > as_of. - Множитель 52 / 12 — это
Decimal(52) / Decimal(12), а не float. - Неизвестная длительность —
ValueError, а не молчаливый ноль.
Проверка. На учебных данных на 30 сентября активные подписки есть у 45 тарифов, MRR prd_03.monthly — 69,86. Тест сравнивает каждый тариф до цента с точным расчётом в SQL. Три тарифа попадают ровно на половину цента (у prd_01.annual — 99,975), так что их последний цент решает правило округления.
Сложность. Один проход, O(n), и память на один итог на тариф.
P12. Import a partner payout file
Заголовок раздела «P12. Import a partner payout file»South Market, one of our partner marketplaces, sends its monthly payout export as a text file, and the file is messy: a BOM at the start, ";" between the fields, a decimal comma in the amounts, a header in mixed case with spaces, blank lines, bad rows and a totals line at the end.
Write import_payouts(lines). It reads the lines once, one by one, because real files are large. It returns the good rows as Payout records with a date and a Decimal, and a list of errors: (line number, code) for each bad row. The codes are bad_row, missing_merchant, bad_amount, negative_amount, bad_date and duplicate.
The last line is the partner's total. If it does not match the sum of the good rows, or the file is cut off or broken, raise ImportFailed and import nothing.
1 Payout ID; Merchant ID ;Paid On;Note;AMOUNT
2 spo_1001;mer_03;2026-09-14;;1234,50
3 spo_1003;;2026-09-14;;10,00
4 spo_1001;mer_03;2026-09-14;;1234,50
5 TOTAL;;;;1234,50
→ records: [Payout('spo_1001', 'mer_03', date(2026, 9, 14), Decimal('1234.50'))]
→ errors: [(3, 'missing_merchant'), (4, 'duplicate')]Полное условие (как в файле задачи)
South Market sends its monthly payout export as a text file. Turn it into clean records and a report of the bad rows.
records, errors = import_payouts(lines)
lines: any iterable of str, for example an open text file. Real exports are large: read the lines once, one by one, and do not build a list of all of them. A line may end with LF or CRLF.
Payout ID; Merchant ID ;Paid On;Note;AMOUNT (the file may start with a BOM, U+FEFF)
spo_1001;mer_03;2026-09-14;;1234,50
spo_1002;mer_07;2026-09-14;Aug fix;87,10
spo_1003;;2026-09-14;;10,00
TOTAL;;;;1321,60
Here spo_1003 is a bad row (no merchant), and the total 1321,60 matches the two good rows.
- Line 1 is the header. Find the columns by name: payout_id, merchant_id, paid_on and amount, after you strip each name, lower-case it and replace spaces with "_". Ignore other columns.
- Fields are separated by ";". Strip spaces around every field. Skip blank lines.
- Amounts use a decimal comma: 1234,50 is Decimal("1234.50"). Dates are YYYY-MM-DD.
- The last non-blank line is the totals line: its first field is TOTAL, its amount is in the amount column.
- Every other line is one payout. A good row becomes Payout(payout_id, merchant_id, paid_on, amount), with a date and a Decimal. A bad row is not imported: add (line_number, code) to errors, with the first code that applies:
bad_row the wrong number of fields, or an empty payout_id
missing_merchant an empty merchant_id
bad_amount not a number written with a decimal comma
negative_amount below zero
bad_date not a real date
duplicate a payout_id that was already imported
- Return (records, errors), both in file order. Line numbers are those of the file.
- Raise ImportFailed and import nothing if there is no header, a required column is missing, there is no totals line, a row comes after the totals line, or the total does not match.Перевод
South Market, один из наших маркетплейсов-партнёров, присылает ежемесячную выгрузку выплат текстовым файлом, и файл грязный: BOM в начале, ; между полями, десятичная запятая в суммах, заголовок в разном регистре и с пробелами, пустые строки, плохие строки и строка итога в конце.
Напишите import_payouts(lines). Функция читает строки один раз, по одной: настоящие файлы большие. Она возвращает хорошие строки как записи Payout с датой и Decimal и список ошибок: (номер строки, код) для каждой плохой строки. Коды: bad_row, missing_merchant, bad_amount, negative_amount, bad_date и duplicate.
Последняя строка — итог от партнёра. Если он не совпадает с суммой хороших строк или файл обрезан либо сломан, бросьте ImportFailed и ничего не импортируйте.
1 Payout ID; Merchant ID ;Paid On;Note;AMOUNT
2 spo_1001;mer_03;2026-09-14;;1234,50
3 spo_1003;;2026-09-14;;10,00
4 spo_1001;mer_03;2026-09-14;;1234,50
5 TOTAL;;;;1234,50
→ записи: [Payout('spo_1001', 'mer_03', date(2026, 9, 14), Decimal('1234.50'))]
→ ошибки: [(3, 'missing_merchant'), (4, 'duplicate')]Сначала спросите
Задайте каждый вопрос вслух до того, как писать код. Ответ интервьюера открывайте только после вопроса.
Запишите вопросы, которые задали бы интервьюеру, и произнесите каждый вслух. Вопросы задачи и ответы на них откроются, когда вы закончите мок.
Does the total include the rows I reject?Входят ли в итог строки, которые я отбрасываю?
No. The partner holds those rows back and counts each payout once, so the total must equal the sum of the rows you import.
Перевод: Нет. Партнёр придерживает эти строки и считает каждую выплату один раз, поэтому итог должен быть равен сумме импортированных строк.
A payout id appears twice: which row wins?id выплаты встречается дважды: какая строка побеждает?
The first row that was imported. A later row with that id is a duplicate, even an exact copy. If the first row was bad, a later good row is imported.
Перевод: Первая импортированная. Более поздняя строка с тем же id — дубль, даже если это точная копия. Если первая строка была плохой, более поздняя хорошая импортируется.
Can an amount have a thousands separator, like 1.234,50?Может ли в сумме быть разделитель тысяч, например
1.234,50?Not in this export. A dot or a space inside an amount is bad_amount: do not guess what it means.
Перевод: Не в этой выгрузке. Точка или пробел внутри суммы — это
bad_amount: не угадывайте, что имелось в виду.Is a zero amount allowed?Допустима ли нулевая сумма?
Yes. Only an amount below zero is negative_amount.
Перевод: Да. Только сумма меньше нуля —
negative_amount.How do I count lines?Как считать строки?
As an editor does: the header is line 1, and blank lines count.
Перевод: Как редактор: заголовок — строка 1, пустые строки тоже считаются.
Should I check merchant ids against our merchants table?Проверять ли id продавцов по нашей таблице
merchants?Not here: only that the field is not empty. A later step checks them.
Перевод: Не здесь: только что поле не пустое. Их проверяет следующий шаг.
from datetime import date
from decimal import Decimal
from typing import NamedTuple
class Payout(NamedTuple):
payout_id: str
merchant_id: str
paid_on: date
amount: Decimal
class ImportFailed(Exception):
pass
def import_payouts(lines):
raise NotImplementedError("your code")
«Запустить» выполняет файл сверху вниз, как python file.py. «Проверить» импортирует его как модуль и запускает тесты.
Подсказка: на что намекнул бы интервьюер
Напишите одну маленькую функцию, которая получает поля одной строки и возвращает либо Payout, либо код ошибки, и сначала проверьте её на отдельных строках. Потом цикл: что нужно помнить о предыдущих строках и в какой момент id выплаты может попасть в эту память?
Скажите вслух: I read the file once and keep only the set of imported ids. An id joins it only after the row passes every check, and the total decides whether anything is imported.
Эталонное решение
import refrom datetime import date, datetimefrom decimal import Decimalfrom typing import NamedTuple
class ImportFailed(Exception): pass
class Payout(NamedTuple): payout_id: str merchant_id: str paid_on: date amount: Decimal
REQUIRED = ("payout_id", "merchant_id", "paid_on", "amount")AMOUNT = re.compile(r"-?\d+(,\d{1,2})?") # 1234,50 — no dot, no space, no thousands separator
def parse_amount(text): """'1234,50' -> Decimal('1234.50'); None when it is not a number with a decimal comma.""" return Decimal(text.replace(",", ".")) if AMOUNT.fullmatch(text) else None
def parse_date(text): try: return datetime.strptime(text, "%Y-%m-%d").date() except ValueError: return None
def check_row(fields, width, col, imported): """(code, None) for a bad row, (None, Payout) for a good one. The first code that applies wins.""" if len(fields) != width or not fields[col["payout_id"]]: return "bad_row", None payout_id, merchant_id = fields[col["payout_id"]], fields[col["merchant_id"]] if not merchant_id: return "missing_merchant", None amount = parse_amount(fields[col["amount"]]) if amount is None: return "bad_amount", None if amount < 0: # zero is a valid payout return "negative_amount", None paid_on = parse_date(fields[col["paid_on"]]) if paid_on is None: return "bad_date", None if payout_id in imported: # only ids of rows that were imported return "duplicate", None return None, Payout(payout_id, merchant_id, paid_on, amount)
def import_payouts(lines): rows = iter(lines) # one pass: works for a file of any size first = next(rows, None) if first is None: raise ImportFailed("empty file: no header") names = ["_".join(n.strip().lower().split()) for n in first.lstrip("\ufeff").split(";")] missing = [c for c in REQUIRED if c not in names] if missing: raise ImportFailed(f"missing columns: {', '.join(missing)}") col = {c: names.index(c) for c in REQUIRED}
records, errors, imported = [], [], set() total = None for number, line in enumerate(rows, start=2): # the header is line 1; blank lines keep their number if not line.strip(): continue if total is not None: raise ImportFailed(f"line {number}: a row after the totals line") fields = [f.strip() for f in line.split(";")] if fields[0].upper() == "TOTAL": total = parse_amount(fields[col["amount"]]) if len(fields) == len(names) else None if total is None: raise ImportFailed(f"line {number}: the totals line has no readable amount") continue code, payout = check_row(fields, len(names), col, imported) if code: errors.append((number, code)) else: imported.add(payout.payout_id) # mark only after the row is known to be good records.append(payout)
if total is None: raise ImportFailed("no totals line: the file may be cut off") good = sum((r.amount for r in records), Decimal("0")) if good != total: raise ImportFailed(f"the totals line says {total}, the good rows add up to {good}") return records, errorsРазборСначала решите задачу сами: разбор полезнее всего после своей попытки.
Зачем. Выгрузка партнёра — то место, где внешние данные попадают в наши книги. Плохая строка не должна останавливать импорт, но и проскочить не должна. Итог в последней строке — собственная проверка партнёра, что мы правильно прочитали каждое число.
Шаги.
- Взять заголовок через
next(rows, None); ничего нет →ImportFailed. Убрать BOM черезlstrip("\ufeff"), потом нормализовать каждое имя:"_".join(name.strip().lower().split()). Сопоставить четыре имени с их позициями; нет хотя бы одного →ImportFailed. - Цикл с
enumerate(rows, start=2): заголовок — строка 1, а пустые строки сохраняют свои номера. Пропускать пустую строку только после того, как она получила номер. - Строка, у которой первое поле
TOTAL, даёт итог. Любая непустая строка после неё →ImportFailed. - Одна маленькая функция проверяет строку в порядке кодов и возвращает первую проблему или
Payout. Сумму сначала сверить со строгим шаблоном-?\d+(,\d{1,2})?и только потом передавать вDecimal; дату разбирать черезstrptime("%Y-%m-%d"). - id выплаты попадает в множество импортированных только после того, как строка признана хорошей.
- В конце: нет итога →
ImportFailed; сумма хороших строк не равна итогу →ImportFailed. Иначе вернуть оба списка.
Ловушки.
strip()не убирает BOM: это не пробельный символ. Первая колонка тогда называется\ufeffpayout_id, и импорт падает из-за отсутствующей колонки.Decimal(text.replace(",", "."))принимает12.50. В файле с десятичной запятой точка значит, что строка в другом формате, и12.50может оказаться 1250. Строгий шаблон превращает её вbad_amount.- id помечен как виденный до проверок: тогда исправленная копия плохой строки попадает в дубли. Это та же ошибка, что в D03: помечать только после успеха.
amount <= 0отбрасывает допустимую нулевую выплату.- Считать только непустые строки или считать с нуля. Поддержка открывает файл в редакторе, поэтому номера должны совпадать с номерами редактора.
lines[0]иlen(lines)падают на открытом файле или генераторе.list(lines)здесь работает, но читает весь файл в память.- Float для сумм: проверка итога тогда расходится на цент.
Проверка. В примере из задачи хорошие строки дают 1234,50 + 87,10 = 1321,60 — это итог в последней строке.
Сложность. Один проход, O(n). Память: возвращаемые записи и один id на каждую импортированную выплату.
Продолжение. «Файл весит 20 ГБ. Что изменится?» Вход уже читается потоком, а выход — нет: список записей растёт вместе с файлом. Записывайте записи пачками в промежуточную (staging) таблицу и храните только id (или уникальный ключ в этой таблице) и текущую сумму. Фиксируйте транзакцию после того, как итог сошёлся, и откатывайте всё, если не сошёлся. Ловушка — генератор, который отдаёт строки до проверки итога: вызывающий код уже использовал строки файла, который потом окажется неверным.
В продакшене. Храните исходный файл, его контрольную сумму и отчёт об ошибках рядом с импортом, чтобы спор с партнёром можно было воспроизвести. Уникальный ключ (channel, payout_id) делает повторный импорт того же файла безвредным.
P14. Write the tests for a payout split
Заголовок раздела «P14. Write the tests for a payout split»This round is about tests. split_payout splits one South Market bundle payout between several merchants by their shares, in whole cents, so that the parts always add up: each merchant first gets its part rounded down, and the cents that are left go to the largest remainders. The function is already written, and it is correct.
Write the tests for it below the YOUR TESTS line: test_* functions that call split_payout, with plain assert, pytest.raises and, if you like, @pytest.mark.parametrize. A few tests are enough if each one has a reason.
Check runs your tests on the correct function, where all of them must pass. Then it runs them on 6 versions with a planted bug, and each time at least one test must fail. A bug that survives is named only by its area.
split_payout(Decimal("10.00"), {"mer_03": 1, "mer_07": 2})
→ [('mer_03', Decimal('3.33')), ('mer_07', Decimal('6.67'))]
# exact parts 3.333… and 6.666…, rounded down: 3.33 + 6.66 = 9.99
# the spare cent goes to the larger remainder, mer_07Полное условие (как в файле задачи)
Some South Market bundles hold products of several merchants. The marketplace pays the bundle as one payout, and we split it between the merchants by their agreed shares. split_payout below is written and correct. Your task is the other half: write the tests for it, the ones you would want to have before anybody changes this function.
split_payout(Decimal("10.00"), {"mer_03": 1, "mer_07": 2})
-> [("mer_03", Decimal("3.33")), ("mer_07", Decimal("6.67"))]
Write pytest test functions below the YOUR TESTS line, at the bottom of this file:
- name them test_..., give them no arguments (@pytest.mark.parametrize is fine), and call split_payout by its name;
- use plain assert and pytest.raises;
- write at least 3.
How Check grades your tests:
1. They must all pass on split_payout as it is.
2. Then Check plants 6 different bugs into split_payout, one at a time, and runs your tests again. Each bug must make at least one of your tests fail. A bug that survives is named by its area only, for example "a bug in how each part is rounded".Перевод
Этот раунд — про тесты. split_payout делит одну выплату South Market за набор продуктов (bundle) между несколькими продавцами по их долям, в целых центах, так что части всегда складываются в сумму: каждый продавец сначала получает свою часть, округлённую вниз, а оставшиеся центы уходят к наибольшим остаткам. Функция уже написана и работает правильно.
Напишите для неё тесты под строкой YOUR TESTS: функции test_*, которые вызывают split_payout, с простым assert, pytest.raises и, если хотите, @pytest.mark.parametrize. Хватит нескольких тестов, если у каждого есть причина.
«Проверить» запускает ваши тесты на правильной функции, и там все они должны пройти. Потом — на 6 версиях с подложенной ошибкой, и каждый раз хотя бы один тест должен упасть. Выжившая ошибка называется только по своей области.
split_payout(Decimal("10.00"), {"mer_03": 1, "mer_07": 2})
→ [('mer_03', Decimal('3.33')), ('mer_07', Decimal('6.67'))]
# точные части 3,333… и 6,666…, вниз: 3,33 + 6,66 = 9,99
# лишний цент уходит к большему остатку, mer_07Сначала спросите
Задайте каждый вопрос вслух до того, как писать код. Ответ интервьюера открывайте только после вопроса.
Запишите вопросы, которые задали бы интервьюеру, и произнесите каждый вслух. Вопросы задачи и ответы на них откроются, когда вы закончите мок.
Can I change split_payout?Можно ли менять
split_payout?No. It is correct: only add tests. If you think you see a bug, say it out loud.
Перевод: Нет. Функция правильная: только добавляйте тесты. Если вам кажется, что вы видите ошибку, скажите это вслух.
May I read the code, or only the docstring?Можно читать код или только docstring?
Read both. But test what the docstring promises, not how this code happens to do it: the code may be rewritten.
Перевод: Читайте и то и другое. Но проверяйте то, что обещает docstring, а не то, как этот код это делает: код могут переписать.
Exact amounts, or properties like "the parts add up"?Точные суммы или свойства вроде «части складываются»?
Both. Exact amounts for a few small cases you can work out by hand, and the sum for more cases.
Перевод: И то и другое. Точные суммы — для нескольких маленьких случаев, которые можно посчитать вручную, а сумму частей — для большего числа случаев.
How many tests do you expect?Сколько тестов вы ждёте?
Not many: each test should catch something the others miss.
Перевод: Немного: каждый тест должен ловить то, что пропускают остальные.
from decimal import Decimal
import pytest
CENT = Decimal("0.01")
def split_payout(amount, shares):
"""Split a payout between merchants by their shares.
amount: a Decimal, zero or more, in whole cents.
shares: {merchant_id: weight}; weights are whole numbers, zero or more, and at least one is above zero.
A merchant's exact part is amount * weight / (sum of the weights).
Returns a list of (merchant_id, Decimal) pairs, in the order of `shares`. The parts are whole cents and
add up to `amount` exactly:
1. every merchant first gets its exact part rounded DOWN to the cent;
2. the cents that are left go one each to the merchants with the largest remainder (the part that was
rounded away); on equal remainders, to the merchant that comes first in `shares`.
Raises ValueError for a negative amount, an amount with a fraction of a cent, a negative weight, or
weights that add up to zero (an empty `shares` included).
"""
if amount < 0 or amount != amount.quantize(CENT):
raise ValueError(f"amount must be zero or more, in whole cents: {amount}")
if any(weight < 0 for weight in shares.values()):
raise ValueError("weights must be zero or more")
total = sum(shares.values())
if total == 0:
raise ValueError("at least one weight must be above zero")
cents = int(amount * 100)
parts, remainders = {}, {}
for merchant, weight in shares.items():
parts[merchant], remainders[merchant] = divmod(cents * weight, total)
left = cents - sum(parts.values())
# sorted() is stable: on equal remainders the merchants keep the order of `shares`
for merchant in sorted(shares, key=lambda m: -remainders[m])[:left]:
parts[merchant] += 1
return [(merchant, Decimal(parts[merchant]).scaleb(-2)) for merchant in shares]
# ---------------------------------------------------------------- YOUR TESTS below this line
def test_first():
raise NotImplementedError("your code")
«Запустить» выполняет файл сверху вниз, как python file.py. «Проверить» импортирует его как модуль и запускает тесты.
Подсказка: на что намекнул бы интервьюер
Прочитайте docstring как список обещаний и дайте каждому свой тест. Для каждого теста спросите себя: если код нарушит это обещание самым вероятным способом, изменится ли ожидаемое значение? Если нет, возьмите другие числа или другие id.
Скажите вслух: I test each promise of the docstring with a case I can work out by hand, and I pick ids out of alphabetical order, so that a wrong order or a wrong tie-break gives a different answer.
Эталонное решение
from decimal import Decimal
import pytest
CENT = Decimal("0.01")
def split_payout(amount, shares): """The function from the task, unchanged (see the task file for its docstring).""" if amount < 0 or amount != amount.quantize(CENT): raise ValueError(f"amount must be zero or more, in whole cents: {amount}") if any(weight < 0 for weight in shares.values()): raise ValueError("weights must be zero or more") total = sum(shares.values()) if total == 0: raise ValueError("at least one weight must be above zero") cents = int(amount * 100) parts, remainders = {}, {} for merchant, weight in shares.items(): parts[merchant], remainders[merchant] = divmod(cents * weight, total) left = cents - sum(parts.values()) # sorted() is stable: on equal remainders the merchants keep the order of `shares` for merchant in sorted(shares, key=lambda m: -remainders[m])[:left]: parts[merchant] += 1 return [(merchant, Decimal(parts[merchant]).scaleb(-2)) for merchant in shares]
# ---------------------------------------------------------------- YOUR TESTS below this line# Each test is worked out by hand, and its ids are NOT in alphabetical order, so "first in shares"# and "first by id" give different answers.D = Decimal
def test_three_equal_shares_give_the_spare_cent_to_the_first(): # 100.00 / 3 = 33.333…: three parts of 33.33 lose a cent; the first merchant gets it assert split_payout(D("100.00"), {"mer_09": 1, "mer_02": 1, "mer_05": 1}) == [ ("mer_09", D("33.34")), ("mer_02", D("33.33")), ("mer_05", D("33.33"))]
def test_the_spare_cent_goes_to_the_largest_remainder_not_to_the_first(): # 10.00 by 1:2 -> 3.333… and 6.666…: rounded down 3.33 + 6.66, and the larger remainder is mer_07's assert split_payout(D("10.00"), {"mer_03": 1, "mer_07": 2}) == [("mer_03", D("3.33")), ("mer_07", D("6.67"))]
def test_equal_remainders_follow_the_order_of_shares_and_so_does_the_result(): assert split_payout(D("0.01"), {"mer_08": 1, "mer_01": 1}) == [("mer_08", D("0.01")), ("mer_01", D("0.00"))]
def test_zero_amount_and_zero_weight_are_valid(): assert split_payout(D("0.00"), {"mer_04": 1, "mer_02": 3}) == [("mer_04", D("0.00")), ("mer_02", D("0.00"))] assert split_payout(D("5.00"), {"mer_04": 0, "mer_02": 3}) == [("mer_04", D("0.00")), ("mer_02", D("5.00"))]
@pytest.mark.parametrize("amount, shares", [ (D("100.00"), {"a": 1, "b": 1, "c": 1}), (D("0.05"), {"a": 1, "b": 1, "c": 1, "d": 1, "e": 1, "f": 1, "g": 1}), (D("1234.57"), {"a": 7000, "b": 2000, "c": 1000}), (D("19.99"), {"a": 3, "b": 3, "c": 1}),])def test_parts_add_up_and_stay_within_a_cent_of_the_exact_share(amount, shares): parts = split_payout(amount, shares) assert sum(part for _, part in parts) == amount total = sum(shares.values()) for merchant, part in parts: assert abs(part - amount * shares[merchant] / total) < CENT
@pytest.mark.parametrize("amount, shares", [ (D("-1.00"), {"a": 1}), # negative amount (D("10.005"), {"a": 1}), # a fraction of a cent (D("10.00"), {"a": 2, "b": -1}), # a negative weight, although the sum is positive (D("10.00"), {"a": 0, "b": 0}), # the weights add up to zero (D("10.00"), {}), # no shares at all])def test_bad_input_raises_value_error(amount, shares): with pytest.raises(ValueError): split_payout(amount, shares)РазборСначала решите задачу сами: разбор полезнее всего после своей попытки.
Зачем. На некоторых раундах дают работающий код и просят написать к нему тесты. Интервьюер смотрит, что вы решили проверить, а не сколько набрали. «Проверить» здесь работает как инструмент мутационного тестирования (mutation testing): нарочно ломает код и смотрит, заметят ли это ваши тесты.
Шаги.
- Прочитать docstring как список обещаний: сначала части округляются вниз, лишние центы уходят к наибольшим остаткам, ничьи решает позиция в
shares, результат идёт в порядкеshares, сумма точная, ноль допустим, и есть четыре видаValueError. - Для каждого обещания назвать самый вероятный неправильный код и подобрать вход, на котором его ответ отличается от правильного. Ожидаемое значение посчитать вручную.
- Сначала написать тесты с точными значениями. Потом добавить один параметризованный тест на свойства (сумма и расстояние до точной доли) и один параметризованный тест на ошибки.
- Одной фразой сказать, зачем нужен каждый тест.
Ловушки.
- id продавцов в алфавитном порядке. Тогда «первый в
shares» и «первый по id» дают один ответ, и неправильное правило ничьей или отсортированный результат выживают. Возьмите{"mer_08": 1, "mer_01": 1}. - Сравнение
dict(result)скрывает порядок результата. - Только равные доли. При 1:1:1 лишний цент уходит первому продавцу, смотрит код на остатки или нет. Возьмите 1:2, где больший остаток у второго продавца.
- Только сумма. Тест на сумму проходит, даже когда цент ушёл не тому продавцу.
- Только некорректный вход. Нулевая сумма и нулевой вес допустимы, а слишком строгая проверка — тоже ошибка.
- Ожидаемое значение, скопированное из вывода самой функции, ничего не проверяет. Считайте вручную.
Проверка. Запустите тесты один раз на коде как есть. Потом сломайте функцию сами, например замените sorted(shares, key=…) на list(shares), и посмотрите, какой тест упадёт. «Проверить» делает ровно это, с шестью разными ошибками.
Продолжение.
- «Какой тест вы бы написали первым?» Тот, что проверяет самое дорогое обещание: части складываются точно. Потерянный цент всплывает в каждой сверке.
- «Как проверить это на случайных данных?» Тест свойств (property-based testing), например с библиотекой hypothesis: для случайных сумм и весов части складываются, каждая часть отличается от точной доли меньше чем на цент, а порядок следует
shares. - «Что даёт мутационное тестирование, чего не даёт покрытие (coverage)?» Покрытие говорит, что строка выполнилась. Подложенная ошибка показывает, заметил бы хоть один тест, что эта строка неверна.
Тексты сайта — по лицензии CC BY 4.0, код — по лицензии MIT. Упражнения выполняются в вашем браузере: PostgreSQL — PGlite, Python — Pyodide.