Money tasks
Six tasks handle money: how much the advances program can pay a merchant, which payment paid which invoice, how to send a payout without paying twice, MRR, a partner’s payout file full of bad rows, and the tests for a function that splits a payout. They test Decimal with the right rounding, validation before any calculation, matching rules applied in a fixed order, retries that are safe for money, and tests that would notice a lost cent. They build on Money and Decimal, Errors and validation, Sets and duplicates, Iteration and generators and Testing and complexity.
P06. How much can we advance?
Section titled “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)
Full statement (as in the task file)
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"))Ask first
Say each question out loud before you code. Open the interviewer's answer only after you asked.
Type the questions you would ask the interviewer, and say each one out loud. The task's questions and their answers open when you end the mock.
How do I round the amount and the fee?
The amount down to cents, the fee half up to cents.
What if the amount is very small?
Below 1.00 we pay nothing: (0.00, 0.00).
Invalid input?
Negative numbers, or refund_rate outside [0, 1] -> ValueError.
from decimal import Decimal
def compute_advance(expected_proceeds, refund_rate, merchant_limit, global_remaining):
raise NotImplementedError("your code")
Run executes the file top to bottom, like python file.py. Check imports it as a module and runs the tests.
Hint: what the interviewer would nudge
Write the three limits as three separate lines and take the smallest. Then decide the rounding: which direction for the amount, and which for the fee?
Say it: Money is Decimal; the amount rounds down so we never advance more than allowed, the fee rounds half up.
Reference solution
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, feeWalkthroughTry the task first: the walkthrough is most useful after your own attempt.
What it is for. The advances program pays a merchant part of a future marketplace payout today. The amount is the smallest of three limits: 70% of the expected proceeds after a refund reserve, the merchant’s risk limit, and what is left of the total budget.
Steps. Validate the input; compute the three numbers; take min; round down to cents; below 1.00 return (0.00, 0.00); otherwise the fee is 3% of the amount, rounded half up.
Traps.
- Only
quantize(Decimal("0.01"), rounding=ROUND_DOWN)rounds down.round()on aDecimalrounds to the nearest value. A test uses 0.70 × 33.33 × 0.9 = 20.99790:round()gives21.00, whilequantizewithROUND_DOWNgives20.99. round()is wrong for the fee too: on aDecimalit rounds an exact half to the even cent. A test has a fee of 3% × 1.50 = 0.045:round()gives0.04, whilequantizewithROUND_HALF_UPgives0.05.- Validate before you compute. A negative budget must be an error, not a negative advance.
- Money is
Decimalonly, created from strings or integers. A float cannot store cents exactly:0.1 + 0.2is0.30000000000000004. - The fee is computed from the rounded amount, the amount that is actually paid.
Check. The example from the task: 0.70 × 1000 × 0.95 = 665.00, and the fee is 19.95.
Complexity. Constant time. The interesting part is the rounding rules, so state them before you code them.
P07. Match payments to invoices
Section titled “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
Full statement (as in the task file)
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).Ask first
Say each question out loud before you code. Open the interviewer's answer only after you asked.
Type the questions you would ask the interviewer, and say each one out loud. The task's questions and their answers open when you end the mock.
Can a reference point to an invoice of another counterparty?
Yes, trust the reference.
What if the reference points to an invoice that is already matched?
Treat the payment as having no reference. References are applied in payment order (date, then id).
What if a payment has no reference?
Same counterparty, same amount, at most 3 days from the due date; the closest date wins, then the smallest invoice id.
def reconcile(invoices, payments):
raise NotImplementedError("your code")
Run executes the file top to bottom, like python file.py. Check imports it as a module and runs the tests.
Hint: what the interviewer would nudge
What goes wrong if a guess takes an invoice that another payment refers to? Decide the order of the two rules before you write them. Then: which invoices can match one payment at all, and how do you find them without scanning every invoice?
Say it: I index open invoices by (counterparty, amount), so each payment only looks at real candidates.
Reference solution
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)}WalkthroughTry the task first: the walkthrough is most useful after your own attempt.
What it is for. Accounting matches incoming payments to invoices. A reference in the payment is a reliable signal. For payments without one there is a heuristic by counterparty, amount and date.
Steps.
- Sort the payments by (date, id) once. Both passes go through them in this order.
- Pass 1: payments whose reference is an open invoice. Match them and remove the invoice from the open ones. If two payments refer to the same invoice, the earlier one gets it, and the other one goes to pass 2.
- Index the remaining open invoices by
(counterparty, amount). - Pass 2: the other payments, still in order. The candidates are open invoices with the same key and at most 3 days between the payment date and the due date. The best one is
minby (difference in days, invoice id). Remove it from the open invoices.
Traps.
- All references first, then the heuristic. Otherwise the heuristic can “steal” an invoice that another payment refers to.
- A reference to an invoice that is already matched counts as no reference: the payment goes to pass 2.
- Sort before pass 1, not only before pass 2. Otherwise, when two payments refer to the same invoice, the one that happens to come first in the input wins.
- A reference to another counterparty’s invoice is still trusted. Do not add a counterparty check to pass 1.
- Use
abs()for the date difference: a payment can come before the due date. - Sort all three lists of the result.
Complexity. With the index by (counterparty, amount), each payment looks only at real candidates, not at every invoice. The rest is the sorts: O(n log n).
Follow-up. Partial payments, a tolerance on the amount, several currencies. Name them as extensions and say where each one would change the code.
P09. Pay out safely with retries
Section titled “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
Full statement (as in the task file)
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.Ask first
Say each question out loud before you code. Open the interviewer's answer only after you asked.
Type the questions you would ask the interviewer, and say each one out loud. The task's questions and their answers open when you end the mock.
Does the bank itself honour the idempotency key?
Assume NOT — that is why we check 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")
Run executes the file top to bottom, like python file.py. Check imports it as a module and runs the tests.
Hint: what the interviewer would nudge
Treat the two errors differently: after a TransientError a retry is safe, after a TimeoutError you first need to know whether the money left. Use one key for all attempts.
Say it: After a timeout I first ask the bank whether the payment exists — a blind retry could pay twice.
Reference solution
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_errorWalkthroughTry the task first: the walkthrough is most useful after your own attempt.
What it is for. A payout through a bank must never leave twice, even when a request hangs.
Steps.
- One idempotency key for every attempt:
f"payout:{payout_id}". - A loop over attempts 1 …
max_attempts. Before retry k, waitbase_delay * 2 ** (k - 1). TransientError→ remember it and retry.TimeoutError→ first askbank.get_payment(key). A payment id → return it;None→ retry.- After the loop,
raise PayoutFailed(...) from last_error.
Traps.
- A blind retry after a timeout can pay twice. That is the whole point of the task.
- A new key on each attempt defeats the idempotency key.
- Catch only
TransientErrorandTimeoutError. Any other error goes up at once. - No wait before the first attempt, and no wait after the last one.
from last_errorkeeps the cause, so the log shows why the payout failed.
Check. Two TransientErrors, then success: pay is called 3 times, and the waits are 0.5 and 1.0.
Follow-up. “The last attempt times out, and get_payment still finds nothing. Did the payout fail?” Not for sure: the outcome is unknown, and the bank may still process it. The exercise raises PayoutFailed to keep the rule simple. In production, raise a separate “unknown outcome” error, or park the payout for a reconciliation job, so the caller does not retry blindly.
In production. Save the payout and its status before calling the bank. Then a crash in the middle, or an unknown outcome, can be resolved later by asking the bank with the same key.
P10. MRR by plan
Section titled “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 monthFull statement (as in the task file)
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.Ask first
Say each question out loud before you code. Open the interviewer's answer only after you asked.
Type the questions you would ask the interviewer, and say each one out loud. The task's questions and their answers open when you end the mock.
What does active at as_of mean?
start_time <= as_of < end_time; not a trial, not a test purchase, not promo; not refunded at or before 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.
When do I round?
Once per plan, at the end, half up to cents.
def mrr_by_plan(transactions, as_of):
raise NotImplementedError("your code")
Run executes the file top to bottom, like python file.py. Check imports it as a module and runs the tests.
Hint: what the interviewer would nudge
Write a small function that decides whether one transaction counts at as_of, and try it alone. Then turn each price into a monthly value and round only at the end.
Say it: I sum in full precision and round once per plan at the end, half up.
Reference solution
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()}WalkthroughTry the task first: the walkthrough is most useful after your own attempt.
What it is for. MRR is how much money per month the subscriptions that are active right now bring in. A yearly plan at 120 gives 10 per month; a weekly one gives the price × 52 / 12. It is a headline number of any subscription business.
Steps.
- A separate function for “active and paid at
as_of”: the same filters as in SQL Q03. - A factor by
plan_period. - A sum per
plan_idinDecimal, at full precision. - One rounding per plan at the end, half up to cents.
Traps.
- Rounding each transaction makes the cents drift.
- A refund in the future does not count yet:
refunded_at is None or refunded_at > as_of. - The factor 52 / 12 must be
Decimal(52) / Decimal(12), not a float. - An unknown duration is a
ValueError, not a silent zero.
Check. On the practice data at 30 September, 45 plans have active subscriptions, and prd_03.monthly has an MRR of 69.86. A test compares every plan, to the cent, with an exact calculation in SQL. Three plans land exactly on half a cent (prd_01.annual is 99.975), so the rounding rule decides their last cent.
Complexity. One pass, O(n), and memory for one total per plan.
P12. Import a partner payout file
Section titled “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')]Full statement (as in the task file)
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.Ask first
Say each question out loud before you code. Open the interviewer's answer only after you asked.
Type the questions you would ask the interviewer, and say each one out loud. The task's questions and their answers open when you end the mock.
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?
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.
Can an amount have a thousands separator, like 1.234,50?
Not in this export. A dot or a space inside an amount is bad_amount: do not guess what it means.
Is a zero amount allowed?
Yes. Only an amount below zero is negative_amount.
How do I count lines?
As an editor does: the header is line 1, and blank lines count.
Should I check merchant ids against our merchants table?
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")
Run executes the file top to bottom, like python file.py. Check imports it as a module and runs the tests.
Hint: what the interviewer would nudge
Write one small function that takes the fields of one row and returns either a Payout or an error code, and try it on single rows first. Then the loop: what must you remember from earlier lines, and at what moment may a payout id join that memory?
Say it: 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.
Reference solution
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, errorsWalkthroughTry the task first: the walkthrough is most useful after your own attempt.
What it is for. A partner’s export is where outside data enters our books. A bad row must not stop the import, and it must not slip in either. The total on the last line is the partner’s own check that we read every number right.
Steps.
- Take the header with
next(rows, None); nothing there →ImportFailed. Remove the BOM withlstrip("\ufeff"), then normalise each name:"_".join(name.strip().lower().split()). Map the four names to their positions; a missing one →ImportFailed. - Loop with
enumerate(rows, start=2): the header is line 1, and blank lines keep their numbers. Skip a blank line only after it has its number. - A line whose first field is
TOTALgives the total. Any non-blank line after it →ImportFailed. - One small function checks a row in the order of the codes and returns the first problem, or a
Payout. The amount is checked against a strict pattern,-?\d+(,\d{1,2})?, beforeDecimal; the date is parsed withstrptime("%Y-%m-%d"). - The payout id joins the set of imported ids only after the row is good.
- At the end: no total →
ImportFailed; the sum of the good amounts differs from the total →ImportFailed. Otherwise return both lists.
Traps.
strip()does not remove a BOM: it is not whitespace. The first column is then called\ufeffpayout_id, and the import fails on a missing column.Decimal(text.replace(",", "."))accepts12.50. In a file with decimal commas a dot means the row is in another format, and12.50could be 1250. A strict pattern turns it intobad_amount.- An id marked as seen before the checks: the corrected copy of a bad row is then reported as a duplicate. It is the same mistake as in D03: mark only after success.
amount <= 0rejects a valid zero payout.- Counting only non-blank lines, or counting from 0. Support opens the file in an editor, so the numbers must match the editor’s.
lines[0]andlen(lines)fail on an open file or a generator.list(lines)works here but reads the whole file into memory.- Floats for the amounts: the total check then fails on a cent.
Check. In the example from the task, the good rows add up to 1234.50 + 87.10 = 1321.60, the total on the last line.
Complexity. One pass, O(n). Memory: the records you return, plus one id per imported payout.
Follow-up. “The file is 20 GB. What changes?” The input already streams; the output does not, because the list of records grows with the file. Write the records in batches to a staging table, and keep only the ids (or a unique key in that table) and the running sum. Commit after the total matches, and roll everything back if it does not. A generator that yields rows before the total is checked is the trap: the caller has already used rows of a file that turns out to be wrong.
In production. Keep the raw file, its checksum and the error report next to the import, so a dispute with the partner can be replayed. A unique key on (channel, payout_id) makes a second import of the same file harmless.
P14. Write the tests for a payout split
Section titled “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_07Full statement (as in the task file)
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".Ask first
Say each question out loud before you code. Open the interviewer's answer only after you asked.
Type the questions you would ask the interviewer, and say each one out loud. The task's questions and their answers open when you end the mock.
Can I change 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?
Read both. But test what the docstring promises, not how this code happens to do it: the code may be rewritten.
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")
Run executes the file top to bottom, like python file.py. Check imports it as a module and runs the tests.
Hint: what the interviewer would nudge
Read the docstring as a list of promises and give each one a test. For each test, ask: if the code broke this promise in the most likely way, would my expected value change? If not, pick other numbers or other ids.
Say it: 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.
Reference solution
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)WalkthroughTry the task first: the walkthrough is most useful after your own attempt.
What it is for. Some rounds give you working code and ask for its tests. The interviewer watches what you choose to test, not how much you type. Check here works like a mutation testing tool: it breaks the code on purpose and asks whether your tests notice.
Steps.
- Read the docstring as a list of promises: parts rounded down first, the spare cents to the largest remainders, ties by position in
shares, the result in the order ofshares, an exact sum, zero is valid, and four kinds ofValueError. - For each promise, name the most likely wrong code, and pick an input where its answer differs from the right one. Work out the expected value by hand.
- Write the exact-value tests first. Then add one parametrised test for properties (the sum, and the distance to the exact share) and one parametrised test for the errors.
- Say in one sentence what each test is for.
Traps.
- Merchant ids in alphabetical order. “First in
shares” and “first by id” then give the same answer, so a wrong tie-break or a sorted result survives. Use{"mer_08": 1, "mer_01": 1}. - Comparing
dict(result)hides the order of the result. - Only equal shares. With 1:1:1 the spare cent goes to the first merchant whether or not the code looks at the remainders. Use 1:2, where the larger remainder belongs to the second merchant.
- Only the sum. A sum test passes when the cent goes to the wrong merchant.
- Only invalid input. A zero amount and a zero weight are valid, and a check that is too strict is a bug too.
- An expected value copied from the function’s own output tests nothing. Compute it by hand.
Check. Run your tests once on the code as it is. Then break the function yourself, for example replace sorted(shares, key=…) with list(shares), and see which test fails. Check does exactly that, with six different bugs.
Follow-up.
- “Which test would you write first?” The one for the promise that is the most expensive to break: the parts add up exactly. A lost cent shows up in every reconciliation.
- “How would you test it on random data?” A property test, for example with the hypothesis library: for random amounts and weights, the parts add up, each part is less than a cent from its exact share, and the order follows
shares. - “What does mutation testing tell you that coverage does not?” Coverage says that a line ran. A planted bug shows whether any test would notice that line being wrong.
Site content: CC BY 4.0. Code: MIT. The exercises run in your browser: PostgreSQL by PGlite, Python by Pyodide.